PaperTrade-India 0.1.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- papertrade_india/__init__.py +250 -0
- papertrade_india/_context.py +144 -0
- papertrade_india/broker.py +546 -0
- papertrade_india/cli.py +474 -0
- papertrade_india/clock.py +29 -0
- papertrade_india/corporate_actions/__init__.py +10 -0
- papertrade_india/corporate_actions/bonus.py +105 -0
- papertrade_india/corporate_actions/dividends.py +99 -0
- papertrade_india/corporate_actions/rights.py +189 -0
- papertrade_india/corporate_actions/splits.py +111 -0
- papertrade_india/corporate_actions/store.py +247 -0
- papertrade_india/data/nse_holidays_2026.json +22 -0
- papertrade_india/data/nse_holidays_2027.json +9 -0
- papertrade_india/data/nse_universe_sample.csv +31 -0
- papertrade_india/domain/__init__.py +6 -0
- papertrade_india/domain/exceptions.py +183 -0
- papertrade_india/domain/models.py +213 -0
- papertrade_india/domain/rules/__init__.py +5 -0
- papertrade_india/domain/rules/risk.py +165 -0
- papertrade_india/domain/rules/tick_lot_band.py +139 -0
- papertrade_india/events.py +29 -0
- papertrade_india/exceptions.py +29 -0
- papertrade_india/execution/__init__.py +5 -0
- papertrade_india/execution/book.py +385 -0
- papertrade_india/execution/fees.py +213 -0
- papertrade_india/execution/settlement.py +360 -0
- papertrade_india/execution/simulation.py +176 -0
- papertrade_india/execution/slippage.py +120 -0
- papertrade_india/fees.py +29 -0
- papertrade_india/idempotency.py +29 -0
- papertrade_india/infrastructure/__init__.py +6 -0
- papertrade_india/infrastructure/clock.py +123 -0
- papertrade_india/infrastructure/events.py +137 -0
- papertrade_india/infrastructure/holidays.py +138 -0
- papertrade_india/infrastructure/idempotency.py +133 -0
- papertrade_india/infrastructure/ledger.py +141 -0
- papertrade_india/infrastructure/market_hours.py +200 -0
- papertrade_india/infrastructure/migrations.py +622 -0
- papertrade_india/infrastructure/observability.py +195 -0
- papertrade_india/infrastructure/persistence.py +130 -0
- papertrade_india/infrastructure/symbols.py +279 -0
- papertrade_india/infrastructure/watchlist.py +78 -0
- papertrade_india/interface.py +92 -0
- papertrade_india/ledger.py +29 -0
- papertrade_india/limit_orders.py +29 -0
- papertrade_india/market_hours.py +29 -0
- papertrade_india/microstructure.py +57 -0
- papertrade_india/migrations.py +29 -0
- papertrade_india/models.py +29 -0
- papertrade_india/observability.py +29 -0
- papertrade_india/orders/__init__.py +5 -0
- papertrade_india/orders/amo.py +98 -0
- papertrade_india/orders/book_helpers.py +111 -0
- papertrade_india/orders/bracket.py +115 -0
- papertrade_india/orders/limit.py +210 -0
- papertrade_india/orders/market.py +264 -0
- papertrade_india/orders/partial_fills.py +92 -0
- papertrade_india/orders/preopen.py +274 -0
- papertrade_india/orders/state.py +640 -0
- papertrade_india/orders/stop.py +122 -0
- papertrade_india/orders/submit.py +385 -0
- papertrade_india/partial_fills.py +29 -0
- papertrade_india/persistence.py +29 -0
- papertrade_india/preopen.py +29 -0
- papertrade_india/presets.py +120 -0
- papertrade_india/price_feed.py +316 -0
- papertrade_india/providers/__init__.py +123 -0
- papertrade_india/providers/alphavantage.py +180 -0
- papertrade_india/providers/base.py +256 -0
- papertrade_india/providers/cache.py +147 -0
- papertrade_india/providers/composite.py +244 -0
- papertrade_india/providers/dhan.py +266 -0
- papertrade_india/providers/finnhub.py +122 -0
- papertrade_india/providers/health.py +233 -0
- papertrade_india/providers/jugaad.py +142 -0
- papertrade_india/providers/kite.py +222 -0
- papertrade_india/providers/nse_bhavcopy.py +210 -0
- papertrade_india/providers/nsepython.py +98 -0
- papertrade_india/providers/registry.py +226 -0
- papertrade_india/providers/stooq.py +173 -0
- papertrade_india/providers/twelvedata.py +198 -0
- papertrade_india/providers/upstox.py +318 -0
- papertrade_india/providers/upstox_instruments.py +171 -0
- papertrade_india/providers/yfinance.py +205 -0
- papertrade_india/quickstart.py +111 -0
- papertrade_india/reads/__init__.py +6 -0
- papertrade_india/reads/account.py +140 -0
- papertrade_india/reads/orders.py +54 -0
- papertrade_india/reads/positions.py +188 -0
- papertrade_india/risk.py +29 -0
- papertrade_india/settlement.py +29 -0
- papertrade_india/simulation.py +29 -0
- papertrade_india/slippage.py +29 -0
- papertrade_india/symbols.py +29 -0
- papertrade_india/workers/__init__.py +6 -0
- papertrade_india/workers/limit_orders.py +390 -0
- papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
- papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
- papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
- papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Limit-order watcher background loop.
|
|
2
|
+
|
|
3
|
+
Market orders fill instantly. Limit orders need a loop that periodically
|
|
4
|
+
checks if the market crossed the limit price.
|
|
5
|
+
|
|
6
|
+
Run only if the user wants limit-order support — it's opt-in to keep the
|
|
7
|
+
MVP simple. Start with::
|
|
8
|
+
|
|
9
|
+
watcher = LimitOrderWatcher(broker, interval_seconds=5)
|
|
10
|
+
watcher.start()
|
|
11
|
+
|
|
12
|
+
and stop with::
|
|
13
|
+
|
|
14
|
+
watcher.stop()
|
|
15
|
+
watcher.join()
|
|
16
|
+
|
|
17
|
+
The loop is a daemon thread by default, so it does not block process
|
|
18
|
+
shutdown if you forget to ``stop()`` it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
import threading
|
|
25
|
+
from typing import TYPE_CHECKING
|
|
26
|
+
|
|
27
|
+
from ..domain.exceptions import OrderNoLongerPending, StalePriceRejected
|
|
28
|
+
from ..domain.models import OrderSide, OrderStatus, OrderType
|
|
29
|
+
from ..infrastructure.market_hours import SessionPhase
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING: # avoid runtime circular import
|
|
32
|
+
from .broker import IndiaPaperBroker
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LimitOrderWatcher(threading.Thread):
|
|
38
|
+
"""Periodically fill pending limit orders that have crossed the market.
|
|
39
|
+
|
|
40
|
+
Each tick:
|
|
41
|
+
1. Skip if the market is closed.
|
|
42
|
+
2. Fetch all PENDING limit orders for the broker's account.
|
|
43
|
+
3. Get current price for each unique symbol.
|
|
44
|
+
4. Fill BUY limits when ``current_price <= limit_price``.
|
|
45
|
+
5. Fill SELL limits when ``current_price >= limit_price``.
|
|
46
|
+
|
|
47
|
+
Failures inside a tick are logged but never bubble — a flaky price
|
|
48
|
+
feed shouldn't kill the watcher.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
broker: IndiaPaperBroker,
|
|
54
|
+
interval_seconds: float = 5.0,
|
|
55
|
+
daemon: bool = True,
|
|
56
|
+
idempotency_cleanup_every: int | None = 100,
|
|
57
|
+
idempotency_ttl_hours: int = 24,
|
|
58
|
+
settle_due_every: int | None = None,
|
|
59
|
+
auto_square_off_intraday: bool = True,
|
|
60
|
+
run_pre_open_auction: bool = True,
|
|
61
|
+
fire_amo_at_open: bool = True,
|
|
62
|
+
expire_day_orders_at_close: bool = True,
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Construct a watcher.
|
|
65
|
+
|
|
66
|
+
Parameters
|
|
67
|
+
----------
|
|
68
|
+
broker:
|
|
69
|
+
The broker to drive.
|
|
70
|
+
interval_seconds:
|
|
71
|
+
Sleep between ticks.
|
|
72
|
+
daemon:
|
|
73
|
+
Whether the thread is a daemon (default True; doesn't block
|
|
74
|
+
process shutdown).
|
|
75
|
+
idempotency_cleanup_every:
|
|
76
|
+
When set, every Nth tick the watcher runs
|
|
77
|
+
``broker.cleanup_idempotency_keys(idempotency_ttl_hours)`` so
|
|
78
|
+
users get bounded-table-size for free without setting up
|
|
79
|
+
their own cron. ``None`` (default) skips it.
|
|
80
|
+
idempotency_ttl_hours:
|
|
81
|
+
TTL passed to the cleanup call when enabled.
|
|
82
|
+
settle_due_every:
|
|
83
|
+
When set, every Nth tick the watcher runs
|
|
84
|
+
``broker.settle_due()`` so T+1 rows roll over without an
|
|
85
|
+
external cron.
|
|
86
|
+
auto_square_off_intraday:
|
|
87
|
+
When True, after the configured square-off time the watcher
|
|
88
|
+
calls :meth:`IndiaPaperBroker.square_off_intraday` once per
|
|
89
|
+
session. Default False — the broker's settlement engine
|
|
90
|
+
still tracks the time-of-day; this flag opts in to the
|
|
91
|
+
automatic execution.
|
|
92
|
+
"""
|
|
93
|
+
super().__init__(daemon=daemon, name="LimitOrderWatcher")
|
|
94
|
+
self.broker = broker
|
|
95
|
+
self.interval = interval_seconds
|
|
96
|
+
self._stop_event = threading.Event()
|
|
97
|
+
self._idempotency_cleanup_every = idempotency_cleanup_every
|
|
98
|
+
self._idempotency_ttl_hours = idempotency_ttl_hours
|
|
99
|
+
self._settle_due_every = settle_due_every
|
|
100
|
+
self._auto_square_off_intraday = auto_square_off_intraday
|
|
101
|
+
self._run_pre_open_auction = run_pre_open_auction
|
|
102
|
+
self._fire_amo_at_open = fire_amo_at_open
|
|
103
|
+
self._expire_day_orders_at_close = expire_day_orders_at_close
|
|
104
|
+
self._squared_off_today = False
|
|
105
|
+
self._auction_done_today = False
|
|
106
|
+
self._amo_fired_today = False
|
|
107
|
+
self._day_expired_today = False
|
|
108
|
+
self._last_settle_date = None
|
|
109
|
+
self._tick_count = 0
|
|
110
|
+
|
|
111
|
+
def run(self) -> None: # pragma: no cover — exercised via integration
|
|
112
|
+
logger.info(
|
|
113
|
+
"LimitOrderWatcher started (interval=%ss)", self.interval,
|
|
114
|
+
)
|
|
115
|
+
while not self._stop_event.is_set():
|
|
116
|
+
try:
|
|
117
|
+
self.tick()
|
|
118
|
+
except Exception as e: # noqa: BLE001 — defensive
|
|
119
|
+
logger.exception("LimitOrderWatcher tick failed: %s", e)
|
|
120
|
+
self._stop_event.wait(self.interval)
|
|
121
|
+
|
|
122
|
+
def tick(self) -> int:
|
|
123
|
+
"""Run a single tick. Returns the number of fills.
|
|
124
|
+
|
|
125
|
+
Public so tests can drive the watcher deterministically without
|
|
126
|
+
starting a thread.
|
|
127
|
+
"""
|
|
128
|
+
self._tick_count += 1
|
|
129
|
+
# Periodic idempotency cleanup, opt-in.
|
|
130
|
+
if (
|
|
131
|
+
self._idempotency_cleanup_every is not None
|
|
132
|
+
and self._tick_count % self._idempotency_cleanup_every == 0
|
|
133
|
+
):
|
|
134
|
+
try:
|
|
135
|
+
n = self.broker.cleanup_idempotency_keys(
|
|
136
|
+
hours=self._idempotency_ttl_hours,
|
|
137
|
+
)
|
|
138
|
+
if n:
|
|
139
|
+
logger.info(
|
|
140
|
+
"Idempotency cleanup: pruned %d expired key(s)", n,
|
|
141
|
+
)
|
|
142
|
+
except Exception as e: # noqa: BLE001 — never let cleanup kill the loop
|
|
143
|
+
logger.exception("Idempotency cleanup failed: %s", e)
|
|
144
|
+
|
|
145
|
+
# Periodic T+1 roll, opt-in.
|
|
146
|
+
if (
|
|
147
|
+
self._settle_due_every is not None
|
|
148
|
+
and self._tick_count % self._settle_due_every == 0
|
|
149
|
+
):
|
|
150
|
+
self._maybe_settle_due()
|
|
151
|
+
|
|
152
|
+
# Daily roll: also settle once per day independent of N-tick cadence,
|
|
153
|
+
# so a watcher running at 5s interval doesn't miss a roll just because
|
|
154
|
+
# the user didn't set ``settle_due_every``.
|
|
155
|
+
today = self.broker.clock.now().date()
|
|
156
|
+
if self._last_settle_date != today:
|
|
157
|
+
self._maybe_settle_due()
|
|
158
|
+
self._last_settle_date = today
|
|
159
|
+
self._squared_off_today = False
|
|
160
|
+
self._auction_done_today = False
|
|
161
|
+
self._amo_fired_today = False
|
|
162
|
+
self._day_expired_today = False
|
|
163
|
+
|
|
164
|
+
# Pre-open auction at the PRE_OPEN → REGULAR transition.
|
|
165
|
+
# Run it at the first REGULAR-phase tick of the day.
|
|
166
|
+
# When ``enforce_market_hours`` is off the broker is being
|
|
167
|
+
# driven manually (typical in tests / backtests), so we leave
|
|
168
|
+
# phase-driven housekeeping to the test code rather than firing
|
|
169
|
+
# auction / AMO / expiry against arbitrary wall-clock state.
|
|
170
|
+
phase = self.broker.calendar.current_phase(self.broker.clock.now())
|
|
171
|
+
run_phase_hooks = self.broker.enforce_market_hours
|
|
172
|
+
if (
|
|
173
|
+
run_phase_hooks
|
|
174
|
+
and self._run_pre_open_auction
|
|
175
|
+
and not self._auction_done_today
|
|
176
|
+
and phase == SessionPhase.REGULAR
|
|
177
|
+
):
|
|
178
|
+
try:
|
|
179
|
+
match = self.broker.run_pre_open_auction()
|
|
180
|
+
if match.matched_volume > 0:
|
|
181
|
+
logger.info(
|
|
182
|
+
"Pre-open auction: %d shares matched at ₹%.2f",
|
|
183
|
+
int(match.matched_volume),
|
|
184
|
+
match.equilibrium_price or 0.0,
|
|
185
|
+
)
|
|
186
|
+
except Exception as e: # noqa: BLE001
|
|
187
|
+
logger.exception("Pre-open auction failed: %s", e)
|
|
188
|
+
self._auction_done_today = True
|
|
189
|
+
|
|
190
|
+
# Fire any pending AMO market orders at session open.
|
|
191
|
+
if (
|
|
192
|
+
run_phase_hooks
|
|
193
|
+
and self._fire_amo_at_open
|
|
194
|
+
and not self._amo_fired_today
|
|
195
|
+
and phase == SessionPhase.REGULAR
|
|
196
|
+
):
|
|
197
|
+
try:
|
|
198
|
+
self.broker.fire_amo_orders()
|
|
199
|
+
except Exception as e: # noqa: BLE001
|
|
200
|
+
logger.exception("AMO firing failed: %s", e)
|
|
201
|
+
self._amo_fired_today = True
|
|
202
|
+
|
|
203
|
+
# Expire DAY orders once we're past close.
|
|
204
|
+
if (
|
|
205
|
+
run_phase_hooks
|
|
206
|
+
and self._expire_day_orders_at_close
|
|
207
|
+
and not self._day_expired_today
|
|
208
|
+
and phase in (SessionPhase.POST_CLOSE, SessionPhase.CLOSED)
|
|
209
|
+
):
|
|
210
|
+
# Only expire if we're past 15:30 today; CLOSED on a holiday
|
|
211
|
+
# / weekend morning shouldn't expire orders submitted
|
|
212
|
+
# against the previous trading day's session — those should
|
|
213
|
+
# still queue for the next REGULAR open. The simplest
|
|
214
|
+
# heuristic: only expire when CLOSED/POST_CLOSE on what was
|
|
215
|
+
# actually a trading day.
|
|
216
|
+
if self.broker.calendar.is_trading_day(today):
|
|
217
|
+
try:
|
|
218
|
+
self.broker.expire_stale_day_orders()
|
|
219
|
+
except Exception as e: # noqa: BLE001
|
|
220
|
+
logger.exception("DAY-order expiry failed: %s", e)
|
|
221
|
+
self._day_expired_today = True
|
|
222
|
+
|
|
223
|
+
# Intraday auto-square-off, opt-in.
|
|
224
|
+
if (
|
|
225
|
+
self._auto_square_off_intraday
|
|
226
|
+
and not self._squared_off_today
|
|
227
|
+
and self.broker.settlement.is_square_off_time(
|
|
228
|
+
self.broker.clock.now(),
|
|
229
|
+
)
|
|
230
|
+
):
|
|
231
|
+
try:
|
|
232
|
+
n = self.broker.square_off_intraday()
|
|
233
|
+
self._squared_off_today = True
|
|
234
|
+
if n:
|
|
235
|
+
logger.info(
|
|
236
|
+
"Auto-squared off %d intraday position(s)", n,
|
|
237
|
+
)
|
|
238
|
+
except Exception as e: # noqa: BLE001
|
|
239
|
+
logger.exception("Auto square-off failed: %s", e)
|
|
240
|
+
|
|
241
|
+
if self.broker.enforce_market_hours and not self.broker.calendar.is_market_open(
|
|
242
|
+
self.broker.clock.now()
|
|
243
|
+
):
|
|
244
|
+
return 0
|
|
245
|
+
|
|
246
|
+
# Pull every order type the watcher cares about.
|
|
247
|
+
all_pending = self.broker.get_orders(status=OrderStatus.PENDING, limit=1000)
|
|
248
|
+
partials = self.broker.get_orders(
|
|
249
|
+
status=OrderStatus.PARTIALLY_FILLED, limit=1000,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
limits: list = []
|
|
253
|
+
stops: list = []
|
|
254
|
+
bracket_children_pending: list = []
|
|
255
|
+
for o in all_pending + partials:
|
|
256
|
+
if o.order_type == OrderType.LIMIT:
|
|
257
|
+
# Bracket children stay quiet until parent fills.
|
|
258
|
+
if o.parent_order_id is not None:
|
|
259
|
+
parent = self.broker.get_order(o.parent_order_id)
|
|
260
|
+
if parent is None or parent.status != OrderStatus.FILLED:
|
|
261
|
+
bracket_children_pending.append(o)
|
|
262
|
+
continue
|
|
263
|
+
limits.append(o)
|
|
264
|
+
elif o.order_type in (OrderType.STOP_MARKET, OrderType.STOP_LIMIT):
|
|
265
|
+
# Same gating for stop children.
|
|
266
|
+
if o.parent_order_id is not None:
|
|
267
|
+
parent = self.broker.get_order(o.parent_order_id)
|
|
268
|
+
if parent is None or parent.status != OrderStatus.FILLED:
|
|
269
|
+
bracket_children_pending.append(o)
|
|
270
|
+
continue
|
|
271
|
+
stops.append(o)
|
|
272
|
+
|
|
273
|
+
if not limits and not stops:
|
|
274
|
+
return 0
|
|
275
|
+
|
|
276
|
+
# One price fetch per symbol per tick.
|
|
277
|
+
symbols = {o.symbol for o in (limits + stops)}
|
|
278
|
+
prices: dict[str, float | None] = {}
|
|
279
|
+
stale_symbols: set[str] = set()
|
|
280
|
+
for s in symbols:
|
|
281
|
+
try:
|
|
282
|
+
quote = self.broker.price_feed.get_quote(s)
|
|
283
|
+
prices[s] = quote.price
|
|
284
|
+
if quote.is_stale:
|
|
285
|
+
stale_symbols.add(s)
|
|
286
|
+
except Exception as e: # noqa: BLE001
|
|
287
|
+
logger.warning("Price unavailable for %s: %s", s, e)
|
|
288
|
+
prices[s] = None
|
|
289
|
+
|
|
290
|
+
fills = 0
|
|
291
|
+
|
|
292
|
+
# ── Stop triggers first: a stop firing this tick could cancel a
|
|
293
|
+
# bracket sibling and shorten the limits list we'd otherwise hit.
|
|
294
|
+
for stop in stops:
|
|
295
|
+
price = prices.get(stop.symbol)
|
|
296
|
+
if price is None or stop.stop_price is None:
|
|
297
|
+
continue
|
|
298
|
+
if (
|
|
299
|
+
self.broker.enforce_fresh_prices
|
|
300
|
+
and stop.symbol in stale_symbols
|
|
301
|
+
):
|
|
302
|
+
continue
|
|
303
|
+
triggered = (
|
|
304
|
+
(stop.side == OrderSide.BUY and price >= stop.stop_price)
|
|
305
|
+
or (stop.side == OrderSide.SELL and price <= stop.stop_price)
|
|
306
|
+
)
|
|
307
|
+
if triggered:
|
|
308
|
+
try:
|
|
309
|
+
self.broker._trigger_stop_order(stop, price)
|
|
310
|
+
fills += 1
|
|
311
|
+
except OrderNoLongerPending:
|
|
312
|
+
logger.debug(
|
|
313
|
+
"Stop %s cleared between selection and trigger",
|
|
314
|
+
stop.id,
|
|
315
|
+
)
|
|
316
|
+
except StalePriceRejected:
|
|
317
|
+
logger.debug("Stop %s skipped: stale price", stop.id)
|
|
318
|
+
except Exception as e: # noqa: BLE001
|
|
319
|
+
logger.exception(
|
|
320
|
+
"Failed to trigger stop %s: %s", stop.id, e,
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
# ── Limit fills (existing behavior, with bracket-aware gating).
|
|
324
|
+
# Re-pull pending limits because stop triggers may have produced
|
|
325
|
+
# new ones (STOP_LIMIT becomes a LIMIT) or cancelled some
|
|
326
|
+
# (bracket OCO).
|
|
327
|
+
if stops:
|
|
328
|
+
limits = [
|
|
329
|
+
o for o in self.broker.get_orders(
|
|
330
|
+
status=OrderStatus.PENDING, limit=1000,
|
|
331
|
+
) + self.broker.get_orders(
|
|
332
|
+
status=OrderStatus.PARTIALLY_FILLED, limit=1000,
|
|
333
|
+
)
|
|
334
|
+
if o.order_type == OrderType.LIMIT
|
|
335
|
+
and (
|
|
336
|
+
o.parent_order_id is None
|
|
337
|
+
or (
|
|
338
|
+
(parent := self.broker.get_order(o.parent_order_id))
|
|
339
|
+
is not None and parent.status == OrderStatus.FILLED
|
|
340
|
+
)
|
|
341
|
+
)
|
|
342
|
+
]
|
|
343
|
+
|
|
344
|
+
for order in limits:
|
|
345
|
+
price = prices.get(order.symbol)
|
|
346
|
+
if price is None or order.limit_price is None:
|
|
347
|
+
continue
|
|
348
|
+
if (
|
|
349
|
+
self.broker.enforce_fresh_prices
|
|
350
|
+
and order.symbol in stale_symbols
|
|
351
|
+
):
|
|
352
|
+
continue
|
|
353
|
+
should_fill = (
|
|
354
|
+
(order.side == OrderSide.BUY and price <= order.limit_price)
|
|
355
|
+
or (order.side == OrderSide.SELL and price >= order.limit_price)
|
|
356
|
+
)
|
|
357
|
+
if should_fill:
|
|
358
|
+
remaining = order.qty - order.filled_qty
|
|
359
|
+
slice_qty = self.broker.partial_fill_config.fill_qty(remaining)
|
|
360
|
+
if slice_qty <= 0:
|
|
361
|
+
continue
|
|
362
|
+
try:
|
|
363
|
+
self.broker._execute_limit_fill(
|
|
364
|
+
order, price, fill_qty=slice_qty,
|
|
365
|
+
)
|
|
366
|
+
fills += 1
|
|
367
|
+
except OrderNoLongerPending:
|
|
368
|
+
logger.debug(
|
|
369
|
+
"Order %s cleared between selection and fill",
|
|
370
|
+
order.id,
|
|
371
|
+
)
|
|
372
|
+
except StalePriceRejected:
|
|
373
|
+
logger.debug("Order %s skipped: stale price", order.id)
|
|
374
|
+
except Exception as e: # noqa: BLE001
|
|
375
|
+
logger.exception(
|
|
376
|
+
"Failed to fill limit order %s: %s", order.id, e,
|
|
377
|
+
)
|
|
378
|
+
return fills
|
|
379
|
+
|
|
380
|
+
def _maybe_settle_due(self) -> None:
|
|
381
|
+
"""Roll T+1 settlements for the broker. Defensive — never raises."""
|
|
382
|
+
try:
|
|
383
|
+
n = self.broker.settle_due()
|
|
384
|
+
if n:
|
|
385
|
+
logger.info("Settled %d T+1 row(s) on watcher tick", n)
|
|
386
|
+
except Exception as e: # noqa: BLE001
|
|
387
|
+
logger.exception("settle_due failed: %s", e)
|
|
388
|
+
|
|
389
|
+
def stop(self) -> None:
|
|
390
|
+
self._stop_event.set()
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: PaperTrade-India
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: Production-grade simulated broker for NSE/BSE paper trading
|
|
5
|
+
Project-URL: Homepage, https://github.com/Mirzabaig313/papertrade-india
|
|
6
|
+
Project-URL: Documentation, https://github.com/Mirzabaig313/papertrade-india#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/Mirzabaig313/papertrade-india
|
|
8
|
+
Project-URL: Issues, https://github.com/Mirzabaig313/papertrade-india/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/Mirzabaig313/papertrade-india/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Mirza
|
|
11
|
+
License: MIT License
|
|
12
|
+
|
|
13
|
+
Copyright (c) 2026 papertrade-india contributors
|
|
14
|
+
|
|
15
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
16
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
17
|
+
in the Software without restriction, including without limitation the rights
|
|
18
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
19
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
20
|
+
furnished to do so, subject to the following conditions:
|
|
21
|
+
|
|
22
|
+
The above copyright notice and this permission notice shall be included in all
|
|
23
|
+
copies or substantial portions of the Software.
|
|
24
|
+
|
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
26
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
27
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
28
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
29
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
30
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
31
|
+
SOFTWARE.
|
|
32
|
+
License-File: LICENSE
|
|
33
|
+
Keywords: algotrading,broker,bse,india,mcp,nse,paper-trading,stock-market,trading,yfinance
|
|
34
|
+
Classifier: Development Status :: 3 - Alpha
|
|
35
|
+
Classifier: Intended Audience :: Developers
|
|
36
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
37
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
38
|
+
Classifier: Operating System :: OS Independent
|
|
39
|
+
Classifier: Programming Language :: Python :: 3
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
43
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
44
|
+
Requires-Python: >=3.10
|
|
45
|
+
Requires-Dist: yfinance>=0.2.30
|
|
46
|
+
Provides-Extra: brokers
|
|
47
|
+
Requires-Dist: dhanhq>=2.0; extra == 'brokers'
|
|
48
|
+
Requires-Dist: kiteconnect>=4.2; extra == 'brokers'
|
|
49
|
+
Provides-Extra: cli
|
|
50
|
+
Requires-Dist: rich>=13.7; extra == 'cli'
|
|
51
|
+
Requires-Dist: typer>=0.12; extra == 'cli'
|
|
52
|
+
Provides-Extra: dev
|
|
53
|
+
Requires-Dist: hypothesis>=6.100; extra == 'dev'
|
|
54
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
55
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
56
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
57
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
58
|
+
Provides-Extra: dhan
|
|
59
|
+
Requires-Dist: dhanhq>=2.0; extra == 'dhan'
|
|
60
|
+
Provides-Extra: jugaad
|
|
61
|
+
Requires-Dist: jugaad-data>=0.27; extra == 'jugaad'
|
|
62
|
+
Provides-Extra: kite
|
|
63
|
+
Requires-Dist: kiteconnect>=4.2; extra == 'kite'
|
|
64
|
+
Provides-Extra: mcp
|
|
65
|
+
Requires-Dist: fastmcp>=0.3; extra == 'mcp'
|
|
66
|
+
Provides-Extra: ui
|
|
67
|
+
Requires-Dist: streamlit>=1.36; extra == 'ui'
|
|
68
|
+
Description-Content-Type: text/markdown
|
|
69
|
+
|
|
70
|
+
<div align="center">
|
|
71
|
+
|
|
72
|
+
# PaperTrade-India
|
|
73
|
+
|
|
74
|
+
**A production-grade simulated broker for NSE & BSE paper trading.**
|
|
75
|
+
|
|
76
|
+
Realistic Indian-market order execution — fees, T+1 settlement, tick/lot/band
|
|
77
|
+
rules, and live prices — behind a clean, Alpaca-style Python API.
|
|
78
|
+
|
|
79
|
+

|
|
80
|
+

|
|
81
|
+

|
|
82
|
+

|
|
83
|
+
|
|
84
|
+
[Quickstart](QUICKSTART.md) · [Examples](examples/) · [Report a bug](../../issues)
|
|
85
|
+
|
|
86
|
+
</div>
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Overview
|
|
91
|
+
|
|
92
|
+
No Indian broker offers a programmatic paper-trading API. **PaperTrade-India**
|
|
93
|
+
fills that gap: a simulated NSE/BSE broker that models the parts of real
|
|
94
|
+
trading that actually move your P&L — statutory fees, T+1 settlement,
|
|
95
|
+
price bands, slippage, and market impact — while exposing the same
|
|
96
|
+
method surface as an Alpaca-style trading client, so you can build and
|
|
97
|
+
test strategies without touching real capital or rewriting your code.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from papertrade_india import IndiaPaperBroker
|
|
101
|
+
|
|
102
|
+
broker = IndiaPaperBroker(initial_capital=1_000_000)
|
|
103
|
+
order = broker.buy("RELIANCE", 10)
|
|
104
|
+
print(order.filled_avg_price, order.fees_paid)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
> **Status:** alpha (pre-1.0). The public API is stable enough to build on,
|
|
108
|
+
> but minor releases may introduce breaking changes until 1.0.
|
|
109
|
+
|
|
110
|
+
## Why
|
|
111
|
+
|
|
112
|
+
| Platform | Paper trading | API access |
|
|
113
|
+
|:---|:---:|:---:|
|
|
114
|
+
| Zerodha Kite | ❌ | ❌ |
|
|
115
|
+
| Upstox | ⚠️ mock only | ⚠️ mock only |
|
|
116
|
+
| Angel One SmartAPI | ❌ | ❌ |
|
|
117
|
+
| Dhan / Fyers / Shoonya | ❌ | ❌ |
|
|
118
|
+
| **papertrade-india** | ✅ | ✅ |
|
|
119
|
+
|
|
120
|
+
## Features
|
|
121
|
+
|
|
122
|
+
**Execution realism** — all on by default, so a fresh broker behaves like a real retail account:
|
|
123
|
+
|
|
124
|
+
- **Indian fee model** — brokerage, STT, exchange charges, GST, SEBI
|
|
125
|
+
charges, stamp duty, and DP charges, configurable per broker and
|
|
126
|
+
date-versioned for mid-year statutory changes.
|
|
127
|
+
- **T+1 settlement** with deliverable-quantity enforcement, plus same-day
|
|
128
|
+
intraday round-trips via `ProductType.INTRADAY` and 15:15 auto-square-off.
|
|
129
|
+
- **Tick / lot / price-band rules** — orders snap to the symbol's tick and
|
|
130
|
+
are rejected outside the daily band.
|
|
131
|
+
- **Order types** — market, limit, `STOP_MARKET`, `STOP_LIMIT`, and
|
|
132
|
+
`BRACKET` with full OCO semantics.
|
|
133
|
+
- **Synthetic L2 order book** — uses real provider depth when available,
|
|
134
|
+
with queue-position tracking and Almgren-style market impact.
|
|
135
|
+
- **Slippage**, **latency**, and **random-rejection** simulation for
|
|
136
|
+
stress-testing strategy robustness.
|
|
137
|
+
- **Mark-to-bid** valuation for realistic unrealized P&L.
|
|
138
|
+
|
|
139
|
+
**Data** — a pluggable `MarketDataProvider` layer:
|
|
140
|
+
|
|
141
|
+
- Built-in providers: `yfinance`, `jugaad-data`, `stooq`, `nse-bhavcopy`
|
|
142
|
+
(official EOD), `nsepython`, `alphavantage`, `twelvedata`, `finnhub`,
|
|
143
|
+
plus live broker feeds `upstox` and `dhan` (real bid/ask + market depth).
|
|
144
|
+
- Per-provider **circuit breakers**, **median aggregation** across sources,
|
|
145
|
+
a first-wins `resilient_feed()` helper, and a name registry.
|
|
146
|
+
- **Live NSE/BSE holiday calendar** from the exchange-published API, cached
|
|
147
|
+
with an offline fallback.
|
|
148
|
+
|
|
149
|
+
**Engineering & safety**
|
|
150
|
+
|
|
151
|
+
- Thread-safe SQLite persistence (WAL, atomic transactions, versioned
|
|
152
|
+
migrations).
|
|
153
|
+
- Session-phase awareness (PRE_OPEN / REGULAR / POST_CLOSE / CLOSED).
|
|
154
|
+
- Risk controls: kill switch, symbol whitelist, per-order and per-position
|
|
155
|
+
notional caps.
|
|
156
|
+
- Idempotency keys, an immutable cash ledger with an invariant check,
|
|
157
|
+
broker fee presets (Zerodha, Upstox, Groww, Angel One, ICICIdirect),
|
|
158
|
+
a symbol master with delisting, corporate actions (splits + dividends),
|
|
159
|
+
and a persisted event log with an in-process observability bus.
|
|
160
|
+
- Multi-account support, an optional CLI, and an optional MCP server so
|
|
161
|
+
LLM agents can trade through tool calls.
|
|
162
|
+
|
|
163
|
+
## Installation
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
pip install papertrade-india # core
|
|
167
|
+
pip install 'papertrade-india[jugaad]' # + NSE-direct fallback data
|
|
168
|
+
pip install 'papertrade-india[cli]' # + Typer/Rich CLI
|
|
169
|
+
pip install 'papertrade-india[mcp]' # + MCP server
|
|
170
|
+
pip install 'papertrade-india[dev]' # + tests and linting
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Requires Python 3.10+.
|
|
174
|
+
|
|
175
|
+
## Quickstart
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from papertrade_india import IndiaPaperBroker
|
|
179
|
+
|
|
180
|
+
broker = IndiaPaperBroker(initial_capital=1_000_000)
|
|
181
|
+
|
|
182
|
+
# Market buy (inside NSE trading hours)
|
|
183
|
+
order = broker.buy("RELIANCE", 10)
|
|
184
|
+
print(order.filled_avg_price, order.fees_paid)
|
|
185
|
+
|
|
186
|
+
# Inspect state
|
|
187
|
+
for position in broker.get_positions():
|
|
188
|
+
print(position.symbol, position.qty, position.unrealized_pl)
|
|
189
|
+
|
|
190
|
+
account = broker.get_account()
|
|
191
|
+
print(f"Equity: ₹{account.equity:,.2f} Cash: ₹{account.cash:,.2f}")
|
|
192
|
+
|
|
193
|
+
# Realize P&L
|
|
194
|
+
broker.sell("RELIANCE", 10)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
The full getting-started walkthrough and a worked example for **every**
|
|
198
|
+
feature — limit orders, multiple accounts, risk controls, live data feeds,
|
|
199
|
+
realism configuration, and more — live in **[QUICKSTART.md](QUICKSTART.md)**.
|
|
200
|
+
Runnable scripts are in [`examples/`](examples/).
|
|
201
|
+
|
|
202
|
+
## Configuration
|
|
203
|
+
|
|
204
|
+
Provide your own broker credentials and data-provider keys via a `.env`
|
|
205
|
+
file — see [`.env.example`](.env.example). Everything is optional: with no
|
|
206
|
+
keys set, the broker uses the free `yfinance → jugaad-data` fallback chain
|
|
207
|
+
and works out of the box. API keys unlock live broker feeds and
|
|
208
|
+
higher-rate data sources.
|
|
209
|
+
|
|
210
|
+
## Fee model
|
|
211
|
+
|
|
212
|
+
Defaults match a typical discount-broker delivery account:
|
|
213
|
+
|
|
214
|
+
| Component | Default rate | Applies to |
|
|
215
|
+
|:---|:---|:---|
|
|
216
|
+
| Brokerage | ₹0 | Both sides (delivery) |
|
|
217
|
+
| STT | 0.1% | Both sides |
|
|
218
|
+
| Exchange charge | 0.00322% (NSE) / 0.00375% (BSE) | Both sides |
|
|
219
|
+
| GST | 18% on (brokerage + exchange) | Both sides |
|
|
220
|
+
| SEBI charges | ₹10 per crore | Both sides |
|
|
221
|
+
| Stamp duty | 0.015% | Buy only |
|
|
222
|
+
| DP charge | ₹13.5 | Sell only |
|
|
223
|
+
|
|
224
|
+
Override any field via `FeeConfig`, or use a named preset, to model
|
|
225
|
+
intraday or full-service brokers.
|
|
226
|
+
|
|
227
|
+
## Scope & limitations
|
|
228
|
+
|
|
229
|
+
The simulator is intentionally focused on **cash equity, delivery,
|
|
230
|
+
long-only** trading. It is a faithful behavioral simulator, not an exchange
|
|
231
|
+
replica:
|
|
232
|
+
|
|
233
|
+
| Limitation | Notes |
|
|
234
|
+
|:---|:---|
|
|
235
|
+
| Synthetic order book, not a real matching engine | Uses real provider depth when available; accurate for retail order sizes. True queue priority isn't reproducible from retail data. |
|
|
236
|
+
| Snapshot prices, not a tick stream | Fills price off the latest snapshot — negligible at daily/swing cadence. |
|
|
237
|
+
| Corporate actions applied manually | Via `apply_split` / `apply_dividend`. |
|
|
238
|
+
| No margin, leverage, or short selling | Cash, long-only by design. |
|
|
239
|
+
| No options or F&O | Equity only. |
|
|
240
|
+
|
|
241
|
+
## Contributing
|
|
242
|
+
|
|
243
|
+
Issues and pull requests are welcome. Install the dev extras and run the
|
|
244
|
+
test suite before submitting:
|
|
245
|
+
|
|
246
|
+
```bash
|
|
247
|
+
pip install -e '.[dev]'
|
|
248
|
+
pytest
|
|
249
|
+
ruff check src tests
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## License
|
|
253
|
+
|
|
254
|
+
[MIT](LICENSE) — use it however you want.
|
|
255
|
+
|
|
256
|
+
## Disclaimer
|
|
257
|
+
|
|
258
|
+
This is a **simulated** broker; it does not place real trades. It is not
|
|
259
|
+
investment advice. Always verify calculations against your actual broker's
|
|
260
|
+
contract notes before relying on the simulator's outputs for tax,
|
|
261
|
+
compliance, or investment decisions.
|