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,122 @@
1
+ """STOP_MARKET and STOP_LIMIT order lifecycle.
2
+
3
+ - :func:`queue` — persist a new PENDING stop order.
4
+ - :func:`trigger` — called by :class:`LimitOrderWatcher` when the stop
5
+ price is crossed; converts to an immediate market fill or a pending
6
+ limit order.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import uuid
13
+ from typing import TYPE_CHECKING
14
+
15
+ from ..domain.models import Order, OrderSide, OrderStatus, OrderType, ProductType
16
+ from . import state as _state
17
+
18
+ if TYPE_CHECKING: # pragma: no cover
19
+ from .._context import BrokerContext
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def queue(
25
+ ctx: BrokerContext,
26
+ symbol: str,
27
+ qty: float,
28
+ side: OrderSide,
29
+ order_type: OrderType,
30
+ stop_price: float,
31
+ limit_price: float | None,
32
+ time_in_force: str,
33
+ product_type: ProductType = ProductType.DELIVERY,
34
+ ) -> Order:
35
+ """Queue a STOP_MARKET or STOP_LIMIT order in PENDING state.
36
+
37
+ The watcher monitors the price feed each tick. When the stop is
38
+ triggered (BUY: last >= stop, SELL: last <= stop), the watcher
39
+ calls :func:`trigger`.
40
+ """
41
+ order_id = uuid.uuid4().hex[:12]
42
+ now = ctx.now_iso()
43
+ with ctx.persistence.transaction() as conn:
44
+ _state.record(
45
+ ctx, conn,
46
+ order_id=order_id, symbol=symbol, side=side, qty=qty,
47
+ order_type=order_type, status=OrderStatus.PENDING,
48
+ filled_qty=0.0, filled_avg_price=None, limit_price=limit_price,
49
+ fees_paid=0.0, realized_pl=0.0, time_in_force=time_in_force,
50
+ created_at=now, filled_at=None, stop_price=stop_price,
51
+ product_type=product_type,
52
+ )
53
+ ctx.emit(conn, event_type="order_submitted", order_id=order_id,
54
+ payload={"symbol": symbol, "side": side.value, "qty": qty,
55
+ "order_type": order_type.value,
56
+ "stop_price": stop_price, "limit_price": limit_price,
57
+ "product_type": product_type.value})
58
+ ctx.drain_pending_events()
59
+ logger.info("QUEUE STOP %s %s %s stop=₹%.2f%s",
60
+ side.value.upper(), qty, symbol, stop_price,
61
+ f" limit=₹{limit_price:.2f}" if limit_price else "")
62
+
63
+ with ctx.persistence.read() as conn:
64
+ row = conn.execute(
65
+ "SELECT * FROM orders WHERE id = ? AND account_id = ?",
66
+ (order_id, ctx.account_id),
67
+ ).fetchone()
68
+ assert row is not None
69
+ return _state.row_to_order(row)
70
+
71
+
72
+ def trigger(ctx: BrokerContext, order: Order, last_price: float) -> None:
73
+ """Convert a triggered STOP into a market or limit fill.
74
+
75
+ Called by :class:`LimitOrderWatcher`. STOP_MARKET fires immediately
76
+ at last; STOP_LIMIT becomes a regular pending LIMIT and waits for
77
+ the watcher's next pass to fill.
78
+
79
+ Race-safe: the row's status flips PENDING → working under an
80
+ UPDATE-with-WHERE-status guard. If we lose the race (concurrent
81
+ cancel), we silently skip.
82
+ """
83
+ from .market import fill_pending_market # noqa: PLC0415
84
+
85
+ now = ctx.now_iso()
86
+ if order.order_type == OrderType.STOP_MARKET:
87
+ with ctx.persistence.transaction() as conn:
88
+ cur = conn.execute(
89
+ "UPDATE orders SET triggered_at = ? "
90
+ "WHERE id = ? AND account_id = ? AND status = ?",
91
+ (now, order.id, ctx.account_id, OrderStatus.PENDING.value),
92
+ )
93
+ if cur.rowcount == 0:
94
+ return
95
+ ctx.emit(conn, event_type="stop_triggered", order_id=order.id,
96
+ payload={"stop_price": order.stop_price,
97
+ "trigger_price": last_price})
98
+ ctx.drain_pending_events()
99
+ fill_pending_market(ctx, order.id)
100
+ else: # STOP_LIMIT
101
+ with ctx.persistence.transaction() as conn:
102
+ cur = conn.execute(
103
+ "UPDATE orders SET order_type = ?, triggered_at = ? "
104
+ "WHERE id = ? AND account_id = ? AND status = ?",
105
+ (
106
+ OrderType.LIMIT.value, now, order.id,
107
+ ctx.account_id, OrderStatus.PENDING.value,
108
+ ),
109
+ )
110
+ if cur.rowcount == 0:
111
+ return
112
+ ctx.emit(conn, event_type="stop_triggered", order_id=order.id,
113
+ payload={"stop_price": order.stop_price,
114
+ "trigger_price": last_price,
115
+ "now_pending_limit": order.limit_price})
116
+ ctx.drain_pending_events()
117
+ logger.info("STOP→LIMIT %s %s @ stop=₹%.2f (limit ₹%.2f) for %s",
118
+ order.side.value.upper(), order.qty,
119
+ order.stop_price, order.limit_price, order.symbol)
120
+
121
+
122
+ __all__ = ["queue", "trigger"]
@@ -0,0 +1,385 @@
1
+ """Order submission pipeline.
2
+
3
+ :func:`submit_order` is the single entry point for ``buy()`` and
4
+ ``sell()``. It validates, checks risk and microstructure, enforces
5
+ session-phase rules, and dispatches to the right execution module.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from typing import TYPE_CHECKING
12
+
13
+ from ..domain.exceptions import (
14
+ AMOWindowClosedError,
15
+ IdempotencyConflict,
16
+ InvalidOrderError,
17
+ MarginNotSupported,
18
+ MarketClosedError,
19
+ RandomBrokerRejection,
20
+ )
21
+ from ..domain.models import Order, OrderSide, OrderType, ProductType
22
+ from ..domain.rules.risk import RiskContext
23
+ from ..domain.rules.tick_lot_band import validate_band, validate_lot, validate_tick
24
+ from ..infrastructure import idempotency as _idempotency
25
+ from ..infrastructure.market_hours import SessionPhase
26
+ from . import amo as _amo
27
+ from . import bracket as _bracket
28
+ from . import limit as _limit
29
+ from . import market as _market
30
+ from . import state as _state
31
+ from . import stop as _stop
32
+ from .book_helpers import symbol_microstructure
33
+
34
+ if TYPE_CHECKING: # pragma: no cover
35
+ from .._context import BrokerContext
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ _QTY_EPSILON = 1e-9
40
+
41
+
42
+ def submit_order(
43
+ ctx: BrokerContext,
44
+ symbol: str,
45
+ qty: float,
46
+ side: OrderSide,
47
+ order_type: OrderType,
48
+ limit_price: float | None,
49
+ time_in_force: str,
50
+ idempotency_key: str | None = None,
51
+ stop_price: float | None = None,
52
+ target_price: float | None = None,
53
+ product_type: ProductType = ProductType.DELIVERY,
54
+ ) -> Order:
55
+ """Validate, check, and dispatch an order.
56
+
57
+ Validation chain (in order):
58
+ 1. Basic parameter guards (qty, product_type, price presence)
59
+ 2. Latency + rejection simulation
60
+ 3. Idempotency replay
61
+ 4. Symbol master validation
62
+ 5. Microstructure (tick / lot / band)
63
+ 6. Risk engine
64
+ 7. TIF + session-phase rules
65
+ 8. T+1 deliverable-qty check (DELIVERY sells only)
66
+ 9. Dispatch to execution module
67
+ 10. Idempotency store
68
+ """
69
+ # ── 1. Basic guards ───────────────────────────────────────────────
70
+ if qty <= 0:
71
+ raise InvalidOrderError("qty must be positive")
72
+ if product_type in (ProductType.MARGIN, ProductType.PLEDGE):
73
+ raise MarginNotSupported(
74
+ f"product_type={product_type.value} requires margin / pledge "
75
+ "accounting which the cash-equity simulator does not model. "
76
+ "Use ProductType.DELIVERY (T+1 cash) or "
77
+ "ProductType.INTRADAY (same-day, auto-square-off).",
78
+ )
79
+ if order_type == OrderType.LIMIT and limit_price is None:
80
+ raise InvalidOrderError("limit_price required for LIMIT orders")
81
+ if order_type == OrderType.LIMIT and limit_price is not None and limit_price <= 0:
82
+ raise InvalidOrderError("limit_price must be positive")
83
+ if order_type in (OrderType.STOP_MARKET, OrderType.STOP_LIMIT):
84
+ if stop_price is None or stop_price <= 0:
85
+ raise InvalidOrderError("stop_price (positive) required for STOP orders")
86
+ if order_type == OrderType.STOP_LIMIT and (
87
+ limit_price is None or limit_price <= 0
88
+ ):
89
+ raise InvalidOrderError("limit_price required for STOP_LIMIT orders")
90
+ if order_type == OrderType.BRACKET:
91
+ if stop_price is None or target_price is None:
92
+ raise InvalidOrderError(
93
+ "BRACKET requires both stop_price and target_price"
94
+ )
95
+
96
+ # ── 2. Latency + rejection simulation ────────────────────────────
97
+ if ctx.latency_sim.enabled:
98
+ ctx.latency_sim.sleep()
99
+ if ctx.reject_sim.enabled:
100
+ scenario = ctx.reject_sim.maybe_reject()
101
+ if scenario is not None:
102
+ raise RandomBrokerRejection(
103
+ f"Simulated broker rejection: {scenario.value}"
104
+ )
105
+
106
+ # ── 3. Idempotency replay ─────────────────────────────────────────
107
+ if idempotency_key is not None:
108
+ replay = _idempotency_replay(
109
+ ctx, key=idempotency_key, side=side, symbol=symbol, qty=qty,
110
+ order_type=order_type, limit_price=limit_price,
111
+ time_in_force=time_in_force,
112
+ )
113
+ if replay is not None:
114
+ return replay
115
+
116
+ # ── 4. Symbol master ──────────────────────────────────────────────
117
+ with ctx.persistence.read() as conn:
118
+ ctx.symbol_master.validate(conn, symbol, ctx.default_exchange)
119
+
120
+ # ── 5. Microstructure ─────────────────────────────────────────────
121
+ _microstructure_check(ctx, symbol, qty, limit_price, stop_price, target_price)
122
+
123
+ # ── 6. Risk ───────────────────────────────────────────────────────
124
+ risk_price = (
125
+ limit_price if order_type == OrderType.LIMIT and limit_price is not None
126
+ else _safe_last_price_for_risk(ctx, symbol)
127
+ )
128
+ _risk_check(ctx, side, symbol, qty, risk_price)
129
+
130
+ # ── 7. TIF + session-phase rules ──────────────────────────────────
131
+ valid_tif = {"DAY", "GTT", "GTC", "AMO", "IOC"}
132
+ if time_in_force not in valid_tif:
133
+ raise InvalidOrderError(
134
+ f"Unsupported time_in_force {time_in_force!r}. "
135
+ f"Valid: {sorted(valid_tif)}"
136
+ )
137
+ if time_in_force == "IOC":
138
+ raise InvalidOrderError(
139
+ "time_in_force='IOC' is reserved and not yet implemented. "
140
+ "Use 'DAY' for normal session orders."
141
+ )
142
+
143
+ phase = ctx.calendar.current_phase(ctx.clock.now())
144
+ is_amo = time_in_force == "AMO"
145
+
146
+ if is_amo and phase == SessionPhase.REGULAR:
147
+ raise AMOWindowClosedError(
148
+ "AMO orders cannot be submitted during the REGULAR session. "
149
+ "Submit AMOs after market close (POST_CLOSE / CLOSED) so "
150
+ "they queue for the next open. For an in-session order, "
151
+ "use time_in_force='DAY'.",
152
+ )
153
+
154
+ market_open = phase == SessionPhase.REGULAR
155
+ if (
156
+ ctx.enforce_market_hours
157
+ and not market_open
158
+ and order_type == OrderType.MARKET
159
+ and not is_amo
160
+ ):
161
+ raise MarketClosedError(
162
+ f"Cannot fill MARKET order — current phase: {phase.value}. "
163
+ f"Next REGULAR open: {ctx.calendar.next_open(ctx.clock.now())}. "
164
+ f"Use time_in_force='AMO' to queue for the next session, "
165
+ f"or a LIMIT order during PRE_OPEN.",
166
+ )
167
+
168
+ # ── 8. T+1 deliverable-qty check ─────────────────────────────────
169
+ from ..execution.settlement import SettlementMode # noqa: PLC0415
170
+
171
+ if (
172
+ side == OrderSide.SELL
173
+ and product_type == ProductType.DELIVERY
174
+ and ctx.settlement.mode == SettlementMode.T_PLUS_1
175
+ ):
176
+ _t_plus_1_sellable_check(ctx, symbol, qty)
177
+
178
+ # ── 9. Dispatch ───────────────────────────────────────────────────
179
+ if order_type == OrderType.MARKET:
180
+ if is_amo:
181
+ order = _amo.queue(ctx, symbol, qty, side, time_in_force, product_type)
182
+ else:
183
+ order = _market.execute(ctx, symbol, qty, side, time_in_force,
184
+ product_type=product_type)
185
+ elif order_type == OrderType.LIMIT:
186
+ assert limit_price is not None
187
+ order = _limit.queue(ctx, symbol, qty, side, limit_price, time_in_force,
188
+ product_type=product_type)
189
+ elif order_type in (OrderType.STOP_MARKET, OrderType.STOP_LIMIT):
190
+ assert stop_price is not None
191
+ order = _stop.queue(ctx, symbol, qty, side, order_type, stop_price,
192
+ limit_price, time_in_force, product_type=product_type)
193
+ else: # BRACKET
194
+ assert stop_price is not None and target_price is not None
195
+ order = _bracket.queue(ctx, symbol, qty, side, limit_price, stop_price,
196
+ target_price, time_in_force,
197
+ product_type=product_type)
198
+
199
+ # ── 10. Idempotency store ─────────────────────────────────────────
200
+ if idempotency_key is not None:
201
+ _idempotency_store(ctx, key=idempotency_key, order_id=order.id,
202
+ side=side, symbol=symbol, qty=qty,
203
+ order_type=order_type, limit_price=limit_price,
204
+ time_in_force=time_in_force)
205
+
206
+ return order
207
+
208
+
209
+ # ── Private helpers ───────────────────────────────────────────────────
210
+
211
+
212
+ def _idempotency_replay(
213
+ ctx: BrokerContext,
214
+ key: str,
215
+ side: OrderSide,
216
+ symbol: str,
217
+ qty: float,
218
+ order_type: OrderType,
219
+ limit_price: float | None,
220
+ time_in_force: str,
221
+ ) -> Order | None:
222
+ with ctx.persistence.read() as conn:
223
+ entry = _idempotency.lookup(conn, ctx.account_id, key)
224
+ if entry is None:
225
+ return None
226
+
227
+ rh = _idempotency.hash_request(
228
+ side=side.value, symbol=symbol, qty=qty,
229
+ order_type=order_type.value, limit_price=limit_price,
230
+ time_in_force=time_in_force,
231
+ )
232
+ if entry.request_hash != rh:
233
+ raise IdempotencyConflict(
234
+ f"Idempotency key {key!r} was previously used with "
235
+ f"different parameters. Use a fresh key for new requests."
236
+ )
237
+
238
+ with ctx.persistence.read() as conn:
239
+ row = conn.execute(
240
+ "SELECT * FROM orders WHERE id = ? AND account_id = ?",
241
+ (entry.order_id, ctx.account_id),
242
+ ).fetchone()
243
+ if row is None:
244
+ logger.warning(
245
+ "Idempotency key %s pointed at missing order %s; replaying as new",
246
+ key, entry.order_id,
247
+ )
248
+ return None
249
+ order = _state.row_to_order(row)
250
+ logger.debug("Idempotency replay: key=%s -> order=%s", key, order.id)
251
+ return order
252
+
253
+
254
+ def _idempotency_store(
255
+ ctx: BrokerContext,
256
+ key: str,
257
+ order_id: str,
258
+ side: OrderSide,
259
+ symbol: str,
260
+ qty: float,
261
+ order_type: OrderType,
262
+ limit_price: float | None,
263
+ time_in_force: str,
264
+ ) -> None:
265
+ rh = _idempotency.hash_request(
266
+ side=side.value, symbol=symbol, qty=qty,
267
+ order_type=order_type.value, limit_price=limit_price,
268
+ time_in_force=time_in_force,
269
+ )
270
+ with ctx.persistence.transaction() as conn:
271
+ _idempotency.store(conn, ctx.account_id, key, rh, order_id,
272
+ ctx.now_iso())
273
+
274
+
275
+ def _safe_last_price_for_risk(ctx: BrokerContext, symbol: str) -> float:
276
+ """Best-effort price for risk-cap math. Falls back to 0.0."""
277
+ try:
278
+ return ctx.price_feed.get_price(symbol)
279
+ except Exception as e: # noqa: BLE001
280
+ logger.debug("Risk pre-check: price unavailable for %s: %s", symbol, e)
281
+ return 0.0
282
+
283
+
284
+ def _risk_check(
285
+ ctx: BrokerContext,
286
+ side: OrderSide,
287
+ symbol: str,
288
+ qty: float,
289
+ price_for_check: float,
290
+ ) -> None:
291
+ existing_qty = 0.0
292
+ existing_avg = 0.0
293
+ with ctx.persistence.read() as conn:
294
+ row = conn.execute(
295
+ "SELECT qty, avg_cost FROM positions "
296
+ "WHERE account_id = ? AND symbol = ?",
297
+ (ctx.account_id, symbol),
298
+ ).fetchone()
299
+ if row is not None:
300
+ existing_qty = row["qty"]
301
+ existing_avg = row["avg_cost"]
302
+ equity_row = conn.execute(
303
+ "SELECT cash FROM account WHERE account_id = ?",
304
+ (ctx.account_id,),
305
+ ).fetchone()
306
+ cash = equity_row["cash"] if equity_row else 0.0
307
+ equity = cash + existing_qty * existing_avg
308
+
309
+ risk_ctx = RiskContext(
310
+ side=side, symbol=symbol, qty=qty, price=price_for_check,
311
+ existing_qty=existing_qty, existing_avg_cost=existing_avg, equity=equity,
312
+ )
313
+ try:
314
+ ctx.risk_engine.check(risk_ctx)
315
+ except Exception as e:
316
+ with ctx.persistence.transaction() as conn:
317
+ ctx.emit(conn, event_type="order_rejected",
318
+ payload={"symbol": symbol, "side": side.value, "qty": qty,
319
+ "reason": type(e).__name__, "detail": str(e)})
320
+ ctx.drain_pending_events()
321
+ raise
322
+
323
+
324
+ def _microstructure_check(
325
+ ctx: BrokerContext,
326
+ symbol: str,
327
+ qty: float,
328
+ limit_price: float | None,
329
+ stop_price: float | None,
330
+ target_price: float | None,
331
+ ) -> None:
332
+ cfg = ctx.microstructure_config
333
+ tick, lot, band_pct = symbol_microstructure(ctx, symbol)
334
+
335
+ if cfg.enforce_tick_size:
336
+ for label, p in (
337
+ ("limit_price", limit_price),
338
+ ("stop_price", stop_price),
339
+ ("target_price", target_price),
340
+ ):
341
+ validate_tick(p, tick, label)
342
+
343
+ if cfg.enforce_lot_size:
344
+ validate_lot(qty, lot)
345
+
346
+ if cfg.enforce_price_band and band_pct and band_pct > 0:
347
+ prev_close = _safe_prev_close(ctx, symbol)
348
+ if prev_close is not None:
349
+ for p in (limit_price, stop_price, target_price):
350
+ if p is not None:
351
+ validate_band(p, prev_close, band_pct)
352
+
353
+
354
+ def _safe_prev_close(ctx: BrokerContext, symbol: str) -> float | None:
355
+ try:
356
+ mq = ctx.price_feed.get_market_quote(symbol)
357
+ except Exception as e: # noqa: BLE001
358
+ logger.debug("prev_close unavailable for %s: %s", symbol, e)
359
+ return None
360
+ return mq.prev_close
361
+
362
+
363
+ def _t_plus_1_sellable_check(ctx: BrokerContext, symbol: str, qty: float) -> None:
364
+ from ..domain.exceptions import InsufficientSharesError # noqa: PLC0415
365
+
366
+ with ctx.persistence.read() as conn:
367
+ row = conn.execute(
368
+ "SELECT qty FROM positions WHERE account_id = ? AND symbol = ?",
369
+ (ctx.account_id, symbol),
370
+ ).fetchone()
371
+ held = float(row["qty"]) if row else 0.0
372
+ sellable = ctx.settlement.deliverable_qty(
373
+ conn, account_id=ctx.account_id, symbol=symbol,
374
+ position_qty=held, as_of=ctx.clock.now().date(),
375
+ )
376
+ if qty > sellable + _QTY_EPSILON:
377
+ raise InsufficientSharesError(
378
+ f"Only {sellable:g} share(s) of {symbol} are deliverable "
379
+ f"today (held={held:g}, in-flight T+1 buys reduce it). "
380
+ f"Use product_type=ProductType.INTRADAY for same-day "
381
+ f"round-trips, or wait for settlement.",
382
+ )
383
+
384
+
385
+ __all__ = ["submit_order"]
@@ -0,0 +1,29 @@
1
+ """Deprecated re-export shim — module moved to :mod:`papertrade_india.orders.partial_fills`.
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.partial_fills is deprecated; "
14
+ "import from papertrade_india.orders.partial_fills instead.",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ import papertrade_india.orders.partial_fills as _src # noqa: E402
20
+ from papertrade_india.orders.partial_fills 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,29 @@
1
+ """Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.persistence`.
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.persistence is deprecated; "
14
+ "import from papertrade_india.infrastructure.persistence instead.",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ import papertrade_india.infrastructure.persistence as _src # noqa: E402
20
+ from papertrade_india.infrastructure.persistence 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,29 @@
1
+ """Deprecated re-export shim — module moved to :mod:`papertrade_india.orders.preopen`.
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.preopen is deprecated; "
14
+ "import from papertrade_india.orders.preopen instead.",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ import papertrade_india.orders.preopen as _src # noqa: E402
20
+ from papertrade_india.orders.preopen 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