Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 46 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ on:

env:
PYTHON_VERSION: "3.12"
NODE_VERSION: "20"
NODE_VERSION: "24"

jobs:
# ─── Backend ───────────────────────────────────────────
Expand All @@ -28,7 +28,7 @@ jobs:
python-version: ${{ env.PYTHON_VERSION }}

- name: Install Poetry
run: pip install poetry==1.8.4
run: pip install poetry==2.4.1

- name: Cache Poetry dependencies
uses: actions/cache@v4
Expand All @@ -40,6 +40,12 @@ jobs:
- name: Install dependencies
run: poetry install --no-interaction

- name: Verify reproducible broker SDK patch
run: |
curl -fsSL https://files.pythonhosted.org/packages/24/dc/553a556fb6dd4b2e4d4251d5ec53536a36cde34f9aae8aaf88280239a5bb/fyers_apiv3-3.1.14-py3-none-any.whl -o "$RUNNER_TEMP/fyers-upstream.whl"
python ../scripts/build-fyers-wheel.py "$RUNNER_TEMP/fyers-upstream.whl" "$RUNNER_TEMP/fyers-patched.whl"
cmp vendor/fyers_apiv3-3.1.14+oap.1-py3-none-any.whl "$RUNNER_TEMP/fyers-patched.whl"

- name: Lint with Ruff
run: poetry run ruff check .

Expand Down Expand Up @@ -88,7 +94,7 @@ jobs:
python-version: ${{ env.PYTHON_VERSION }}

- name: Install Poetry
run: pip install poetry==1.8.4
run: pip install poetry==2.4.1

- name: Install dependencies
run: poetry install --no-interaction
Expand All @@ -97,7 +103,7 @@ jobs:
env:
DATABASE_URL: postgresql+asyncpg://postgres:postgres@localhost:5432/test_db
REDIS_URL: redis://localhost:6379/1
JWT_SECRET: test-secret-key
JWT_SECRET: isolated-ci-signing-secret-at-least-32-characters
APP_ENV: development
run: poetry run pytest -v --cov=app --cov-report=xml

Expand Down Expand Up @@ -128,6 +134,12 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Verify reproducible lint dependency patch
run: |
curl -fsSL https://registry.npmjs.org/braces/-/braces-3.0.3.tgz -o "$RUNNER_TEMP/braces-upstream.tgz"
python3 ../scripts/build-braces-package.py "$RUNNER_TEMP/braces-upstream.tgz" "$RUNNER_TEMP/braces-patched.tgz"
cmp vendor/braces-3.0.3-oap.1.tgz "$RUNNER_TEMP/braces-patched.tgz"

- name: Lint
run: npm run lint

Expand Down Expand Up @@ -175,9 +187,34 @@ jobs:

- name: Verify backend health
run: |
docker run -d --name backend-test -p 8000:8000 \
-e JWT_SECRET=test -e APP_ENV=development \
docker network create oap-ci
docker run -d --name oap-ci-db --network oap-ci \
-e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=option_analytics timescale/timescaledb:latest-pg16
docker run -d --name oap-ci-redis --network oap-ci redis:7-alpine
docker run -d --name backend-test --network oap-ci -p 127.0.0.1:8000:8000 \
-e JWT_SECRET=isolated-ci-signing-secret-at-least-32-characters -e APP_ENV=development \
-e DATABASE_URL=postgresql+asyncpg://postgres:postgres@oap-ci-db:5432/option_analytics \
-e REDIS_URL=redis://oap-ci-redis:6379/0 \
-e MARKET_DATA_BACKFILL_ENABLED=false -e IV_UNIVERSE_BACKFILL_ENABLED=false \
-e PARTICIPANT_DATA_ENABLED=false -e ALERT_EVALUATION_ENABLED=false \
-e BASKET_MONITOR_ENABLED=false -e OPEN_INTEREST_SNAPSHOT_ENABLED=false \
oap-backend:ci
sleep 10
curl -f http://localhost:8000/api/v1/health || exit 1
docker stop backend-test
for attempt in $(seq 1 60); do
if curl -fsS http://localhost:8000/api/v1/health; then break; fi
sleep 2
done
curl -fsS http://localhost:8000/api/v1/health
test "$(curl -s -o /dev/null -w '%{http_code}' -X POST http://localhost:8000/api/v1/auth/auto-login)" = 403
docker run -d --name frontend-test -p 127.0.0.1:3000:3000 oap-frontend:ci
for attempt in $(seq 1 30); do
if curl -fsS http://localhost:3000/accounts > /dev/null; then break; fi
sleep 2
done
curl -fsS http://localhost:3000/accounts > /dev/null

