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.
Files changed (101) hide show
  1. papertrade_india/__init__.py +250 -0
  2. papertrade_india/_context.py +144 -0
  3. papertrade_india/broker.py +546 -0
  4. papertrade_india/cli.py +474 -0
  5. papertrade_india/clock.py +29 -0
  6. papertrade_india/corporate_actions/__init__.py +10 -0
  7. papertrade_india/corporate_actions/bonus.py +105 -0
  8. papertrade_india/corporate_actions/dividends.py +99 -0
  9. papertrade_india/corporate_actions/rights.py +189 -0
  10. papertrade_india/corporate_actions/splits.py +111 -0
  11. papertrade_india/corporate_actions/store.py +247 -0
  12. papertrade_india/data/nse_holidays_2026.json +22 -0
  13. papertrade_india/data/nse_holidays_2027.json +9 -0
  14. papertrade_india/data/nse_universe_sample.csv +31 -0
  15. papertrade_india/domain/__init__.py +6 -0
  16. papertrade_india/domain/exceptions.py +183 -0
  17. papertrade_india/domain/models.py +213 -0
  18. papertrade_india/domain/rules/__init__.py +5 -0
  19. papertrade_india/domain/rules/risk.py +165 -0
  20. papertrade_india/domain/rules/tick_lot_band.py +139 -0
  21. papertrade_india/events.py +29 -0
  22. papertrade_india/exceptions.py +29 -0
  23. papertrade_india/execution/__init__.py +5 -0
  24. papertrade_india/execution/book.py +385 -0
  25. papertrade_india/execution/fees.py +213 -0
  26. papertrade_india/execution/settlement.py +360 -0
  27. papertrade_india/execution/simulation.py +176 -0
  28. papertrade_india/execution/slippage.py +120 -0
  29. papertrade_india/fees.py +29 -0
  30. papertrade_india/idempotency.py +29 -0
  31. papertrade_india/infrastructure/__init__.py +6 -0
  32. papertrade_india/infrastructure/clock.py +123 -0
  33. papertrade_india/infrastructure/events.py +137 -0
  34. papertrade_india/infrastructure/holidays.py +138 -0
  35. papertrade_india/infrastructure/idempotency.py +133 -0
  36. papertrade_india/infrastructure/ledger.py +141 -0
  37. papertrade_india/infrastructure/market_hours.py +200 -0
  38. papertrade_india/infrastructure/migrations.py +622 -0
  39. papertrade_india/infrastructure/observability.py +195 -0
  40. papertrade_india/infrastructure/persistence.py +130 -0
  41. papertrade_india/infrastructure/symbols.py +279 -0
  42. papertrade_india/infrastructure/watchlist.py +78 -0
  43. papertrade_india/interface.py +92 -0
  44. papertrade_india/ledger.py +29 -0
  45. papertrade_india/limit_orders.py +29 -0
  46. papertrade_india/market_hours.py +29 -0
  47. papertrade_india/microstructure.py +57 -0
  48. papertrade_india/migrations.py +29 -0
  49. papertrade_india/models.py +29 -0
  50. papertrade_india/observability.py +29 -0
  51. papertrade_india/orders/__init__.py +5 -0
  52. papertrade_india/orders/amo.py +98 -0
  53. papertrade_india/orders/book_helpers.py +111 -0
  54. papertrade_india/orders/bracket.py +115 -0
  55. papertrade_india/orders/limit.py +210 -0
  56. papertrade_india/orders/market.py +264 -0
  57. papertrade_india/orders/partial_fills.py +92 -0
  58. papertrade_india/orders/preopen.py +274 -0
  59. papertrade_india/orders/state.py +640 -0
  60. papertrade_india/orders/stop.py +122 -0
  61. papertrade_india/orders/submit.py +385 -0
  62. papertrade_india/partial_fills.py +29 -0
  63. papertrade_india/persistence.py +29 -0
  64. papertrade_india/preopen.py +29 -0
  65. papertrade_india/presets.py +120 -0
  66. papertrade_india/price_feed.py +316 -0
  67. papertrade_india/providers/__init__.py +123 -0
  68. papertrade_india/providers/alphavantage.py +180 -0
  69. papertrade_india/providers/base.py +256 -0
  70. papertrade_india/providers/cache.py +147 -0
  71. papertrade_india/providers/composite.py +244 -0
  72. papertrade_india/providers/dhan.py +266 -0
  73. papertrade_india/providers/finnhub.py +122 -0
  74. papertrade_india/providers/health.py +233 -0
  75. papertrade_india/providers/jugaad.py +142 -0
  76. papertrade_india/providers/kite.py +222 -0
  77. papertrade_india/providers/nse_bhavcopy.py +210 -0
  78. papertrade_india/providers/nsepython.py +98 -0
  79. papertrade_india/providers/registry.py +226 -0
  80. papertrade_india/providers/stooq.py +173 -0
  81. papertrade_india/providers/twelvedata.py +198 -0
  82. papertrade_india/providers/upstox.py +318 -0
  83. papertrade_india/providers/upstox_instruments.py +171 -0
  84. papertrade_india/providers/yfinance.py +205 -0
  85. papertrade_india/quickstart.py +111 -0
  86. papertrade_india/reads/__init__.py +6 -0
  87. papertrade_india/reads/account.py +140 -0
  88. papertrade_india/reads/orders.py +54 -0
  89. papertrade_india/reads/positions.py +188 -0
  90. papertrade_india/risk.py +29 -0
  91. papertrade_india/settlement.py +29 -0
  92. papertrade_india/simulation.py +29 -0
  93. papertrade_india/slippage.py +29 -0
  94. papertrade_india/symbols.py +29 -0
  95. papertrade_india/workers/__init__.py +6 -0
  96. papertrade_india/workers/limit_orders.py +390 -0
  97. papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
  98. papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
  99. papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
  100. papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  101. papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,546 @@
