← Back to Portfolio
Case Study — Algorithmic Trading Platform

D-TradeX
Automated Trading Suite

A production-grade algorithmic trading platform connecting five Indian brokers through a unified adapter layer, with real-time options analytics, a canonical Black-76/BSM Greeks engine, a LightGBM ML signal classifier, and sub-200ms tick-to-frontend delivery via Redis Streams. Built from the ground up with a strict no-mock-data principle.

Actively in development — live at finance.dhimansoft.com →
Next.js 16 FastAPI / Python Redis Streams LightGBM PostgreSQL + MongoDB 🆕 Personal Project · In Progress
5 Brokers Connected
<200ms Tick-to-UI Latency
9K WS Token Cap Managed
31 Env Variables in Prod
01 — The Problem

Why Build a Custom Trading Platform?

Indian retail algorithmic trading is fragmented across incompatible broker APIs, inconsistent Greeks calculations, and platforms that hide their data sources. Building on top of existing tools means inheriting all of that debt.

🔗

Fragmented Broker APIs

Each broker (Zerodha, Upstox, Angel One, Nuvama, Dhan) exposes a different API shape, authentication flow, and tick format. No unified abstraction exists in the market.

🆂

Inconsistent Greeks

Broker-native Greeks use different models and reference rates. Comparing options positions across brokers produces misleading risk numbers. A canonical engine was essential.

📊

Mock Data Everywhere

Most retail algo platforms seed their databases with static or simulated data. Any strategy backtested or paper-traded against it is measuring noise, not market reality.

02 — Broker Layer

Five Brokers, One Adapter

A single broker adapter pattern normalizes authentication, tick formats, order placement, and historical data across all five supported brokers. Adding a sixth broker requires implementing one interface, not rewriting the platform.

⛟
Zerodha
Kite Connect
📈
Upstox
Upstox API v2
💵
Angel One
SmartAPI
👔
Nuvama
Nuvama API
🆕
Dhan
DhanHQ API

Zerodha WebSocket Token Cap

Kite Connect's WebSocket allows up to 9,000 instrument tokens per connection. The subscription manager enforces this cap automatically, routing tokens within the limit to the WebSocket and falling back to REST polling for instruments that exceed it. This prevents silent disconnects at market open when watchlists are large.

03 — Architecture

How the Platform Is Wired

Seven distinct layers from live market feed to the trader's browser, each with a single clear responsibility.

Market Data
Broker WebSocket Feeds Kite Connect Historical API TrueData / GFDL (licensed)
↓ Normalized tick via broker adapter
Adapter Layer
Broker Adapter (per broker) Token Subscription Manager REST Polling Fallback
↓ Uniform tick format pushed to Redis Streams
Streaming
Redis Streams <200ms tick-to-consumer SLA Consumer group per strategy
↓ Analytics workers consume stream
Analytics
Greeks Engine (Black-76/BSM) LightGBM Signal Classifier Celery + Beat task scheduler
↓ Computed data written to DB + cache
Persistence
PostgreSQL (auth, orders, users) MongoDB (TTL tick cache) Redis (session + stream)
↓ FastAPI serves data to Next.js frontend
API
FastAPI (Python) fastapi-users 13.x (auth) JWT HttpOnly + refresh rotation
↓ Rendered to trader dashboard
Frontend
Next.js 16 (App Router) Auth.js v5 (Google + GitHub OAuth) React Native Android (planned)
04 — Features

What the Platform Delivers

Nine production capabilities covering data ingestion, analytics, execution, and risk management.

📈

Live Options Chain

Unified options chain streaming from all connected brokers. Strikes, OI, volume, bid/ask, and computed Greeks displayed in real time with sub-200ms refresh.

🆂

Canonical Greeks Engine

Delta, Gamma, Theta, Vega, and Rho calculated using Black-76 (futures-style) and BSM (equity options) rather than relying on broker-native Greeks, which differ by model and reference rate.

🤖

ML Signal Classifier