- name: Container diagnostics
if: failure()
run: |
docker logs backend-test || true
docker logs frontend-test || true
23 changes: 11 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Implemented workspaces include:
- **Strategy Builder and Replay:** strategy presets, custom legs, payoff and net-Greek calculations, Monte Carlo analysis, backtesting, and historical-candle replay with modeled fallbacks.
- **Trading and preferences:** paper/live modes, orders, positions, a trade journal, persisted alerts, and server-synced settings with a local fallback.

The backend holds one active broker connection per API process. Connecting another account replaces the previous session; this is a single-account workspace.
The backend runs one worker and holds one active broker connection per API process. Connecting another account replaces the previous session; this is a single-account workspace.

### Built With

Expand All @@ -78,14 +78,14 @@ The backend holds one active broker connection per API process. Connecting anoth

## Getting Started

Run from source with Docker, or run the application natively while Docker supplies PostgreSQL and Redis. The repository is private and has no published GitHub releases.
Run from source with Docker, or run the application natively while Docker supplies PostgreSQL and Redis. The repository is private. Source releases are published in its GitHub Releases page.

### Prerequisites

- Git and access to [DagerottDev/AnalyticsPlateform][repo-url].
- Docker with the Compose plugin and a running Docker daemon.
- For broker-backed analytics: a Fyers app ID and secret with either OAuth authorization or client ID, PIN and TOTP secret; alternatively, a Dhan client ID and a current access token.
- For native development only: Python **3.12**, Poetry **1.8.4**, and Node.js **20** with npm, matching the Dockerfiles and CI configuration.
- For native development only: Python **3.12**, Poetry **2.4.1**, and Node.js **24** with npm, matching the Dockerfiles and CI configuration.

