Skip to main content

PaperTrade-India

A production-grade simulated broker for NSE & BSE paper trading.

Realistic Indian-market order execution — fees, T+1 settlement, tick/lot/band rules, and live prices — behind a clean, Alpaca-style Python API.

Python License Status Tests

Quickstart · Examples · Changelog · Report a bug


Overview

No Indian broker offers a programmatic paper-trading API. PaperTrade-India fills that gap: a simulated NSE/BSE broker that models the parts of real trading that actually move your P&L — statutory fees, T+1 settlement, price bands, slippage, and market impact — while exposing the same method surface as an Alpaca-style trading client, so you can build and test strategies without touching real capital or rewriting your code.

from papertrade_india import IndiaPaperBroker

broker = IndiaPaperBroker(initial_capital=1_000_000)
order = broker.buy("RELIANCE", 10)
print(order.filled_avg_price, order.fees_paid)

Status: alpha (pre-1.0). The public API is stable enough to build on, but minor releases may introduce breaking changes until 1.0.

Why

Platform Paper trading API access
Zerodha Kite ❌ ❌
Upstox ⚠️ mock only ⚠️ mock only
Angel One SmartAPI ❌ ❌
Dhan / Fyers / Shoonya ❌ ❌
papertrade-india ✅ ✅

Features

Execution realism — all on by default, so a fresh broker behaves like a real retail account:

  • Indian fee model — brokerage, STT, exchange charges, GST, SEBI charges, stamp duty, and DP charges, configurable per broker and date-versioned for mid-year statutory changes.
  • T+1 settlement on the exchange's trading calendar, with deliverable-quantity enforcement and settled / unsettled cash on the account, plus same-day intraday round-trips via ProductType.INTRADAY and 15:15 auto-square-off.
  • Tick / lot / price-band rules — official lot and tick sizes for NSE and BSE (papertrade-india sync-symbols), and both order prices and execution prices are held inside the daily band.
  • Order types — market, limit, STOP_MARKET, STOP_LIMIT, and BRACKET with full OCO semantics.
  • Synthetic L2 order book — uses real provider depth when available, with Almgren-style market impact. A resting limit order waits for the shares queued ahead of it at its price.
  • Slippage, latency, and random-rejection simulation for stress-testing strategy robustness.
  • Mark-to-bid valuation for realistic unrealized P&L.

Data — a pluggable MarketDataProvider layer:

  • Built-in providers: yfinance, jugaad-data, stooq, nse-bhavcopy (official EOD), nsepython, alphavantage, twelvedata, finnhub, plus live broker feeds upstox, dhan and kite (real bid/ask + market depth).
  • Per-provider circuit breakers, median aggregation across sources, a first-wins resilient_feed() helper, and a name registry.
  • NSE/BSE holiday calendar — bundled exchange-published lists, with an optional live source. The calendar warns once when asked about a year it has no complete list for.

Engineering & safety

  • Thread-safe SQLite persistence (WAL, atomic transactions, versioned migrations).
  • Session-phase awareness (PRE_OPEN / REGULAR / POST_CLOSE / CLOSED).
  • Risk controls: kill switch, symbol whitelist, per-order and per-position notional caps.
  • Idempotency keys, an immutable cash ledger with an invariant check, broker fee presets (Zerodha, Upstox, Groww, Angel One, ICICIdirect), a symbol master with delisting, corporate actions (splits, bonuses, rights and dividends), and a persisted event log with an in-process observability bus.
  • Multi-account support, an optional CLI, a local Streamlit app, and an MCP server example so LLM agents can trade through tool calls.

What's new in 0.2.0

0.2.0 closes the places where the simulator did less than its feature list said. Back up your SQLite database before upgrading: it moves to schema version 6 the first time 0.2.0 opens it, and older versions cannot open it after that.

  • Limit orders wait for the queue. A resting limit fills at once when the market trades through its price. When the market trades exactly at its price, it fills after the shares estimated ahead of it have traded.
  • Official lot and tick sizes. papertrade-india sync-symbols --exchange NSE (or BSE) loads names, ISINs, market lots and tick sizes for every listed share. No credentials needed.
  • Holiday-aware settlement. Delivery trades settle on the next trading day of the exchange calendar, and the account reports unsettled_cash and settled_cash.
  • Keys from .env with no code. Importing the package reads its own keys from a .env file in the folder you run from.
  • Recover lost trade history. papertrade-india rebuild-trades rebuilds one trade per order for databases damaged by an upgrade before 0.1.1.
  • Corrected holiday data. The 2026 NSE list is regenerated from the exchange's published calendar, and the 2026 BSE list is bundled.
  • The Streamlit app and the MCP server example now complete limit orders: both run the background order watcher.
  • Backtests on a replay clock get fresh quotes as simulated time moves.