1
+ """IndiaPaperBroker — thin orchestrator over cohesive subsystems.
2
+
3
+ Exposes an Alpaca-style interface (same method signatures and
4
+ dataclass-shaped return values), so it can sit behind a broker router
5
+ keyed on ``market`` and callers don't change their code across brokers.
6
+
7
+ Architecture
8
+ ------------
9
+ This class is a façade. Every method delegates to a subsystem module:
10
+
11
+ - Order placement → :mod:`orders.submit`
12
+ - Market fills → :mod:`orders.market`
13
+ - Limit fills → :mod:`orders.limit`
14
+ - Stop / bracket / AMO → :mod:`orders.stop`, :mod:`orders.bracket`, :mod:`orders.amo`
15
+ - Pre-open auction → :mod:`orders.preopen`
16
+ - Order state (cancel, expire, square-off) → :mod:`orders.state`
17
+ - Read-only views → :mod:`reads.positions`, :mod:`reads.account`, :mod:`reads.orders`
18
+ - Corporate actions → :mod:`corporate_actions.splits` etc.
19
+ - Shared collaborators → :class:`_context.BrokerContext`
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ import sqlite3
26
+ from datetime import datetime
27
+
28
+ from ._context import BrokerContext
29
+ from .corporate_actions import bonus as _ca_bonus
30
+ from .corporate_actions import dividends as _ca_dividends
31
+ from .corporate_actions import rights as _ca_rights
32
+ from .corporate_actions import splits as _ca_splits
33
+ from .domain.exceptions import AccountNotFoundError
34
+ from .domain.models import (
35
+ Account,
36
+ Exchange,
37
+ Order,
38
+ OrderSide,
39
+ OrderStatus,
40
+ OrderType,
41
+ Position,
42
+ ProductType,
43
+ )
44
+ from .domain.rules.risk import RiskConfig, RiskEngine
45
+ from .domain.rules.tick_lot_band import MicrostructureConfig
46
+ from .execution.book import OrderBookConfig, OrderBookSimulator
47
+ from .execution.fees import FeeConfig, FeeSchedule, IndianFeeEngine
48
+ from .execution.settlement import SettlementConfig, SettlementEngine
49
+ from .execution.simulation import (
50
+ LatencyConfig,
51
+ LatencySimulator,
52
+ RejectionConfig,
53
+ RejectionSimulator,
54
+ )
55
+ from .execution.slippage import SlippageConfig
56
+ from .infrastructure import events as _events
57
+ from .infrastructure import ledger as _ledger
58
+ from .infrastructure.clock import Clock, WallClock
59
+ from .infrastructure.market_hours import NSECalendar, SessionPhase
60
+ from .infrastructure.observability import BrokerEvent, EventBus
61
+ from .infrastructure.persistence import PathLike, Persistence
62
+ from .infrastructure.symbols import SymbolMaster
63
+ from .infrastructure.watchlist import WatchlistStore
64
+ from .interface import BrokerInterface
65
+ from .orders import amo as _amo
66
+ from .orders import state as _orders_state
67
+ from .orders.partial_fills import PartialFillConfig
68
+ from .orders.preopen import AuctionMatch
69
+ from .orders.submit import submit_order as _submit_order_fn
70
+ from .price_feed import PriceFeed
71
+ from .reads import account as _reads_account
72
+ from .reads import orders as _reads_orders
73
+ from .reads import positions as _reads_positions
74
+
75
+ logger = logging.getLogger(__name__)
76
+
77
+ _QTY_EPSILON = 1e-9
78
+
79
+
80
+ class IndiaPaperBroker(BrokerInterface):
81
+ """Production-grade simulated broker for NSE/BSE paper trading.
82
+
83
+ Features
84
+ --------
85
+ - Real NSE/BSE prices via yfinance (with jugaad-data fallback)
86
+ - Realistic Indian fees (STT, GST, exchange, SEBI, stamp, DP)
87
+ - Thread-safe SQLite persistence with WAL mode
88
+ - Market-hours and holiday-calendar awareness
89
+ - Limit-order support (queue + optional ``LimitOrderWatcher``)
90
+ - Multi-account support via ``account_id``
91
+
92
+ Examples
93
+ --------
94
+ >>> broker = IndiaPaperBroker(initial_capital=1_000_000)
95
+ >>> broker.buy("RELIANCE", 10)
96
+ >>> positions = broker.get_positions()
97
+ >>> account = broker.get_account()
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ initial_capital: float = 1_000_000.0,
103
+ db_path: PathLike = "data/india_paper.db",
104
+ account_id: str = "default",
105
+ exchange: Exchange = Exchange.NSE,
106
+ fee_config: FeeConfig | FeeSchedule | None = None,
107
+ price_feed: PriceFeed | None = None,
108
+ calendar: NSECalendar | None = None,
109
+ enforce_market_hours: bool = True,
110
+ strict_open: bool = False,
111
+ slippage_config: SlippageConfig | None = None,
112
+ risk_config: RiskConfig | None = None,
113
+ symbol_master: SymbolMaster | None = None,
114
+ enforce_fresh_prices: bool = True,
115
+ partial_fill_config: PartialFillConfig | None = None,
116
+ event_bus: EventBus | None = None,
117
+ clock: Clock | None = None,
118
+ microstructure_config: MicrostructureConfig | None = None,
119
+ order_book_config: OrderBookConfig | None = None,
120
+ settlement_config: SettlementConfig | None = None,
121
+ latency_config: LatencyConfig | None = None,
122
+ rejection_config: RejectionConfig | None = None,
123
+ mark_to_bid: bool = True,
124
+ enforce_real_time: bool = False,
125
+ ) -> None:
126
+ """Construct a broker bound to ``account_id`` in ``db_path``.
127
+
128
+ If the account row doesn't exist:
129
+ - ``strict_open=False`` (default): create it with ``initial_capital``.
130
+ - ``strict_open=True``: raise ``AccountNotFoundError``.
131
+
132
+ See the class docstring for the design overview.
133
+ """
134
+ self.account_id = account_id
135
+ self.default_exchange = exchange
136
+ self.enforce_market_hours = enforce_market_hours
137
+ self.enforce_fresh_prices = enforce_fresh_prices
138
+ self.enforce_real_time = enforce_real_time
139
+
140
+ self.persistence = Persistence(db_path)
141
+ self._watchlist = WatchlistStore(self.persistence)
142
+ self.price_feed = price_feed or PriceFeed()
143
+ self.calendar = calendar or NSECalendar()
144
+
145
+ schedule: FeeSchedule
146
+ if fee_config is None:
147
+ schedule = FeeSchedule(default=FeeConfig())
148
+ elif isinstance(fee_config, FeeSchedule):
149
+ schedule = fee_config
150
+ else:
151
+ schedule = FeeSchedule(default=fee_config)
152
+ self.fee_schedule = schedule
153
+
154
+ self.slippage_config = slippage_config or SlippageConfig()
155
+ self.risk_engine = RiskEngine(risk_config or RiskConfig())
156
+ self.symbol_master = symbol_master or SymbolMaster(strict=False)
157
+
158
+ self.partial_fill_config = partial_fill_config or PartialFillConfig(
159
+ enabled=True, max_pct_per_tick=0.25, min_fill_qty=1,
160
+ )
161
+ self.events: EventBus = event_bus or EventBus()
162
+ self._pending_events: list[BrokerEvent] = []
163
+ self._clock: Clock = clock or WallClock()
164
+
165
+ self.microstructure_config = microstructure_config or MicrostructureConfig()
166
+ self._book_sim = OrderBookSimulator(order_book_config or OrderBookConfig())
167
+ self.settlement = SettlementEngine(settlement_config or SettlementConfig())
168
+ self._latency_sim = LatencySimulator(latency_config or LatencyConfig())
169
+ self._reject_sim = RejectionSimulator(rejection_config or RejectionConfig())
170
+ self.mark_to_bid = bool(mark_to_bid)
171
+
172
+ # Shared context handed to every subsystem function.
173
+ self._ctx = BrokerContext(
174
+ account_id=self.account_id,
175
+ default_exchange=self.default_exchange,
176
+ persistence=self.persistence,
177
+ price_feed=self.price_feed,
178
+ calendar=self.calendar,
179
+ fee_schedule=self.fee_schedule,
180
+ slippage_config=self.slippage_config,
181
+ risk_engine=self.risk_engine,
182
+ symbol_master=self.symbol_master,
183
+ microstructure_config=self.microstructure_config,
184
+ book_sim=self._book_sim,
185
+ settlement=self.settlement,
186
+ latency_sim=self._latency_sim,
187
+ reject_sim=self._reject_sim,
188
+ partial_fill_config=self.partial_fill_config,
189
+ events=self.events,
190
+ clock=self._clock,
191
+ enforce_market_hours=self.enforce_market_hours,
192
+ enforce_fresh_prices=self.enforce_fresh_prices,
193
+ mark_to_bid=self.mark_to_bid,
194
+ enforce_real_time=self.enforce_real_time,
195
+ pending_events=self._pending_events,
196
+ )
197
+
198
+ self._ensure_account_exists(initial_capital, strict_open=strict_open)
199
+
200
+ # ── Clock / fee helpers (kept for backwards-compat callers) ───────
201
+
202
+ def _fee_engine_for(self, when_iso: str) -> IndianFeeEngine:
203
+ d = datetime.fromisoformat(when_iso).date()
204
+ return IndianFeeEngine(self.fee_schedule.config_on(d))
205
+
206
+ @property
207
+ def fee_engine(self) -> IndianFeeEngine:
208
+ """Backwards-compat: fee engine for today (IST)."""
209
+ return IndianFeeEngine(self.fee_schedule.config_on(self._clock.now().date()))
210
+
211
+ def _now_iso(self) -> str:
212
+ return self._clock.now().isoformat()
213
+
214
+ @property
215
+ def clock(self) -> Clock:
216
+ return self._clock
217
+
218
+ # ── Event helpers (kept for reset() and backwards-compat) ─────────
219
+
220
+ def _emit_event(
221
+ self,
222
+ conn: sqlite3.Connection,
223
+ event_type: str,
224
+ order_id: str | None = None,
225
+ payload: dict | None = None,
226
+ ) -> None:
227
+ self._ctx.emit(conn, event_type=event_type,
228
+ order_id=order_id, payload=payload)
229
+
230
+ def _drain_pending_events(self) -> None:
231
+ self._ctx.drain_pending_events()
232
+
233
+ # ── Account lifecycle ──────────────────────────────────────────────
234
+
235
+ def _ensure_account_exists(
236
+ self, initial_capital: float, strict_open: bool,
237
+ ) -> None:
238
+ with self.persistence.transaction() as conn:
239
+ row = conn.execute(
240
+ "SELECT cash FROM account WHERE account_id = ?",
241
+ (self.account_id,),
242
+ ).fetchone()
243
+ if row is None:
244
+ if strict_open:
245
+ raise AccountNotFoundError(
246
+ f"Account {self.account_id!r} does not exist in "
247
+ f"{self.persistence.db_path}"
248
+ )
249
+ now = self._now_iso()
250
+ conn.execute(
251
+ "INSERT INTO account (account_id, cash, created_at) "
252
+ "VALUES (?, ?, ?)",
253
+ (self.account_id, float(initial_capital), now),
254
+ )
255
+ _ledger.record(
256
+ conn,
257
+ account_id=self.account_id,
258
+ amount=float(initial_capital),
259
+ reason="initial_capital",
260
+ recorded_at_iso=now,
261
+ notes="Account opened",
262
+ )
263
+
264
+ # ── Public API: order placement ────────────────────────────────────
265
+
266
+ def buy(
267
+ self,
268
+ symbol: str,
269
+ qty: float,
270
+ order_type: OrderType = OrderType.MARKET,
271
+ limit_price: float | None = None,
272
+ time_in_force: str = "DAY",
273
+ idempotency_key: str | None = None,
274
+ stop_price: float | None = None,
275
+ target_price: float | None = None,
276
+ product_type: ProductType = ProductType.DELIVERY,
277
+ ) -> Order:
278
+ return _submit_order_fn(
279
+ self._ctx, symbol, qty, OrderSide.BUY, order_type, limit_price,
280
+ time_in_force, idempotency_key=idempotency_key,
281
+ stop_price=stop_price, target_price=target_price,
282
+ product_type=product_type,
283
+ )
284
+
285
+ def sell(
286
+ self,
287
+ symbol: str,
288
+ qty: float,
289
+ order_type: OrderType = OrderType.MARKET,
290
+ limit_price: float | None = None,
291
+ time_in_force: str = "DAY",
292
+ idempotency_key: str | None = None,
293
+ stop_price: float | None = None,
294
+ target_price: float | None = None,
295
+ product_type: ProductType = ProductType.DELIVERY,
296
+ ) -> Order:
297
+ return _submit_order_fn(
298
+ self._ctx, symbol, qty, OrderSide.SELL, order_type, limit_price,
299
+ time_in_force, idempotency_key=idempotency_key,
300
+ stop_price=stop_price, target_price=target_price,
301
+ product_type=product_type,
302
+ )
303
+
304
+ # ── Public API: reads ──────────────────────────────────────────────
305
+
306
+ def get_positions(self) -> list[Position]:
307
+ return _reads_positions.list_all(self)
308
+
309
+ def get_position(self, symbol: str) -> Position | None:
310
+ return _reads_positions.get(self, symbol)
311
+
312
+ def _mark_price(self, symbol: str) -> tuple[float, str]:
313
+ return _reads_positions.mark_price(self, symbol)
314
+
315
+ def get_account(self) -> Account:
316
+ return _reads_account.summary(self)
317
+
318
+ def get_orders(
319
+ self,
320
+ status: OrderStatus | None = None,
321
+ limit: int = 100,
322
+ ) -> list[Order]:
323
+ return _reads_orders.list_all(self, status=status, limit=limit)
324
+
325
+ def get_order(self, order_id: str) -> Order | None:
326
+ return _reads_orders.get(self, order_id)
327
+
328
+ # ── Public API: watchlist (UI favorites, SQLite-backed) ────────────
329
+ def get_watchlist(self) -> list[str]:
330
+ """Return the saved watchlist symbols in user order."""
331
+ return self._watchlist.list_symbols()
332
+
333
+ def set_watchlist(self, symbols: list[str]) -> list[str]:
334
+ """Replace the watchlist with ``symbols``; returns the stored list."""
335
+ return self._watchlist.set_symbols(symbols)
336
+
337
+ def add_to_watchlist(self, symbol: str) -> None:
338
+ self._watchlist.add(symbol)
339
+
340
+ def remove_from_watchlist(self, symbol: str) -> None:
341
+ self._watchlist.remove(symbol)
342
+
343
+ # ── Public API: order management ──────────────────────────────────
344
+
345
+ def cancel_order(self, order_id: str) -> bool:
346
+ return _orders_state.cancel(self._ctx, order_id)
347
+
348
+ def cancel_all_orders(self) -> int:
349
+ return _orders_state.cancel_all(self._ctx)
350
+
351
+ def expire_stale_day_orders(self) -> int:
352
+ return _orders_state.expire_day_orders(self._ctx)
353
+
354
+ def get_queue_position(
355
+ self,
356
+ symbol: str,
357
+ side: OrderSide,
358
+ price: float,
359
+ ) -> int | None:
360
+ """Public accessor for queued shares-ahead at a price level."""
361
+ if not self._book_sim.config.enabled:
362
+ return None
363
+ from .orders.book_helpers import symbol_microstructure # noqa: PLC0415
364
+ tick, _, _ = symbol_microstructure(self._ctx, symbol)
365
+ return self._book_sim.queue_position(symbol, side, price, tick)
366
+
367
+ # ── Public API: workers' hooks ─────────────────────────────────────
368
+
369
+ def fire_amo_orders(self) -> int:
370
+ return _amo.fire_pending(self._ctx)
371
+
372
+ def run_pre_open_auction(self) -> AuctionMatch:
373
+ from .orders.preopen import run as _run_auction # noqa: PLC0415
374
+ return _run_auction(self._ctx)
375
+
376
+ def settle_due(self) -> int:
377
+ with self.persistence.transaction() as conn:
378
+ return self.settlement.settle_due(
379
+ conn,
380
+ account_id=self.account_id,
381
+ as_of=self._clock.now().date(),
382
+ )
383
+
384
+ def square_off_intraday(self) -> int:
385
+ return _orders_state.square_off_intraday(self._ctx)
386
+
387
+ # ── Public API: corporate actions ─────────────────────────────────
388
+
389
+ def apply_split(
390
+ self,
391
+ symbol: str,
392
+ ratio_num: int,
393
+ ratio_den: int = 1,
394
+ ex_date: str | None = None,
395
+ notes: str | None = None,
396
+ ) -> str:
397
+ return _ca_splits.apply(self._ctx, symbol, ratio_num, ratio_den,
398
+ ex_date=ex_date, notes=notes)
399
+
400
+ def apply_bonus(
401
+ self,
402
+ symbol: str,
403
+ ratio_num: int,
404
+ ratio_den: int = 1,
405
+ ex_date: str | None = None,
406
+ notes: str | None = None,
407
+ ) -> str:
408
+ return _ca_bonus.apply(self._ctx, symbol, ratio_num, ratio_den,
409
+ ex_date=ex_date, notes=notes)
410
+
411
+ def apply_rights(
412
+ self,
413
+ symbol: str,
414
+ ratio_num: int,
415
+ ratio_den: int,
416
+ subscription_price: float,
417
+ subscribe: bool = False,
418
+ ex_date: str | None = None,
419
+ notes: str | None = None,
420
+ ) -> str:
421
+ return _ca_rights.apply(self._ctx, symbol, ratio_num, ratio_den,
422
+ subscription_price, subscribe=subscribe,
423
+ ex_date=ex_date, notes=notes)
424
+
425
+ def apply_dividend(
426
+ self,
427
+ symbol: str,
428
+ amount_per_share: float,
429
+ ex_date: str | None = None,
430
+ notes: str | None = None,
431
+ ) -> str:
432
+ return _ca_dividends.apply(self._ctx, symbol, amount_per_share,
433
+ ex_date=ex_date, notes=notes)
434
+
435
+ # ── Public API: ledger / events / session ─────────────────────────
436
+
437
+ def get_cash_movements(self, limit: int = 200) -> list[_ledger.CashMovement]:
438
+ return _reads_account.list_cash_movements(self, limit=limit)
439
+
440
+ def get_position_basis_breakdown(self, symbol: str) -> dict | None:
441
+ return _reads_positions.basis_breakdown(self, symbol)
442
+
443
+ def verify_cash_invariant(self, tolerance: float = 0.01) -> bool:
444
+ return _reads_account.verify_cash_invariant(self, tolerance=tolerance)
445
+
446
+ def get_events(
447
+ self,
448
+ limit: int = 200,
449
+ event_types: tuple[str, ...] | None = None,
450
+ ) -> list[_events.Event]:
451
+ return _reads_account.list_events(self, limit=limit,
452
+ event_types=event_types)
453
+
454
+ def current_session_phase(self) -> SessionPhase:
455
+ return _reads_account.current_session_phase(self)
456
+
457
+ # ── Public API: idempotency cleanup ───────────────────────────────
458
+
459
+ def cleanup_idempotency_keys(self, hours: int = 24) -> int:
460
+ """Delete idempotency rows older than ``hours``. Returns count."""
461
+ from datetime import timedelta # noqa: PLC0415
462
+
463
+ from .infrastructure import idempotency as _idempotency # noqa: PLC0415
464
+ with self.persistence.transaction() as conn:
465
+ return _idempotency.cleanup_expired(conn, ttl=timedelta(hours=hours))
466
+
467
+ # ── Public API: account reset ─────────────────────────────────────
468
+
469
+ def reset(self, initial_capital: float | None = None) -> None:
470
+ """Reset account to initial state (paper-trading reset)."""
471
+ with self.persistence.transaction() as conn:
472
+ conn.execute("DELETE FROM orders WHERE account_id = ?",
473
+ (self.account_id,))
474
+ conn.execute("DELETE FROM trades WHERE account_id = ?",
475
+ (self.account_id,))
476
+ conn.execute("DELETE FROM positions WHERE account_id = ?",
477
+ (self.account_id,))
478
+ conn.execute("DELETE FROM cash_movements WHERE account_id = ?",
479
+ (self.account_id,))
480
+ now = self._now_iso()
481
+ if initial_capital is not None:
482
+ conn.execute(
483
+ "UPDATE account SET cash = ?, realized_pl_total = 0 "
484
+ "WHERE account_id = ?",
485
+ (initial_capital, self.account_id),
486
+ )
487
+ _ledger.record(conn, account_id=self.account_id,
488
+ amount=float(initial_capital),
489
+ reason="initial_capital", recorded_at_iso=now,
490
+ notes="Account reset")
491
+ else:
492
+ cash_row = conn.execute(
493
+ "SELECT cash FROM account WHERE account_id = ?",
494
+ (self.account_id,),
495
+ ).fetchone()
496
+ conn.execute(
497
+ "UPDATE account SET realized_pl_total = 0 WHERE account_id = ?",
498
+ (self.account_id,),
499
+ )
500
+ _ledger.record(conn, account_id=self.account_id,
501
+ amount=float(cash_row["cash"]),
502
+ reason="initial_capital", recorded_at_iso=now,
503
+ notes="Account reset (cash preserved)")
504
+ self._emit_event(conn, event_type="account_reset",
505
+ payload={"initial_capital": initial_capital})
506
+ self._drain_pending_events()
507
+ logger.info("RESET account %s", self.account_id)
508
+
509
+ # ── Backwards-compat shims (remove in v0.3) ───────────────────────
510
+
511
+ def _row_to_order(self, row: sqlite3.Row) -> Order:
512
+ """Shim: delegates to orders.state.row_to_order."""
513
+ return _orders_state.row_to_order(row)
514
+
515
+ def _execute_limit_fill(
516
+ self,
517
+ order: Order,
518
+ fill_price: float,
519
+ fill_qty: float | None = None,
520
+ ) -> None:
521
+ """Shim: delegates to orders.limit.fill (used by LimitOrderWatcher)."""
522
+ from .orders.limit import fill as _limit_fill # noqa: PLC0415
523
+ _limit_fill(self._ctx, order, fill_price, fill_qty=fill_qty)
524
+
525
+ def _trigger_stop_order(self, order: Order, last_price: float) -> None:
526
+ """Shim: delegates to orders.stop.trigger (used by LimitOrderWatcher)."""
527
+ from .orders.stop import trigger as _stop_trigger # noqa: PLC0415
528
+ _stop_trigger(self._ctx, order, last_price)
529
+
530
+ def _fill_pending_market_parent(self, parent_id: str) -> None:
531
+ """Shim: delegates to orders.market.fill_pending_market."""
532
+ from .orders.market import fill_pending_market # noqa: PLC0415
533
+ fill_pending_market(self._ctx, parent_id)
534
+
535
+ # ── Utilities ──────────────────────────────────────────────────────
536
+
537
+ def __repr__(self) -> str:
538
+ return (
539
+ f"IndiaPaperBroker(account_id={self.account_id!r}, "
540
+ f"exchange={self.default_exchange.value}, "
541
+ f"db_path={self.persistence.db_path!r})"
542
+ )
543
+
544
+ @property
545
+ def db_path(self) -> str:
546
+ return self.persistence.db_path