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,31 @@
1
+ symbol,name,lot_size
2
+ RELIANCE,Reliance Industries,1
3
+ TCS,Tata Consultancy Services,1
4
+ HDFCBANK,HDFC Bank,1
5
+ INFY,Infosys,1
6
+ ICICIBANK,ICICI Bank,1
7
+ SBIN,State Bank of India,1
8
+ BHARTIARTL,Bharti Airtel,1
9
+ KOTAKBANK,Kotak Mahindra Bank,1
10
+ LT,Larsen & Toubro,1
11
+ HINDUNILVR,Hindustan Unilever,1
12
+ AXISBANK,Axis Bank,1
13
+ ITC,ITC Limited,1
14
+ BAJFINANCE,Bajaj Finance,1
15
+ ASIANPAINT,Asian Paints,1
16
+ MARUTI,Maruti Suzuki,1
17
+ HCLTECH,HCL Technologies,1
18
+ SUNPHARMA,Sun Pharmaceutical,1
19
+ WIPRO,Wipro,1
20
+ ULTRACEMCO,UltraTech Cement,1
21
+ TITAN,Titan Company,1
22
+ ONGC,Oil and Natural Gas Corporation,1
23
+ TATAMOTORS,Tata Motors,1
24
+ NESTLEIND,Nestle India,1
25
+ M&M,Mahindra & Mahindra,1
26
+ NTPC,NTPC,1
27
+ POWERGRID,Power Grid Corporation,1
28
+ ADANIENT,Adani Enterprises,1
29
+ JSWSTEEL,JSW Steel,1
30
+ COALINDIA,Coal India,1
31
+ TATASTEEL,Tata Steel,1
@@ -0,0 +1,6 @@
1
+ """Pure domain layer.
2
+
3
+ Contains value types, domain exceptions, and stateless rules. No I/O,
4
+ no infrastructure dependencies. Anything in this package must be safe
5
+ to load standalone, with zero internal imports from sibling subsystems.
6
+ """
@@ -0,0 +1,183 @@
1
+ """Domain exceptions for the India paper broker.
2
+
3
+ Every exception is a subclass of ``IndiaPaperBrokerError`` so callers can
4
+ catch broadly when they don't care about the specific failure, or narrowly
5
+ when they do (e.g. retry on ``PriceUnavailableError`` but reject on
6
+ ``InsufficientFundsError``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+
12
+ class IndiaPaperBrokerError(Exception):
13
+ """Base for all paper broker errors."""
14
+
15
+
16
+ class InsufficientFundsError(IndiaPaperBrokerError):
17
+ """Tried to buy more than available cash allows (incl. fees)."""
18
+
19
+
20
+ class InsufficientSharesError(IndiaPaperBrokerError):
21
+ """Tried to sell more shares than held."""
22
+
23
+
24
+ class MarketClosedError(IndiaPaperBrokerError):
25
+ """Tried to submit a market order outside NSE trading hours."""
26
+
27
+
28
+ class InvalidOrderError(IndiaPaperBrokerError):
29
+ """Order parameters violate constraints.
30
+
31
+ Examples: non-positive qty, missing limit price on a limit order.
32
+ """
33
+
34
+
35
+ class PriceUnavailableError(IndiaPaperBrokerError):
36
+ """All price providers failed and no cached price is available."""
37
+
38
+
39
+ class StalePriceRejected(IndiaPaperBrokerError): # noqa: N818
40
+ """``enforce_fresh_prices=True`` mode rejected a fill because the
41
+ underlying price came from the long-lived cached fallback rather
42
+ than a live provider.
43
+
44
+ Use this mode for autonomous-agent deployments where you'd rather
45
+ halt than execute against a price that may be stale by minutes or
46
+ hours.
47
+
48
+ Naming: keeps ``raise StalePriceRejected`` readable; the base class
49
+ already carries the ``Error`` suffix.
50
+ """
51
+
52
+
53
+ class OrderNoLongerPending(IndiaPaperBrokerError): # noqa: N818
54
+ """Internal: a limit order moved out of PENDING between selection
55
+ and fill (e.g. user cancelled while the watcher was working).
56
+
57
+ The watcher catches this and skips the order; callers shouldn't
58
+ normally see it.
59
+
60
+ Naming: keeps the conditional read (``raise OrderNoLongerPending``)
61
+ rather than a verbose ``OrderNoLongerPendingError``. The base class
62
+ already carries the ``Error`` suffix.
63
+ """
64
+
65
+
66
+ class AccountNotFoundError(IndiaPaperBrokerError):
67
+ """Strict-open mode: tried to attach to an account that doesn't exist."""
68
+
69
+
70
+ class RiskViolation(IndiaPaperBrokerError): # noqa: N818
71
+ """A pre-trade risk control rejected the order.
72
+
73
+ Examples: order notional exceeds ``max_order_notional``, post-fill
74
+ position exceeds ``max_position_notional`` or its share-of-equity cap,
75
+ symbol not in whitelist.
76
+
77
+ Naming: keeps ``raise RiskViolation`` readable; the base class
78
+ already carries the ``Error`` suffix.
79
+ """
80
+
81
+
82
+ class KillSwitchActive(RiskViolation):
83
+ """The broker's kill switch is engaged.
84
+
85
+ Either ``RiskConfig.kill_switch=True`` or the env var
86
+ ``PAPERTRADE_INDIA_KILL_SWITCH=1``. All orders are rejected until
87
+ cleared.
88
+ """
89
+
90
+
91
+ class IdempotencyConflict(IndiaPaperBrokerError): # noqa: N818
92
+ """An idempotency key was reused with different request parameters.
93
+
94
+ Replaying with the same key + same params is fine (returns the
95
+ stored order). Replaying with the same key + different params is a
96
+ client bug — almost always a key generated too coarsely for its scope.
97
+
98
+ Naming: keeps ``raise IdempotencyConflict`` readable; the base class
99
+ already carries the ``Error`` suffix.
100
+ """
101
+
102
+
103
+ class SymbolNotFound(IndiaPaperBrokerError): # noqa: N818
104
+ """Symbol master is in strict mode and the symbol isn't registered."""
105
+
106
+
107
+ class SymbolDelisted(IndiaPaperBrokerError): # noqa: N818
108
+ """Symbol exists in the master but has been marked delisted."""
109
+
110
+
111
+ # ── Microstructure rejections ────────────────────────────────────────
112
+
113
+
114
+ class TickSizeViolation(RiskViolation):
115
+ """Limit/stop price isn't aligned to the symbol's tick size.
116
+
117
+ Real exchanges reject these outright. The simulator does the same
118
+ when ``EnforceMicrostructure(tick_size=True)`` is on (default).
119
+ """
120
+
121
+
122
+ class LotSizeViolation(RiskViolation):
123
+ """Order qty isn't a multiple of the symbol's lot size.
124
+
125
+ For cash equities this is almost always 1 (single-share orders are
126
+ legal). It matters for F&O contracts (out of scope) and the rare
127
+ cash-equity that trades in lots (e.g., some delisted scrips).
128
+ """
129
+
130
+
131
+ class PriceBandViolation(RiskViolation):
132
+ """Order would fill outside the symbol's daily price band.
133
+
134
+ NSE bands are ±5%/10%/20% off the previous day's close, set by
135
+ the exchange per scrip. Orders that would cross the band freeze
136
+ pending exchange action; here we reject pre-trade to keep the
137
+ simulator deterministic.
138
+ """
139
+
140
+
141
+ # ── Settlement ───────────────────────────────────────────────────────
142
+
143
+
144
+ class SettlementError(IndiaPaperBrokerError):
145
+ """Settlement bookkeeping failed (very rare — usually a bug)."""
146
+
147
+
148
+ # ── Random simulated rejections ──────────────────────────────────────
149
+
150
+
151
+ class RandomBrokerRejection(IndiaPaperBrokerError): # noqa: N818
152
+ """Order was rejected by the simulated broker for a non-deterministic
153
+ reason (network, throttle, freeze qty, scrip suspended, …).
154
+
155
+ Only raised when :class:`papertrade_india.RejectionConfig` is enabled
156
+ on the broker. Lets agent tests exercise reject-handling code paths
157
+ without hitting a real broker. Naming: keeps ``raise
158
+ RandomBrokerRejection`` readable; the base already carries the
159
+ ``Error`` suffix.
160
+ """
161
+
162
+
163
+ # ── Out-of-scope features ────────────────────────────────────────────
164
+
165
+
166
+ class MarginNotSupported(IndiaPaperBrokerError): # noqa: N818
167
+ """The simulator is cash-equity only; this order would require
168
+ margin or pledge accounting.
169
+
170
+ Raised whenever an order is submitted with ``ProductType.MARGIN``
171
+ or ``ProductType.PLEDGE``. Loud failure beats silent acceptance —
172
+ an agent that thinks it's running margin should know the simulator
173
+ isn't modeling its real-money risk.
174
+ """
175
+
176
+
177
+ class AMOWindowClosedError(IndiaPaperBrokerError):
178
+ """Tried to submit an AMO outside its accepted window.
179
+
180
+ Real Indian brokers accept AMO only between the post-close window
181
+ and ~08:58 IST the next morning. Submissions inside the regular
182
+ session are rejected — they should be plain MARKET / LIMIT orders.
183
+ """
@@ -0,0 +1,213 @@
1
+ """Domain models for the India paper broker.
2
+
3
+ Strict typing, immutable dataclasses (``frozen=True``). The broker mutates
4
+ state via the persistence layer — domain objects themselves are values.
5
+
6
+ These shapes are intentionally close to Alpaca's dataclasses so a caller
7
+ that consumes either type sees a familiar interface. The differences
8
+ (``exchange``, ``fees_paid``, ``realized_pl``) are India-specific
9
+ additions.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass, field
15
+ from datetime import datetime
16
+ from enum import Enum
17
+ from typing import Literal
18
+
19
+
20
+ class OrderType(str, Enum):
21
+ """Order type.
22
+
23
+ - ``MARKET``: fills instantly at last known price (slippage-adjusted).
24
+ - ``LIMIT``: queued, fills when the market crosses the limit price.
25
+ - ``STOP_MARKET``: queued, fires a market order once the stop price
26
+ is touched (BUY: when last >= stop; SELL: when last <= stop).
27
+ Used for stop-losses on long positions and breakout entries.
28
+ - ``STOP_LIMIT``: queued, fires a *limit* order once the stop price
29
+ is touched. Avoids the "stop hits and slips through bad price"
30
+ failure mode at the cost of possibly not filling at all.
31
+ - ``BRACKET``: parent order (entry as MARKET or LIMIT) plus child
32
+ stop-loss + child target. Children auto-cancel each other on
33
+ fill (OCO — One-Cancels-Other) and auto-cancel if the parent is
34
+ cancelled before fill.
35
+ """
36
+
37
+ MARKET = "market"
38
+ LIMIT = "limit"
39
+ STOP_MARKET = "stop_market"
40
+ STOP_LIMIT = "stop_limit"
41
+ BRACKET = "bracket"
42
+
43
+
44
+ class OrderSide(str, Enum):
45
+ BUY = "buy"
46
+ SELL = "sell"
47
+
48
+
49
+ class OrderStatus(str, Enum):
50
+ """Order lifecycle states.
51
+
52
+ States used today by the simulator:
53
+ - PENDING: limit order queued, awaiting price condition
54
+ - FILLED: market order or limit order completed
55
+ - CANCELLED: explicitly cancelled by the user before fill
56
+ - EXPIRED: DAY-tif limit order swept at session close
57
+
58
+ Reserved for future use (defined for forward compatibility):
59
+ - PARTIALLY_FILLED: when partial-fill modeling is added
60
+ - REJECTED: surfaced when broker-side validation rejects pre-fill
61
+ """
62
+
63
+ PENDING = "pending"
64
+ FILLED = "filled"
65
+ PARTIALLY_FILLED = "partially_filled"
66
+ CANCELLED = "cancelled"
67
+ REJECTED = "rejected"
68
+ EXPIRED = "expired"
69
+
70
+
71
+ class Exchange(str, Enum):
72
+ NSE = "NSE"
73
+ BSE = "BSE"
74
+
75
+
76
+ class ProductType(str, Enum):
77
+ """Indian retail product type, in the Zerodha/Upstox parlance.
78
+
79
+ - ``DELIVERY`` (CNC at Zerodha, D at Upstox): T+1 settlement, no
80
+ auto-square-off, attracts STT on delivery rates and DP charges.
81
+ The default for most strategies.
82
+ - ``INTRADAY`` (MIS): same-session round-trip, no DP charge, broker
83
+ auto-squares-off any open MIS positions at 15:15 IST. Modeled
84
+ via :class:`papertrade_india.SettlementEngine`.
85
+ - ``MARGIN``, ``PLEDGE``: explicit "not modeled" sentinels. The
86
+ simulator is cash-equity only; orders submitted with these
87
+ product types raise :class:`papertrade_india.MarginNotSupported`
88
+ so failures are loud rather than silent.
89
+
90
+ Out of scope: NRML (overnight derivatives), BO/CO (cover/bracket as
91
+ separate product flags — we model bracket as an order type instead),
92
+ MTF (margin trading).
93
+ """
94
+
95
+ DELIVERY = "delivery"
96
+ INTRADAY = "intraday"
97
+ MARGIN = "margin"
98
+ PLEDGE = "pledge"
99
+
100
+
101
+ class TimeInForce(str, Enum):
102
+ """Order lifetime / queueing behavior.
103
+
104
+ - ``DAY``: pending until the session ends, then expired by
105
+ :meth:`IndiaPaperBroker.expire_stale_day_orders`. The default.
106
+ - ``GTT`` (Good-Till-Triggered): NSE's persistent stop-style order
107
+ that survives across sessions. Stays PENDING across day rollovers
108
+ until the price condition triggers it or the user cancels.
109
+ Most useful with STOP_MARKET / STOP_LIMIT order types.
110
+ - ``IOC`` (Immediate-Or-Cancel): fill what's immediately available,
111
+ cancel the rest. Reserved — not yet implemented.
112
+ - ``AMO`` (After-Market Order): queues overnight. The watcher fires
113
+ it at the next session open. Supported for MARKET and LIMIT.
114
+
115
+ The string is held on :attr:`Order.time_in_force` for back-compat;
116
+ this enum is the authoritative set of values the simulator supports.
117
+ """
118
+
119
+ DAY = "DAY"
120
+ GTT = "GTT"
121
+ IOC = "IOC"
122
+ AMO = "AMO"
123
+
124
+
125
+ Currency = Literal["INR", "USD"]
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class Position:
130
+ """Open position with mark-to-market valuation."""
131
+
132
+ symbol: str
133
+ exchange: Exchange
134
+ qty: float
135
+ avg_cost: float # Per-share economic basis (INR), incl. prorated buy fees
136
+ current_price: float # Last known market price (or avg_cost if stale)
137
+ market_value: float # qty * current_price
138
+ cost_basis: float # qty * avg_cost
139
+ unrealized_pl: float # market_value - cost_basis
140
+ unrealized_pl_percent: float # (unrealized_pl / cost_basis) * 100
141
+ entry_date: datetime
142
+ # True when the price feed could not produce a fresh quote and the
143
+ # broker fell back to ``avg_cost``. Lets agents distinguish a real
144
+ # break-even position from a stale-valuation one.
145
+ current_price_stale: bool = False
146
+ # Mark-to-market basis. ``"last"`` is the historical default;
147
+ # ``"bid"`` (long) / ``"ask"`` (short) is what real brokers use to
148
+ # compute exit P&L. Set to ``"mid"`` when only mid is available.
149
+ mark_basis: str = "last"
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class Order:
154
+ """Submitted order (filled, pending, or terminal)."""
155
+
156
+ id: str
157
+ symbol: str
158
+ exchange: Exchange
159
+ side: OrderSide
160
+ qty: float
161
+ order_type: OrderType
162
+ status: OrderStatus
163
+ filled_qty: float = 0.0
164
+ filled_avg_price: float | None = None
165
+ limit_price: float | None = None
166
+ fees_paid: float = 0.0 # Total Indian fees on this order
167
+ realized_pl: float = 0.0 # Non-zero on sells (after fees, full round-trip)
168
+ time_in_force: str = "DAY"
169
+ created_at: datetime = field(default_factory=datetime.now)
170
+ filled_at: datetime | None = None
171
+ cancelled_at: datetime | None = None
172
+ expired_at: datetime | None = None
173
+ rejection_reason: str | None = None
174
+ # Stop / Bracket extensions (default ``None`` for plain MARKET/LIMIT).
175
+ stop_price: float | None = None # STOP_MARKET / STOP_LIMIT
176
+ target_price: float | None = None # BRACKET take-profit leg
177
+ parent_order_id: str | None = None # BRACKET child → parent linkage
178
+ product_type: ProductType = ProductType.DELIVERY
179
+ triggered_at: datetime | None = None # When a STOP transitioned PENDING → working
180
+
181
+
182
+ @dataclass(frozen=True)
183
+ class Account:
184
+ """Account summary: cash, holdings value, P&L."""
185
+
186
+ account_id: str
187
+ equity: float # cash + portfolio_value
188
+ cash: float
189
+ portfolio_value: float # Sum of all positions' market_value
190
+ buying_power: float # cash minus pending buy-limit notional
191
+ realized_pl_total: float # Cumulative realized P&L (after fees)
192
+ unrealized_pl_total: float # Sum across positions
193
+ currency: Currency = "INR"
194
+ updated_at: datetime = field(default_factory=datetime.now)
195
+
196
+
197
+ @dataclass(frozen=True)
198
+ class Trade:
199
+ """Atomic execution event. One order can produce multiple trades.
200
+
201
+ Currently the simulator emits exactly one trade per filled order, but
202
+ the schema is shaped for future partial-fill support.
203
+ """
204
+
205
+ id: str
206
+ order_id: str
207
+ symbol: str
208
+ side: OrderSide
209
+ qty: float
210
+ price: float
211
+ fees: float
212
+ realized_pl: float = 0.0 # Only on sells
213
+ executed_at: datetime = field(default_factory=datetime.now)
@@ -0,0 +1,5 @@
1
+ """Stateless validation rules over orders and positions.
2
+
3
+ Each rule module exposes a small, pure surface (typically a ``check`` or
4
+ ``validate`` function) that subsystems compose in order pipelines.
5
+ """
@@ -0,0 +1,165 @@
1
+ """Pre-trade risk controls.
2
+
3
+ A small set of guardrails an autonomous agent actually needs:
4
+
5
+ - **Kill switch**: a single flag (or env var ``PAPERTRADE_INDIA_KILL_SWITCH=1``)
6
+ that rejects every new order. Useful when something has clearly gone
7
+ wrong and you want trading to stop immediately without restarting the
8
+ process or recreating the broker.
9
+ - **Symbol whitelist**: when set, only listed symbols are tradeable.
10
+ ``None`` (the default) allows everything. Empty list = allow nothing,
11
+ for a "manual approval" workflow.
12
+ - **Per-order notional cap**: max INR value of any single order. Prevents
13
+ fat-finger fills.
14
+ - **Per-position notional cap**: max INR value of any single position.
15
+ Enforced post-fill (hypothetical).
16
+ - **Per-position equity-fraction cap**: position cannot exceed X% of
17
+ current equity. Same enforcement timing as the absolute cap.
18
+
19
+ Each control is independent; pass ``None`` (or omit) any field to disable.
20
+
21
+ Risk checks run inside ``IndiaPaperBroker._submit_order`` *before* market
22
+ hours / price feed / DB writes. A violation raises ``RiskViolation`` (or
23
+ ``KillSwitchActive`` for the kill switch). No state is mutated.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+ import os
30
+ from dataclasses import dataclass
31
+
32
+ from ..exceptions import KillSwitchActive, RiskViolation
33
+ from ..models import OrderSide
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ _KILL_SWITCH_ENV = "PAPERTRADE_INDIA_KILL_SWITCH"
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class RiskConfig:
43
+ """Pre-trade risk-control configuration.
44
+
45
+ All caps are in INR unless suffixed ``_pct``.
46
+ """
47
+
48
+ # Single-flip kill switch. Also honored via env var
49
+ # PAPERTRADE_INDIA_KILL_SWITCH=1.
50
+ kill_switch: bool = False
51
+
52
+ # Allow-list of tradeable symbols. ``None`` = unrestricted.
53
+ symbol_whitelist: frozenset[str] | None = None
54
+
55
+ # Reject any single order with notional (qty * price) above this cap.
56
+ # ``None`` = no cap.
57
+ max_order_notional: float | None = None
58
+
59
+ # Reject the order if the resulting position's market value would
60
+ # exceed this absolute INR cap.
61
+ max_position_notional: float | None = None
62
+
63
+ # Reject the order if the resulting position's market value would
64
+ # exceed this fraction of *current* account equity. 0.10 = 10%.
65
+ max_position_pct_of_equity: float | None = None
66
+
67
+
68
+ @dataclass
69
+ class RiskContext:
70
+ """Per-order context passed to ``RiskEngine.check``.
71
+
72
+ Held as a regular dataclass (not frozen) for ergonomic construction
73
+ in the broker.
74
+ """
75
+
76
+ side: OrderSide
77
+ symbol: str
78
+ qty: float
79
+ price: float
80
+ # Currently held qty in this symbol on this account (0 if none).
81
+ existing_qty: float = 0.0
82
+ existing_avg_cost: float = 0.0
83
+ # Account state used by equity-fraction cap.
84
+ equity: float = 0.0
85
+
86
+
87
+ class RiskEngine:
88
+ """Stateless pre-trade risk evaluator."""
89
+
90
+ def __init__(self, config: RiskConfig | None = None) -> None:
91
+ self.config = config or RiskConfig()
92
+
93
+ # ── Kill switch ────────────────────────────────────────────────────
94
+
95
+ def is_killed(self) -> bool:
96
+ if self.config.kill_switch:
97
+ return True
98
+ return os.getenv(_KILL_SWITCH_ENV, "").lower() in (
99
+ "1", "true", "yes", "on",
100
+ )
101
+
102
+ # ── Top-level check ────────────────────────────────────────────────
103
+
104
+ def check(self, ctx: RiskContext) -> None:
105
+ """Raise ``RiskViolation`` (or subclass) on violation; else return.
106
+
107
+ Order of checks is deterministic so failure modes are predictable:
108
+ kill switch first (fail fast), then whitelist (cheapest), then
109
+ notional caps in increasing complexity.
110
+ """
111
+ if self.is_killed():
112
+ raise KillSwitchActive(
113
+ "Kill switch active — all new orders are rejected. "
114
+ f"Clear via RiskConfig.kill_switch=False or unset "
115
+ f"the {_KILL_SWITCH_ENV} env var."
116
+ )
117
+
118
+ wl = self.config.symbol_whitelist
119
+ if wl is not None and ctx.symbol not in wl:
120
+ raise RiskViolation(
121
+ f"Symbol {ctx.symbol!r} is not in the whitelist "
122
+ f"({len(wl)} symbol(s) allowed)"
123
+ )
124
+
125
+ notional = ctx.qty * ctx.price
126
+ if (
127
+ self.config.max_order_notional is not None
128
+ and notional > self.config.max_order_notional
129
+ ):
130
+ raise RiskViolation(
131
+ f"Order notional ₹{notional:,.2f} exceeds cap "
132
+ f"₹{self.config.max_order_notional:,.2f}"
133
+ )
134
+
135
+ # Position-level caps only apply on buys (sells reduce exposure).
136
+ if ctx.side == OrderSide.BUY:
137
+ self._check_post_fill_position(ctx)
138
+
139
+ # ── Helpers ────────────────────────────────────────────────────────
140
+
141
+ def _check_post_fill_position(self, ctx: RiskContext) -> None:
142
+ """Compute the hypothetical post-fill position value and apply caps."""
143
+ post_qty = ctx.existing_qty + ctx.qty
144
+ # Use the fill price as a proxy for post-fill mark-to-market.
145
+ # Slightly conservative (ignores the fact that other holdings
146
+ # have moved since their entry), but it's a pre-trade check —
147
+ # exactness isn't worth the round-trip cost.
148
+ post_value = post_qty * ctx.price
149
+
150
+ cap_abs = self.config.max_position_notional
151
+ if cap_abs is not None and post_value > cap_abs:
152
+ raise RiskViolation(
153
+ f"Position value would be ₹{post_value:,.2f} after fill, "
154
+ f"exceeding cap ₹{cap_abs:,.2f}"
155
+ )
156
+
157
+ cap_pct = self.config.max_position_pct_of_equity
158
+ if cap_pct is not None and ctx.equity > 0:
159
+ limit = ctx.equity * cap_pct
160
+ if post_value > limit:
161
+ raise RiskViolation(
162
+ f"Position value would be ₹{post_value:,.2f} after fill, "
163
+ f"exceeding {cap_pct * 100:.1f}% of equity "
164
+ f"(₹{limit:,.2f}). Equity = ₹{ctx.equity:,.2f}."
165
+ )