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,120 @@
1
+ """Named broker fee presets.
2
+
3
+ Hand-curated ``FeeConfig`` instances that map to common Indian discount-
4
+ broker schedules. Use as drop-in fee configs::
5
+
6
+ from papertrade_india import IndiaPaperBroker
7
+ from papertrade_india.presets import ZERODHA_DELIVERY
8
+
9
+ broker = IndiaPaperBroker(fee_config=ZERODHA_DELIVERY)
10
+
11
+ The defaults baked into ``FeeConfig()`` already match a Zerodha-style
12
+ delivery account, so ``ZERODHA_DELIVERY`` is just an alias. The other
13
+ presets exist so users don't have to reverse-engineer a competitor's
14
+ schedule from first principles.
15
+
16
+ Sources used (paraphrased for compliance with licensing): public Indian
17
+ broker fee structures (Zerodha, Upstox, Groww, Angel One, ICICIdirect)
18
+ published 2025–2026. Verify against your contract note before relying.
19
+
20
+ PRESETS dict at the bottom is for the CLI / configuration loaders.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from .execution.fees import FeeConfig
26
+
27
+ # ── Zerodha ────────────────────────────────────────────────────────────
28
+
29
+
30
+ # Delivery: ₹0 brokerage, all statutory components apply.
31
+ ZERODHA_DELIVERY = FeeConfig() # uses package defaults
32
+
33
+
34
+ # Intraday / equity F&O: ₹20 or 0.03% per executed order, whichever is
35
+ # lower. STT is asymmetric for intraday but we model delivery-equivalent
36
+ # rates here; override stt_pct_buy=0 when running an intraday-only test.
37
+ ZERODHA_INTRADAY = FeeConfig(
38
+ brokerage_pct=0.0003,
39
+ brokerage_max=20.0,
40
+ )
41
+
42
+
43
+ # ── Upstox ────────────────────────────────────────────────────────────
44
+
45
+
46
+ # Delivery: ₹20 flat per order or 2.5% of turnover, whichever is lower.
47
+ UPSTOX_DELIVERY = FeeConfig(
48
+ brokerage_pct=0.025,
49
+ brokerage_max=20.0,
50
+ )
51
+
52
+
53
+ UPSTOX_INTRADAY = FeeConfig(
54
+ brokerage_pct=0.0005, # 0.05%
55
+ brokerage_max=20.0,
56
+ )
57
+
58
+
59
+ # ── Groww ─────────────────────────────────────────────────────────────
60
+
61
+
62
+ # Groww: ₹20 flat or 0.1% per executed order (delivery), whichever is lower.
63
+ GROWW_DELIVERY = FeeConfig(
64
+ brokerage_pct=0.001,
65
+ brokerage_max=20.0,
66
+ )
67
+
68
+
69
+ # ── Angel One ─────────────────────────────────────────────────────────
70
+
71
+
72
+ # Angel One: zero brokerage on delivery, ₹20/order on intraday.
73
+ ANGEL_ONE_DELIVERY = FeeConfig()
74
+
75
+
76
+ ANGEL_ONE_INTRADAY = FeeConfig(
77
+ brokerage_flat=20.0,
78
+ )
79
+
80
+
81
+ # ── ICICIdirect (full-service) ────────────────────────────────────────
82
+
83
+
84
+ # Full-service brokers charge percentage-of-turnover with no cap. The
85
+ # rates below approximate the ICICIdirect "I-Secure" plan; their actual
86
+ # tier structure depends on volume and is broker-specific.
87
+ ICICIDIRECT_DELIVERY = FeeConfig(
88
+ brokerage_pct=0.0055, # 0.55%
89
+ )
90
+
91
+
92
+ # ── Lookup map ────────────────────────────────────────────────────────
93
+
94
+
95
+ PRESETS: dict[str, FeeConfig] = {
96
+ "zerodha-delivery": ZERODHA_DELIVERY,
97
+ "zerodha-intraday": ZERODHA_INTRADAY,
98
+ "upstox-delivery": UPSTOX_DELIVERY,
99
+ "upstox-intraday": UPSTOX_INTRADAY,
100
+ "groww-delivery": GROWW_DELIVERY,
101
+ "angel-one-delivery": ANGEL_ONE_DELIVERY,
102
+ "angel-one-intraday": ANGEL_ONE_INTRADAY,
103
+ "icicidirect-delivery": ICICIDIRECT_DELIVERY,
104
+ }
105
+
106
+
107
+ def get_preset(name: str) -> FeeConfig:
108
+ """Look up a preset by name.
109
+
110
+ Case-insensitive; underscores and hyphens treated as equivalent.
111
+ Raises ``KeyError`` with a helpful list of valid names on miss.
112
+ """
113
+ norm = name.lower().replace("_", "-")
114
+ cfg = PRESETS.get(norm)
115
+ if cfg is None:
116
+ raise KeyError(
117
+ f"Unknown preset {name!r}. "
118
+ f"Available: {sorted(PRESETS)}"
119
+ )
120
+ return cfg
@@ -0,0 +1,316 @@
1
+ """Price feed — coordinates the chain of market-data providers.
2
+
3
+ Backwards-compat layer over :mod:`papertrade_india.providers`. Existing
4
+ callers see the same surface they always have:
5
+
6
+ - :class:`PriceProvider` Protocol (any object with a ``get_price`` method)
7
+ - :class:`YFinanceProvider`, :class:`JugaadDataProvider`,
8
+ :class:`CachedLastKnownProvider`
9
+ - :class:`PriceFeed` with ``get_price`` and ``get_quote``
10
+ - :class:`Quote` (legacy quote dataclass)
11
+
12
+ New code should prefer :mod:`papertrade_india.providers` directly:
13
+
14
+ >>> from papertrade_india.providers import (
15
+ ... YFinanceProvider, MedianAggregation, CompositeProvider,
16
+ ... CircuitBreakerProvider, MarketQuote,
17
+ ... )
18
+
19
+ The bridge:
20
+
21
+ - :class:`PriceFeed` accepts both legacy ``PriceProvider`` objects (only
22
+ ``get_price``) and the new :class:`MarketDataProvider` ABC, so old
23
+ test stubs keep working.
24
+ - :class:`Quote` and :class:`MarketQuote` are interchangeable in spirit;
25
+ :class:`Quote` is the narrower view (``price``, ``source``,
26
+ ``fetched_at``, ``is_stale``) the broker already consumes.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import logging
32
+ import time
33
+ from dataclasses import dataclass
34
+ from datetime import datetime
35
+ from typing import Protocol
36
+
37
+ from .domain.exceptions import PriceUnavailableError
38
+ from .providers import (
39
+ CachedLastKnownProvider,
40
+ InMemoryShortCache,
41
+ JugaadDataProvider,
42
+ MarketDataProvider,
43
+ MarketQuote,
44
+ YFinanceProvider,
45
+ )
46
+ from .providers.base import ProviderError as _ProviderError
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ # ── Legacy types kept for back-compat ────────────────────────────────
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Quote:
56
+ """A price observation with provenance (legacy view).
57
+
58
+ Newer code should prefer :class:`papertrade_india.providers.MarketQuote`,
59
+ which carries bid/ask/volume/OHLC. ``Quote`` keeps the narrower
60
+ surface the broker already consumes (price + source + fetched_at +
61
+ is_stale) so existing callers don't need to migrate.
62
+ is_stale:
63
+ ``True`` only when served from the long-lived fallback cache
64
+ (all live providers failed). The broker's ``enforce_fresh_prices``
65
+ mode rejects fills on these.
66
+ is_real_time:
67
+ ``False`` when the underlying provider is delayed/EOD (e.g.
68
+ yfinance ~15 min) even though the quote is freshly fetched and
69
+ not cache-stale. The broker's opt-in ``enforce_real_time`` mode
70
+ rejects fills on delayed feeds; it defaults off so the public
71
+ delayed providers keep working unchanged.
72
+ """
73
+
74
+ price: float
75
+ source: str
76
+ fetched_at: datetime
77
+ is_stale: bool
78
+ is_real_time: bool = True
79
+
80
+
81
+ class PriceProvider(Protocol):
82
+ """Anything with a ``get_price(symbol) -> float | None``.
83
+
84
+ Both legacy stubs and the new :class:`MarketDataProvider` satisfy
85
+ this. Kept for backwards compatibility with ``PriceFeed(providers=[...])``.
86
+ """
87
+
88
+ def get_price(self, symbol: str) -> float | None:
89
+ ...
90
+
91
+
92
+ # Legacy aliases — kept for ``from papertrade_india import ...``
93
+ __all__ = [
94
+ "Quote",
95
+ "PriceProvider",
96
+ "PriceFeed",
97
+ "YFinanceProvider",
98
+ "JugaadDataProvider",
99
+ "CachedLastKnownProvider",
100
+ ]
101
+
102
+
103
+ # ── Coordinator ───────────────────────────────────────────────────────
104
+
105
+
106
+ class PriceFeed:
107
+ """Multi-provider price feed with fallback chain.
108
+
109
+ Tries each provider in order, returns the first non-``None`` price.
110
+ Logs every fallback so degradation is visible in the structured log.
111
+
112
+ The class accepts both legacy-shaped ``PriceProvider`` objects and
113
+ new :class:`MarketDataProvider` instances. When a provider is the
114
+ new shape, ``get_quote`` calls flow through ``provider.get_quote()``
115
+ (which carries source/timestamp/staleness directly); when it's the
116
+ legacy shape we fabricate a quote with ``source=type(provider).__name__``
117
+ and ``fetched_at=now``.
118
+ """
119
+
120
+ def __init__(
121
+ self,
122
+ providers: list[PriceProvider | MarketDataProvider] | None = None,
123
+ cache_ttl_seconds: int = 60 * 60,
124
+ short_cache_ttl_seconds: float = 5.0,
125
+ ) -> None:
126
+ self.cache = CachedLastKnownProvider(ttl_seconds=cache_ttl_seconds)
127
+ self.providers: list[PriceProvider | MarketDataProvider] = (
128
+ providers
129
+ if providers is not None
130
+ else [YFinanceProvider("NS"), JugaadDataProvider()]
131
+ )
132
+ self._short_cache = InMemoryShortCache(ttl_seconds=short_cache_ttl_seconds)
133
+
134
+ def get_price(self, symbol: str) -> float:
135
+ """Backwards-compatible bare-float accessor."""
136
+ return self.get_quote(symbol).price
137
+
138
+ def get_quote(self, symbol: str) -> Quote:
139
+ """Fetch a price with provenance.
140
+
141
+ Tries the short cache, then each live provider in order, then
142
+ the long-lived cache. Always returns a :class:`Quote` or raises
143
+ :class:`PriceUnavailableError` — never silently degrades.
144
+ """
145
+ # Short cache check — preserves the cached quote's real-time
146
+ # provenance so a delayed feed can't be laundered into a
147
+ # real-time hit (which would defeat enforce_real_time).
148
+ cached = self._short_cache.get(symbol)
149
+ if cached is not None:
150
+ price, t, is_real_time = cached
151
+ return Quote(
152
+ price=price,
153
+ source="short_cache",
154
+ fetched_at=datetime.fromtimestamp(t),
155
+ is_stale=False,
156
+ is_real_time=is_real_time,
157
+ )
158
+
159
+ for provider in self.providers:
160
+ quote = self._call_provider(provider, symbol)
161
+ if quote is not None:
162
+ self.cache.update(symbol, quote.last)
163
+ self._short_cache.put(symbol, quote.last, quote.is_real_time)
164
+ # Quote.is_stale historically means "served from the
165
+ # long cache", *not* "delayed feed". A live yfinance
166
+ # quote is delayed but not stale in this sense.
167
+ return Quote(
168
+ price=quote.last,
169
+ source=quote.source,
170
+ fetched_at=quote.timestamp,
171
+ is_stale=False,
172
+ is_real_time=quote.is_real_time,
173
+ )
174
+
175
+ # Last resort: long-lived cache.
176
+ cached_quote = self.cache.get_quote(symbol)
177
+ if cached_quote is not None:
178
+ logger.warning(
179
+ "Using cached price for %s — all live providers failed "
180
+ "(cache age: %s)",
181
+ symbol, datetime.now() - cached_quote.timestamp,
182
+ )
183
+ return Quote(
184
+ price=cached_quote.last,
185
+ source=cached_quote.source,
186
+ fetched_at=cached_quote.timestamp,
187
+ is_stale=True,
188
+ is_real_time=False,
189
+ )
190
+
191
+ raise PriceUnavailableError(
192
+ f"Cannot fetch price for {symbol} — "
193
+ f"all providers failed and no cached value is available",
194
+ )
195
+
196
+ def prime(self, symbol: str, price: float) -> None:
197
+ """Seed the cache (useful in tests, or with EOD bhavcopy data)."""
198
+ self.cache.update(symbol, price)
199
+ self._short_cache.put(symbol, price)
200
+
201
+ # ── Internals ─────────────────────────────────────────────────────
202
+
203
+ def _call_provider(
204
+ self,
205
+ provider: PriceProvider | MarketDataProvider,
206
+ symbol: str,
207
+ ) -> MarketQuote | None:
208
+ """Call ``provider`` and normalize its return into a MarketQuote.
209
+
210
+ Accepts both legacy ``get_price(symbol) -> float | None`` providers
211
+ and new ``MarketDataProvider``s.
212
+ """
213
+ # New-style provider: prefer get_quote when present.
214
+ if isinstance(provider, MarketDataProvider):
215
+ try:
216
+ return provider.get_quote(symbol)
217
+ except _ProviderError as e:
218
+ logger.warning("provider %s raised: %s", provider.name, e)
219
+ return None
220
+ except Exception as e: # noqa: BLE001 — defensive
221
+ logger.warning(
222
+ "provider %s raised unexpectedly: %s",
223
+ provider.name, e,
224
+ )
225
+ return None
226
+
227
+ # Legacy-style provider: thin shim.
228
+ try:
229
+ price = provider.get_price(symbol)
230
+ except Exception as e: # noqa: BLE001 — defensive
231
+ logger.warning(
232
+ "Provider %s raised: %s", type(provider).__name__, e,
233
+ )
234
+ return None
235
+ if price is None:
236
+ return None
237
+ return MarketQuote(
238
+ last=float(price),
239
+ timestamp=datetime.now(),
240
+ source=type(provider).__name__,
241
+ is_real_time=False,
242
+ )
243
+
244
+ # ── Convenience for new code ─────────────────────────────────────
245
+
246
+ def get_market_quote(self, symbol: str) -> MarketQuote:
247
+ """Return the rich :class:`MarketQuote` (bid/ask/volume/OHLC).
248
+
249
+ Companion to :meth:`get_quote`. Useful for callers that want
250
+ the full quote shape without going through the legacy
251
+ :class:`Quote` adapter.
252
+ """
253
+ for provider in self.providers:
254
+ quote = self._call_provider(provider, symbol)
255
+ if quote is not None:
256
+ self.cache.update(symbol, quote.last)
257
+ self._short_cache.put(symbol, quote.last, quote.is_real_time)
258
+ return quote
259
+ cached_quote = self.cache.get_quote(symbol)
260
+ if cached_quote is not None:
261
+ return cached_quote
262
+ raise PriceUnavailableError(
263
+ f"Cannot fetch price for {symbol} — all providers failed "
264
+ f"and no cached value is available",
265
+ )
266
+
267
+
268
+ # ``time`` is only used to keep the legacy import surface stable for any
269
+ # downstream that imported the module with ``import time``-side effects.
270
+ _ = time
271
+
272
+
273
+ def resilient_feed(
274
+ providers: list[PriceProvider | MarketDataProvider],
275
+ *,
276
+ wrap_circuit_breaker: bool = True,
277
+ **feed_kwargs: object,
278
+ ) -> PriceFeed:
279
+ """Build a multi-provider :class:`PriceFeed` tuned for "use all sources".
280
+
281
+ The chain is consumed first-wins (lowest latency — returns the first
282
+ live quote and short-circuits), so ordering matters: put the
283
+ highest-fidelity real-time feeds first, delayed/EOD sources last,
284
+ e.g. ``[upstox, dhan, finnhub, yfinance]``.
285
+
286
+ With ``wrap_circuit_breaker=True`` (default) every new-style
287
+ :class:`MarketDataProvider` is wrapped in a
288
+ :class:`~papertrade_india.providers.CircuitBreakerProvider`, so a
289
+ source that starts failing or lagging is ejected automatically and
290
+ probed back when it recovers — this is what keeps data quality
291
+ stable over time without adding per-quote latency. Inspect
292
+ ``feed.providers[i].health`` for the breaker state.
293
+
294
+ Legacy ``get_price`` providers are passed through unwrapped (the
295
+ breaker wraps the new ABC only); they still benefit from PriceFeed's
296
+ built-in short + long caches.
297
+
298
+ ``ponytail``: deliberately first-wins, not median. Median consensus
299
+ would make every fill wait for the slowest provider — the opposite
300
+ of the low-lag goal. Cross-source validation belongs in a background
301
+ audit, not the hot fill path.
302
+ """
303
+ chain: list[PriceProvider | MarketDataProvider] = []
304
+ if wrap_circuit_breaker:
305
+ from .providers import CircuitBreakerProvider # noqa: PLC0415
306
+
307
+ for p in providers:
308
+ if isinstance(p, MarketDataProvider) and not isinstance(
309
+ p, CircuitBreakerProvider
310
+ ):
311
+ chain.append(CircuitBreakerProvider(p))
312
+ else:
313
+ chain.append(p)
314
+ else:
315
+ chain = list(providers)
316
+ return PriceFeed(providers=chain, **feed_kwargs) # type: ignore[arg-type]
@@ -0,0 +1,123 @@
1
+ """Data-provider subpackage for papertrade-india.
2
+
3
+ This package owns every external market-data source the broker can talk
4
+ to. The headline split is:
5
+
6
+ - :mod:`base` — the :class:`MarketDataProvider` ABC, capability flags,
7
+ and the rich data types (``MarketQuote``, ``OHLCV``) that providers
8
+ surface.
9
+ - One module per provider (yfinance, jugaad-data, nsepython, stooq,
10
+ alpha vantage, twelve data, finnhub, NSE bhavcopy). Each module
11
+ implements ``MarketDataProvider`` and is optional at install time —
12
+ the package imports cleanly even when third-party deps are missing.
13
+ - :mod:`health` — circuit-breaker wrapper that tracks per-provider
14
+ failure rates and trips out failing providers without restart.
15
+ - :mod:`composite` — fan-out that aggregates quotes from multiple
16
+ providers (median by default) for higher fidelity than first-wins.
17
+ - :mod:`registry` — name → provider lookup so config and the CLI can
18
+ refer to providers by stable identifiers.
19
+
20
+ Backwards-compat
21
+ ----------------
22
+ The legacy :class:`papertrade_india.PriceProvider` ``Protocol`` is the
23
+ narrow ``get_price(symbol) -> float | None`` contract. Every new
24
+ provider here also satisfies that protocol via its ``get_price``
25
+ method, so anything that consumes the old protocol keeps working
26
+ unchanged.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from .base import (
32
+ OHLCV,
33
+ MarketDataProvider,
34
+ MarketQuote,
35
+ ProviderCapability,
36
+ ProviderError,
37
+ ProviderInfo,
38
+ )
39
+ from .cache import CachedLastKnownProvider, InMemoryShortCache
40
+ from .composite import CompositeProvider, MedianAggregation
41
+ from .health import CircuitBreakerProvider, ProviderHealth
42
+ from .jugaad import JugaadDataProvider
43
+ from .nse_bhavcopy import NSEBhavcopyProvider
44
+ from .registry import ProviderRegistry, default_registry
45
+ from .stooq import StooqProvider
46
+ from .yfinance import YFinanceProvider
47
+
48
+ # Optional providers — imported lazily inside try/except so a missing
49
+ # third-party dep doesn't break ``from papertrade_india.providers import ...``.
50
+ try:
51
+ from .nsepython import NSEPythonProvider
52
+ except Exception: # noqa: BLE001
53
+ NSEPythonProvider = None # type: ignore[assignment]
54
+
55
+ try:
56
+ from .alphavantage import AlphaVantageProvider
57
+ except Exception: # noqa: BLE001
58
+ AlphaVantageProvider = None # type: ignore[assignment]
59
+
60
+ try:
61
+ from .twelvedata import TwelveDataProvider
62
+ except Exception: # noqa: BLE001
63
+ TwelveDataProvider = None # type: ignore[assignment]
64
+
65
+ try:
66
+ from .finnhub import FinnhubProvider
67
+ except Exception: # noqa: BLE001
68
+ FinnhubProvider = None # type: ignore[assignment]
69
+
70
+ # Broker-feed providers (real bid/ask + depth). Kite/Dhan need a vendor
71
+ # SDK; Upstox is stdlib REST. All are optional and credential-gated.
72
+ try:
73
+ from .kite import KiteProvider
74
+ except Exception: # noqa: BLE001
75
+ KiteProvider = None # type: ignore[assignment]
76
+
77
+ try:
78
+ from .dhan import DhanProvider
79
+ except Exception: # noqa: BLE001
80
+ DhanProvider = None # type: ignore[assignment]
81
+
82
+ try:
83
+ from .upstox import UpstoxProvider
84
+ except Exception: # noqa: BLE001
85
+ UpstoxProvider = None # type: ignore[assignment]
86
+
87
+ from .upstox_instruments import UpstoxInstrumentMaster
88
+
89
+ __all__ = [
90
+ # Base interface
91
+ "MarketDataProvider",
92
+ "MarketQuote",
93
+ "OHLCV",
94
+ "ProviderCapability",
95
+ "ProviderError",
96
+ "ProviderInfo",
97
+ # Cache
98
+ "CachedLastKnownProvider",
99
+ "InMemoryShortCache",
100
+ # Resilience
101
+ "CircuitBreakerProvider",
102
+ "ProviderHealth",
103
+ # Aggregation / lookup
104
+ "CompositeProvider",
105
+ "MedianAggregation",
106
+ "ProviderRegistry",
107
+ "default_registry",
108
+ # Concrete providers (always available)
109
+ "YFinanceProvider",
110
+ "JugaadDataProvider",
111
+ "StooqProvider",
112
+ "NSEBhavcopyProvider",
113
+ # Concrete providers (optional)
114
+ "NSEPythonProvider",
115
+ "AlphaVantageProvider",
116
+ "TwelveDataProvider",
117
+ "FinnhubProvider",
118
+ # Broker-feed providers (optional)
119
+ "KiteProvider",
120
+ "DhanProvider",
121
+ "UpstoxProvider",
122
+ "UpstoxInstrumentMaster",
123
+ ]