LightGBM model trained on Nifty 50 price and options flow features. Outputs directional signal probabilities used to filter or weight strategy entries.

📄

Strategy Backtesting

Backtest against Kite Connect historical data or licensed TrueData/GFDL feeds. No static seed data. All backtest results reflect real market conditions.

🆕

Paper Trading

Paper trading mode uses live feed pricing with unmissable UI labeling. No simulated prices. Strategies are validated against the same tick stream as live execution.

🔒

RBAC + Multi-Tenant Auth

Role-based access control with per-user broker credential isolation. Each user's tokens and positions are scoped independently. JWT HttpOnly cookies with refresh token rotation.

📊

Risk Controls

Per-strategy daily loss limits, max open position caps, and automatic strategy pause triggers. Risk rules are enforced at the API layer, not just the UI.

📄

Broker Token Automation

Daily access token refresh automation for brokers that require it. Tokens are rotated before market open without manual intervention using scheduled Celery tasks.

📱

Android App (Planned)

React Native mobile client sharing the same FastAPI backend. Planned for position monitoring, alerts, and strategy toggle on the go without full desktop access.

05 — Stack

Technology Choices

Every choice maps to a specific platform constraint. Low latency, real-time data, and multi-broker normalization drove every decision.

Layer Technology Why This Choice
Frontend Next.js 16 (App Router) Server components for data-heavy dashboard pages. Shared TypeScript types with the FastAPI schemas via code generation reduce type drift between layers.
Backend FastAPI (Python) Python is the primary language for quantitative finance and ML. FastAPI's async support handles concurrent broker WebSocket connections without blocking the main thread.
Streaming Redis Streams Persistent consumer groups allow multiple analytics workers to consume the same tick stream independently. Delivery latency stays under 200ms. Redis also serves as the session and cache layer.
ML LightGBM Gradient-boosted trees outperform deep learning on tabular market data with limited training samples. LightGBM's inference speed is compatible with tick-by-tick signal evaluation.
Primary DB PostgreSQL Transactional integrity for order records, user accounts, and position state. ACID guarantees are non-negotiable when real capital is involved.
Tick Cache MongoDB (TTL) Time-series tick data is expensive to query repeatedly from broker APIs. MongoDB's TTL indexes expire cached ticks automatically, keeping the cache lean without manual cleanup jobs.
Task Queue Celery + Beat Replaces APScheduler for more reliable distributed task execution. Beat handles daily token rotation, strategy health checks, and scheduled backtests.
Auth fastapi-users 13.x + Auth.js v5 fastapi-users handles backend user management and JWT rotation. Auth.js v5 on the Next.js side adds Google and GitHub OAuth without duplicating session logic.
Infra Docker + IONOS VPS + Plesk Four-container stack (backend, frontend, MongoDB, Redis) managed via Docker Compose. GHCR stores images. Plesk handles Apache reverse proxy and SSL on the same VPS.
06 — Hard Problems

What Was Actually Difficult

Four non-trivial engineering problems that shaped the platform's architecture.

✁ PostgreSQL-to-MongoDB User Identity Bridge

Auth lives in PostgreSQL (via fastapi-users). Tick cache and time-series data live in MongoDB. When a user action needs to join data across both stores, there is no foreign key. The fix was a canonical user UUID propagated to both systems on registration, with a lightweight cross-store lookup service that resolves identity without a full join. CORS, WebSocket, and CSP issues on the Plesk/nginx stack were resolved in the same audit pass.

✓ Canonical UUID bridge + unified audit

🌎 Zerodha 9,000-Token WebSocket Cap

Kite Connect's WebSocket silently drops instrument subscriptions above 9,000 tokens per connection. During market open, a full Nifty options chain easily exceeds this. The subscription manager maintains a live token counter and routes overflow instruments to a REST polling queue with a configurable refresh interval. The WebSocket receives priority instruments; REST fills the gap. No instruments are silently dropped.

✓ Token counter + REST polling fallback