Broker access and data availability determine which workspaces can load market data. See [Data and Trading Constraints](#data-and-trading-constraints) before choosing a broker.

Expand All @@ -96,12 +96,11 @@ For a fresh checkout:
```bash
git clone https://github.com/DagerottDev/AnalyticsPlateform.git
cd AnalyticsPlateform
cp backend/.env.example backend/.env
cp frontend/.env.example frontend/.env.local
./install.sh
./start.sh
```

If you already have environment files, keep them rather than repeating the copy commands. `start.sh` builds and starts the four-service development stack with frontend and backend hot reload. The backend waits for PostgreSQL and runs `alembic upgrade head` before starting the API.
The installer creates missing environment files with distinct random signing/encryption keys and mode 0600. It preserves existing environment files. Existing installations must replace a placeholder or short `JWT_SECRET` before upgrading; keep any existing encryption key. `start.sh` builds and starts the four-service development stack with frontend and backend hot reload. The backend waits for PostgreSQL and runs `alembic upgrade head` before starting the API.

| Service | Local address |
| --- | --- |
Expand Down Expand Up @@ -129,26 +128,26 @@ The committed [backend example](backend/.env.example) and [frontend example](fro
| `NEXT_PUBLIC_API_URL` | Browser-facing API base, `http://localhost:8001` |
| `DATABASE_URL` | Native backend: `postgresql+asyncpg://postgres:postgres@localhost:5433/option_analytics` |
| `REDIS_URL` | Native backend: `redis://localhost:6380/0` |
| `JWT_SECRET` | Application signing secret; replace the example value before deployment |
| `JWT_SECRET` | Required independently generated signing secret, at least 32 characters; shipped placeholders are rejected |
| `JWT_ALGORITHM`, `JWT_EXPIRY_MINUTES` | Application token settings, default `HS256` and `480` |
| `APP_ENV`, `APP_DEBUG`, `CORS_ORIGINS` | Local defaults: `development`, `true`, `http://localhost:3001` |
| `APP_ENV`, `APP_DEBUG`, `CORS_ORIGINS` | Local defaults: `development`, `false`, `http://localhost:3001` |
| `BROKER_TOKEN_ENCRYPTION_KEY` | Optional Fernet key for persisted broker secrets; without it, persistence is plaintext |
| `MARKET_QUOTE_POLL_INTERVAL_SECONDS` | REST fallback polling interval, default `3.0` seconds |
| `API_RATE_LIMIT_BROKER_REQUESTS` | Broker-route budget, default `120` per client IP per minute |
| `MARKET_DATA_BACKFILL_ENABLED`, `MARKET_DATA_BACKFILL_SYMBOLS` | Scheduled daily candle storage, default `true` and `NIFTY,BANKNIFTY` |
| `LOG_LEVEL`, `SENTRY_DSN`, `SENTRY_TRACES_SAMPLE_RATE` | Optional logging and error reporting |

**Docker environment handling:** the development bind mount exposes `backend/.env`, but Compose's explicit `environment` values take precedence. It sets container database/cache addresses, development mode, CORS and `JWT_SECRET`. To override the latter, export `JWT_SECRET` in the shell before starting Compose. The production backend image does not copy `backend/.env`; additional settings must be passed into the container through a Compose override or another deployment configuration. Exporting an arbitrary setting alone does not forward it unless Compose references it.
**Docker environment handling:** Compose loads `backend/.env` through `env_file` and overrides only container database/cache addresses and migration control. Configure `JWT_SECRET`, encryption, `APP_ENV`, debug and CORS in that file. All published ports bind to `127.0.0.1`. The production image does not contain environment files. Set `NEXT_PUBLIC_API_URL` in the Compose shell before building to supply the frontend build argument; runtime changes do not rewrite the client bundle.

`RUN_MIGRATIONS=false` skips the Docker migration step only when migrations are handled separately. To build production images locally, use the base Compose file alone:

```bash
docker compose -f docker/docker-compose.yml up --build -d
```

That file retains local development credentials and environment settings; it needs deployment-specific configuration before use on a server. Set the browser API URL at frontend **build time** for production: `NEXT_PUBLIC_*` values are bundled into the client, and runtime-only changes do not rewrite that build. See [Deployment](docs/DEPLOYMENT.md), checking its examples against the current Compose files and ports.
That file retains local database credentials; use deployment-specific database credentials and a TLS reverse proxy before use on a server. Set the browser API URL at frontend **build time** for production: `NEXT_PUBLIC_*` values are bundled into the client, and runtime-only changes do not rewrite that build. See [Deployment](docs/DEPLOYMENT.md), checking its examples against the current Compose files and ports.

The login form saves credentials, including PIN/TOTP fields and Dhan tokens, in browser local storage for reuse. Use a trusted browser profile. Database encryption does not encrypt these browser values.
Recovery requires an existing unexpired, nonrevoked browser JWT bound to the same account, broker and trading mode. Expired or missing browser tokens require manual broker login. The login form saves credentials, including PIN/TOTP fields and Dhan tokens, in browser local storage for reuse. Use a trusted browser profile. Database encryption does not encrypt these browser values.

### Native Development

Expand Down Expand Up @@ -223,7 +222,7 @@ npm test
npm run build
```

`npm run test:watch` starts interactive Vitest. The existing `npm run lint` script invokes `next lint`, which is not a command in the installed Next.js 15.5 CLI; use ESLint directly as above. The CI frontend lint step currently calls that legacy script too.
`npm run test:watch` starts interactive Vitest. `npm run lint` runs the same ESLint check used in CI.

To serve a native production frontend after building, from `frontend/`:

Expand Down
11 changes: 6 additions & 5 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
# body, not via environment variables. The first successful TOTP login
# (client_id + totp_secret + pin) has its credentials saved automatically —
# encrypted, in the broker_credentials DB table — and that becomes the
# source of truth for POST /api/v1/auth/auto-login, which lets the frontend
# skip the manual login form on subsequent startups. No env config needed.
# source of truth for POST /api/v1/auth/auto-login, which lets the authenticated frontend
# recover the same account while its JWT is valid. Expired JWTs require manual login.

# How long a headless-login access token is cached before a fresh TOTP login
# is forced, in seconds. Optional — defaults to a sane value if unset.
Expand All @@ -27,7 +27,8 @@
# MARKET_DATA_BACKFILL_OVERLAP_DAYS=7

# JWT Configuration
JWT_SECRET=change-this-to-a-secure-random-string-in-production
# Required: independently generate at least 32 random characters (install.sh does this).
JWT_SECRET=
JWT_ALGORITHM=HS256
JWT_EXPIRY_MINUTES=480

Expand All @@ -41,11 +42,11 @@ DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5433/option_analyt
# broker_sessions table (app.core.crypto). Generate one with:
# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
# Left unset, the token is stored in plaintext (with a startup warning).
# BROKER_TOKEN_ENCRYPTION_KEY=
BROKER_TOKEN_ENCRYPTION_KEY=

# App
APP_ENV=development
APP_DEBUG=true
APP_DEBUG=false
# LOG_LEVEL=INFO
# SENTRY_DSN=https://<key>@o0.ingest.sentry.io/<project>
# SENTRY_TRACES_SAMPLE_RATE=0.1
Expand Down
5 changes: 3 additions & 2 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ RUN apt-get update && \
rm -rf /var/lib/apt/lists/*

# Install Poetry
RUN pip install --no-cache-dir poetry==1.8.4
RUN pip install --no-cache-dir poetry==2.4.1

# Copy dependency files
COPY pyproject.toml poetry.lock* ./
COPY vendor/ ./vendor/

# Install dependencies (no dev dependencies in production)
RUN poetry config virtualenvs.in-project true && \
Expand Down Expand Up @@ -81,4 +82,4 @@ EXPOSE 8000
ENTRYPOINT ["/usr/local/bin/oap-entrypoint.sh"]

# Run with uvicorn
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
1 change: 1 addition & 0 deletions backend/alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ async def run_async_migrations() -> None:
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
hide_parameters=True,
)

async with connectable.connect() as connection:
Expand Down
1 change: 1 addition & 0 deletions backend/alembic/versions/0006_create_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0006"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0007"
Expand Down
1 change: 1 addition & 0 deletions backend/alembic/versions/0008_create_trade_journal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0008"
Expand Down
1 change: 1 addition & 0 deletions backend/alembic/versions/0009_add_broker_to_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0009"
Expand Down
3 changes: 2 additions & 1 deletion backend/alembic/versions/0013_create_gtt_orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
Revises: 0012
"""

from alembic import op
import sqlalchemy as sa

from alembic import op

revision = "0013_create_gtt_orders"
down_revision = "0012"
branch_labels = None
Expand Down
1 change: 1 addition & 0 deletions backend/alembic/versions/0014_create_user_preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0014_create_user_preferences"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0015_open_interest_snapshots"
Expand Down
1 change: 1 addition & 0 deletions backend/alembic/versions/0016_nse_participant_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "0016_nse_participant_data"
Expand Down
Loading
Loading