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,244 @@
1
+ """Composite provider — fan-out across multiple sources.
2
+
3
+ Two strategies, both implemented as :class:`MarketDataProvider`s so they
4
+ slot anywhere a single provider would:
5
+
6
+ - :class:`CompositeProvider` (default: first-wins) — try each provider
7
+ in order, return the first non-``None`` quote. This is what the legacy
8
+ :class:`PriceFeed` already did, lifted into a provider for composability.
9
+ - :class:`CompositeProvider` with :class:`MedianAggregation` — fan out
10
+ to every provider in parallel, return the median of the live quotes.
11
+ More realistic than first-wins because no single provider sets the
12
+ fill price; one outlier can't drag a fill price.
13
+
14
+ The aggregation is a strategy object so callers can write their own
15
+ (weighted-average, IQR-trim, "throw out the highest and lowest", etc.)
16
+ without subclassing :class:`CompositeProvider`.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ from collections.abc import Callable, Sequence
23
+ from concurrent.futures import ThreadPoolExecutor, as_completed
24
+ from dataclasses import dataclass
25
+ from datetime import datetime
26
+
27
+ from .base import (
28
+ MarketDataProvider,
29
+ MarketQuote,
30
+ ProviderCapability,
31
+ ProviderInfo,
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ # An aggregation function takes the live quotes from N providers and
38
+ # returns the merged quote. Returning ``None`` means "couldn't form a
39
+ # consensus" — the composite then returns ``None`` to its caller.
40
+ AggregationFn = Callable[[list[MarketQuote]], MarketQuote | None]
41
+
42
+
43
+ def first_wins(quotes: list[MarketQuote]) -> MarketQuote | None:
44
+ """Return the first available quote (legacy behavior)."""
45
+ return quotes[0] if quotes else None
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class MedianAggregation:
50
+ """Median of last-prices across providers.
51
+
52
+ The merged quote uses:
53
+ - ``last`` = median of inputs' ``last``
54
+ - ``bid``/``ask`` = median of inputs that supplied them (or None)
55
+ - ``volume`` = max across inputs (a sane proxy when sources
56
+ disagree — prefer the one that actually saw the trade)
57
+ - ``timestamp`` = max (most recent) across inputs
58
+ - ``source`` = ``"composite-median:<n>"`` where n is the number
59
+ of contributing providers
60
+ - ``is_real_time`` = ``all(inputs.is_real_time)``
61
+
62
+ Parameters
63
+ ----------
64
+ min_providers:
65
+ Need at least this many live quotes to form a median; otherwise
66
+ return ``None``. Default 1 (single-provider median == that
67
+ provider's quote).
68
+ max_disagreement_bps:
69
+ If the spread between the lowest and highest input ``last`` is
70
+ wider than this, log a warning and still return the median.
71
+ Default 200 bps (2%). Set to ``None`` to disable the check.
72
+ """
73
+
74
+ min_providers: int = 1
75
+ max_disagreement_bps: float | None = 200.0
76
+
77
+ def __call__(self, quotes: list[MarketQuote]) -> MarketQuote | None:
78
+ if len(quotes) < self.min_providers:
79
+ return None
80
+ prices = sorted(q.last for q in quotes)
81
+ median_last = _median(prices)
82
+
83
+ if self.max_disagreement_bps is not None and len(prices) >= 2:
84
+ spread_bps = (prices[-1] - prices[0]) / median_last * 10000.0
85
+ if spread_bps > self.max_disagreement_bps:
86
+ logger.warning(
87
+ "Provider disagreement: %.0f bps (low=%.2f, high=%.2f, n=%d)",
88
+ spread_bps, prices[0], prices[-1], len(prices),
89
+ )
90
+
91
+ bids = [q.bid for q in quotes if q.bid is not None]
92
+ asks = [q.ask for q in quotes if q.ask is not None]
93
+ opens = [q.open for q in quotes if q.open is not None]
94
+ highs = [q.high for q in quotes if q.high is not None]
95
+ lows = [q.low for q in quotes if q.low is not None]
96
+ prev_closes = [q.prev_close for q in quotes if q.prev_close is not None]
97
+ volumes = [q.volume for q in quotes if q.volume is not None]
98
+ timestamps = [q.timestamp for q in quotes]
99
+
100
+ return MarketQuote(
101
+ last=median_last,
102
+ timestamp=max(timestamps),
103
+ bid=_median(sorted(bids)) if bids else None,
104
+ ask=_median(sorted(asks)) if asks else None,
105
+ open=_median(sorted(opens)) if opens else None,
106
+ high=max(highs) if highs else None,
107
+ low=min(lows) if lows else None,
108
+ prev_close=_median(sorted(prev_closes)) if prev_closes else None,
109
+ volume=max(volumes) if volumes else None,
110
+ currency=quotes[0].currency,
111
+ source=f"composite-median:{len(quotes)}",
112
+ is_real_time=all(q.is_real_time for q in quotes),
113
+ )
114
+
115
+
116
+ def _median(sorted_values: list[float]) -> float:
117
+ n = len(sorted_values)
118
+ if n == 0:
119
+ raise ValueError("median of empty list")
120
+ mid = n // 2
121
+ if n % 2 == 1:
122
+ return sorted_values[mid]
123
+ return (sorted_values[mid - 1] + sorted_values[mid]) / 2.0
124
+
125
+
126
+ class CompositeProvider(MarketDataProvider):
127
+ """Fan-out across providers, then aggregate.
128
+
129
+ Defaults to first-wins (legacy semantics). Pass
130
+ ``aggregation=MedianAggregation()`` to fan out to *every* provider
131
+ in parallel and return the median.
132
+
133
+ Parameters
134
+ ----------
135
+ providers:
136
+ Ordered list. With first-wins, order matters; with median, order
137
+ only affects log/error reporting.
138
+ aggregation:
139
+ Aggregation strategy. Defaults to :func:`first_wins`.
140
+ parallel:
141
+ When True (default for non-first-wins aggregations), call all
142
+ providers concurrently in a thread pool. When False, call serially
143
+ (cheaper, easier to reason about, fine for first-wins).
144
+ name:
145
+ Optional override for ``info.name``.
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ providers: Sequence[MarketDataProvider],
151
+ aggregation: AggregationFn = first_wins,
152
+ parallel: bool | None = None,
153
+ name: str = "composite",
154
+ ) -> None:
155
+ self._providers: list[MarketDataProvider] = list(providers)
156
+ self._aggregation = aggregation
157
+ self._parallel = parallel if parallel is not None else (aggregation is not first_wins)
158
+ self._name = name
159
+
160
+ @property
161
+ def info(self) -> ProviderInfo:
162
+ # Union of capabilities — composite can deliver anything any of
163
+ # its members can.
164
+ caps = ProviderCapability.NONE
165
+ for p in self._providers:
166
+ caps |= p.capabilities
167
+ return ProviderInfo(
168
+ name=self._name,
169
+ description=f"Composite over {len(self._providers)} providers.",
170
+ capabilities=caps,
171
+ requires_api_key=any(p.info.requires_api_key for p in self._providers),
172
+ requires_network=any(p.info.requires_network for p in self._providers),
173
+ notes=", ".join(p.name for p in self._providers),
174
+ )
175
+
176
+ @property
177
+ def providers(self) -> list[MarketDataProvider]:
178
+ return list(self._providers)
179
+
180
+ def get_quote(self, symbol: str) -> MarketQuote | None:
181
+ if not self._providers:
182
+ return None
183
+
184
+ # First-wins fast path: short-circuit on the first hit.
185
+ if self._aggregation is first_wins and not self._parallel:
186
+ for p in self._providers:
187
+ try:
188
+ q = p.get_quote(symbol)
189
+ except Exception as e: # noqa: BLE001 — defensive
190
+ logger.warning("provider %s raised: %s", p.name, e)
191
+ continue
192
+ if q is not None:
193
+ return q
194
+ return None
195
+
196
+ # Fan-out path: parallel.
197
+ if self._parallel:
198
+ quotes = self._fanout_parallel(symbol)
199
+ else:
200
+ quotes = self._fanout_serial(symbol)
201
+ return self._aggregation(quotes)
202
+
203
+ # ── Internals ─────────────────────────────────────────────────────
204
+
205
+ def _fanout_serial(self, symbol: str) -> list[MarketQuote]:
206
+ out: list[MarketQuote] = []
207
+ for p in self._providers:
208
+ q = self._safe_call(p, symbol)
209
+ if q is not None:
210
+ out.append(q)
211
+ return out
212
+
213
+ def _fanout_parallel(self, symbol: str) -> list[MarketQuote]:
214
+ out: list[MarketQuote] = []
215
+ with ThreadPoolExecutor(max_workers=len(self._providers)) as pool:
216
+ futures = {
217
+ pool.submit(self._safe_call, p, symbol): p
218
+ for p in self._providers
219
+ }
220
+ for fut in as_completed(futures):
221
+ try:
222
+ q = fut.result(timeout=15)
223
+ except Exception as e: # noqa: BLE001 — defensive
224
+ logger.warning(
225
+ "provider %s raised: %s",
226
+ futures[fut].name, e,
227
+ )
228
+ continue
229
+ if q is not None:
230
+ out.append(q)
231
+ return out
232
+
233
+ @staticmethod
234
+ def _safe_call(p: MarketDataProvider, symbol: str) -> MarketQuote | None:
235
+ try:
236
+ return p.get_quote(symbol)
237
+ except Exception as e: # noqa: BLE001 — defensive
238
+ logger.warning("provider %s raised: %s", p.name, e)
239
+ return None
240
+
241
+
242
+ # Convenience: tag now to avoid clock skew across composed quotes.
243
+ def _now_str() -> str:
244
+ return datetime.now().isoformat(timespec="seconds")
@@ -0,0 +1,266 @@
1
+ """Dhan provider — free real broker feed with depth.
2
+
3
+ Dhan's market-data API is free for account holders and returns live
4
+ last price, OHLC, and 5-level market depth (bid/ask + sizes) — the same
5
+ fidelity the order-book simulator wants, at no monthly cost.
6
+
7
+ The security-id wrinkle
8
+ -----------------------
9
+ Unlike Kite (which keys quotes by ``"NSE:RELIANCE"``), Dhan keys
10
+ everything by a numeric ``security_id`` taken from its instrument master
11
+ CSV. So this provider needs a way to turn a trading symbol into a
12
+ security id. Supply one of:
13
+
14
+ - ``security_id_map={"RELIANCE": "2885", ...}`` at construction, or
15
+ - a ``resolve`` callable ``(symbol, segment) -> security_id | None``.
16
+
17
+ When a symbol can't be resolved we return ``None`` (treated as "unknown
18
+ symbol" by the fallback chain) rather than raising.
19
+
20
+ Auth
21
+ ----
22
+ Reads ``DHAN_CLIENT_ID`` and ``DHAN_ACCESS_TOKEN`` from the environment
23
+ by default. The access token is long-lived (unlike Kite's daily token).
24
+
25
+ Install: ``pip install papertrade-india[dhan]`` (pulls ``dhanhq``).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import logging
31
+ import os
32
+ from collections.abc import Callable
33
+ from datetime import datetime
34
+
35
+ from .base import (
36
+ MarketDataProvider,
37
+ MarketQuote,
38
+ ProviderCapability,
39
+ ProviderError,
40
+ ProviderInfo,
41
+ )
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # Dhan exchange-segment identifiers.
46
+ _SEGMENT = {"NSE": "NSE_EQ", "BSE": "BSE_EQ"}
47
+
48
+
49
+ class DhanProvider(MarketDataProvider):
50
+ """Dhan HQ market-data provider.
51
+
52
+ Parameters
53
+ ----------
54
+ client_id, access_token:
55
+ Dhan credentials. Fall back to ``DHAN_CLIENT_ID`` /
56
+ ``DHAN_ACCESS_TOKEN``.
57
+ exchange:
58
+ ``"NSE"`` (default) or ``"BSE"``.
59
+ security_id_map:
60
+ Optional ``{symbol: security_id}`` lookup. Required (or
61
+ ``resolve``) because Dhan keys quotes by numeric security id.
62
+ resolve:
63
+ Optional callable ``(symbol, segment) -> security_id | None``
64
+ for dynamic resolution against your own instrument master.
65
+ dhan:
66
+ Pre-built ``dhanhq`` client (mostly for tests). When supplied,
67
+ ``client_id`` / ``access_token`` are ignored.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ client_id: str | None = None,
73
+ access_token: str | None = None,
74
+ exchange: str = "NSE",
75
+ security_id_map: dict[str, str] | None = None,
76
+ resolve: Callable[[str, str], str | None] | None = None,
77
+ dhan: object | None = None,
78
+ ) -> None:
79
+ self._client_id = client_id or os.environ.get("DHAN_CLIENT_ID")
80
+ self._access_token = access_token or os.environ.get("DHAN_ACCESS_TOKEN")
81
+ self._exchange = exchange.upper()
82
+ self._segment = _SEGMENT.get(self._exchange, "NSE_EQ")
83
+ self._security_id_map = {
84
+ k.upper(): str(v) for k, v in (security_id_map or {}).items()
85
+ }
86
+ self._resolve = resolve
87
+ self._dhan = dhan
88
+
89
+ @property
90
+ def info(self) -> ProviderInfo:
91
+ caps = (
92
+ ProviderCapability.LAST_PRICE
93
+ | ProviderCapability.QUOTE
94
+ | ProviderCapability.REAL_TIME
95
+ )
96
+ if self._exchange == "NSE":
97
+ caps |= ProviderCapability.SUPPORTS_NSE
98
+ elif self._exchange == "BSE":
99
+ caps |= ProviderCapability.SUPPORTS_BSE
100
+ return ProviderInfo(
101
+ name="dhan",
102
+ description="Dhan HQ live market data (bid/ask + 5-level depth).",
103
+ capabilities=caps,
104
+ requires_api_key=True,
105
+ homepage="https://dhanhq.co/",
106
+ notes=(
107
+ "Set DHAN_CLIENT_ID and DHAN_ACCESS_TOKEN. Free for account "
108
+ "holders. Needs a symbol->security_id map (Dhan keys by id)."
109
+ ),
110
+ )
111
+
112
+ # ── Client + resolution ───────────────────────────────────────────
113
+
114
+ def _client(self) -> object:
115
+ if self._dhan is not None:
116
+ return self._dhan
117
+ if not self._client_id or not self._access_token:
118
+ raise ProviderError(
119
+ "Dhan credentials missing. Set DHAN_CLIENT_ID and "
120
+ "DHAN_ACCESS_TOKEN (or pass client_id=/access_token=)."
121
+ )
122
+ try:
123
+ from dhanhq import dhanhq # noqa: PLC0415
124
+ except ImportError as e:
125
+ raise ProviderError(
126
+ "dhanhq is not installed. "
127
+ "Install with: pip install papertrade-india[dhan]"
128
+ ) from e
129
+ client = dhanhq(self._client_id, self._access_token)
130
+ self._dhan = client
131
+ return client
132
+
133
+ def _security_id(self, symbol: str) -> str | None:
134
+ sym = symbol.upper()
135
+ if sym in self._security_id_map:
136
+ return self._security_id_map[sym]
137
+ if self._resolve is not None:
138
+ try:
139
+ return self._resolve(sym, self._segment)
140
+ except Exception as e: # noqa: BLE001
141
+ logger.debug("dhan resolve failed for %s: %s", sym, e)
142
+ return None
143
+ return None
144
+
145
+ # ── Quote ─────────────────────────────────────────────────────────
146
+
147
+ def get_quote(self, symbol: str) -> MarketQuote | None:
148
+ security_id = self._security_id(symbol)
149
+ if security_id is None:
150
+ logger.debug(
151
+ "dhan: no security_id for %s; supply security_id_map or resolve",
152
+ symbol,
153
+ )
154
+ return None
155
+
156
+ client = self._client()
157
+ try:
158
+ resp = client.quote_data( # type: ignore[attr-defined]
159
+ securities={self._segment: [int(security_id)]},
160
+ )
161
+ except Exception as e: # noqa: BLE001
162
+ raise ProviderError(f"dhan quote failed for {symbol}: {e}") from e
163
+
164
+ data = _extract(resp, self._segment, str(security_id))
165
+ if not data:
166
+ return None
167
+
168
+ last = _f(data.get("last_price"))
169
+ if last is None:
170
+ return None
171
+
172
+ bid, bid_size = _best(data, "buy")
173
+ ask, ask_size = _best(data, "sell")
174
+ ohlc = data.get("ohlc") or {}
175
+
176
+ ts = _parse_ts(data.get("last_trade_time") or data.get("LTT"))
177
+
178
+ return MarketQuote(
179
+ last=last,
180
+ timestamp=ts or datetime.now(),
181
+ bid=bid,
182
+ ask=ask,
183
+ bid_size=bid_size,
184
+ ask_size=ask_size,
185
+ open=_f(ohlc.get("open")),
186
+ high=_f(ohlc.get("high")),
187
+ low=_f(ohlc.get("low")),
188
+ prev_close=_f(ohlc.get("close")),
189
+ volume=_i(data.get("volume")),
190
+ source="dhan",
191
+ is_real_time=True,
192
+ )
193
+
194
+
195
+ # ── Parse helpers ─────────────────────────────────────────────────────
196
+
197
+
198
+ def _extract(resp: object, segment: str, security_id: str) -> dict | None:
199
+ """Dig the per-instrument block out of Dhan's nested response.
200
+
201
+ Dhan wraps the payload as ``{"status": "success", "data": {"data":
202
+ {"<segment>": {"<security_id>": {...}}}}}``. We tolerate a couple of
203
+ shape variations (with / without the outer ``data`` envelope).
204
+ """
205
+ if not isinstance(resp, dict):
206
+ return None
207
+ payload = resp.get("data", resp)
208
+ if isinstance(payload, dict) and "data" in payload:
209
+ payload = payload["data"]
210
+ if not isinstance(payload, dict):
211
+ return None
212
+ seg = payload.get(segment)
213
+ if not isinstance(seg, dict):
214
+ return None
215
+ block = seg.get(security_id) or seg.get(str(security_id))
216
+ return block if isinstance(block, dict) else None
217
+
218
+
219
+ def _best(data: dict, side: str) -> tuple[float | None, int | None]:
220
+ depth = data.get("depth") or {}
221
+ levels = depth.get(side) or []
222
+ if not levels:
223
+ return (None, None)
224
+ top = levels[0] or {}
225
+ return (_f(top.get("price")), _i(top.get("quantity")))
226
+
227
+
228
+ def _parse_ts(value: object) -> datetime | None:
229
+ """Parse Dhan's last-trade time (epoch seconds/ms or ISO string)."""
230
+ if isinstance(value, (int, float)) and value > 0:
231
+ # Dhan epochs are seconds; ms values are ~1e12.
232
+ secs = value / 1000.0 if value > 1e11 else float(value)
233
+ try:
234
+ return datetime.fromtimestamp(secs)
235
+ except (OverflowError, OSError, ValueError):
236
+ return None
237
+ if isinstance(value, str):
238
+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"):
239
+ try:
240
+ return datetime.strptime(value, fmt)
241
+ except ValueError:
242
+ continue
243
+ return None
244
+
245
+
246
+ def _f(x: object) -> float | None:
247
+ try:
248
+ if x is None:
249
+ return None
250
+ v = float(x)
251
+ return v if v > 0 else None
252
+ except (TypeError, ValueError):
253
+ return None
254
+
255
+
256
+ def _i(x: object) -> int | None:
257
+ try:
258
+ if x is None:
259
+ return None
260
+ v = int(float(x))
261
+ return v if v >= 0 else None
262
+ except (TypeError, ValueError):
263
+ return None
264
+
265
+
266
+ __all__ = ["DhanProvider"]
@@ -0,0 +1,122 @@
1
+ """Finnhub provider — REST API with a free tier (60 req/min).
2
+
3
+ Sets a real-time-ish (~quote-level) feed on the free tier for many
4
+ exchanges, including BSE and NSE. API key from env ``FINNHUB_API_KEY``
5
+ by default.
6
+
7
+ Indian symbols: append ``.NS`` for NSE, ``.BO`` for BSE on Finnhub.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ import urllib.parse
16
+ import urllib.request
17
+ from datetime import datetime
18
+ from urllib.error import HTTPError, URLError
19
+
20
+ from .base import (
21
+ MarketDataProvider,
22
+ MarketQuote,
23
+ ProviderCapability,
24
+ ProviderError,
25
+ ProviderInfo,
26
+ )
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ _BASE = "https://finnhub.io/api/v1"
31
+
32
+
33
+ class FinnhubProvider(MarketDataProvider):
34
+ """Finnhub REST API."""
35
+
36
+ def __init__(
37
+ self,
38
+ api_key: str | None = None,
39
+ suffix: str = "NS",
40
+ timeout: float = 10.0,
41
+ ) -> None:
42
+ self._api_key = api_key or os.environ.get("FINNHUB_API_KEY")
43
+ self._suffix = suffix.lstrip(".")
44
+ self._timeout = float(timeout)
45
+
46
+ @property
47
+ def info(self) -> ProviderInfo:
48
+ caps = (
49
+ ProviderCapability.LAST_PRICE
50
+ | ProviderCapability.QUOTE
51
+ | ProviderCapability.REAL_TIME
52
+ )
53
+ if self._suffix.upper() == "NS":
54
+ caps |= ProviderCapability.SUPPORTS_NSE
55
+ elif self._suffix.upper() == "BO":
56
+ caps |= ProviderCapability.SUPPORTS_BSE
57
+ return ProviderInfo(
58
+ name="finnhub",
59
+ description="Finnhub REST API.",
60
+ capabilities=caps,
61
+ requires_api_key=True,
62
+ homepage="https://finnhub.io/",
63
+ notes="Set FINNHUB_API_KEY. Free tier: 60 req/min.",
64
+ )
65
+
66
+ def get_quote(self, symbol: str) -> MarketQuote | None:
67
+ if not self._api_key:
68
+ raise ProviderError(
69
+ "Finnhub API key missing. Set FINNHUB_API_KEY or pass api_key=...",
70
+ )
71
+ params = urllib.parse.urlencode(
72
+ {"symbol": f"{symbol.upper()}.{self._suffix}", "token": self._api_key},
73
+ )
74
+ url = f"{_BASE}/quote?{params}"
75
+ try:
76
+ with urllib.request.urlopen(url, timeout=self._timeout) as resp: # noqa: S310
77
+ body = resp.read().decode("utf-8", errors="replace")
78
+ except HTTPError as e:
79
+ if e.code in (401, 403):
80
+ raise ProviderError(f"finnhub auth failed (HTTP {e.code})") from e
81
+ raise ProviderError(f"finnhub HTTP {e.code}") from e
82
+ except (URLError, TimeoutError) as e:
83
+ raise ProviderError(f"finnhub fetch failed: {e}") from e
84
+
85
+ try:
86
+ data = json.loads(body)
87
+ except json.JSONDecodeError as e:
88
+ raise ProviderError(f"finnhub non-JSON: {body[:200]}") from e
89
+
90
+ # Finnhub returns ``{"c": 0, ...}`` for unknown symbols.
91
+ try:
92
+ last = float(data.get("c") or 0)
93
+ except (TypeError, ValueError):
94
+ return None
95
+ if last <= 0:
96
+ return None
97
+
98
+ timestamp = (
99
+ datetime.fromtimestamp(int(data["t"]))
100
+ if isinstance(data.get("t"), (int, float)) and data["t"] > 0
101
+ else datetime.now()
102
+ )
103
+ return MarketQuote(
104
+ last=last,
105
+ timestamp=timestamp,
106
+ open=_f(data.get("o")),
107
+ high=_f(data.get("h")),
108
+ low=_f(data.get("l")),
109
+ prev_close=_f(data.get("pc")),
110
+ source="finnhub",
111
+ is_real_time=True, # Finnhub is generally near-real-time
112
+ )
113
+
114
+
115
+ def _f(x: object) -> float | None:
116
+ try:
117
+ if x is None:
118
+ return None
119
+ v = float(x)
120
+ return v if v > 0 else None
121
+ except (TypeError, ValueError):
122
+ return None