Some behaviour changed on purpose. The ones most likely to affect an existing strategy:

  • A limit order at exactly its price may wait where it used to fill at once. OrderBookConfig(queue_gates_limit_fills=False) restores the old behaviour.
  • After sync-symbols, official tick sizes apply, so some limit prices are refused, and SME shares need whole lots.
  • A split or bonus cancels open orders on that symbol, including a bracket's exit legs. Place new ones after the action.
  • CircuitBreakerProvider raises on a failed call instead of returning nothing. PriceFeed already handles this; code that calls a breaker directly must catch ProviderError.

The full list is in the changelog.

Installation & Upgrade

pip install papertrade-india               # core
pip install 'papertrade-india[jugaad]'     # + NSE-direct fallback data
pip install 'papertrade-india[cli]'        # + Typer/Rich CLI
pip install 'papertrade-india[ui]'         # + Streamlit, for the local app
pip install 'papertrade-india[mcp]'        # + FastMCP, for the MCP server example
pip install 'papertrade-india[dev]'        # + tests and linting

Requires Python 3.10+.

To upgrade an existing install:

pip install --upgrade papertrade-india
python -c "import papertrade_india; print(papertrade_india.__version__)"

Back up your SQLite database before you upgrade. The broker migrates the file the first time it opens it with a new version, and a migration cannot be undone:

cp data/india_paper.db data/india_paper.db.backup

data/india_paper.db is the default path; use the db_path you passed to IndiaPaperBroker if it differs. If the database is in use, stop the process first so the copy is complete. Then read the changelog for behaviour changes before running a strategy on the new version.

If the broker warns that filled orders have no trade history, the database was damaged by an upgrade before 0.1.1. Rebuild one trade per order with:

papertrade-india rebuild-trades --db data/india_paper.db

Running the Streamlit app and the MCP server

The app and the MCP server are scripts in the source tree, not part of the installed package. Run them from a clone of this repository:

pip install -e '.[ui]'
streamlit run app.py

pip install -e '.[mcp]'
python examples/05_mcp_server.py

Both start the order watcher, so limit orders fill, expire and square off. Set PAPERTRADE_INDIA_WATCHER_INTERVAL (seconds, default 5) to change how often it runs.

Quickstart

from papertrade_india import IndiaPaperBroker

broker = IndiaPaperBroker(initial_capital=1_000_000)

# Market buy (inside NSE trading hours)
order = broker.buy("RELIANCE", 10)
print(order.filled_avg_price, order.fees_paid)

# Inspect state
for position in broker.get_positions():
    print(position.symbol, position.qty, position.unrealized_pl)

account = broker.get_account()
print(f"Equity: ₹{account.equity:,.2f}  Cash: ₹{account.cash:,.2f}")

# Realize P&L. Under the default T+1 settlement, delivery shares can be
# sold from the next trading day.
broker.sell("RELIANCE", 10)

For a same-day round trip, trade the intraday product:

from papertrade_india import ProductType

broker.buy("RELIANCE", 10, product_type=ProductType.INTRADAY)
broker.sell("RELIANCE", 10, product_type=ProductType.INTRADAY)

To use official lot and tick sizes, load them once into your database:

papertrade-india sync-symbols --db data/india_paper.db --exchange NSE
papertrade-india sync-symbols --db data/india_paper.db --exchange BSE

The full getting-started walkthrough and a worked example for every feature — limit orders, multiple accounts, risk controls, live data feeds, realism configuration, and more — live in QUICKSTART.md. Runnable scripts are in examples/.

Configuration

Most providers and live broker feeds need an API key or token. Everything is optional — with no keys set, the broker uses the free yfinance → jugaad-data fallback chain and works out of the box. There are three ways to supply credentials:

1. Pass them directly to the provider (most explicit — no env needed):

from papertrade_india import IndiaPaperBroker, resilient_feed
from papertrade_india.providers import UpstoxProvider, UpstoxInstrumentMaster

feed = resilient_feed([
    UpstoxProvider(access_token="your-token", resolve=UpstoxInstrumentMaster().resolve),
])
broker = IndiaPaperBroker(price_feed=feed)

Every provider accepts its key this way: FinnhubProvider(api_key=...), DhanProvider(client_id=..., access_token=...), KiteProvider(api_key=..., access_token=...), and so on.

