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,180 @@
1
+ """Alpha Vantage provider — REST API, free tier (5 req/min).
2
+
3
+ API key from env var ``ALPHA_VANTAGE_API_KEY`` by default. The free
4
+ tier is heavily rate-limited; pair with the circuit breaker and reserve
5
+ this provider for backtests + occasional live checks.
6
+
7
+ Capabilities
8
+ ------------
9
+ - LAST_PRICE, QUOTE (last/open/high/low/prev_close/volume)
10
+ - OHLCV_DAILY (via TIME_SERIES_DAILY function)
11
+ - Indian symbols use the ``.BSE`` suffix on Alpha Vantage; NSE coverage
12
+ is partial. Check :class:`MarketQuote.last is None` for misses.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import logging
19
+ import os
20
+ import urllib.parse
21
+ import urllib.request
22
+ from datetime import date, datetime
23
+ from urllib.error import HTTPError, URLError
24
+
25
+ from .base import (
26
+ OHLCV,
27
+ MarketDataProvider,
28
+ MarketQuote,
29
+ ProviderCapability,
30
+ ProviderError,
31
+ ProviderInfo,
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ _BASE = "https://www.alphavantage.co/query"
37
+
38
+
39
+ class AlphaVantageProvider(MarketDataProvider):
40
+ """Alpha Vantage REST quotes."""
41
+
42
+ def __init__(
43
+ self,
44
+ api_key: str | None = None,
45
+ suffix: str = ".BSE",
46
+ timeout: float = 10.0,
47
+ ) -> None:
48
+ self._api_key = api_key or os.environ.get("ALPHA_VANTAGE_API_KEY")
49
+ self._suffix = suffix
50
+ self._timeout = float(timeout)
51
+
52
+ @property
53
+ def info(self) -> ProviderInfo:
54
+ return ProviderInfo(
55
+ name="alphavantage",
56
+ description="Alpha Vantage REST API.",
57
+ capabilities=(
58
+ ProviderCapability.LAST_PRICE
59
+ | ProviderCapability.QUOTE
60
+ | ProviderCapability.OHLCV_DAILY
61
+ | ProviderCapability.SUPPORTS_BSE
62
+ | ProviderCapability.DELAYED
63
+ ),
64
+ requires_api_key=True,
65
+ homepage="https://www.alphavantage.co/",
66
+ notes="Free tier capped at 5 req/min; set ALPHA_VANTAGE_API_KEY.",
67
+ )
68
+
69
+ def _ticker(self, symbol: str) -> str:
70
+ return f"{symbol.upper()}{self._suffix}"
71
+
72
+ def _fetch_json(self, params: dict[str, str]) -> dict:
73
+ if not self._api_key:
74
+ raise ProviderError(
75
+ "Alpha Vantage API key missing. "
76
+ "Set ALPHA_VANTAGE_API_KEY or pass api_key=..."
77
+ )
78
+ params = {**params, "apikey": self._api_key}
79
+ url = f"{_BASE}?{urllib.parse.urlencode(params)}"
80
+ try:
81
+ with urllib.request.urlopen(url, timeout=self._timeout) as resp: # noqa: S310
82
+ body = resp.read().decode("utf-8", errors="replace")
83
+ except HTTPError as e:
84
+ raise ProviderError(f"alphavantage HTTP {e.code}") from e
85
+ except (URLError, TimeoutError) as e:
86
+ raise ProviderError(f"alphavantage fetch failed: {e}") from e
87
+ try:
88
+ data = json.loads(body)
89
+ except json.JSONDecodeError as e:
90
+ raise ProviderError(f"alphavantage non-JSON response: {body[:200]}") from e
91
+ if "Note" in data or "Information" in data:
92
+ raise ProviderError(
93
+ "alphavantage rate-limited: "
94
+ f"{data.get('Note') or data.get('Information')}",
95
+ )
96
+ if "Error Message" in data:
97
+ return {}
98
+ return data
99
+
100
+ def get_quote(self, symbol: str) -> MarketQuote | None:
101
+ data = self._fetch_json(
102
+ {"function": "GLOBAL_QUOTE", "symbol": self._ticker(symbol)},
103
+ )
104
+ gq = data.get("Global Quote") or data.get("globalQuote") or {}
105
+ if not gq:
106
+ return None
107
+ try:
108
+ last = float(gq.get("05. price") or 0)
109
+ except (TypeError, ValueError):
110
+ return None
111
+ if last <= 0:
112
+ return None
113
+
114
+ return MarketQuote(
115
+ last=last,
116
+ timestamp=datetime.now(),
117
+ open=_f(gq.get("02. open")),
118
+ high=_f(gq.get("03. high")),
119
+ low=_f(gq.get("04. low")),
120
+ prev_close=_f(gq.get("08. previous close")),
121
+ volume=_i(gq.get("06. volume")),
122
+ source="alphavantage",
123
+ is_real_time=False,
124
+ )
125
+
126
+ def get_history(
127
+ self,
128
+ symbol: str,
129
+ start: date,
130
+ end: date,
131
+ interval: str = "1d",
132
+ ) -> list[OHLCV]:
133
+ if interval != "1d":
134
+ return []
135
+ data = self._fetch_json(
136
+ {
137
+ "function": "TIME_SERIES_DAILY",
138
+ "symbol": self._ticker(symbol),
139
+ "outputsize": "full",
140
+ },
141
+ )
142
+ series = data.get("Time Series (Daily)") or {}
143
+ out: list[OHLCV] = []
144
+ for date_str, row in series.items():
145
+ try:
146
+ d = datetime.strptime(date_str, "%Y-%m-%d").date()
147
+ if d < start or d > end:
148
+ continue
149
+ out.append(
150
+ OHLCV(
151
+ timestamp=datetime.combine(d, datetime.min.time()),
152
+ open=float(row["1. open"]),
153
+ high=float(row["2. high"]),
154
+ low=float(row["3. low"]),
155
+ close=float(row["4. close"]),
156
+ volume=int(float(row["5. volume"])),
157
+ )
158
+ )
159
+ except (KeyError, ValueError):
160
+ continue
161
+ return sorted(out, key=lambda b: b.timestamp)
162
+
163
+
164
+ def _f(x: object) -> float | None:
165
+ try:
166
+ if x is None:
167
+ return None
168
+ v = float(x)
169
+ return v if v > 0 else None
170
+ except (TypeError, ValueError):
171
+ return None
172
+
173
+
174
+ def _i(x: object) -> int | None:
175
+ try:
176
+ if x is None:
177
+ return None
178
+ return int(float(x))
179
+ except (TypeError, ValueError):
180
+ return None
@@ -0,0 +1,256 @@
1
+ """Provider interface — the single contract every data source implements.
2
+
3
+ Why an ABC and not just a Protocol
4
+ -----------------------------------
5
+ The legacy ``PriceProvider`` Protocol (``get_price(symbol) -> float | None``)
6
+ covers one method. Real providers expose more: full quotes (bid/ask/last/
7
+ volume), historical bars, capability flags (does this source give
8
+ intraday? bid/ask? options chains?), and provenance (which provider was
9
+ hit, when, was the response cached).
10
+
11
+ An explicit ABC gives us:
12
+ - A single place to document what providers must do.
13
+ - Capability flags so the composite layer can route requests to providers
14
+ that can answer them (``capabilities & QUOTE`` etc.).
15
+ - A typed ``ProviderInfo`` so the CLI and dashboards can introspect
16
+ registered providers without instantiating them.
17
+ - A consistent error type (``ProviderError``) so callers can distinguish
18
+ "provider failed" from "symbol is genuinely unknown".
19
+
20
+ Backwards-compat: every concrete provider here also defines a thin
21
+ ``get_price`` method that satisfies the legacy Protocol, so the existing
22
+ ``PriceFeed`` → providers wiring keeps working.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import abc
28
+ from dataclasses import dataclass
29
+ from datetime import date, datetime
30
+ from enum import Flag, auto
31
+
32
+
33
+ class ProviderCapability(Flag):
34
+ """What a provider can deliver. Combine with ``|``.
35
+
36
+ The composite/registry layer uses these to pick the right provider
37
+ for each query — e.g. asking a delayed-only provider for a real-time
38
+ quote should fail fast or fall through.
39
+ """
40
+
41
+ NONE = 0
42
+ LAST_PRICE = auto() # last-traded price (the bare minimum)
43
+ QUOTE = auto() # bid/ask + last
44
+ OHLCV_INTRADAY = auto() # intraday bars (1m/5m/...)
45
+ OHLCV_DAILY = auto() # daily/EOD bars
46
+ REAL_TIME = auto() # live (no delay)
47
+ DELAYED = auto() # 15-min or end-of-day delayed
48
+ SUPPORTS_NSE = auto()
49
+ SUPPORTS_BSE = auto()
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class MarketQuote:
54
+ """A rich price snapshot.
55
+
56
+ Required: ``last`` and ``timestamp``. Everything else is optional
57
+ so partial-fidelity providers can fill in only what they have.
58
+ Consumers should check for ``None`` before using bid/ask/volume.
59
+
60
+ Fields
61
+ ------
62
+ last:
63
+ Last-traded price (always populated).
64
+ timestamp:
65
+ When the underlying provider produced this quote.
66
+ bid, ask:
67
+ Best bid / best ask. Sometimes one without the other (e.g. an
68
+ EOD source has neither).
69
+ bid_size, ask_size:
70
+ Depth at the top of book.
71
+ open, high, low, prev_close:
72
+ Day's OHL + previous close (for percent-change displays).
73
+ volume:
74
+ Traded shares so far today.
75
+ adjusted_close:
76
+ Split- and dividend-adjusted close. Set by providers that can
77
+ deliver an adjusted history (yfinance ``auto_adjust=True``,
78
+ Alpha Vantage ``TIME_SERIES_DAILY_ADJUSTED``). ``None`` when
79
+ the source only delivers raw closes. Backtesters should prefer
80
+ ``adjusted_close`` when present so historical splits don't
81
+ cause spurious P&L jumps.
82
+ currency:
83
+ ISO code, defaults to INR for the Indian market.
84
+ source:
85
+ Provider identifier (filled in by the provider itself).
86
+ is_real_time:
87
+ False when the source is delayed/cached. The broker's
88
+ ``enforce_fresh_prices`` mode rejects fills on stale snapshots.
89
+ """
90
+
91
+ last: float
92
+ timestamp: datetime
93
+ bid: float | None = None
94
+ ask: float | None = None
95
+ bid_size: int | None = None
96
+ ask_size: int | None = None
97
+ open: float | None = None
98
+ high: float | None = None
99
+ low: float | None = None
100
+ prev_close: float | None = None
101
+ volume: int | None = None
102
+ adjusted_close: float | None = None
103
+ currency: str = "INR"
104
+ source: str = "unknown"
105
+ is_real_time: bool = False
106
+ # Full L2 depth ladders when the provider supplies them (best-first,
107
+ # each entry ``(price, size)``). ``None`` means depth-unknown — the
108
+ # book simulator then synthesizes from bid/ask. Upstox returns 5
109
+ # levels; ``bid``/``ask`` above mirror ``bids[0]``/``asks[0]``.
110
+ bids: tuple[tuple[float, int], ...] | None = None
111
+ asks: tuple[tuple[float, int], ...] | None = None
112
+
113
+ @property
114
+ def has_depth(self) -> bool:
115
+ """True when real multi-level depth is available on both sides."""
116
+ return bool(self.bids and self.asks)
117
+
118
+ @property
119
+ def mid(self) -> float | None:
120
+ """Mid-price between bid and ask, or ``None`` when either is missing."""
121
+ if self.bid is None or self.ask is None:
122
+ return None
123
+ return (self.bid + self.ask) / 2.0
124
+
125
+ @property
126
+ def spread_bps(self) -> float | None:
127
+ """Bid/ask spread expressed in basis points off mid, or ``None``."""
128
+ m = self.mid
129
+ if m is None or m <= 0 or self.bid is None or self.ask is None:
130
+ return None
131
+ return (self.ask - self.bid) / m * 10000.0
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class OHLCV:
136
+ """A single OHLCV bar."""
137
+
138
+ timestamp: datetime
139
+ open: float
140
+ high: float
141
+ low: float
142
+ close: float
143
+ volume: int
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class ProviderInfo:
148
+ """Static metadata about a registered provider.
149
+
150
+ Used by the registry, CLI introspection, and dashboards. Does not
151
+ require instantiating the provider.
152
+ """
153
+
154
+ name: str
155
+ description: str
156
+ capabilities: ProviderCapability
157
+ requires_api_key: bool = False
158
+ requires_network: bool = True
159
+ homepage: str | None = None
160
+ notes: str = ""
161
+
162
+
163
+ class ProviderError(Exception):
164
+ """Raised by providers when a fetch genuinely failed.
165
+
166
+ Distinct from "no data for this symbol" — providers should return
167
+ ``None`` for unknown symbols and raise this only when the call
168
+ itself broke (network down, rate limit, parse error).
169
+ """
170
+
171
+
172
+ class MarketDataProvider(abc.ABC):
173
+ """Abstract base for every market-data provider.
174
+
175
+ Implementations must override ``info`` and ``get_quote``. Other
176
+ methods have safe defaults built on top of those two so a minimal
177
+ provider can ship with just the basics.
178
+
179
+ Implementations should:
180
+ - Return ``None`` for unknown symbols (it's not an error).
181
+ - Raise :class:`ProviderError` when the upstream call fails.
182
+ - Set ``MarketQuote.source`` to a stable, lowercase identifier.
183
+ """
184
+
185
+ # ── Introspection ─────────────────────────────────────────────────
186
+
187
+ @property
188
+ @abc.abstractmethod
189
+ def info(self) -> ProviderInfo:
190
+ """Static metadata describing this provider."""
191
+
192
+ @property
193
+ def name(self) -> str:
194
+ """Stable identifier (lowercased provider name)."""
195
+ return self.info.name
196
+
197
+ @property
198
+ def capabilities(self) -> ProviderCapability:
199
+ """Capability flags for routing decisions."""
200
+ return self.info.capabilities
201
+
202
+ def supports(self, capability: ProviderCapability) -> bool:
203
+ """True when this provider can deliver ``capability``."""
204
+ return bool(self.capabilities & capability)
205
+
206
+ # ── Required hot path ─────────────────────────────────────────────
207
+
208
+ @abc.abstractmethod
209
+ def get_quote(self, symbol: str) -> MarketQuote | None:
210
+ """Return a quote for ``symbol`` or ``None`` if unknown.
211
+
212
+ Raises :class:`ProviderError` on infrastructure failures
213
+ (network, parse, rate-limit). Returning ``None`` means the
214
+ symbol is genuinely not tracked by this provider — callers
215
+ should try the next one.
216
+ """
217
+
218
+ # ── Convenience defaults ──────────────────────────────────────────
219
+
220
+ def get_price(self, symbol: str) -> float | None:
221
+ """Legacy ``PriceProvider`` shim.
222
+
223
+ Returns last-traded price or ``None``. Errors are swallowed
224
+ because the legacy fallback chain expects ``None``-on-failure;
225
+ :meth:`get_quote` is the correct entry point for new code.
226
+ """
227
+ try:
228
+ quote = self.get_quote(symbol)
229
+ except ProviderError:
230
+ return None
231
+ return quote.last if quote is not None else None
232
+
233
+ def get_history(
234
+ self,
235
+ symbol: str,
236
+ start: date,
237
+ end: date,
238
+ interval: str = "1d",
239
+ ) -> list[OHLCV]:
240
+ """Return historical bars between ``start`` and ``end`` inclusive.
241
+
242
+ Default implementation returns an empty list — providers that
243
+ only deliver spot quotes can leave this alone. Override when
244
+ the source supports historical data.
245
+ """
246
+ return []
247
+
248
+ # ── Fluent ergonomics ─────────────────────────────────────────────
249
+
250
+ def __repr__(self) -> str: # pragma: no cover — trivial
251
+ return f"<{type(self).__name__} name={self.name}>"
252
+
253
+
254
+ # Sentinel used by registry/discovery to stand in for an optional
255
+ # provider whose deps aren't installed. Imported by registry.py.
256
+ _UNAVAILABLE: object = object()
@@ -0,0 +1,147 @@
1
+ """Local caches used by the price feed.
2
+
3
+ Two layers:
4
+
5
+ - :class:`InMemoryShortCache` — sub-second TTL, absorbs bursts (e.g. one
6
+ ``get_positions()`` call asking for 30 quotes).
7
+ - :class:`CachedLastKnownProvider` — hour-scale TTL, last line of
8
+ defense when every live provider is down. Pretends to be a
9
+ :class:`MarketDataProvider` so the composite/health layer can
10
+ treat it uniformly.
11
+
12
+ Both deliberately live outside the broker so they can be shared,
13
+ swapped, or replaced (e.g. with Redis) without touching broker code.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import time
19
+ from datetime import datetime
20
+ from threading import RLock
21
+
22
+ from .base import (
23
+ MarketDataProvider,
24
+ MarketQuote,
25
+ ProviderCapability,
26
+ ProviderInfo,
27
+ )
28
+
29
+
30
+ class InMemoryShortCache:
31
+ """Tiny TTL cache for the (provider→quote) hot path.
32
+
33
+ Used by :class:`papertrade_india.PriceFeed` to avoid hammering an
34
+ upstream when the broker iterates positions in a single tick.
35
+ Thread-safe via ``RLock`` because the limit-order watcher touches
36
+ it from a background thread.
37
+ """
38
+
39
+ def __init__(self, ttl_seconds: float = 5.0) -> None:
40
+ self._ttl = float(ttl_seconds)
41
+ # symbol -> (price, wall_time, is_real_time)
42
+ self._data: dict[str, tuple[float, float, bool]] = {}
43
+ self._lock = RLock()
44
+
45
+ @property
46
+ def ttl_seconds(self) -> float:
47
+ return self._ttl
48
+
49
+ def get(self, symbol: str) -> tuple[float, float, bool] | None:
50
+ """Return ``(price, wall_t, is_real_time)`` if fresh, else ``None``."""
51
+ with self._lock:
52
+ entry = self._data.get(symbol)
53
+ if entry is None:
54
+ return None
55
+ price, t, is_real_time = entry
56
+ if (time.time() - t) >= self._ttl:
57
+ return None
58
+ return price, t, is_real_time
59
+
60
+ def put(self, symbol: str, price: float, is_real_time: bool = True) -> None:
61
+ """Store the latest price + its real-time provenance.
62
+
63
+ ``is_real_time`` is carried so a cache hit can't launder a
64
+ delayed quote into a real-time one (which would defeat the
65
+ broker's ``enforce_real_time`` guard).
66
+ """
67
+ with self._lock:
68
+ self._data[symbol] = (price, time.time(), is_real_time)
69
+
70
+ def clear(self) -> None:
71
+ """Drop everything (test helper)."""
72
+ with self._lock:
73
+ self._data.clear()
74
+
75
+
76
+ class CachedLastKnownProvider(MarketDataProvider):
77
+ """Long-lived "last known good" cache, surfaced as a provider.
78
+
79
+ When every live provider fails, this is what keeps the broker
80
+ answering — at the cost of staleness. The broker uses
81
+ :attr:`MarketQuote.is_real_time` to detect the staleness path
82
+ (``False`` for cache hits) and the ``enforce_fresh_prices`` mode
83
+ rejects fills served from here.
84
+ """
85
+
86
+ def __init__(self, ttl_seconds: int = 60 * 60) -> None:
87
+ self._ttl = int(ttl_seconds)
88
+ self._cache: dict[str, tuple[float, datetime]] = {}
89
+ self._lock = RLock()
90
+
91
+ @property
92
+ def info(self) -> ProviderInfo:
93
+ return ProviderInfo(
94
+ name="long_cache",
95
+ description="Last-known-price cache used as the final fallback.",
96
+ capabilities=(
97
+ ProviderCapability.LAST_PRICE
98
+ | ProviderCapability.SUPPORTS_NSE
99
+ | ProviderCapability.SUPPORTS_BSE
100
+ | ProviderCapability.DELAYED
101
+ ),
102
+ requires_network=False,
103
+ notes="Returns the most recently fetched live price within TTL.",
104
+ )
105
+
106
+ @property
107
+ def ttl(self) -> int:
108
+ return self._ttl
109
+
110
+ # ── Lifecycle ─────────────────────────────────────────────────────
111
+
112
+ def update(self, symbol: str, price: float) -> None:
113
+ """Record a fresh observation."""
114
+ with self._lock:
115
+ self._cache[symbol] = (float(price), datetime.now())
116
+
117
+ def get_price(self, symbol: str) -> float | None:
118
+ entry = self.get_entry(symbol)
119
+ return entry[0] if entry is not None else None
120
+
121
+ def get_entry(self, symbol: str) -> tuple[float, datetime] | None:
122
+ """Return ``(price, fetched_at)`` if fresh enough, else ``None``."""
123
+ with self._lock:
124
+ entry = self._cache.get(symbol)
125
+ if entry is None:
126
+ return None
127
+ price, fetched_at = entry
128
+ if (datetime.now() - fetched_at).total_seconds() > self._ttl:
129
+ return None
130
+ return price, fetched_at
131
+
132
+ def get_quote(self, symbol: str) -> MarketQuote | None:
133
+ entry = self.get_entry(symbol)
134
+ if entry is None:
135
+ return None
136
+ price, fetched_at = entry
137
+ return MarketQuote(
138
+ last=price,
139
+ timestamp=fetched_at,
140
+ source="long_cache",
141
+ is_real_time=False,
142
+ )
143
+
144
+ def clear(self) -> None:
145
+ """Drop everything (test helper)."""
146
+ with self._lock:
147
+ self._cache.clear()