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.
- papertrade_india/__init__.py +250 -0
- papertrade_india/_context.py +144 -0
- papertrade_india/broker.py +546 -0
- papertrade_india/cli.py +474 -0
- papertrade_india/clock.py +29 -0
- papertrade_india/corporate_actions/__init__.py +10 -0
- papertrade_india/corporate_actions/bonus.py +105 -0
- papertrade_india/corporate_actions/dividends.py +99 -0
- papertrade_india/corporate_actions/rights.py +189 -0
- papertrade_india/corporate_actions/splits.py +111 -0
- papertrade_india/corporate_actions/store.py +247 -0
- papertrade_india/data/nse_holidays_2026.json +22 -0
- papertrade_india/data/nse_holidays_2027.json +9 -0
- papertrade_india/data/nse_universe_sample.csv +31 -0
- papertrade_india/domain/__init__.py +6 -0
- papertrade_india/domain/exceptions.py +183 -0
- papertrade_india/domain/models.py +213 -0
- papertrade_india/domain/rules/__init__.py +5 -0
- papertrade_india/domain/rules/risk.py +165 -0
- papertrade_india/domain/rules/tick_lot_band.py +139 -0
- papertrade_india/events.py +29 -0
- papertrade_india/exceptions.py +29 -0
- papertrade_india/execution/__init__.py +5 -0
- papertrade_india/execution/book.py +385 -0
- papertrade_india/execution/fees.py +213 -0
- papertrade_india/execution/settlement.py +360 -0
- papertrade_india/execution/simulation.py +176 -0
- papertrade_india/execution/slippage.py +120 -0
- papertrade_india/fees.py +29 -0
- papertrade_india/idempotency.py +29 -0
- papertrade_india/infrastructure/__init__.py +6 -0
- papertrade_india/infrastructure/clock.py +123 -0
- papertrade_india/infrastructure/events.py +137 -0
- papertrade_india/infrastructure/holidays.py +138 -0
- papertrade_india/infrastructure/idempotency.py +133 -0
- papertrade_india/infrastructure/ledger.py +141 -0
- papertrade_india/infrastructure/market_hours.py +200 -0
- papertrade_india/infrastructure/migrations.py +622 -0
- papertrade_india/infrastructure/observability.py +195 -0
- papertrade_india/infrastructure/persistence.py +130 -0
- papertrade_india/infrastructure/symbols.py +279 -0
- papertrade_india/infrastructure/watchlist.py +78 -0
- papertrade_india/interface.py +92 -0
- papertrade_india/ledger.py +29 -0
- papertrade_india/limit_orders.py +29 -0
- papertrade_india/market_hours.py +29 -0
- papertrade_india/microstructure.py +57 -0
- papertrade_india/migrations.py +29 -0
- papertrade_india/models.py +29 -0
- papertrade_india/observability.py +29 -0
- papertrade_india/orders/__init__.py +5 -0
- papertrade_india/orders/amo.py +98 -0
- papertrade_india/orders/book_helpers.py +111 -0
- papertrade_india/orders/bracket.py +115 -0
- papertrade_india/orders/limit.py +210 -0
- papertrade_india/orders/market.py +264 -0
- papertrade_india/orders/partial_fills.py +92 -0
- papertrade_india/orders/preopen.py +274 -0
- papertrade_india/orders/state.py +640 -0
- papertrade_india/orders/stop.py +122 -0
- papertrade_india/orders/submit.py +385 -0
- papertrade_india/partial_fills.py +29 -0
- papertrade_india/persistence.py +29 -0
- papertrade_india/preopen.py +29 -0
- papertrade_india/presets.py +120 -0
- papertrade_india/price_feed.py +316 -0
- papertrade_india/providers/__init__.py +123 -0
- papertrade_india/providers/alphavantage.py +180 -0
- papertrade_india/providers/base.py +256 -0
- papertrade_india/providers/cache.py +147 -0
- papertrade_india/providers/composite.py +244 -0
- papertrade_india/providers/dhan.py +266 -0
- papertrade_india/providers/finnhub.py +122 -0
- papertrade_india/providers/health.py +233 -0
- papertrade_india/providers/jugaad.py +142 -0
- papertrade_india/providers/kite.py +222 -0
- papertrade_india/providers/nse_bhavcopy.py +210 -0
- papertrade_india/providers/nsepython.py +98 -0
- papertrade_india/providers/registry.py +226 -0
- papertrade_india/providers/stooq.py +173 -0
- papertrade_india/providers/twelvedata.py +198 -0
- papertrade_india/providers/upstox.py +318 -0
- papertrade_india/providers/upstox_instruments.py +171 -0
- papertrade_india/providers/yfinance.py +205 -0
- papertrade_india/quickstart.py +111 -0
- papertrade_india/reads/__init__.py +6 -0
- papertrade_india/reads/account.py +140 -0
- papertrade_india/reads/orders.py +54 -0
- papertrade_india/reads/positions.py +188 -0
- papertrade_india/risk.py +29 -0
- papertrade_india/settlement.py +29 -0
- papertrade_india/simulation.py +29 -0
- papertrade_india/slippage.py +29 -0
- papertrade_india/symbols.py +29 -0
- papertrade_india/workers/__init__.py +6 -0
- papertrade_india/workers/limit_orders.py +390 -0
- papertrade_india-0.1.0.dev0.dist-info/METADATA +261 -0
- papertrade_india-0.1.0.dev0.dist-info/RECORD +101 -0
- papertrade_india-0.1.0.dev0.dist-info/WHEEL +4 -0
- papertrade_india-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- papertrade_india-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Per-provider health tracking + circuit breaker.
|
|
2
|
+
|
|
3
|
+
Every external call must be wrapped in a circuit breaker (per the
|
|
4
|
+
backend-rules steering). The breaker has three states:
|
|
5
|
+
|
|
6
|
+
- CLOSED: requests flow. Failures are counted in a rolling window.
|
|
7
|
+
- OPEN: requests fail fast (returning ``None`` to the upstream
|
|
8
|
+
composite, which then tries the next provider). Triggered on
|
|
9
|
+
≥ ``failure_threshold`` consecutive failures or > 50% failures in
|
|
10
|
+
the rolling window.
|
|
11
|
+
- HALF_OPEN: after ``open_seconds``, one probe is allowed. On success
|
|
12
|
+
the breaker closes; on failure it re-opens.
|
|
13
|
+
|
|
14
|
+
Wrapping is opt-in at construction time:
|
|
15
|
+
|
|
16
|
+
>>> wrapped = CircuitBreakerProvider(YFinanceProvider("NS"))
|
|
17
|
+
|
|
18
|
+
The wrapper preserves the underlying provider's :class:`ProviderInfo`
|
|
19
|
+
so the registry/CLI sees the original name and capabilities.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
import time
|
|
26
|
+
from collections import deque
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from datetime import date, datetime
|
|
29
|
+
from enum import Enum
|
|
30
|
+
from threading import RLock
|
|
31
|
+
|
|
32
|
+
from .base import (
|
|
33
|
+
OHLCV,
|
|
34
|
+
MarketDataProvider,
|
|
35
|
+
MarketQuote,
|
|
36
|
+
ProviderError,
|
|
37
|
+
ProviderInfo,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _State(str, Enum):
|
|
44
|
+
CLOSED = "closed"
|
|
45
|
+
OPEN = "open"
|
|
46
|
+
HALF_OPEN = "half_open"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class ProviderHealth:
|
|
51
|
+
"""Snapshot of a provider's circuit-breaker state.
|
|
52
|
+
|
|
53
|
+
Surfaced via :attr:`CircuitBreakerProvider.health` for dashboards
|
|
54
|
+
and the CLI.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
name: str
|
|
58
|
+
state: _State = _State.CLOSED
|
|
59
|
+
consecutive_failures: int = 0
|
|
60
|
+
total_calls: int = 0
|
|
61
|
+
total_failures: int = 0
|
|
62
|
+
last_failure_at: datetime | None = None
|
|
63
|
+
last_success_at: datetime | None = None
|
|
64
|
+
opened_at: float | None = None # monotonic
|
|
65
|
+
recent_results: deque[bool] = field(default_factory=lambda: deque(maxlen=20))
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def is_open(self) -> bool:
|
|
69
|
+
return self.state == _State.OPEN
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def failure_rate(self) -> float:
|
|
73
|
+
"""Failure rate over the rolling window (0.0–1.0)."""
|
|
74
|
+
if not self.recent_results:
|
|
75
|
+
return 0.0
|
|
76
|
+
fails = sum(1 for ok in self.recent_results if not ok)
|
|
77
|
+
return fails / len(self.recent_results)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class CircuitBreakerProvider(MarketDataProvider):
|
|
81
|
+
"""Wraps a :class:`MarketDataProvider` with a circuit breaker.
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
inner:
|
|
86
|
+
The provider being wrapped.
|
|
87
|
+
failure_threshold:
|
|
88
|
+
Open after this many consecutive failures. Default 5.
|
|
89
|
+
failure_rate_threshold:
|
|
90
|
+
Open when the rolling window's failure rate exceeds this.
|
|
91
|
+
Default 0.5 (50%).
|
|
92
|
+
window_size:
|
|
93
|
+
Rolling-window size in calls. Default 20.
|
|
94
|
+
open_seconds:
|
|
95
|
+
How long the breaker stays OPEN before allowing a probe.
|
|
96
|
+
Default 30 seconds.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
inner: MarketDataProvider,
|
|
102
|
+
failure_threshold: int = 5,
|
|
103
|
+
failure_rate_threshold: float = 0.5,
|
|
104
|
+
window_size: int = 20,
|
|
105
|
+
open_seconds: float = 30.0,
|
|
106
|
+
) -> None:
|
|
107
|
+
self._inner = inner
|
|
108
|
+
self._failure_threshold = int(failure_threshold)
|
|
109
|
+
self._failure_rate_threshold = float(failure_rate_threshold)
|
|
110
|
+
self._open_seconds = float(open_seconds)
|
|
111
|
+
self._lock = RLock()
|
|
112
|
+
self._health = ProviderHealth(
|
|
113
|
+
name=inner.name,
|
|
114
|
+
recent_results=deque(maxlen=int(window_size)),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# ── Pass-through introspection ────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def info(self) -> ProviderInfo:
|
|
121
|
+
return self._inner.info
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def inner(self) -> MarketDataProvider:
|
|
125
|
+
return self._inner
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def health(self) -> ProviderHealth:
|
|
129
|
+
with self._lock:
|
|
130
|
+
return self._health
|
|
131
|
+
|
|
132
|
+
# ── Breaker mechanics ─────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
def _allow_call(self) -> bool:
|
|
135
|
+
"""Decide whether to attempt a call to the inner provider."""
|
|
136
|
+
with self._lock:
|
|
137
|
+
if self._health.state == _State.CLOSED:
|
|
138
|
+
return True
|
|
139
|
+
if self._health.state == _State.HALF_OPEN:
|
|
140
|
+
# Already probing — only one in-flight request.
|
|
141
|
+
return False
|
|
142
|
+
# OPEN: check whether to transition to HALF_OPEN.
|
|
143
|
+
opened_at = self._health.opened_at or 0.0
|
|
144
|
+
if (time.monotonic() - opened_at) >= self._open_seconds:
|
|
145
|
+
self._health.state = _State.HALF_OPEN
|
|
146
|
+
logger.info(
|
|
147
|
+
"Circuit breaker for %s → HALF_OPEN (probing)",
|
|
148
|
+
self._inner.name,
|
|
149
|
+
)
|
|
150
|
+
return True
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
def _record_success(self) -> None:
|
|
154
|
+
with self._lock:
|
|
155
|
+
self._health.total_calls += 1
|
|
156
|
+
self._health.consecutive_failures = 0
|
|
157
|
+
self._health.last_success_at = datetime.now()
|
|
158
|
+
self._health.recent_results.append(True)
|
|
159
|
+
if self._health.state in (_State.HALF_OPEN, _State.OPEN):
|
|
160
|
+
logger.info(
|
|
161
|
+
"Circuit breaker for %s → CLOSED",
|
|
162
|
+
self._inner.name,
|
|
163
|
+
)
|
|
164
|
+
self._health.state = _State.CLOSED
|
|
165
|
+
self._health.opened_at = None
|
|
166
|
+
|
|
167
|
+
def _record_failure(self) -> None:
|
|
168
|
+
with self._lock:
|
|
169
|
+
self._health.total_calls += 1
|
|
170
|
+
self._health.total_failures += 1
|
|
171
|
+
self._health.consecutive_failures += 1
|
|
172
|
+
self._health.last_failure_at = datetime.now()
|
|
173
|
+
self._health.recent_results.append(False)
|
|
174
|
+
should_open = (
|
|
175
|
+
self._health.consecutive_failures >= self._failure_threshold
|
|
176
|
+
or self._health.failure_rate > self._failure_rate_threshold
|
|
177
|
+
)
|
|
178
|
+
if should_open and self._health.state != _State.OPEN:
|
|
179
|
+
self._health.state = _State.OPEN
|
|
180
|
+
self._health.opened_at = time.monotonic()
|
|
181
|
+
logger.warning(
|
|
182
|
+
"Circuit breaker OPEN for %s "
|
|
183
|
+
"(consec=%d, rate=%.0f%%, opening for %ss)",
|
|
184
|
+
self._inner.name,
|
|
185
|
+
self._health.consecutive_failures,
|
|
186
|
+
self._health.failure_rate * 100,
|
|
187
|
+
self._open_seconds,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
def reset(self) -> None:
|
|
191
|
+
"""Force the breaker back to CLOSED. For tests + ops."""
|
|
192
|
+
with self._lock:
|
|
193
|
+
self._health.state = _State.CLOSED
|
|
194
|
+
self._health.consecutive_failures = 0
|
|
195
|
+
self._health.opened_at = None
|
|
196
|
+
self._health.recent_results.clear()
|
|
197
|
+
|
|
198
|
+
# ── Provider hot path ─────────────────────────────────────────────
|
|
199
|
+
|
|
200
|
+
def get_quote(self, symbol: str) -> MarketQuote | None:
|
|
201
|
+
if not self._allow_call():
|
|
202
|
+
return None
|
|
203
|
+
try:
|
|
204
|
+
quote = self._inner.get_quote(symbol)
|
|
205
|
+
except ProviderError:
|
|
206
|
+
self._record_failure()
|
|
207
|
+
return None
|
|
208
|
+
except Exception: # noqa: BLE001 — defensive
|
|
209
|
+
self._record_failure()
|
|
210
|
+
return None
|
|
211
|
+
# ``None`` for an unknown symbol is *not* a circuit-breaker
|
|
212
|
+
# failure — it's the provider correctly saying "not mine".
|
|
213
|
+
if quote is not None:
|
|
214
|
+
self._record_success()
|
|
215
|
+
return quote
|
|
216
|
+
|
|
217
|
+
def get_history(
|
|
218
|
+
self,
|
|
219
|
+
symbol: str,
|
|
220
|
+
start: date,
|
|
221
|
+
end: date,
|
|
222
|
+
interval: str = "1d",
|
|
223
|
+
) -> list[OHLCV]:
|
|
224
|
+
if not self._allow_call():
|
|
225
|
+
return []
|
|
226
|
+
try:
|
|
227
|
+
bars = self._inner.get_history(symbol, start, end, interval)
|
|
228
|
+
except Exception: # noqa: BLE001
|
|
229
|
+
self._record_failure()
|
|
230
|
+
return []
|
|
231
|
+
if bars:
|
|
232
|
+
self._record_success()
|
|
233
|
+
return bars
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""jugaad-data provider — direct NSE scraping.
|
|
2
|
+
|
|
3
|
+
Community-maintained scraper of the NSE site. Fragile by design (any
|
|
4
|
+
markup change can break it), but useful as a fallback when Yahoo
|
|
5
|
+
rate-limits. NSE-only — there's no BSE equivalent in jugaad.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from datetime import date, datetime, timedelta
|
|
12
|
+
|
|
13
|
+
from .base import (
|
|
14
|
+
OHLCV,
|
|
15
|
+
MarketDataProvider,
|
|
16
|
+
MarketQuote,
|
|
17
|
+
ProviderCapability,
|
|
18
|
+
ProviderError,
|
|
19
|
+
ProviderInfo,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class JugaadDataProvider(MarketDataProvider):
|
|
26
|
+
"""NSE direct via the ``jugaad-data`` package.
|
|
27
|
+
|
|
28
|
+
Install with the optional extra: ``pip install 'papertrade-india[jugaad]'``.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def info(self) -> ProviderInfo:
|
|
33
|
+
return ProviderInfo(
|
|
34
|
+
name="jugaad-data",
|
|
35
|
+
description="Community NSE scraper via jugaad-data.",
|
|
36
|
+
capabilities=(
|
|
37
|
+
ProviderCapability.LAST_PRICE
|
|
38
|
+
| ProviderCapability.QUOTE
|
|
39
|
+
| ProviderCapability.OHLCV_DAILY
|
|
40
|
+
| ProviderCapability.SUPPORTS_NSE
|
|
41
|
+
| ProviderCapability.DELAYED
|
|
42
|
+
),
|
|
43
|
+
requires_api_key=False,
|
|
44
|
+
homepage="https://github.com/jugaad-py/jugaad-data",
|
|
45
|
+
notes="NSE only. Scraper — treat failures as expected.",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def get_quote(self, symbol: str) -> MarketQuote | None:
|
|
49
|
+
try:
|
|
50
|
+
from jugaad_data.nse import NSELive # type: ignore
|
|
51
|
+
except ImportError as e:
|
|
52
|
+
raise ProviderError(
|
|
53
|
+
"jugaad-data is not installed. "
|
|
54
|
+
"Install with: pip install 'papertrade-india[jugaad]'"
|
|
55
|
+
) from e
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
n = NSELive()
|
|
59
|
+
data = n.stock_quote(symbol)
|
|
60
|
+
except Exception as e: # noqa: BLE001 — scraper volatility
|
|
61
|
+
logger.warning("jugaad-data failed for %s: %s", symbol, e)
|
|
62
|
+
raise ProviderError(f"jugaad-data failed for {symbol}: {e}") from e
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
price_info = data.get("priceInfo") or {}
|
|
66
|
+
last = float(price_info["lastPrice"])
|
|
67
|
+
except (KeyError, TypeError, ValueError):
|
|
68
|
+
return None # symbol unknown to NSE
|
|
69
|
+
|
|
70
|
+
# ``iNavValue`` exists in some NSE responses but isn't a true bid;
|
|
71
|
+
# we leave bid/ask out and let consumers detect missing fields.
|
|
72
|
+
ohlc = price_info.get("intraDayHighLow") or {}
|
|
73
|
+
day_high = _safe_get(ohlc, "max")
|
|
74
|
+
day_low = _safe_get(ohlc, "min")
|
|
75
|
+
prev_close = _safe_get(price_info, "previousClose")
|
|
76
|
+
day_open = _safe_get(price_info, "open")
|
|
77
|
+
|
|
78
|
+
return MarketQuote(
|
|
79
|
+
last=last,
|
|
80
|
+
timestamp=datetime.now(),
|
|
81
|
+
bid=None,
|
|
82
|
+
ask=None,
|
|
83
|
+
open=day_open,
|
|
84
|
+
high=day_high,
|
|
85
|
+
low=day_low,
|
|
86
|
+
prev_close=prev_close,
|
|
87
|
+
source="jugaad-data",
|
|
88
|
+
is_real_time=False,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def get_history(
|
|
92
|
+
self,
|
|
93
|
+
symbol: str,
|
|
94
|
+
start: date,
|
|
95
|
+
end: date,
|
|
96
|
+
interval: str = "1d",
|
|
97
|
+
) -> list[OHLCV]:
|
|
98
|
+
if interval != "1d":
|
|
99
|
+
return []
|
|
100
|
+
try:
|
|
101
|
+
from jugaad_data.nse import stock_df # type: ignore
|
|
102
|
+
except ImportError as e:
|
|
103
|
+
raise ProviderError("jugaad-data is not installed") from e
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
df = stock_df(
|
|
107
|
+
symbol=symbol,
|
|
108
|
+
from_date=start,
|
|
109
|
+
to_date=end + timedelta(days=0),
|
|
110
|
+
series="EQ",
|
|
111
|
+
)
|
|
112
|
+
except Exception as e: # noqa: BLE001
|
|
113
|
+
raise ProviderError(f"jugaad-data history failed: {e}") from e
|
|
114
|
+
|
|
115
|
+
out: list[OHLCV] = []
|
|
116
|
+
for _, row in df.iterrows():
|
|
117
|
+
try:
|
|
118
|
+
ts = row["DATE"]
|
|
119
|
+
ts = ts if isinstance(ts, datetime) else datetime.combine(
|
|
120
|
+
ts, datetime.min.time(),
|
|
121
|
+
)
|
|
122
|
+
out.append(
|
|
123
|
+
OHLCV(
|
|
124
|
+
timestamp=ts,
|
|
125
|
+
open=float(row["OPEN"]),
|
|
126
|
+
high=float(row["HIGH"]),
|
|
127
|
+
low=float(row["LOW"]),
|
|
128
|
+
close=float(row["CLOSE"]),
|
|
129
|
+
volume=int(row.get("VOLUME", 0) or 0),
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
except Exception: # noqa: BLE001
|
|
133
|
+
continue
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _safe_get(d: dict, key: str) -> float | None:
|
|
138
|
+
try:
|
|
139
|
+
v = d.get(key)
|
|
140
|
+
return float(v) if v is not None else None
|
|
141
|
+
except (TypeError, ValueError):
|
|
142
|
+
return None
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Zerodha Kite Connect provider — real broker feed with full depth.
|
|
2
|
+
|
|
3
|
+
This is the highest-fidelity provider for Indian equities short of a
|
|
4
|
+
paid tick feed: it returns the live last-traded price, the best bid/ask
|
|
5
|
+
with sizes, and the top-of-book depth that the order-book simulator
|
|
6
|
+
needs to walk realistic fills.
|
|
7
|
+
|
|
8
|
+
Why this matters
|
|
9
|
+
----------------
|
|
10
|
+
yfinance and the other public providers deliver a delayed last-trade
|
|
11
|
+
with no bid/ask. With no real spread, :class:`OrderBookSimulator`
|
|
12
|
+
falls back to a synthetic book. A Kite quote carries the genuine
|
|
13
|
+
bid/ask + depth, so fills land where a real Zerodha order would land.
|
|
14
|
+
|
|
15
|
+
Auth
|
|
16
|
+
----
|
|
17
|
+
Kite uses an API key + a daily-rotated access token (obtained via the
|
|
18
|
+
login flow). Both are read from the environment by default:
|
|
19
|
+
|
|
20
|
+
- ``KITE_API_KEY``
|
|
21
|
+
- ``KITE_ACCESS_TOKEN``
|
|
22
|
+
|
|
23
|
+
The access token expires every trading day; refreshing it is the
|
|
24
|
+
caller's responsibility (run your login flow, then set the env var or
|
|
25
|
+
pass ``access_token=...``). When the token is stale, Kite returns a
|
|
26
|
+
``TokenException`` which we surface as :class:`ProviderError` so the
|
|
27
|
+
fallback chain can move on.
|
|
28
|
+
|
|
29
|
+
Pricing: Kite Connect is ₹500/month per API key for live + historical
|
|
30
|
+
data (free "Personal" tier covers order placement but not market data).
|
|
31
|
+
|
|
32
|
+
Install: ``pip install papertrade-india[kite]`` (pulls ``kiteconnect``).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import logging
|
|
38
|
+
import os
|
|
39
|
+
from datetime import datetime
|
|
40
|
+
|
|
41
|
+
from .base import (
|
|
42
|
+
MarketDataProvider,
|
|
43
|
+
MarketQuote,
|
|
44
|
+
ProviderCapability,
|
|
45
|
+
ProviderError,
|
|
46
|
+
ProviderInfo,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger(__name__)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class KiteProvider(MarketDataProvider):
|
|
53
|
+
"""Zerodha Kite Connect market-data provider.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
api_key:
|
|
58
|
+
Kite Connect API key. Falls back to ``KITE_API_KEY``.
|
|
59
|
+
access_token:
|
|
60
|
+
Daily access token from the login flow. Falls back to
|
|
61
|
+
``KITE_ACCESS_TOKEN``.
|
|
62
|
+
exchange:
|
|
63
|
+
``"NSE"`` (default) or ``"BSE"``. Kite quote keys are
|
|
64
|
+
``"<EXCHANGE>:<TRADINGSYMBOL>"`` e.g. ``"NSE:RELIANCE"``.
|
|
65
|
+
kite:
|
|
66
|
+
Pre-built ``KiteConnect`` client (mostly for tests / advanced
|
|
67
|
+
callers who already manage the session). When supplied,
|
|
68
|
+
``api_key`` / ``access_token`` are ignored.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
api_key: str | None = None,
|
|
74
|
+
access_token: str | None = None,
|
|
75
|
+
exchange: str = "NSE",
|
|
76
|
+
kite: object | None = None,
|
|
77
|
+
) -> None:
|
|
78
|
+
self._api_key = api_key or os.environ.get("KITE_API_KEY")
|
|
79
|
+
self._access_token = access_token or os.environ.get("KITE_ACCESS_TOKEN")
|
|
80
|
+
self._exchange = exchange.upper()
|
|
81
|
+
self._kite = kite # injected client wins over lazy construction
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def info(self) -> ProviderInfo:
|
|
85
|
+
caps = (
|
|
86
|
+
ProviderCapability.LAST_PRICE
|
|
87
|
+
| ProviderCapability.QUOTE
|
|
88
|
+
| ProviderCapability.REAL_TIME
|
|
89
|
+
)
|
|
90
|
+
if self._exchange == "NSE":
|
|
91
|
+
caps |= ProviderCapability.SUPPORTS_NSE
|
|
92
|
+
elif self._exchange == "BSE":
|
|
93
|
+
caps |= ProviderCapability.SUPPORTS_BSE
|
|
94
|
+
return ProviderInfo(
|
|
95
|
+
name="kite",
|
|
96
|
+
description="Zerodha Kite Connect live market data (bid/ask + depth).",
|
|
97
|
+
capabilities=caps,
|
|
98
|
+
requires_api_key=True,
|
|
99
|
+
homepage="https://kite.trade/",
|
|
100
|
+
notes=(
|
|
101
|
+
"Set KITE_API_KEY and KITE_ACCESS_TOKEN (token rotates daily). "
|
|
102
|
+
"Live data plan: Rs.500/month per API key."
|
|
103
|
+
),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# ── Client construction ───────────────────────────────────────────
|
|
107
|
+
|
|
108
|
+
def _client(self) -> object:
|
|
109
|
+
"""Return the Kite client, building it lazily on first use."""
|
|
110
|
+
if self._kite is not None:
|
|
111
|
+
return self._kite
|
|
112
|
+
if not self._api_key or not self._access_token:
|
|
113
|
+
raise ProviderError(
|
|
114
|
+
"Kite credentials missing. Set KITE_API_KEY and "
|
|
115
|
+
"KITE_ACCESS_TOKEN (or pass api_key=/access_token=)."
|
|
116
|
+
)
|
|
117
|
+
try:
|
|
118
|
+
from kiteconnect import KiteConnect # noqa: PLC0415
|
|
119
|
+
except ImportError as e:
|
|
120
|
+
raise ProviderError(
|
|
121
|
+
"kiteconnect is not installed. "
|
|
122
|
+
"Install with: pip install papertrade-india[kite]"
|
|
123
|
+
) from e
|
|
124
|
+
client = KiteConnect(api_key=self._api_key)
|
|
125
|
+
client.set_access_token(self._access_token)
|
|
126
|
+
self._kite = client
|
|
127
|
+
return client
|
|
128
|
+
|
|
129
|
+
# ── Quote ─────────────────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
def get_quote(self, symbol: str) -> MarketQuote | None:
|
|
132
|
+
client = self._client()
|
|
133
|
+
instrument = f"{self._exchange}:{symbol.upper()}"
|
|
134
|
+
try:
|
|
135
|
+
resp = client.quote(instrument) # type: ignore[attr-defined]
|
|
136
|
+
except Exception as e: # noqa: BLE001 — SDK raises various exc types
|
|
137
|
+
# TokenException, NetworkException, etc. all become ProviderError
|
|
138
|
+
# so the fallback chain can try the next provider.
|
|
139
|
+
raise ProviderError(f"kite quote failed for {symbol}: {e}") from e
|
|
140
|
+
|
|
141
|
+
data = resp.get(instrument) if isinstance(resp, dict) else None
|
|
142
|
+
if not data:
|
|
143
|
+
return None # genuinely unknown symbol
|
|
144
|
+
|
|
145
|
+
last = _f(data.get("last_price"))
|
|
146
|
+
if last is None:
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
bid, bid_size = _best(data, "buy")
|
|
150
|
+
ask, ask_size = _best(data, "sell")
|
|
151
|
+
ohlc = data.get("ohlc") or {}
|
|
152
|
+
|
|
153
|
+
ts = _parse_ts(data.get("timestamp") or data.get("last_trade_time"))
|
|
154
|
+
|
|
155
|
+
return MarketQuote(
|
|
156
|
+
last=last,
|
|
157
|
+
timestamp=ts or datetime.now(),
|
|
158
|
+
bid=bid,
|
|
159
|
+
ask=ask,
|
|
160
|
+
bid_size=bid_size,
|
|
161
|
+
ask_size=ask_size,
|
|
162
|
+
open=_f(ohlc.get("open")),
|
|
163
|
+
high=_f(ohlc.get("high")),
|
|
164
|
+
low=_f(ohlc.get("low")),
|
|
165
|
+
prev_close=_f(ohlc.get("close")),
|
|
166
|
+
volume=_i(data.get("volume")),
|
|
167
|
+
source="kite",
|
|
168
|
+
is_real_time=True,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ── Parse helpers ─────────────────────────────────────────────────────
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _best(data: dict, side: str) -> tuple[float | None, int | None]:
|
|
176
|
+
"""Extract best (price, quantity) from the Kite depth block.
|
|
177
|
+
|
|
178
|
+
``data["depth"]["buy"|"sell"]`` is a list of ``{price, quantity,
|
|
179
|
+
orders}`` ordered best-first. Returns ``(None, None)`` when depth is
|
|
180
|
+
absent (e.g. a non-depth quote endpoint).
|
|
181
|
+
"""
|
|
182
|
+
depth = data.get("depth") or {}
|
|
183
|
+
levels = depth.get(side) or []
|
|
184
|
+
if not levels:
|
|
185
|
+
return (None, None)
|
|
186
|
+
top = levels[0] or {}
|
|
187
|
+
return (_f(top.get("price")), _i(top.get("quantity")))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _parse_ts(value: object) -> datetime | None:
|
|
191
|
+
if isinstance(value, datetime):
|
|
192
|
+
return value
|
|
193
|
+
if isinstance(value, str):
|
|
194
|
+
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"):
|
|
195
|
+
try:
|
|
196
|
+
return datetime.strptime(value, fmt)
|
|
197
|
+
except ValueError:
|
|
198
|
+
continue
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _f(x: object) -> float | None:
|
|
203
|
+
try:
|
|
204
|
+
if x is None:
|
|
205
|
+
return None
|
|
206
|
+
v = float(x)
|
|
207
|
+
return v if v > 0 else None
|
|
208
|
+
except (TypeError, ValueError):
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _i(x: object) -> int | None:
|
|
213
|
+
try:
|
|
214
|
+
if x is None:
|
|
215
|
+
return None
|
|
216
|
+
v = int(float(x))
|
|
217
|
+
return v if v >= 0 else None
|
|
218
|
+
except (TypeError, ValueError):
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
__all__ = ["KiteProvider"]
|