2. Set an environment variable — every provider falls back to it:

export UPSTOX_ACCESS_TOKEN="your-token"
python your_script.py

The variable names are listed in .env.example (e.g. UPSTOX_ACCESS_TOKEN, FINNHUB_API_KEY, ALPHA_VANTAGE_API_KEY, DHAN_CLIENT_ID / DHAN_ACCESS_TOKEN).

3. Use a .env file — copy .env.example to .env in the folder you run from and fill in your keys. That's all: the library reads it when it is imported, so there is no code to add.

cp .env.example .env      # then edit .env
python your_script.py

Only the variables listed in .env.example are read; anything else in the file is ignored. A variable already set in your shell wins over the file. Set PAPERTRADE_INDIA_NO_DOTENV=1 to turn this off.

Fee model

Defaults match a typical discount-broker delivery account:

Component Default rate Applies to
Brokerage ₹0 Both sides (delivery)
STT 0.1% Both sides
Exchange charge 0.00322% (NSE) / 0.00375% (BSE) Both sides
GST 18% on (brokerage + exchange) Both sides
SEBI charges ₹10 per crore Both sides
Stamp duty 0.015% Buy only
DP charge ₹13.5 Delivery sells, once per order

Flat components (the DP charge, a flat brokerage and the brokerage cap) are charged once per order, however many partial fills it has. Intraday sells pay no DP charge. Override any field via FeeConfig, or use a named preset, to model intraday or full-service brokers. Formulas are in docs/FEES.md.

Scope & limitations

The simulator is intentionally focused on cash equity, delivery, long-only trading. It is a faithful behavioral simulator, not an exchange replica:

Limitation Notes
Synthetic order book, not a real matching engine Uses real provider depth when available; accurate for retail order sizes. The queue ahead of a limit order is an estimate from the displayed book, kept in memory.
Snapshot prices, not a tick stream Fills price off the latest snapshot — negligible at daily/swing cadence.
Corporate actions applied manually Via apply_split, apply_bonus, apply_rights and apply_dividend. A split or bonus cancels open orders on the symbol.
Market orders fill in full or not at all A market order that real provider depth cannot supply is declined; there are no partial market fills.
Holidays for published years only 2026 is bundled for NSE and BSE. For later years, use the live holiday provider or pass holidays=; the calendar warns until it has a complete list.
Settled cash is reported, not enforced There is no withdrawal operation.
Replay on a live feed uses today's prices For a backtest without look-ahead, use a historical or stub provider with PriceFeed(reject_future_quotes=True).
No margin, leverage, or short selling Cash, long-only by design.
No options or F&O Equity only.

Release history and behaviour changes are in the changelog.

Contributing

Issues and pull requests are welcome. Install the dev extras and run the test suite before submitting:

pip install -e '.[dev]'
pytest
ruff check src tests examples

License

MIT — use it however you want.

Disclaimer

This is a simulated broker; it does not place real trades. It is not investment advice. Always verify calculations against your actual broker's contract notes before relying on the simulator's outputs for tax, compliance, or investment decisions.

Metadata

Release files for PaperTrade-India 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for PaperTrade-India 0.2.0
File Size Uploaded Provenance Actions
papertrade_india-0.2.0.tar.gz 408.9 kB With provenance Details for papertrade_india-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for PaperTrade-India 0.2.0
File Interpreter ABI Platform Actions
papertrade_india-0.2.0-py3-none-any.whl Python 3 none any Details for papertrade_india-0.2.0-py3-none-any.whl

Total release size: 691.6 kB

Release files / papertrade_india-0.2.0.tar.gz

Download URL papertrade_india-0.2.0.tar.gz
Size 408.9 kB
Tags Source
SHA-256 checksum
How to use checksums
97555b04e256f3f2ce7e1eed17f6841c18d7768ed4f94e231fa518d6fa840810
BLAKE2b-256 checksum
How to use checksums
996d25ccd98ffc591e27f9e9ae9df0c8f28aa92d690425143ea70113feb1ca31
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / papertrade_india-0.2.0-py3-none-any.whl

Download URL papertrade_india-0.2.0-py3-none-any.whl
Size 282.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f07291a78273199a1807e9f2aa114ac9288fe3332059fd09ccce2ad5a9e6ed70
BLAKE2b-256 checksum
How to use checksums
5aac81c7776931368402eebc27e85d995a43281fe8d231d3a21d2fd9a082d308
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for PaperTrade-India 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for papertrade_india-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page