🚫 No-Mock-Data Constraint Across All Environments

Standard development practice seeds a local database with fake prices and fake trades. For a trading platform, that produces strategies that work against invented data and fail in production. The constraint: all financial data must come from live broker connections or licensed feeds (Kite Connect, TrueData, GFDL). MongoDB serves as a TTL cache, never an authoritative seed. Paper trading retains simulated execution but uses live feed pricing with an unmissable UI label. This constraint was enforced at the architecture level, not by convention.

✓ Live-only data policy enforced architecturally

📚 pydantic-settings CORS_ORIGINS Format Bug

pydantic-settings 2.2.1 parses comma-separated environment variables as a string, not a list. CORS_ORIGINS set to comma-separated values crashed the FastAPI startup. The fix is JSON array format in the .env file. The bug was identified during a production stabilization pass that also resolved a Next.js healthcheck binding mismatch (HOSTNAME=0.0.0.0 vs localhost), a MongoDB Atlas switchover, and a Redis module install regression — all in the same deployment window.

✓ JSON array format + multi-issue stabilization
07 — Design Decisions

Five Calls That Shaped the Architecture

The choices that determined reliability, data integrity, and long-term extensibility.

01

Canonical Greeks over broker-native Greeks

Broker-native Greeks differ by model (some use BSM, some use a simplified approximation) and by the risk-free rate reference. Comparing positions across brokers using their native Greeks produces meaningless risk aggregates. The platform computes all Greeks internally using Black-76 for futures-style options and BSM for equity options, with a consistent risk-free rate. Broker data is used only for market prices and OI, never for derived risk metrics.

02

MongoDB as a TTL cache, not a database

Time-series tick data is high-volume and short-lived. Storing it persistently in PostgreSQL would inflate the primary database with data that has a natural expiry. MongoDB's TTL indexes expire ticks automatically at a configurable interval. The cache reduces broker API calls on repeated queries while keeping storage lean. MongoDB is explicitly excluded from being treated as an authoritative data source for any financial calculation.

03

Redis Streams over WebSocket fan-out from the backend

Pushing ticks directly from broker WebSockets to connected browser clients creates tight coupling: every new broker connection needs its own fan-out logic, and a broker disconnect propagates immediately to the UI. Redis Streams decouple ingestion from delivery. The adapter writes to the stream; analytics workers and the Next.js data layer consume independently. A broker hiccup does not cascade to the trader's screen.

04

LightGBM over deep learning for signal classification

Neural networks require large labeled datasets to generalize. Indian equity options data with reliable labels (actual outcomes, not just price moves) is limited in depth. LightGBM performs well on tabular features with moderate training data, provides feature importance that is interpretable for strategy debugging, and runs fast enough for tick-by-tick evaluation. Deep learning was evaluated and ruled out at this stage.

05

Celery + Beat over APScheduler

APScheduler runs in-process and loses scheduled tasks on restart. For a trading platform, missed daily token rotation means broker connections fail at market open. Celery + Beat runs as a separate process, persists task state to Redis, and survives application restarts. Any task critical to market participation runs through Celery, not in-process schedulers.

08 — Current State

What Has Been Built

A production-deployed platform actively in development, with the core data pipeline and analytics layer operational.

Live Deployment Status Running at finance.dhimansoft.com; all four containers healthy
5 Brokers Integrated Zerodha, Upstox, Angel One, Nuvama, Dhan via unified adapter
<200ms Tick-to-UI SLA Redis Streams consumer groups delivering within latency target
0 Mock Data in Prod All market data from live broker APIs or licensed feed vendors
09 — Live Site

See It in Production

The platform is live at finance.dhimansoft.com and actively being developed.

finance.dhimansoft.com
🔒
Source Protected
Active development — preview restricted
Visit Live Site →

Building something in
FinTech or trading?

I build full-stack systems at the intersection of real-time data, financial APIs, and ML. If you need a technical partner who understands broker infrastructure and market data pipelines, get in touch.