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,474 @@
1
+ """Optional CLI for inspecting account state.
2
+
3
+ Usage::
4
+
5
+ papertrade-india account
6
+ papertrade-india positions
7
+ papertrade-india orders --status pending
8
+ papertrade-india cancel-all
9
+ papertrade-india reset --capital 1000000
10
+
11
+ The CLI is opt-in (``pip install 'papertrade-india[cli]'``); if Typer is
12
+ not installed, importing this module raises a friendly error.
13
+
14
+ Common flags
15
+ ------------
16
+ ``--db PATH``: SQLite file path (default: ``data/india_paper.db``).
17
+ ``--account ID``: account id (default: ``default``).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import sys
23
+
24
+ try:
25
+ import typer
26
+ from rich.console import Console
27
+ from rich.table import Table
28
+ except ImportError: # pragma: no cover
29
+ sys.stderr.write(
30
+ "papertrade-india CLI requires extras: "
31
+ "pip install 'papertrade-india[cli]'\n"
32
+ )
33
+ raise
34
+
35
+ from .broker import IndiaPaperBroker
36
+ from .domain.exceptions import AccountNotFoundError
37
+ from .domain.models import OrderStatus
38
+
39
+ app = typer.Typer(
40
+ name="papertrade-india",
41
+ help="Inspect and control a local India paper trading broker.",
42
+ no_args_is_help=True,
43
+ )
44
+ console = Console()
45
+
46
+
47
+ def _broker(db: str, account: str, strict_open: bool = True) -> IndiaPaperBroker:
48
+ """Open a broker against an EXISTING account.
49
+
50
+ By default ``strict_open=True``: inspection commands fail fast rather
51
+ than silently spawning a fresh ₹1M account when the user mistypes
52
+ ``--account`` or points at the wrong DB.
53
+
54
+ Pass ``strict_open=False`` for the rare commands that legitimately
55
+ create accounts (none of the inspection commands do).
56
+ """
57
+ try:
58
+ return IndiaPaperBroker(
59
+ db_path=db, account_id=account, strict_open=strict_open,
60
+ )
61
+ except AccountNotFoundError as e:
62
+ console.print(f"[red]{e}[/red]")
63
+ raise typer.Exit(code=2) from e
64
+
65
+
66
+ @app.command()
67
+ def account(
68
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
69
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
70
+ ) -> None:
71
+ """Show the account summary."""
72
+ b = _broker(db, account_id)
73
+ a = b.get_account()
74
+ table = Table(title=f"Account {a.account_id}")
75
+ table.add_column("Field", style="cyan")
76
+ table.add_column("Value", justify="right")
77
+ rows = [
78
+ ("Equity", f"₹{a.equity:,.2f}"),
79
+ ("Cash", f"₹{a.cash:,.2f}"),
80
+ ("Portfolio value", f"₹{a.portfolio_value:,.2f}"),
81
+ ("Buying power", f"₹{a.buying_power:,.2f}"),
82
+ ("Realized P&L", f"₹{a.realized_pl_total:,.2f}"),
83
+ ("Unrealized P&L", f"₹{a.unrealized_pl_total:,.2f}"),
84
+ ("Currency", a.currency),
85
+ ]
86
+ for k, v in rows:
87
+ table.add_row(k, v)
88
+ console.print(table)
89
+
90
+
91
+ @app.command()
92
+ def positions(
93
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
94
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
95
+ ) -> None:
96
+ """List all open positions."""
97
+ b = _broker(db, account_id)
98
+ pos = b.get_positions()
99
+ if not pos:
100
+ console.print("[yellow]No open positions.[/yellow]")
101
+ return
102
+ table = Table(title=f"Positions ({account_id})")
103
+ for col in ("Symbol", "Exch", "Qty", "Avg Cost", "Mkt Price",
104
+ "Mkt Value", "Unrealized P&L", "P&L %"):
105
+ table.add_column(col)
106
+ for p in pos:
107
+ table.add_row(
108
+ p.symbol,
109
+ p.exchange.value,
110
+ f"{p.qty:g}",
111
+ f"₹{p.avg_cost:,.2f}",
112
+ f"₹{p.current_price:,.2f}",
113
+ f"₹{p.market_value:,.2f}",
114
+ f"₹{p.unrealized_pl:,.2f}",
115
+ f"{p.unrealized_pl_percent:+.2f}%",
116
+ )
117
+ console.print(table)
118
+
119
+
120
+ @app.command()
121
+ def orders(
122
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
123
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
124
+ status: str | None = typer.Option(
125
+ None, help="Filter by status (pending/filled/cancelled/...)"
126
+ ),
127
+ limit: int = typer.Option(50, help="Max rows to show"),
128
+ ) -> None:
129
+ """List orders, most recent first."""
130
+ b = _broker(db, account_id)
131
+ s = OrderStatus(status) if status else None
132
+ rows = b.get_orders(status=s, limit=limit)
133
+ if not rows:
134
+ console.print("[yellow]No orders.[/yellow]")
135
+ return
136
+ table = Table(title=f"Orders ({account_id})")
137
+ for col in ("Created", "ID", "Sym", "Side", "Qty", "Type",
138
+ "Status", "Fill Px", "Limit", "Fees", "P&L"):
139
+ table.add_column(col)
140
+ for o in rows:
141
+ table.add_row(
142
+ o.created_at.strftime("%Y-%m-%d %H:%M:%S"),
143
+ o.id,
144
+ o.symbol,
145
+ o.side.value,
146
+ f"{o.qty:g}",
147
+ o.order_type.value,
148
+ o.status.value,
149
+ f"₹{o.filled_avg_price:,.2f}" if o.filled_avg_price else "-",
150
+ f"₹{o.limit_price:,.2f}" if o.limit_price else "-",
151
+ f"₹{o.fees_paid:,.2f}",
152
+ f"₹{o.realized_pl:,.2f}",
153
+ )
154
+ console.print(table)
155
+
156
+
157
+ @app.command("cancel-all")
158
+ def cancel_all(
159
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
160
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
161
+ ) -> None:
162
+ """Cancel all pending orders."""
163
+ b = _broker(db, account_id)
164
+ n = b.cancel_all_orders()
165
+ console.print(f"[green]Cancelled {n} pending order(s).[/green]")
166
+
167
+
168
+ @app.command()
169
+ def reset(
170
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
171
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
172
+ capital: float | None = typer.Option(
173
+ None, help="Reset cash to this amount (otherwise leave cash as-is)"
174
+ ),
175
+ yes: bool = typer.Option(
176
+ False, "--yes", "-y",
177
+ help="Skip the confirmation prompt",
178
+ ),
179
+ ) -> None:
180
+ """Reset the account: clear positions, orders, trades."""
181
+ if not yes:
182
+ typer.confirm(
183
+ f"This will delete all positions, orders and trades for "
184
+ f"account '{account_id}'. Continue?",
185
+ abort=True,
186
+ )
187
+ b = _broker(db, account_id)
188
+ b.reset(initial_capital=capital)
189
+ console.print(f"[green]Account '{account_id}' reset.[/green]")
190
+
191
+
192
+ @app.command("expire-day-orders")
193
+ def expire_day_orders(
194
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
195
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
196
+ ) -> None:
197
+ """Expire all PENDING DAY-tif limit orders. Run at session close."""
198
+ b = _broker(db, account_id)
199
+ n = b.expire_stale_day_orders()
200
+ console.print(f"[green]Expired {n} DAY order(s).[/green]")
201
+
202
+
203
+ @app.command("ledger")
204
+ def ledger(
205
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
206
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
207
+ limit: int = typer.Option(50, help="Max rows to show, newest first"),
208
+ ) -> None:
209
+ """Show recent rows from the immutable cash-movement ledger."""
210
+ b = _broker(db, account_id)
211
+ movements = b.get_cash_movements(limit=limit)
212
+ if not movements:
213
+ console.print("[yellow]No cash movements.[/yellow]")
214
+ return
215
+ table = Table(title=f"Cash ledger ({account_id}, latest {len(movements)})")
216
+ for col in ("Recorded", "Reason", "Amount", "Symbol", "Order", "Notes"):
217
+ table.add_column(col)
218
+ for m in movements:
219
+ sign = "[green]" if m.amount >= 0 else "[red]"
220
+ table.add_row(
221
+ m.recorded_at.strftime("%Y-%m-%d %H:%M:%S"),
222
+ m.reason,
223
+ f"{sign}₹{m.amount:,.2f}[/]",
224
+ m.symbol or "-",
225
+ (m.order_id or "")[:8] or "-",
226
+ (m.notes or "")[:40],
227
+ )
228
+ console.print(table)
229
+
230
+
231
+ @app.command("verify-invariant")
232
+ def verify_invariant(
233
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
234
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
235
+ ) -> None:
236
+ """Assert ``account.cash == sum(cash_movements)``. Exit 0 if OK, 3 if drift."""
237
+ b = _broker(db, account_id)
238
+ if b.verify_cash_invariant():
239
+ a = b.get_account()
240
+ console.print(
241
+ f"[green]✓[/green] Cash invariant holds. "
242
+ f"Cash = ₹{a.cash:,.2f}."
243
+ )
244
+ raise typer.Exit(code=0)
245
+ a = b.get_account()
246
+ movements_sum = sum(m.amount for m in b.get_cash_movements(limit=10**9))
247
+ console.print(
248
+ f"[red]✗ Cash invariant broken![/red]\n"
249
+ f" account.cash = ₹{a.cash:,.2f}\n"
250
+ f" sum(movements) = ₹{movements_sum:,.2f}\n"
251
+ f" drift = ₹{a.cash - movements_sum:,.2f}\n"
252
+ f"This indicates a bug — file an issue."
253
+ )
254
+ raise typer.Exit(code=3)
255
+
256
+
257
+ @app.command("events")
258
+ def events(
259
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
260
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
261
+ limit: int = typer.Option(50, help="Max rows, newest first"),
262
+ event_type: str | None = typer.Option(
263
+ None, "--type",
264
+ help="Filter by event type, e.g. 'order_filled'",
265
+ ),
266
+ ) -> None:
267
+ """Recent rows from the persisted event log."""
268
+ b = _broker(db, account_id)
269
+ types = (event_type,) if event_type else None
270
+ rows = b.get_events(limit=limit, event_types=types)
271
+ if not rows:
272
+ console.print("[yellow]No events.[/yellow]")
273
+ return
274
+ table = Table(title=f"Events ({account_id}, latest {len(rows)})")
275
+ for col in ("Recorded", "Type", "Order", "Payload"):
276
+ table.add_column(col)
277
+ for e in rows:
278
+ payload_summary = ", ".join(
279
+ f"{k}={v}" for k, v in list(e.payload.items())[:3]
280
+ )
281
+ if len(e.payload) > 3:
282
+ payload_summary += " …"
283
+ table.add_row(
284
+ e.recorded_at.strftime("%Y-%m-%d %H:%M:%S"),
285
+ e.event_type,
286
+ (e.order_id or "")[:8] or "-",
287
+ payload_summary or "-",
288
+ )
289
+ console.print(table)
290
+
291
+
292
+ @app.command("phase")
293
+ def phase(
294
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
295
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
296
+ ) -> None:
297
+ """Show the current NSE session phase (live time, IST)."""
298
+ b = _broker(db, account_id)
299
+ p = b.current_session_phase()
300
+ next_open = b.calendar.next_open()
301
+ console.print(
302
+ f"Current phase: [cyan]{p.value}[/cyan]\n"
303
+ f"Next REGULAR open: {next_open.isoformat()}"
304
+ )
305
+
306
+
307
+ @app.command("status")
308
+ def status(
309
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
310
+ account_id: str = typer.Option("default", "--account", help="Account ID"),
311
+ ledger_rows: int = typer.Option(5, help="Recent ledger rows to show"),
312
+ event_rows: int = typer.Option(5, help="Recent events to show"),
313
+ ) -> None:
314
+ """Consolidated audit panel: account + positions + ledger + events + invariant.
315
+
316
+ One command instead of five. Use this as the first thing you run
317
+ when something looks wrong; everything you'd want to inspect at a
318
+ glance is here.
319
+
320
+ Exit code is 0 normally, 3 if the cash invariant is broken — same
321
+ contract as ``verify-invariant`` so this command can also be used
322
+ in a cron / health-check.
323
+ """
324
+ b = _broker(db, account_id)
325
+
326
+ # Account summary
327
+ a = b.get_account()
328
+ acct = Table(title=f"Account {a.account_id}", show_header=False)
329
+ acct.add_column("k", style="cyan")
330
+ acct.add_column("v", justify="right")
331
+ for k, v in (
332
+ ("Equity", f"₹{a.equity:,.2f}"),
333
+ ("Cash", f"₹{a.cash:,.2f}"),
334
+ ("Portfolio value", f"₹{a.portfolio_value:,.2f}"),
335
+ ("Buying power", f"₹{a.buying_power:,.2f}"),
336
+ ("Realized P&L", f"₹{a.realized_pl_total:,.2f}"),
337
+ ("Unrealized P&L", f"₹{a.unrealized_pl_total:,.2f}"),
338
+ ("Phase", b.current_session_phase().value),
339
+ ):
340
+ acct.add_row(k, v)
341
+ console.print(acct)
342
+
343
+ # Positions
344
+ pos_list = b.get_positions()
345
+ if pos_list:
346
+ pt = Table(title=f"Open positions ({len(pos_list)})")
347
+ for col in ("Symbol", "Qty", "Avg cost", "Mkt", "Unrealized P&L", "Stale?"):
348
+ pt.add_column(col)
349
+ for p in pos_list:
350
+ pt.add_row(
351
+ p.symbol,
352
+ f"{p.qty:g}",
353
+ f"₹{p.avg_cost:,.2f}",
354
+ f"₹{p.current_price:,.2f}",
355
+ f"₹{p.unrealized_pl:,.2f} ({p.unrealized_pl_percent:+.2f}%)",
356
+ "yes" if p.current_price_stale else "no",
357
+ )
358
+ console.print(pt)
359
+ else:
360
+ console.print("[yellow]No open positions.[/yellow]")
361
+
362
+ # Ledger tail
363
+ movements = b.get_cash_movements(limit=ledger_rows)
364
+ if movements:
365
+ lt = Table(title=f"Ledger (latest {len(movements)})")
366
+ for col in ("Recorded", "Reason", "Amount", "Symbol"):
367
+ lt.add_column(col)
368
+ for m in movements:
369
+ sign = "[green]" if m.amount >= 0 else "[red]"
370
+ lt.add_row(
371
+ m.recorded_at.strftime("%Y-%m-%d %H:%M:%S"),
372
+ m.reason,
373
+ f"{sign}₹{m.amount:,.2f}[/]",
374
+ m.symbol or "-",
375
+ )
376
+ console.print(lt)
377
+
378
+ # Events tail
379
+ evs = b.get_events(limit=event_rows)
380
+ if evs:
381
+ et = Table(title=f"Events (latest {len(evs)})")
382
+ for col in ("Recorded", "Type", "Order"):
383
+ et.add_column(col)
384
+ for e in evs:
385
+ et.add_row(
386
+ e.recorded_at.strftime("%Y-%m-%d %H:%M:%S"),
387
+ e.event_type,
388
+ (e.order_id or "")[:8] or "-",
389
+ )
390
+ console.print(et)
391
+
392
+ # Invariant check
393
+ if b.verify_cash_invariant():
394
+ console.print("[green]✓ Cash invariant holds.[/green]")
395
+ else:
396
+ movements_sum = sum(m.amount for m in b.get_cash_movements(limit=10**9))
397
+ console.print(
398
+ f"[red]✗ Cash invariant broken![/red] "
399
+ f"cash=₹{a.cash:,.2f} sum(movements)=₹{movements_sum:,.2f} "
400
+ f"drift=₹{a.cash - movements_sum:,.2f}"
401
+ )
402
+ raise typer.Exit(code=3)
403
+
404
+
405
+ @app.command("create-account")
406
+ def create_account(
407
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
408
+ account_id: str = typer.Option(..., "--account", help="Account ID"),
409
+ capital: float = typer.Option(
410
+ 1_000_000.0, help="Initial cash for the new account",
411
+ ),
412
+ ) -> None:
413
+ """Create a new paper-trading account."""
414
+ # strict_open=False here is the *one* command that legitimately
415
+ # creates accounts.
416
+ b = _broker(db, account_id, strict_open=False)
417
+ a = b.get_account()
418
+ console.print(
419
+ f"[green]Account '{a.account_id}' ready with "
420
+ f"₹{a.cash:,.2f} cash.[/green]"
421
+ )
422
+
423
+
424
+ @app.command("migrate")
425
+ def migrate(
426
+ db: str = typer.Option("data/india_paper.db", help="SQLite DB path"),
427
+ ) -> None:
428
+ """Run any pending schema migrations.
429
+
430
+ Operates at the *file* level — there's no account scope on
431
+ migrations. ``Persistence.__init__`` already runs migrations on
432
+ every connect, so this command is mainly useful for:
433
+
434
+ - Inspecting which migrations would run before opening the broker.
435
+ - Pre-warming a DB during deployment without instantiating a
436
+ broker.
437
+ - Recovering after a partial deploy where migrations weren't
438
+ applied.
439
+
440
+ Exits 0 on success (whether anything ran or not). Exits non-zero
441
+ only if migrations themselves raise.
442
+ """
443
+ import sqlite3
444
+
445
+ from .infrastructure.migrations import (
446
+ applied_version,
447
+ current_version,
448
+ run_migrations,
449
+ )
450
+
451
+ raw = sqlite3.connect(db)
452
+ raw.row_factory = sqlite3.Row
453
+ try:
454
+ before = applied_version(raw)
455
+ target = current_version()
456
+ if before == target:
457
+ console.print(
458
+ f"[green]✓[/green] Database at {db!r} is already at "
459
+ f"schema version {target}. Nothing to do."
460
+ )
461
+ return
462
+
463
+ applied = run_migrations(raw)
464
+ after = applied_version(raw)
465
+ console.print(
466
+ f"[green]✓[/green] Migrated {db!r} from v{before} to v{after}.\n"
467
+ f" Applied: {applied}"
468
+ )
469
+ finally:
470
+ raw.close()
471
+
472
+
473
+ if __name__ == "__main__": # pragma: no cover
474
+ app()
@@ -0,0 +1,29 @@
1
+ """Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.clock`.
2
+
3
+ Importing from here still works during the deprecation window but emits
4
+ a :class:`DeprecationWarning`. Update imports to the new path; this
5
+ shim will be removed in v0.3.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import warnings as _warnings
11
+
12
+ _warnings.warn(
13
+ "papertrade_india.clock is deprecated; "
14
+ "import from papertrade_india.infrastructure.clock instead.",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ import papertrade_india.infrastructure.clock as _src # noqa: E402
20
+ from papertrade_india.infrastructure.clock import * # noqa: E402, F401, F403
21
+
22
+ # Re-export every attribute defined on the new module — including
23
+ # underscore-prefixed names — so callers that imported private symbols
24
+ # during the refactor window keep working. Dunders are skipped.
25
+ globals().update(
26
+ {name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
27
+ )
28
+
29
+ del _src, _warnings
@@ -0,0 +1,10 @@
1
+ """Corporate actions: splits, bonuses, rights, dividends.
2
+
3
+ The ``store`` module exposes the persistence record type
4
+ (``CorporateAction``) and CRUD helpers; sibling modules implement the
5
+ position/cash adjustments for each action type.
6
+ """
7
+
8
+ from .store import CorporateAction
9
+
10
+ __all__ = ["CorporateAction"]
@@ -0,0 +1,105 @@
1
+ """Bonus issue corporate action.
2
+
3
+ A bonus issue gives ``num`` extra shares per ``den`` held — economically
4
+ equivalent to a ``(num + den) : den`` split but recorded with
5
+ ``action_type='bonus'`` so the audit trail stays distinct.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from fractions import Fraction
12
+ from typing import TYPE_CHECKING
13
+
14
+ from . import store as _store
15
+
16
+ if TYPE_CHECKING: # pragma: no cover
17
+ from .._context import BrokerContext
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def apply(
23
+ ctx: BrokerContext,
24
+ symbol: str,
25
+ ratio_num: int,
26
+ ratio_den: int = 1,
27
+ ex_date: str | None = None,
28
+ notes: str | None = None,
29
+ ) -> str:
30
+ """Apply a bonus issue to the broker's holding.
31
+
32
+ Bonus issue economics: holders receive ``ratio_num`` extra shares per
33
+ ``ratio_den`` held. A 1:1 bonus doubles holdings (one new share per
34
+ one held). A 1:2 bonus gives one new share for every two — total
35
+ holding becomes 1.5x.
36
+
37
+ Mathematically equivalent to a ``(num + den) : den`` split:
38
+ ``new_qty = old_qty * (num + den) / den``, with avg_cost adjusted to
39
+ preserve total cost basis.
40
+
41
+ Returns the action id. Idempotency is *not* enforced.
42
+ """
43
+ if ratio_num <= 0 or ratio_den <= 0:
44
+ raise ValueError("ratio components must be positive integers")
45
+ bonus_ratio = Fraction(ratio_num, ratio_den)
46
+ # Split-equivalent: shares grow by (num + den) / den.
47
+ split_equiv = Fraction(ratio_num + ratio_den, ratio_den)
48
+ ex_date = ex_date or ctx.clock.now().date().isoformat()
49
+ now = ctx.now_iso()
50
+
51
+ with ctx.persistence.transaction() as conn:
52
+ action_id = _store.record_bonus(
53
+ conn,
54
+ symbol=symbol,
55
+ exchange=ctx.default_exchange.value,
56
+ ratio=bonus_ratio,
57
+ ex_date=ex_date,
58
+ applied_at_iso=now,
59
+ notes=notes,
60
+ )
61
+ existing = conn.execute(
62
+ "SELECT qty, avg_cost FROM positions "
63
+ "WHERE account_id = ? AND symbol = ?",
64
+ (ctx.account_id, symbol),
65
+ ).fetchone()
66
+ if existing is None:
67
+ logger.info(
68
+ "BONUS %s %d:%d recorded; no holding to adjust",
69
+ symbol, ratio_num, ratio_den,
70
+ )
71
+ return action_id
72
+
73
+ old_qty = existing["qty"]
74
+ old_avg = existing["avg_cost"]
75
+ new_qty = old_qty * float(split_equiv)
76
+ new_avg = old_avg / float(split_equiv)
77
+ conn.execute(
78
+ "UPDATE positions SET qty = ?, avg_cost = ? "
79
+ "WHERE account_id = ? AND symbol = ?",
80
+ (new_qty, new_avg, ctx.account_id, symbol),
81
+ )
82
+ ctx.emit(
83
+ conn,
84
+ event_type="corporate_action",
85
+ payload={
86
+ "type": "bonus",
87
+ "symbol": symbol,
88
+ "ratio_num": ratio_num,
89
+ "ratio_den": ratio_den,
90
+ "ex_date": ex_date,
91
+ "old_qty": old_qty,
92
+ "new_qty": new_qty,
93
+ },
94
+ )
95
+
96
+ ctx.drain_pending_events()
97
+ logger.info(
98
+ "BONUS %s %d:%d applied to %s: %g → %g shares (avg ₹%.4f → ₹%.4f)",
99
+ symbol, ratio_num, ratio_den, ctx.account_id,
100
+ old_qty, new_qty, old_avg, new_avg,
101
+ )
102
+ return action_id
103
+
104
+
105
+ __all__ = ["apply"]