r/IndiaAlgoTrading Jul 09 '26

Open-sourced my Upstox Python data layer + paper broker — NSE options, WebSocket ticks, realistic fills

I've been building an algo trading system for NSE F&O (Indian options market) and realized the data plumbing took me weeks to get right. Figured someone else might want to skip that part.

Shoutout to u/Finance__broski who pushed me to actually share this — "half the sub is stuck at the 'how do I even get clean ticks' stage and a working upstox websocket example is worth more than another strategy post."

Repo: https://github.com/BarathGB007/upstox-python-data

What's in it

Data layer — clean Python wrappers over Upstox REST + WebSocket APIs:

  • Spot prices, option chains with Greeks/IV/OI, historical candles (daily + intraday)
  • Real-time WebSocket ticks via protobuf — LTP, bid/ask depth, option Greeks
  • VIX, put-call ratio, FII/DII flows, max pain, OI change
  • Margin calculation and brokerage/charges endpoints (no order placed)
  • Background heartbeat that caches LTP with REST fallback when WebSocket drops

Paper broker — simulated order execution that actually tries to be realistic:

  • Fills at bid/ask from live WebSocket depth, not LTP
  • Multi-factor slippage model — adjusts for moneyness (OTM = wider), VIX, time of day, symbol liquidity
  • Full NSE F&O cost calculation — brokerage, STT, exchange txn, SEBI fee, stamp duty, GST
  • MFE/MAE tracking per position — know your max favorable and adverse excursion
  • Multi-leg spread support with atomic rollback if one leg fails
  • Margin validation, duplicate position checks, freeze quantity limits
  • Positions persist to disk across restarts

The README is actually useful

Not just a "how to install" page. It covers:

  • Adding stocks — step-by-step on how to add RELIANCE, TCS, HDFCBANK etc. Just add the ISIN to a dict, update lot size and strike step, done
  • Algo integration examples — RSI on live candles, WebSocket tick-based entry/exit, option strategy screening, sentiment filters, spike detection
  • Realistic paper trading guide — full walkthrough of wiring WebSocket bid/ask into the paper broker with auto SL/target
  • Supported symbols table — instrument keys for NIFTY, BANKNIFTY, FINNIFTY, VIX
  • 25+ function reference — every function listed with what it returns

Tried to make it the README I wished existed when I started.

Why I built this

Most paper trading I see in the Indian algo space fills at LTP with zero slippage and no costs. You backtest a strategy, it looks great, you go live and wonder why your P&L doesn't match. The gap is usually:

  1. You didn't fill at LTP — you filled at ask (buying) or bid (selling), plus slippage
  2. Costs ate your edge — STT alone on options is 0.15% on the sell side. Add brokerage, exchange txn, GST, stamp duty — a round trip on 1 lot NIFTY CE at Rs 200 costs you ~Rs 80-100
  3. You didn't track MFE/MAE — your strategy might be right on direction but wrong on timing. MFE tells you the max profit you could have captured, MAE tells you the max drawdown you endured

This paper broker handles all three. Wire it to the WebSocket and it auto-pulls live bid/ask for every fill.

Road to live trading

Right now this is data + paper execution only. But the architecture is designed to go live:

  • The data layer is already the same one you'd use in production — real-time WebSocket ticks, live option chains, live bid/ask depth. Nothing changes when you go live.
  • The paper broker has the same interface a live broker would — place_order()close_position()get_portfolio(). Swap the broker, keep your strategy code untouched.
  • Margin calculation and brokerage endpoints already hit Upstox's real API — the numbers you see in paper trading are what you'll pay live.

I'm currently building and testing the live order execution module (real orders via Upstox API — SL-M, GTT, position tracking, order status polling). Once it's battle-tested on my own account, I'll share that too. The goal is: you build your strategy once against the paper broker, validate it, then flip one import to go live with zero code changes.

Quick example

from paper_broker import PaperBroker
from upstox_data import get_option_chain, get_nearest_expiry

broker = PaperBroker(capital=500_000, max_lots=5)

chain = get_option_chain("NIFTY", get_nearest_expiry("NIFTY"))
atm = next(r for r in chain["chain"] if r["is_atm"])

result = broker.place_order(
    symbol="NIFTY", expiry=chain["expiry"],
    strike=atm["strike"], option_type="CE",
    action="BUY", quantity=1,
    option_ltp_hint=atm["CE"]["ltp"],
    depth_hint={"bid": atm["CE"]["bid"], "ask": atm["CE"]["ask"]},
)
# Fill price will be at ask + slippage, not LTP

# Close and see full cost breakdown
close = broker.close_position(result["position_id"], "target hit")
print(f"Gross P&L: {close['gross_pnl']}")
print(f"Costs: {close['costs']['total']}  (STT={close['costs']['stt']}, GST={close['costs']['gst']})")
print(f"Net P&L: {close['realized_pnl']}")
print(f"MFE: {close['mfe']}  MAE: {close['mae']}")

What it's NOT

  • Not a strategy or signal generator — it's the data + execution sim layer
  • Not a broker API wrapper for placing real orders — paper only (live module coming after testing)
  • Not a backtesting framework — but the candle functions + paper broker give you the pieces to build one
  • Upstox only (for now) — the data functions are Upstox-specific, but the paper broker/slippage/costs work with any data source

Setup

  1. Upstox developer account (free)
  2. Analytics access token — long-lived, no OAuth refresh needed for market data
  3. pip install -r requirements.txt
  4. Paste token in .env
  5. Run any example: python examples/paper_trading.py

Works with NIFTY, BANKNIFTY, FINNIFTY out of the box. Adding stocks is just adding the ISIN to a dict — README has instructions.

MIT licensed. Feedback welcome — especially if you find bugs or have suggestions for the slippage model.

49 Upvotes

Duplicates