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,176 @@
1
+ """Latency + rejection simulation.
2
+
3
+ Real broker APIs aren't deterministic. They:
4
+ - Take 50–500ms to acknowledge an order (more on a bad day).
5
+ - Sporadically reject orders for non-business reasons (network, throttle,
6
+ exchange freeze quantity, scrip just suspended, OFS window, …).
7
+
8
+ This module lets you opt into both, so agent tests can confirm their
9
+ code handles a slow / flaky broker without ever touching a real one.
10
+
11
+ Usage:
12
+
13
+ broker = IndiaPaperBroker(
14
+ latency_config=LatencyConfig(submit_ms_mean=80, submit_ms_p99=400),
15
+ rejection_config=RejectionConfig(
16
+ rate=0.001,
17
+ scenarios=[RejectScenario.FREEZE_QTY, RejectScenario.NETWORK],
18
+ ),
19
+ )
20
+
21
+ Defaults are off (zero latency, zero rejection rate) so existing tests
22
+ and behavior are unchanged.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ import random
29
+ import time
30
+ from dataclasses import dataclass, field
31
+ from enum import Enum
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ # ── Latency ──────────────────────────────────────────────────────────
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class LatencyConfig:
41
+ """Approximate the wall-clock delay of a real broker submit.
42
+
43
+ We model latency as a log-normal so the tail behaves like real
44
+ broker submit latencies (occasional 1s outliers on top of an 80ms
45
+ median). All times in milliseconds.
46
+
47
+ Defaults assume a typical Indian discount broker (Zerodha,
48
+ Upstox, Groww) on a healthy network: median ~80ms, p99 ~400ms.
49
+ Set ``submit_ms_mean=0`` to disable for deterministic backtests.
50
+
51
+ The default seed is fixed so the simulator is reproducible across
52
+ runs. Set ``seed=None`` for non-deterministic latency.
53
+ """
54
+
55
+ submit_ms_mean: float = 80.0
56
+ submit_ms_p99: float = 400.0
57
+ seed: int | None = 42
58
+
59
+
60
+ class LatencySimulator:
61
+ """Sleeps the calling thread by a sampled latency."""
62
+
63
+ def __init__(self, config: LatencyConfig | None = None) -> None:
64
+ self.config = config or LatencyConfig()
65
+ self._rng = random.Random(self.config.seed)
66
+
67
+ @property
68
+ def enabled(self) -> bool:
69
+ return self.config.submit_ms_mean > 0
70
+
71
+ def sample_ms(self) -> float:
72
+ """Draw a single latency in milliseconds."""
73
+ cfg = self.config
74
+ if cfg.submit_ms_mean <= 0:
75
+ return 0.0
76
+ if cfg.submit_ms_p99 <= cfg.submit_ms_mean:
77
+ # Degenerate inputs — fall back to constant latency.
78
+ return cfg.submit_ms_mean
79
+ # Log-normal calibrated so mean ≈ submit_ms_mean and 99th
80
+ # percentile ≈ submit_ms_p99. Solve for mu/sigma.
81
+ # mu = ln(mean) - sigma^2 / 2
82
+ # p99 = exp(mu + 2.326 * sigma)
83
+ # Solve numerically (cheap, runs once per call).
84
+ import math
85
+ mean = cfg.submit_ms_mean
86
+ p99 = cfg.submit_ms_p99
87
+ # Crude bisection on sigma.
88
+ lo, hi = 0.01, 3.0
89
+ for _ in range(50):
90
+ sigma = (lo + hi) / 2.0
91
+ mu = math.log(mean) - sigma * sigma / 2.0
92
+ est_p99 = math.exp(mu + 2.326 * sigma)
93
+ if est_p99 < p99:
94
+ lo = sigma
95
+ else:
96
+ hi = sigma
97
+ sigma = (lo + hi) / 2.0
98
+ mu = math.log(mean) - sigma * sigma / 2.0
99
+ return self._rng.lognormvariate(mu, sigma)
100
+
101
+ def sleep(self) -> float:
102
+ """Sample and sleep. Returns the actual delay in ms."""
103
+ if not self.enabled:
104
+ return 0.0
105
+ ms = max(0.0, self.sample_ms())
106
+ time.sleep(ms / 1000.0)
107
+ return ms
108
+
109
+
110
+ # ── Rejection scenarios ──────────────────────────────────────────────
111
+
112
+
113
+ class RejectScenario(str, Enum):
114
+ """Why a real broker might bounce an order back at you.
115
+
116
+ Documented for callers' reference; the simulator uses these as
117
+ string codes attached to the rejection.
118
+ """
119
+
120
+ NETWORK = "network" # transient connectivity blip
121
+ THROTTLED = "throttled" # broker rate-limit hit
122
+ FREEZE_QTY = "freeze_qty" # exchange freeze qty exceeded
123
+ SCRIP_SUSPENDED = "scrip_suspended"
124
+ AUCTION_WINDOW = "auction_window"
125
+ OFS_WINDOW = "ofs_window"
126
+ UNKNOWN = "unknown"
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class RejectionConfig:
131
+ """Probabilistic rejection injection.
132
+
133
+ ``rate`` is per-order. ``scenarios`` weights which scenario gets
134
+ chosen on a hit (uniform over the list).
135
+
136
+ Default rate is ``0.001`` (1 in 1000) — small enough that day-to-day
137
+ flows look normal, frequent enough that an agent run of any length
138
+ will see at least one rejection and have to handle it. Set
139
+ ``rate=0`` if you want a deterministic backtest.
140
+
141
+ The default seed is fixed so simulator runs are reproducible.
142
+ """
143
+
144
+ rate: float = 0.001
145
+ scenarios: list[RejectScenario] = field(
146
+ default_factory=lambda: [
147
+ RejectScenario.NETWORK,
148
+ RejectScenario.THROTTLED,
149
+ RejectScenario.FREEZE_QTY,
150
+ ],
151
+ )
152
+ seed: int | None = 42
153
+
154
+
155
+ class RejectionSimulator:
156
+ """Coin-flip rejection injector. Independent RNG so it's reproducible."""
157
+
158
+ def __init__(self, config: RejectionConfig | None = None) -> None:
159
+ self.config = config or RejectionConfig()
160
+ self._rng = random.Random(self.config.seed)
161
+
162
+ @property
163
+ def enabled(self) -> bool:
164
+ return self.config.rate > 0 and bool(self.config.scenarios)
165
+
166
+ def maybe_reject(self) -> RejectScenario | None:
167
+ """Return a scenario to reject with, or ``None`` to allow.
168
+
169
+ Caller raises :class:`RandomBrokerRejection` with the returned
170
+ scenario as context.
171
+ """
172
+ if not self.enabled:
173
+ return None
174
+ if self._rng.random() >= self.config.rate:
175
+ return None
176
+ return self._rng.choice(self.config.scenarios)
@@ -0,0 +1,120 @@
1
+ """Slippage model.
2
+
3
+ The simplest realistic-enough model: fill at ``last_price * (1 ± bps/10000)``,
4
+ where ``bps`` is the configured slippage (default 5 bps = 0.05%). Buys pay
5
+ *above* last (impact + half-spread); sells receive *below* last.
6
+
7
+ This is intentionally simple: a single-knob model that makes paper P&L
8
+ land closer to reality without requiring per-symbol bid/ask data. For
9
+ liquid NSE mid/large caps with daily-cadence trading, 3–10 bps is
10
+ realistic; tune ``SlippageConfig.bps`` to match your strategy's fills.
11
+
12
+ Per-symbol overrides
13
+ --------------------
14
+ ``SlippageConfig.per_symbol_bps`` lets you override the default for
15
+ specific tickers — e.g. illiquid micro-caps deserve 25–50 bps even when
16
+ mid-caps trade at 5. The override is still a configured knob, not real
17
+ bid/ask data. Use it to encode your *belief* about per-symbol liquidity.
18
+
19
+ Limit orders use a different rule:
20
+ - BUY limit: fills at ``min(limit_price, last + slippage)``. The slippage
21
+ bound prevents an instant-fill of a stale-aggressive limit at the full
22
+ limit price when the market is well below it; with ``bps=0`` the legacy
23
+ "fill at last_price when market crosses" behavior is preserved.
24
+ - SELL limit: fills at ``max(limit_price, last - slippage)``.
25
+
26
+ Set ``bps=0`` and an empty ``per_symbol_bps`` to disable slippage entirely.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from dataclasses import dataclass, field
32
+
33
+ from ..domain.models import OrderSide, OrderType
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class SlippageConfig:
38
+ """Configurable slippage model.
39
+
40
+ Parameters
41
+ ----------
42
+ bps:
43
+ Default basis points of slippage applied symmetrically (1 bp = 0.01%).
44
+ 5 bps is conservative for liquid NSE mid/large caps. Used when a
45
+ symbol isn't in ``per_symbol_bps``.
46
+ per_symbol_bps:
47
+ Per-symbol override map. Symbols not present use ``bps``. Values
48
+ are full bps (e.g. ``{"PENNYCO": 50.0}`` is 0.50%). The override
49
+ applies symmetrically to buys and sells.
50
+ apply_to_limits:
51
+ When True, limit orders also pay slippage relative to last
52
+ price (capped by the limit). Default False — most users want
53
+ limit fills at the limit price.
54
+ """
55
+
56
+ bps: float = 5.0
57
+ per_symbol_bps: dict[str, float] = field(default_factory=dict)
58
+ apply_to_limits: bool = False
59
+
60
+ def bps_for(self, symbol: str) -> float:
61
+ """Resolve the bps to apply for ``symbol``. Per-symbol wins."""
62
+ return self.per_symbol_bps.get(symbol, self.bps)
63
+
64
+
65
+ def apply_slippage(
66
+ config: SlippageConfig,
67
+ side: OrderSide,
68
+ order_type: OrderType,
69
+ last_price: float,
70
+ limit_price: float | None = None,
71
+ symbol: str | None = None,
72
+ ) -> float:
73
+ """Compute the simulated fill price for an order leg.
74
+
75
+ Parameters
76
+ ----------
77
+ config:
78
+ The slippage configuration in effect.
79
+ side:
80
+ BUY pays slippage above last; SELL pays below.
81
+ order_type:
82
+ MARKET orders always pay slippage; LIMIT orders only when
83
+ ``config.apply_to_limits`` is True.
84
+ last_price:
85
+ The price reported by the price feed.
86
+ limit_price:
87
+ Required only for LIMIT orders. Bounds the fill price.
88
+ symbol:
89
+ Optional. When provided, ``per_symbol_bps`` overrides ``bps``.
90
+
91
+ Returns
92
+ -------
93
+ The simulated fill price.
94
+ """
95
+ if last_price <= 0:
96
+ # Defensive: never produce a non-positive fill price.
97
+ raise ValueError(f"last_price must be positive, got {last_price}")
98
+
99
+ if order_type == OrderType.LIMIT and not config.apply_to_limits:
100
+ # Legacy behavior: fill at limit price when crossed. The
101
+ # broker's watcher passes ``last_price=limit_price`` in that
102
+ # case, so this branch returns it as-is.
103
+ return last_price
104
+
105
+ eff_bps = config.bps_for(symbol) if symbol is not None else config.bps
106
+ bps = max(0.0, eff_bps) / 10000.0
107
+ if side == OrderSide.BUY:
108
+ slipped = last_price * (1.0 + bps)
109
+ else:
110
+ slipped = last_price * (1.0 - bps)
111
+
112
+ if order_type == OrderType.LIMIT and limit_price is not None:
113
+ # Cap by the limit: a BUY limit will not fill *above* its limit;
114
+ # a SELL limit will not fill *below* its limit.
115
+ if side == OrderSide.BUY:
116
+ slipped = min(slipped, limit_price)
117
+ else:
118
+ slipped = max(slipped, limit_price)
119
+
120
+ return slipped
@@ -0,0 +1,29 @@
1
+ """Deprecated re-export shim — module moved to :mod:`papertrade_india.execution.fees`.
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.fees is deprecated; "
14
+ "import from papertrade_india.execution.fees instead.",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ import papertrade_india.execution.fees as _src # noqa: E402
20
+ from papertrade_india.execution.fees 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.idempotency`.
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.idempotency is deprecated; "
14
+ "import from papertrade_india.infrastructure.idempotency instead.",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ import papertrade_india.infrastructure.idempotency as _src # noqa: E402
20
+ from papertrade_india.infrastructure.idempotency 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,6 @@
1
+ """Persistence, observability, clock, and other I/O concerns.
2
+
3
+ These modules can be imported by anyone, but must only depend on
4
+ ``domain``. They are the outer ring of the application: they implement
5
+ the side effects that domain rules and use cases describe.
6
+ """
@@ -0,0 +1,123 @@
1
+ """Clock abstraction for live vs replay (backtest) mode.
2
+
3
+ By default the broker uses ``WallClock``, which delegates to
4
+ ``datetime.now(IST)``. For backtesting, pass a ``ReplayClock`` whose
5
+ "now" advances explicitly.
6
+
7
+ Why this lives in a separate module
8
+ -----------------------------------
9
+ The broker calls ``datetime.now(IST)`` in many places: order timestamps,
10
+ ledger ``recorded_at``, event ``recorded_at``, calendar phase checks,
11
+ DAY-tif expiry timestamps, idempotency cleanup, etc. Replacing every
12
+ call with ``self._clock.now()`` is a small refactor; centralizing the
13
+ implementation behind a ``Clock`` protocol keeps the broker code tidy
14
+ and lets us swap clocks at construction time.
15
+
16
+ Why we don't use ``freezegun`` or similar
17
+ -----------------------------------------
18
+ ``freezegun`` patches ``datetime.now`` globally, which is contagious
19
+ and breaks third-party libraries during tests. A first-class clock
20
+ parameter is opt-in, scoped, and explicit.
21
+
22
+ Design
23
+ ------
24
+ - ``Clock`` is a Protocol with one method: ``now() -> datetime``.
25
+ - ``WallClock(tz=IST)`` returns the wall clock in IST. It's the default.
26
+ - ``ReplayClock(start_at)`` is deterministic. Mutate via ``advance(delta)``
27
+ or ``set(dt)``.
28
+
29
+ The broker also uses the calendar to decide market-open / phase. The
30
+ calendar accepts an explicit ``dt`` argument on every method, so we
31
+ just pass ``self._clock.now()`` everywhere we used to pass nothing.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from datetime import datetime, timedelta
37
+ from typing import Protocol
38
+
39
+ from .market_hours import IST
40
+
41
+
42
+ class Clock(Protocol):
43
+ """Anything that can produce a 'now' datetime."""
44
+
45
+ def now(self) -> datetime:
46
+ ...
47
+
48
+
49
+ class WallClock:
50
+ """Live wall-clock time in the configured timezone (default: IST).
51
+
52
+ This is the broker's default. ``WallClock().now()`` is exactly
53
+ ``datetime.now(tz)``.
54
+ """
55
+
56
+ def __init__(self, tz=IST) -> None:
57
+ self.tz = tz
58
+
59
+ def now(self) -> datetime:
60
+ return datetime.now(self.tz)
61
+
62
+ def __repr__(self) -> str:
63
+ return f"WallClock(tz={self.tz})"
64
+
65
+
66
+ class ReplayClock:
67
+ """Deterministic clock for backtesting.
68
+
69
+ Starts at ``start_at`` and only advances when explicitly asked via
70
+ ``advance`` or ``set``. ``now()`` returns the current value.
71
+
72
+ Examples
73
+ --------
74
+ >>> from datetime import datetime, timedelta
75
+ >>> from papertrade_india import IST
76
+ >>> c = ReplayClock(datetime(2026, 5, 18, 10, 0, tzinfo=IST))
77
+ >>> c.now().hour
78
+ 10
79
+ >>> c.advance(timedelta(hours=2))
80
+ >>> c.now().hour
81
+ 12
82
+
83
+ Thread-safety
84
+ -------------
85
+ Single-threaded backtests are the expected use case. Concurrent
86
+ advances from multiple threads are not supported; wrap externally
87
+ with a lock if you need that.
88
+ """
89
+
90
+ def __init__(self, start_at: datetime) -> None:
91
+ if start_at.tzinfo is None:
92
+ # Coerce to IST for consistency with the rest of the package.
93
+ start_at = start_at.replace(tzinfo=IST)
94
+ self._t = start_at
95
+
96
+ def now(self) -> datetime:
97
+ return self._t
98
+
99
+ def advance(self, delta: timedelta) -> None:
100
+ """Move the clock forward by ``delta``.
101
+
102
+ Negative deltas raise ``ValueError`` — the simulator's audit log
103
+ and ledger assume monotonic time, and going backwards would
104
+ corrupt the ordering invariants.
105
+ """
106
+ if delta.total_seconds() < 0:
107
+ raise ValueError(
108
+ f"ReplayClock.advance requires non-negative delta, got {delta}"
109
+ )
110
+ self._t = self._t + delta
111
+
112
+ def set(self, dt: datetime) -> None:
113
+ """Jump to a specific datetime. Must be >= current value."""
114
+ if dt.tzinfo is None:
115
+ dt = dt.replace(tzinfo=IST)
116
+ if dt < self._t:
117
+ raise ValueError(
118
+ f"ReplayClock.set: cannot move backwards from {self._t} to {dt}"
119
+ )
120
+ self._t = dt
121
+
122
+ def __repr__(self) -> str:
123
+ return f"ReplayClock(now={self._t.isoformat()})"
@@ -0,0 +1,137 @@
1
+ """Append-only event log.
2
+
3
+ A parallel audit stream of every domain event the broker emits. This is
4
+ NOT event-sourcing — the broker still owns its state in ``account``,
5
+ ``positions``, ``orders``, etc. The event log is purely additive: a
6
+ chronological narrative of what happened, useful for replay analysis,
7
+ debugging, and post-hoc audits.
8
+
9
+ Why a separate stream from the cash ledger
10
+ ------------------------------------------
11
+ - The ledger answers "where did the cash go?" (financial truth).
12
+ - The event log answers "what did the broker do, and when?" (operational
13
+ truth — including events that don't move cash, like order placement,
14
+ cancellations, splits, kill-switch trips).
15
+
16
+ Schema
17
+ ------
18
+ Single table with a typed ``event_type``, optional ``account_id`` (some
19
+ events are not account-scoped), an ``order_id`` cross-reference, a JSON
20
+ ``payload`` blob for free-form context, and a wall-clock timestamp.
21
+
22
+ Event types defined today
23
+ -------------------------
24
+ - ``order_submitted`` — an order entered the broker (any status)
25
+ - ``order_filled`` — moved to FILLED
26
+ - ``order_cancelled`` — moved to CANCELLED
27
+ - ``order_expired`` — DAY-tif sweep moved it to EXPIRED
28
+ - ``order_rejected`` — pre-trade rejection (risk, validation, market closed)
29
+ - ``position_opened`` — first share of a symbol acquired
30
+ - ``position_closed`` — last share of a symbol disposed
31
+ - ``corporate_action`` — split or dividend applied
32
+ - ``kill_switch_tripped`` — risk engine refused an order
33
+ - ``account_reset`` — broker.reset() called
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import json
39
+ import sqlite3
40
+ import uuid
41
+ from dataclasses import dataclass
42
+ from datetime import datetime
43
+ from typing import Any
44
+
45
+ SCHEMA = """
46
+ CREATE TABLE IF NOT EXISTS events (
47
+ id TEXT PRIMARY KEY,
48
+ -- Some events (e.g. corporate_action) aren't account-scoped, so
49
+ -- this is nullable. Account-scoped events should always populate it.
50
+ account_id TEXT,
51
+ event_type TEXT NOT NULL,
52
+ -- Optional cross-reference to the order this event relates to.
53
+ order_id TEXT,
54
+ -- JSON-encoded payload for free-form context. Keep it small —
55
+ -- consumers query SQLite, not Mongo.
56
+ payload TEXT NOT NULL DEFAULT '{}',
57
+ recorded_at TEXT NOT NULL
58
+ );
59
+
60
+ CREATE INDEX IF NOT EXISTS idx_events_account_recorded
61
+ ON events(account_id, recorded_at DESC);
62
+
63
+ CREATE INDEX IF NOT EXISTS idx_events_type_recorded
64
+ ON events(event_type, recorded_at DESC);
65
+
66
+ CREATE INDEX IF NOT EXISTS idx_events_order
67
+ ON events(order_id);
68
+ """
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Event:
73
+ id: str
74
+ account_id: str | None
75
+ event_type: str
76
+ order_id: str | None
77
+ payload: dict[str, Any]
78
+ recorded_at: datetime
79
+
80
+
81
+ def emit(
82
+ conn: sqlite3.Connection,
83
+ event_type: str,
84
+ recorded_at_iso: str,
85
+ account_id: str | None = None,
86
+ order_id: str | None = None,
87
+ payload: dict[str, Any] | None = None,
88
+ ) -> str:
89
+ """Append one immutable event row. Returns the event id."""
90
+ event_id = uuid.uuid4().hex[:12]
91
+ payload_json = json.dumps(payload or {}, sort_keys=True, default=str)
92
+ conn.execute(
93
+ "INSERT INTO events "
94
+ "(id, account_id, event_type, order_id, payload, recorded_at) "
95
+ "VALUES (?, ?, ?, ?, ?, ?)",
96
+ (event_id, account_id, event_type, order_id,
97
+ payload_json, recorded_at_iso),
98
+ )
99
+ return event_id
100
+
101
+
102
+ def list_for_account(
103
+ conn: sqlite3.Connection,
104
+ account_id: str,
105
+ limit: int = 200,
106
+ event_types: tuple[str, ...] | None = None,
107
+ ) -> list[Event]:
108
+ """Recent events for an account, newest first.
109
+
110
+ ``event_types`` filters by a tuple of types when provided.
111
+ """
112
+ if event_types:
113
+ placeholders = ",".join("?" for _ in event_types)
114
+ rows = conn.execute(
115
+ f"SELECT id, account_id, event_type, order_id, payload, recorded_at "
116
+ f"FROM events WHERE account_id = ? AND event_type IN ({placeholders}) "
117
+ f"ORDER BY recorded_at DESC, id DESC LIMIT ?",
118
+ (account_id, *event_types, limit),
119
+ ).fetchall()
120
+ else:
121
+ rows = conn.execute(
122
+ "SELECT id, account_id, event_type, order_id, payload, recorded_at "
123
+ "FROM events WHERE account_id = ? "
124
+ "ORDER BY recorded_at DESC, id DESC LIMIT ?",
125
+ (account_id, limit),
126
+ ).fetchall()
127
+ return [
128
+ Event(
129
+ id=r["id"],
130
+ account_id=r["account_id"],
131
+ event_type=r["event_type"],
132
+ order_id=r["order_id"],
133
+ payload=json.loads(r["payload"]),
134
+ recorded_at=datetime.fromisoformat(r["recorded_at"]),
135
+ )
136
+ for r in rows
137
+ ]