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,274 @@
1
+ """Pre-open auction matching.
2
+
3
+ NSE runs an order-collection auction from 09:00 to 09:08 IST. During
4
+ this window:
5
+
6
+ - Buyers and sellers submit limit orders. No continuous matching.
7
+ - At 09:08 the exchange computes a single equilibrium price ("call
8
+ auction" rules).
9
+ - Orders that cross at the equilibrium price fill there. Orders that
10
+ don't cross transition to the regular session and queue normally.
11
+
12
+ Our equilibrium algorithm
13
+ -------------------------
14
+ We use the same rules NSE publishes:
15
+
16
+ 1. **Maximum executable volume**: pick the price that maximizes the
17
+ total tradeable quantity (min(buy_qty_at_price, sell_qty_at_price)).
18
+ 2. **Minimum imbalance**: among prices with equal max volume, pick the
19
+ one with the smallest |buy_qty - sell_qty|.
20
+ 3. **Tie-break by price proximity to last close**: among prices still
21
+ tied, pick the one closest to the previous day's close (which we
22
+ approximate from :attr:`MarketQuote.prev_close` or, failing that,
23
+ the current ``last`` price).
24
+ 4. **Lexicographic by price** if all else ties — pick the higher price
25
+ so buyers get filled at "their" price.
26
+
27
+ Why all-or-nothing pro-rata
28
+ ---------------------------
29
+ Real NSE pro-rates allocations among orders at each price level. We
30
+ simplify: orders at the equilibrium price (or better) fill *fully* in
31
+ order of submission until the matched volume is exhausted. The leftover
32
+ orders pass through to the regular session unchanged — they just keep
33
+ their queued state.
34
+
35
+ What this does not model
36
+ ------------------------
37
+ - Iceberg / disclosed-qty orders.
38
+ - Indicative price computation that real NSE publishes during the window.
39
+ - AON (all-or-none) and FOK (fill-or-kill) flag handling — every order
40
+ is treated as "ordinary limit, partial OK on rollover".
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import logging
46
+ from dataclasses import dataclass
47
+ from typing import TYPE_CHECKING
48
+
49
+ if TYPE_CHECKING: # pragma: no cover
50
+ from .._context import BrokerContext
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class _BookRow:
57
+ """One side of one price level in the auction book."""
58
+
59
+ price: float
60
+ qty: float
61
+ order_id: str
62
+ submission_seq: int
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class AuctionMatch:
67
+ """Result of a pre-open auction run.
68
+
69
+ Fields
70
+ ------
71
+ equilibrium_price:
72
+ The clearing price (``None`` when no overlap → no fills).
73
+ matched_volume:
74
+ Total quantity matched at the equilibrium price.
75
+ fills:
76
+ ``[(order_id, fill_qty, fill_price)]`` for every order that
77
+ partially or fully filled. Caller is responsible for applying
78
+ the fills via :meth:`IndiaPaperBroker._execute_limit_fill` or
79
+ equivalent.
80
+ """
81
+
82
+ equilibrium_price: float | None
83
+ matched_volume: float
84
+ fills: list[tuple[str, float, float]]
85
+
86
+
87
+ def compute_equilibrium(
88
+ buys: list[_BookRow],
89
+ sells: list[_BookRow],
90
+ reference_price: float | None = None,
91
+ ) -> AuctionMatch:
92
+ """Run the auction over the given two-sided book.
93
+
94
+ Parameters
95
+ ----------
96
+ buys, sells:
97
+ The collected limit orders for each side. Caller orders them by
98
+ submission time so we can assign fills first-in-first-out.
99
+ reference_price:
100
+ Used as the price-proximity tie-break (typically previous close
101
+ or current last). ``None`` falls back to the midpoint of best
102
+ bid/ask.
103
+
104
+ Returns
105
+ -------
106
+ :class:`AuctionMatch`. ``equilibrium_price`` is ``None`` when no
107
+ crossover exists (no fills happen).
108
+ """
109
+ if not buys or not sells:
110
+ return AuctionMatch(equilibrium_price=None, matched_volume=0.0, fills=[])
111
+
112
+ # Quick non-overlap check: highest buy < lowest sell ⇒ no auction match.
113
+ max_buy = max(b.price for b in buys)
114
+ min_sell = min(s.price for s in sells)
115
+ if max_buy < min_sell:
116
+ return AuctionMatch(equilibrium_price=None, matched_volume=0.0, fills=[])
117
+
118
+ # Candidate prices: every distinct limit price on either side.
119
+ candidates = sorted({b.price for b in buys} | {s.price for s in sells})
120
+
121
+ best: tuple[float, float, float, float] | None = None # (vol, -imbalance, -|p-ref|, p)
122
+ if reference_price is None:
123
+ # Midpoint of crossing range as a sane reference.
124
+ reference_price = (max_buy + min_sell) / 2.0
125
+
126
+ for p in candidates:
127
+ # Buyers willing at price p: every buy with limit >= p.
128
+ buy_vol = sum(b.qty for b in buys if b.price >= p)
129
+ # Sellers willing at price p: every sell with limit <= p.
130
+ sell_vol = sum(s.qty for s in sells if s.price <= p)
131
+ vol = min(buy_vol, sell_vol)
132
+ if vol <= 0:
133
+ continue
134
+ imbalance = abs(buy_vol - sell_vol)
135
+ proximity = abs(p - reference_price)
136
+ # Larger vol wins; smaller imbalance wins on tie; closer to ref
137
+ # wins next; higher price wins last (favors buyers).
138
+ score = (vol, -imbalance, -proximity, p)
139
+ if best is None or score > best:
140
+ best = score
141
+
142
+ if best is None:
143
+ return AuctionMatch(equilibrium_price=None, matched_volume=0.0, fills=[])
144
+ matched_volume = best[0]
145
+ equilibrium = best[3]
146
+
147
+ # Allocate fills: FIFO across buys whose limit >= equilibrium, and
148
+ # sells whose limit <= equilibrium, bounded by ``matched_volume``.
149
+ fills: list[tuple[str, float, float]] = []
150
+ eligible_buys = sorted(
151
+ (b for b in buys if b.price >= equilibrium),
152
+ key=lambda x: x.submission_seq,
153
+ )
154
+ eligible_sells = sorted(
155
+ (s for s in sells if s.price <= equilibrium),
156
+ key=lambda x: x.submission_seq,
157
+ )
158
+
159
+ remaining = matched_volume
160
+ for order in eligible_buys:
161
+ if remaining <= 0:
162
+ break
163
+ take = min(order.qty, remaining)
164
+ fills.append((order.order_id, take, equilibrium))
165
+ remaining -= take
166
+
167
+ remaining = matched_volume
168
+ for order in eligible_sells:
169
+ if remaining <= 0:
170
+ break
171
+ take = min(order.qty, remaining)
172
+ fills.append((order.order_id, take, equilibrium))
173
+ remaining -= take
174
+
175
+ return AuctionMatch(
176
+ equilibrium_price=equilibrium,
177
+ matched_volume=matched_volume,
178
+ fills=fills,
179
+ )
180
+
181
+
182
+ def run(ctx: BrokerContext) -> AuctionMatch: # type: ignore[name-defined]
183
+ """Match all PENDING limit orders for this account at the equilibrium price.
184
+
185
+ Called by the watcher at the PRE_OPEN → REGULAR transition (or
186
+ manually for tests). Implements NSE's call-auction rules: max
187
+ executable volume → min imbalance → closest to reference price →
188
+ higher price.
189
+
190
+ Returns the :class:`AuctionMatch`. ``equilibrium_price=None`` when
191
+ no overlap exists (no fills happen).
192
+
193
+ Symbol scoping: the auction runs **per symbol**. We loop over every
194
+ symbol with at least one PENDING limit on this account.
195
+ """
196
+ from ..domain.exceptions import OrderNoLongerPending # noqa: PLC0415
197
+ from ..domain.models import OrderSide, OrderStatus, OrderType # noqa: PLC0415
198
+ from . import state as _state # noqa: PLC0415
199
+ from .limit import fill as _limit_fill # noqa: PLC0415
200
+
201
+ with ctx.persistence.read() as conn:
202
+ rows = conn.execute(
203
+ "SELECT * FROM orders WHERE account_id = ? AND status = ? "
204
+ "ORDER BY created_at ASC",
205
+ (ctx.account_id, OrderStatus.PENDING.value),
206
+ ).fetchall()
207
+
208
+ all_pending = [
209
+ _state.row_to_order(r) for r in rows
210
+ if OrderType(r["order_type"]) == OrderType.LIMIT
211
+ and r["parent_order_id"] is None
212
+ and r["time_in_force"] in ("DAY", "GTT")
213
+ ]
214
+ if not all_pending:
215
+ return AuctionMatch(equilibrium_price=None, matched_volume=0.0, fills=[])
216
+
217
+ by_symbol: dict[str, list] = {}
218
+ for o in all_pending:
219
+ by_symbol.setdefault(o.symbol, []).append(o)
220
+
221
+ all_fills: list[tuple[str, float, float]] = []
222
+ total_matched = 0.0
223
+ last_price: float | None = None
224
+
225
+ for symbol, orders in by_symbol.items():
226
+ buys = [
227
+ _BookRow(
228
+ price=o.limit_price, # type: ignore[arg-type]
229
+ qty=o.qty - o.filled_qty,
230
+ order_id=o.id,
231
+ submission_seq=int(o.created_at.timestamp() * 1000),
232
+ )
233
+ for o in orders if o.side == OrderSide.BUY
234
+ ]
235
+ sells = [
236
+ _BookRow(
237
+ price=o.limit_price, # type: ignore[arg-type]
238
+ qty=o.qty - o.filled_qty,
239
+ order_id=o.id,
240
+ submission_seq=int(o.created_at.timestamp() * 1000),
241
+ )
242
+ for o in orders if o.side == OrderSide.SELL
243
+ ]
244
+ try:
245
+ ref_price = ctx.price_feed.get_price(symbol)
246
+ except Exception: # noqa: BLE001
247
+ ref_price = None
248
+
249
+ match = compute_equilibrium(buys=buys, sells=sells,
250
+ reference_price=ref_price)
251
+ if match.equilibrium_price is None:
252
+ continue
253
+ for fill_id, fill_qty, fill_price in match.fills:
254
+ with ctx.persistence.read() as conn:
255
+ row = conn.execute(
256
+ "SELECT * FROM orders WHERE id = ? AND account_id = ?",
257
+ (fill_id, ctx.account_id),
258
+ ).fetchone()
259
+ if row is None:
260
+ continue
261
+ order = _state.row_to_order(row)
262
+ try:
263
+ _limit_fill(ctx, order, fill_price, fill_qty=fill_qty)
264
+ all_fills.append((fill_id, fill_qty, fill_price))
265
+ total_matched += fill_qty
266
+ last_price = fill_price
267
+ except OrderNoLongerPending:
268
+ continue
269
+
270
+ return AuctionMatch(
271
+ equilibrium_price=last_price,
272
+ matched_volume=total_matched,
273
+ fills=all_fills,
274
+ )