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,198 @@
|
|
|
1
|
+
"""Twelve Data provider — REST API with a free tier.
|
|
2
|
+
|
|
3
|
+
Free tier: 800 requests/day, 8 req/min. API key required (env
|
|
4
|
+
``TWELVE_DATA_API_KEY`` by default). Twelve Data covers Indian equities
|
|
5
|
+
on both NSE (``:NSE``) and BSE (``:BSE``) — pass ``exchange="NSE"`` or
|
|
6
|
+
``"BSE"`` at construction time.
|
|
7
|
+
|
|
8
|
+
Capabilities
|
|
9
|
+
------------
|
|
10
|
+
- LAST_PRICE, QUOTE (last/open/high/low/prev_close/volume + 52w hi/lo)
|
|
11
|
+
- OHLCV_DAILY
|
|
12
|
+
- DELAYED on free tier (real-time costs more)
|
|
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://api.twelvedata.com"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TwelveDataProvider(MarketDataProvider):
|
|
40
|
+
"""Twelve Data REST API."""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
api_key: str | None = None,
|
|
45
|
+
exchange: str = "NSE",
|
|
46
|
+
timeout: float = 10.0,
|
|
47
|
+
) -> None:
|
|
48
|
+
self._api_key = api_key or os.environ.get("TWELVE_DATA_API_KEY")
|
|
49
|
+
self._exchange = exchange.upper()
|
|
50
|
+
self._timeout = float(timeout)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def info(self) -> ProviderInfo:
|
|
54
|
+
caps = (
|
|
55
|
+
ProviderCapability.LAST_PRICE
|
|
56
|
+
| ProviderCapability.QUOTE
|
|
57
|
+
| ProviderCapability.OHLCV_DAILY
|
|
58
|
+
| ProviderCapability.DELAYED
|
|
59
|
+
)
|
|
60
|
+
if self._exchange == "NSE":
|
|
61
|
+
caps |= ProviderCapability.SUPPORTS_NSE
|
|
62
|
+
elif self._exchange == "BSE":
|
|
63
|
+
caps |= ProviderCapability.SUPPORTS_BSE
|
|
64
|
+
return ProviderInfo(
|
|
65
|
+
name="twelvedata",
|
|
66
|
+
description="Twelve Data REST API for global equities.",
|
|
67
|
+
capabilities=caps,
|
|
68
|
+
requires_api_key=True,
|
|
69
|
+
homepage="https://twelvedata.com/",
|
|
70
|
+
notes="Set TWELVE_DATA_API_KEY. Free tier: 800/day, 8/min.",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def _fetch(self, path: str, params: dict[str, str]) -> dict:
|
|
74
|
+
if not self._api_key:
|
|
75
|
+
raise ProviderError(
|
|
76
|
+
"Twelve Data API key missing. "
|
|
77
|
+
"Set TWELVE_DATA_API_KEY or pass api_key=...",
|
|
78
|
+
)
|
|
79
|
+
params = {**params, "apikey": self._api_key}
|
|
80
|
+
url = f"{_BASE}{path}?{urllib.parse.urlencode(params)}"
|
|
81
|
+
try:
|
|
82
|
+
with urllib.request.urlopen(url, timeout=self._timeout) as resp: # noqa: S310
|
|
83
|
+
body = resp.read().decode("utf-8", errors="replace")
|
|
84
|
+
except HTTPError as e:
|
|
85
|
+
raise ProviderError(f"twelvedata HTTP {e.code}") from e
|
|
86
|
+
except (URLError, TimeoutError) as e:
|
|
87
|
+
raise ProviderError(f"twelvedata fetch failed: {e}") from e
|
|
88
|
+
try:
|
|
89
|
+
data = json.loads(body)
|
|
90
|
+
except json.JSONDecodeError as e:
|
|
91
|
+
raise ProviderError(f"twelvedata non-JSON: {body[:200]}") from e
|
|
92
|
+
if isinstance(data, dict) and data.get("status") == "error":
|
|
93
|
+
code = data.get("code")
|
|
94
|
+
msg = data.get("message", "unknown")
|
|
95
|
+
if code == 404:
|
|
96
|
+
# genuinely unknown symbol — treat as None
|
|
97
|
+
return {}
|
|
98
|
+
raise ProviderError(f"twelvedata error {code}: {msg}")
|
|
99
|
+
return data
|
|
100
|
+
|
|
101
|
+
def get_quote(self, symbol: str) -> MarketQuote | None:
|
|
102
|
+
data = self._fetch(
|
|
103
|
+
"/quote",
|
|
104
|
+
{"symbol": symbol.upper(), "exchange": self._exchange},
|
|
105
|
+
)
|
|
106
|
+
if not data:
|
|
107
|
+
return None
|
|
108
|
+
try:
|
|
109
|
+
last = float(data.get("close") or 0)
|
|
110
|
+
except (TypeError, ValueError):
|
|
111
|
+
return None
|
|
112
|
+
if last <= 0:
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
return MarketQuote(
|
|
116
|
+
last=last,
|
|
117
|
+
timestamp=_parse_dt(data.get("datetime")) or datetime.now(),
|
|
118
|
+
open=_f(data.get("open")),
|
|
119
|
+
high=_f(data.get("high")),
|
|
120
|
+
low=_f(data.get("low")),
|
|
121
|
+
prev_close=_f(data.get("previous_close")),
|
|
122
|
+
volume=_i(data.get("volume")),
|
|
123
|
+
source="twelvedata",
|
|
124
|
+
is_real_time=False,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def get_history(
|
|
128
|
+
self,
|
|
129
|
+
symbol: str,
|
|
130
|
+
start: date,
|
|
131
|
+
end: date,
|
|
132
|
+
interval: str = "1d",
|
|
133
|
+
) -> list[OHLCV]:
|
|
134
|
+
td_interval = {"1d": "1day", "1h": "1h", "5m": "5min", "1m": "1min"}.get(
|
|
135
|
+
interval,
|
|
136
|
+
)
|
|
137
|
+
if td_interval is None:
|
|
138
|
+
return []
|
|
139
|
+
data = self._fetch(
|
|
140
|
+
"/time_series",
|
|
141
|
+
{
|
|
142
|
+
"symbol": symbol.upper(),
|
|
143
|
+
"exchange": self._exchange,
|
|
144
|
+
"interval": td_interval,
|
|
145
|
+
"start_date": start.isoformat(),
|
|
146
|
+
"end_date": end.isoformat(),
|
|
147
|
+
"outputsize": "5000",
|
|
148
|
+
},
|
|
149
|
+
)
|
|
150
|
+
out: list[OHLCV] = []
|
|
151
|
+
for row in data.get("values", []) or []:
|
|
152
|
+
try:
|
|
153
|
+
ts = _parse_dt(row.get("datetime"))
|
|
154
|
+
if ts is None:
|
|
155
|
+
continue
|
|
156
|
+
out.append(
|
|
157
|
+
OHLCV(
|
|
158
|
+
timestamp=ts,
|
|
159
|
+
open=float(row["open"]),
|
|
160
|
+
high=float(row["high"]),
|
|
161
|
+
low=float(row["low"]),
|
|
162
|
+
close=float(row["close"]),
|
|
163
|
+
volume=int(float(row.get("volume") or 0)),
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
except (KeyError, ValueError):
|
|
167
|
+
continue
|
|
168
|
+
return sorted(out, key=lambda b: b.timestamp)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _parse_dt(s: object) -> datetime | None:
|
|
172
|
+
if not isinstance(s, str):
|
|
173
|
+
return None
|
|
174
|
+
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
|
175
|
+
try:
|
|
176
|
+
return datetime.strptime(s, fmt)
|
|
177
|
+
except ValueError:
|
|
178
|
+
continue
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _f(x: object) -> float | None:
|
|
183
|
+
try:
|
|
184
|
+
if x is None:
|
|
185
|
+
return None
|
|
186
|
+
v = float(x)
|
|
187
|
+
return v if v > 0 else None
|
|
188
|
+
except (TypeError, ValueError):
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _i(x: object) -> int | None:
|
|
193
|
+
try:
|
|
194
|
+
if x is None:
|
|
195
|
+
return None
|
|
196
|
+
return int(float(x))
|
|
197
|
+
except (TypeError, ValueError):
|
|
198
|
+
return None
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Upstox provider — free real broker feed with depth (REST).
|
|
2
|
+
|
|
3
|
+
Upstox's market-quote API is free for account holders and returns live
|
|
4
|
+
last price, OHLC, volume, and full market depth (bid/ask + sizes). This
|
|
5
|
+
provider talks to the v2 REST endpoint directly via ``urllib`` (no SDK
|
|
6
|
+
dependency), so it's stubbable in tests the same way as the other REST
|
|
7
|
+
providers.
|
|
8
|
+
|
|
9
|
+
The instrument-key wrinkle
|
|
10
|
+
--------------------------
|
|
11
|
+
Upstox keys quotes by an ``instrument_key`` (e.g.
|
|
12
|
+
``"NSE_EQ|INE002A01018"`` for RELIANCE), not by trading symbol. Supply
|
|
13
|
+
one of:
|
|
14
|
+
|
|
15
|
+
- ``instrument_key_map={"RELIANCE": "NSE_EQ|INE002A01018", ...}``, or
|
|
16
|
+
- a ``resolve`` callable ``(symbol, segment) -> instrument_key | None``.
|
|
17
|
+
|
|
18
|
+
A symbol that can't be resolved yields ``None`` (treated as "unknown").
|
|
19
|
+
|
|
20
|
+
Auth
|
|
21
|
+
----
|
|
22
|
+
Reads ``UPSTOX_ACCESS_TOKEN`` from the environment by default. Tokens
|
|
23
|
+
are issued by the Upstox login flow and rotate daily.
|
|
24
|
+
|
|
25
|
+
No extra install needed — uses the standard library.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import json
|
|
31
|
+
import logging
|
|
32
|
+
import os
|
|
33
|
+
import urllib.parse
|
|
34
|
+
import urllib.request
|
|
35
|
+
from collections.abc import Callable
|
|
36
|
+
from datetime import datetime
|
|
37
|
+
from urllib.error import HTTPError, URLError
|
|
38
|
+
|
|
39
|
+
from .base import (
|
|
40
|
+
MarketDataProvider,
|
|
41
|
+
MarketQuote,
|
|
42
|
+
ProviderCapability,
|
|
43
|
+
ProviderError,
|
|
44
|
+
ProviderInfo,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
_BASE = "https://api.upstox.com/v2"
|
|
50
|
+
_SEGMENT = {"NSE": "NSE_EQ", "BSE": "BSE_EQ"}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class UpstoxProvider(MarketDataProvider):
|
|
54
|
+
"""Upstox v2 market-quote provider (REST).
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
access_token:
|
|
59
|
+
Upstox bearer token. Falls back to ``UPSTOX_ACCESS_TOKEN``.
|
|
60
|
+
exchange:
|
|
61
|
+
``"NSE"`` (default) or ``"BSE"``.
|
|
62
|
+
instrument_key_map:
|
|
63
|
+
Optional ``{symbol: instrument_key}`` lookup. Required (or
|
|
64
|
+
``resolve``) because Upstox keys quotes by instrument key.
|
|
65
|
+
resolve:
|
|
66
|
+
Optional callable ``(symbol, segment) -> instrument_key | None``
|
|
67
|
+
for dynamic resolution against your own instrument master.
|
|
68
|
+
timeout:
|
|
69
|
+
Per-request timeout in seconds.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
access_token: str | None = None,
|
|
75
|
+
exchange: str = "NSE",
|
|
76
|
+
instrument_key_map: dict[str, str] | None = None,
|
|
77
|
+
resolve: Callable[[str, str], str | None] | None = None,
|
|
78
|
+
timeout: float = 10.0,
|
|
79
|
+
) -> None:
|
|
80
|
+
self._access_token = access_token or os.environ.get("UPSTOX_ACCESS_TOKEN")
|
|
81
|
+
self._exchange = exchange.upper()
|
|
82
|
+
self._segment = _SEGMENT.get(self._exchange, "NSE_EQ")
|
|
83
|
+
self._instrument_key_map = {
|
|
84
|
+
k.upper(): str(v) for k, v in (instrument_key_map or {}).items()
|
|
85
|
+
}
|
|
86
|
+
self._resolve = resolve
|
|
87
|
+
self._timeout = float(timeout)
|
|
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="upstox",
|
|
102
|
+
description="Upstox v2 live market quotes (bid/ask + depth).",
|
|
103
|
+
capabilities=caps,
|
|
104
|
+
requires_api_key=True,
|
|
105
|
+
homepage="https://upstox.com/developer/api-documentation/",
|
|
106
|
+
notes=(
|
|
107
|
+
"Set UPSTOX_ACCESS_TOKEN (rotates daily). Free for account "
|
|
108
|
+
"holders. Needs a symbol->instrument_key map."
|
|
109
|
+
),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# ── Resolution ────────────────────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
def _instrument_key(self, symbol: str) -> str | None:
|
|
115
|
+
sym = symbol.upper()
|
|
116
|
+
if sym in self._instrument_key_map:
|
|
117
|
+
return self._instrument_key_map[sym]
|
|
118
|
+
if self._resolve is not None:
|
|
119
|
+
try:
|
|
120
|
+
return self._resolve(sym, self._segment)
|
|
121
|
+
except ProviderError:
|
|
122
|
+
# A resolver outage (e.g. instrument-master download
|
|
123
|
+
# failed) is a provider failure, not "unknown symbol" —
|
|
124
|
+
# let it propagate so the feed logs it and falls back.
|
|
125
|
+
raise
|
|
126
|
+
except Exception as e: # noqa: BLE001
|
|
127
|
+
logger.debug("upstox resolve failed for %s: %s", sym, e)
|
|
128
|
+
return None
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
# ── Quote ─────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
def get_quote(self, symbol: str) -> MarketQuote | None:
|
|
134
|
+
if not self._access_token:
|
|
135
|
+
raise ProviderError(
|
|
136
|
+
"Upstox access token missing. Set UPSTOX_ACCESS_TOKEN "
|
|
137
|
+
"or pass access_token=..."
|
|
138
|
+
)
|
|
139
|
+
instrument_key = self._instrument_key(symbol)
|
|
140
|
+
if instrument_key is None:
|
|
141
|
+
logger.debug(
|
|
142
|
+
"upstox: no instrument_key for %s; supply instrument_key_map",
|
|
143
|
+
symbol,
|
|
144
|
+
)
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
params = urllib.parse.urlencode({"instrument_key": instrument_key})
|
|
148
|
+
url = f"{_BASE}/market-quote/quotes?{params}"
|
|
149
|
+
req = urllib.request.Request( # noqa: S310
|
|
150
|
+
url,
|
|
151
|
+
headers={
|
|
152
|
+
"Authorization": f"Bearer {self._access_token}",
|
|
153
|
+
"Accept": "application/json",
|
|
154
|
+
# Upstox sits behind Cloudflare, which bans the default
|
|
155
|
+
# ``Python-urllib/x.y`` UA (Error 1010) before auth is
|
|
156
|
+
# even evaluated. A descriptive client UA passes.
|
|
157
|
+
"User-Agent": "papertrade-india/0.1 (+https://github.com/Mirzabaig313/papertrade-india)",
|
|
158
|
+
},
|
|
159
|
+
)
|
|
160
|
+
try:
|
|
161
|
+
with urllib.request.urlopen(req, timeout=self._timeout) as resp: # noqa: S310
|
|
162
|
+
# Cap the read — a single quote response is a few KB.
|
|
163
|
+
body = resp.read(4 * 1024 * 1024).decode("utf-8", errors="replace")
|
|
164
|
+
except HTTPError as e:
|
|
165
|
+
if e.code in (401, 403):
|
|
166
|
+
raise ProviderError(f"upstox auth failed (HTTP {e.code})") from e
|
|
167
|
+
raise ProviderError(f"upstox HTTP {e.code}") from e
|
|
168
|
+
except (URLError, TimeoutError) as e:
|
|
169
|
+
raise ProviderError(f"upstox fetch failed: {e}") from e
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
payload = json.loads(body)
|
|
173
|
+
except json.JSONDecodeError as e:
|
|
174
|
+
raise ProviderError("upstox returned non-JSON response") from e
|
|
175
|
+
|
|
176
|
+
data = _extract(payload, instrument_key, symbol)
|
|
177
|
+
if not data:
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
last = _f(data.get("last_price"))
|
|
181
|
+
if last is None:
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
bid, bid_size = _best(data, "buy")
|
|
185
|
+
ask, ask_size = _best(data, "sell")
|
|
186
|
+
ohlc = data.get("ohlc") or {}
|
|
187
|
+
|
|
188
|
+
ts = _parse_ts(data.get("last_trade_time") or data.get("ltt"))
|
|
189
|
+
|
|
190
|
+
return MarketQuote(
|
|
191
|
+
last=last,
|
|
192
|
+
timestamp=ts or datetime.now(),
|
|
193
|
+
bid=bid,
|
|
194
|
+
ask=ask,
|
|
195
|
+
bid_size=bid_size,
|
|
196
|
+
ask_size=ask_size,
|
|
197
|
+
open=_f(ohlc.get("open")),
|
|
198
|
+
high=_f(ohlc.get("high")),
|
|
199
|
+
low=_f(ohlc.get("low")),
|
|
200
|
+
prev_close=_f(ohlc.get("close")),
|
|
201
|
+
volume=_i(data.get("volume")),
|
|
202
|
+
source="upstox",
|
|
203
|
+
is_real_time=True,
|
|
204
|
+
bids=_ladder(data, "buy"),
|
|
205
|
+
asks=_ladder(data, "sell"),
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ── Parse helpers ─────────────────────────────────────────────────────
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _extract(payload: object, instrument_key: str, symbol: str) -> dict | None:
|
|
213
|
+
"""Pull the per-instrument block out of the Upstox response.
|
|
214
|
+
|
|
215
|
+
Upstox responds with ``{"status": "success", "data": {"<KEY>":
|
|
216
|
+
{...}}}`` where ``<KEY>`` is usually ``"<SEGMENT>:<SYMBOL>"`` (e.g.
|
|
217
|
+
``"NSE_EQ:RELIANCE"``) rather than the raw instrument key. We accept
|
|
218
|
+
any single-entry data block, then fall back to matching by the
|
|
219
|
+
instrument key or symbol suffix.
|
|
220
|
+
"""
|
|
221
|
+
if not isinstance(payload, dict):
|
|
222
|
+
return None
|
|
223
|
+
data = payload.get("data")
|
|
224
|
+
if not isinstance(data, dict) or not data:
|
|
225
|
+
return None
|
|
226
|
+
# Exact instrument-key match first.
|
|
227
|
+
if instrument_key in data and isinstance(data[instrument_key], dict):
|
|
228
|
+
return data[instrument_key]
|
|
229
|
+
# Match by trailing symbol (``NSE_EQ:RELIANCE``).
|
|
230
|
+
sym = symbol.upper()
|
|
231
|
+
for key, block in data.items():
|
|
232
|
+
if isinstance(block, dict) and key.upper().endswith(f":{sym}"):
|
|
233
|
+
return block
|
|
234
|
+
# Single-entry response: accept the only block, but only when it
|
|
235
|
+
# doesn't positively contradict the requested symbol (guards against
|
|
236
|
+
# returning a mismatched instrument).
|
|
237
|
+
if len(data) == 1:
|
|
238
|
+
only_key, only = next(iter(data.items()))
|
|
239
|
+
if not isinstance(only, dict):
|
|
240
|
+
return None
|
|
241
|
+
key_up = only_key.upper()
|
|
242
|
+
if ":" in key_up and not key_up.endswith(f":{sym}"):
|
|
243
|
+
return None # names a different symbol
|
|
244
|
+
return only
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _best(data: dict, side: str) -> tuple[float | None, int | None]:
|
|
249
|
+
depth = data.get("depth") or {}
|
|
250
|
+
levels = depth.get(side) or []
|
|
251
|
+
if not levels:
|
|
252
|
+
return (None, None)
|
|
253
|
+
top = levels[0] or {}
|
|
254
|
+
return (_f(top.get("price")), _i(top.get("quantity")))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _ladder(data: dict, side: str) -> tuple[tuple[float, int], ...] | None:
|
|
258
|
+
"""All depth levels for ``side`` as best-first ``(price, size)`` pairs.
|
|
259
|
+
|
|
260
|
+
Upstox returns up to 5 levels under ``depth.buy`` / ``depth.sell``.
|
|
261
|
+
Returns ``None`` when depth is absent (e.g. a closed market with no
|
|
262
|
+
resting orders), so the book simulator falls back to synthesis.
|
|
263
|
+
"""
|
|
264
|
+
depth = data.get("depth") or {}
|
|
265
|
+
levels = depth.get(side) or []
|
|
266
|
+
out: list[tuple[float, int]] = []
|
|
267
|
+
for lvl in levels:
|
|
268
|
+
price = _f((lvl or {}).get("price"))
|
|
269
|
+
qty = _i((lvl or {}).get("quantity"))
|
|
270
|
+
# Skip padding levels with no real liquidity (price present but
|
|
271
|
+
# zero/blank size) so has_depth reflects genuine depth.
|
|
272
|
+
if price is None or not qty:
|
|
273
|
+
continue
|
|
274
|
+
out.append((price, qty))
|
|
275
|
+
return tuple(out) or None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _parse_ts(value: object) -> datetime | None:
|
|
279
|
+
"""Parse Upstox last-trade time (epoch ms/seconds or ISO string)."""
|
|
280
|
+
if isinstance(value, (int, float)) and value > 0:
|
|
281
|
+
secs = value / 1000.0 if value > 1e11 else float(value)
|
|
282
|
+
try:
|
|
283
|
+
return datetime.fromtimestamp(secs)
|
|
284
|
+
except (OverflowError, OSError, ValueError):
|
|
285
|
+
return None
|
|
286
|
+
if isinstance(value, str):
|
|
287
|
+
# Numeric epoch delivered as a string.
|
|
288
|
+
if value.isdigit():
|
|
289
|
+
return _parse_ts(int(value))
|
|
290
|
+
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"):
|
|
291
|
+
try:
|
|
292
|
+
return datetime.strptime(value, fmt)
|
|
293
|
+
except ValueError:
|
|
294
|
+
continue
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _f(x: object) -> float | None:
|
|
299
|
+
try:
|
|
300
|
+
if x is None:
|
|
301
|
+
return None
|
|
302
|
+
v = float(x)
|
|
303
|
+
return v if v > 0 else None
|
|
304
|
+
except (TypeError, ValueError):
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _i(x: object) -> int | None:
|
|
309
|
+
try:
|
|
310
|
+
if x is None:
|
|
311
|
+
return None
|
|
312
|
+
v = int(float(x))
|
|
313
|
+
return v if v >= 0 else None
|
|
314
|
+
except (TypeError, ValueError):
|
|
315
|
+
return None
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
__all__ = ["UpstoxProvider"]
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Upstox instrument-master resolver.
|
|
2
|
+
|
|
3
|
+
Turns a trading symbol (``"RELIANCE"``) into an Upstox
|
|
4
|
+
``instrument_key`` (``"NSE_EQ|INE002A01018"``) by downloading Upstox's
|
|
5
|
+
public NSE instrument file once and caching it locally. This is what
|
|
6
|
+
lets :class:`~papertrade_india.providers.UpstoxProvider` price *any* NSE
|
|
7
|
+
symbol without a hand-maintained map.
|
|
8
|
+
|
|
9
|
+
The master is a ~2 MB gzipped JSON of ~96k instruments; we keep only the
|
|
10
|
+
equity (``segment == "NSE_EQ"``) ``trading_symbol → instrument_key``
|
|
11
|
+
mapping in memory. The raw file is cached on disk with a TTL (default 1
|
|
12
|
+
day) since instruments change rarely.
|
|
13
|
+
|
|
14
|
+
Usage::
|
|
15
|
+
|
|
16
|
+
master = UpstoxInstrumentMaster()
|
|
17
|
+
provider = UpstoxProvider(resolve=master.resolve) # any NSE symbol
|
|
18
|
+
|
|
19
|
+
No network happens until the first :meth:`resolve` call.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import gzip
|
|
25
|
+
import json
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
import time
|
|
29
|
+
import urllib.request
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from urllib.error import URLError
|
|
32
|
+
|
|
33
|
+
from .base import ProviderError
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
_NSE_URL = "https://assets.upstox.com/market-quote/instruments/exchange/NSE.json.gz"
|
|
38
|
+
_DEFAULT_CACHE = Path("data/upstox_nse_instruments.json.gz")
|
|
39
|
+
# Cloudflare bans the default Python-urllib UA (see UpstoxProvider).
|
|
40
|
+
_UA = "papertrade-india/0.1 (+https://github.com/Mirzabaig313/papertrade-india)"
|
|
41
|
+
# Guards against a compromised/swapped endpoint sending a huge payload
|
|
42
|
+
# (decompression bomb / OOM). The real NSE file is ~2.3 MB gzipped.
|
|
43
|
+
_MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024 # 64 MB compressed ceiling
|
|
44
|
+
_MAX_DECOMPRESSED_BYTES = 512 * 1024 * 1024 # 512 MB decompressed ceiling
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class UpstoxInstrumentMaster:
|
|
48
|
+
"""Lazy, cached symbol → instrument_key resolver for NSE equities.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
cache_path:
|
|
53
|
+
Where to cache the downloaded ``.json.gz``. Defaults to
|
|
54
|
+
``data/upstox_nse_instruments.json.gz``.
|
|
55
|
+
ttl_seconds:
|
|
56
|
+
Re-download when the cache is older than this. Default 1 day.
|
|
57
|
+
records:
|
|
58
|
+
Inject a pre-parsed records list (for tests) — skips all I/O.
|
|
59
|
+
url:
|
|
60
|
+
Override the source URL.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
cache_path: Path | str | None = None,
|
|
66
|
+
ttl_seconds: int = 86_400,
|
|
67
|
+
records: list[dict] | None = None,
|
|
68
|
+
url: str = _NSE_URL,
|
|
69
|
+
) -> None:
|
|
70
|
+
self._cache_path = Path(cache_path) if cache_path else _DEFAULT_CACHE
|
|
71
|
+
self._ttl = int(ttl_seconds)
|
|
72
|
+
self._url = url
|
|
73
|
+
self._injected = records
|
|
74
|
+
self._index: dict[str, str] | None = None
|
|
75
|
+
if records is not None:
|
|
76
|
+
self._index = self._build_index(records)
|
|
77
|
+
|
|
78
|
+
# ── Public API ────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
def resolve(self, symbol: str, segment: str = "NSE_EQ") -> str | None:
|
|
81
|
+
"""Return the ``instrument_key`` for ``symbol`` (NSE equity)."""
|
|
82
|
+
if segment != "NSE_EQ":
|
|
83
|
+
return None # this master only indexes NSE equities
|
|
84
|
+
return self._get_index().get(symbol.upper())
|
|
85
|
+
|
|
86
|
+
def symbols(self) -> list[str]:
|
|
87
|
+
"""All known NSE equity trading symbols (sorted)."""
|
|
88
|
+
return sorted(self._get_index())
|
|
89
|
+
|
|
90
|
+
# ── Internals ─────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
def _get_index(self) -> dict[str, str]:
|
|
93
|
+
if self._index is None:
|
|
94
|
+
self._index = self._build_index(self._load_records())
|
|
95
|
+
return self._index
|
|
96
|
+
|
|
97
|
+
@staticmethod
|
|
98
|
+
def _build_index(records: list[dict]) -> dict[str, str]:
|
|
99
|
+
index: dict[str, str] = {}
|
|
100
|
+
for rec in records:
|
|
101
|
+
if rec.get("segment") != "NSE_EQ":
|
|
102
|
+
continue
|
|
103
|
+
if rec.get("instrument_type") not in (None, "EQ"):
|
|
104
|
+
continue
|
|
105
|
+
sym = rec.get("trading_symbol") or rec.get("tradingsymbol")
|
|
106
|
+
key = rec.get("instrument_key")
|
|
107
|
+
if sym and key:
|
|
108
|
+
index[sym.upper()] = key
|
|
109
|
+
logger.info("Upstox instrument index: %d NSE equities", len(index))
|
|
110
|
+
return index
|
|
111
|
+
|
|
112
|
+
def _load_records(self) -> list[dict]:
|
|
113
|
+
raw = self._read_cache()
|
|
114
|
+
if raw is not None:
|
|
115
|
+
try:
|
|
116
|
+
return self._decode(raw)
|
|
117
|
+
except (gzip.BadGzipFile, EOFError, OSError, json.JSONDecodeError) as e:
|
|
118
|
+
# Cache is truncated/corrupt (e.g. crash mid-write) —
|
|
119
|
+
# discard it and re-download rather than wedging resolve().
|
|
120
|
+
logger.warning("Corrupt instrument cache (%s); re-downloading", e)
|
|
121
|
+
raw = self._download()
|
|
122
|
+
self._write_cache(raw)
|
|
123
|
+
return self._decode(raw)
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def _decode(raw: bytes) -> list[dict]:
|
|
127
|
+
data = gzip.decompress(raw)
|
|
128
|
+
if len(data) > _MAX_DECOMPRESSED_BYTES:
|
|
129
|
+
raise ProviderError("instrument master exceeds size limit")
|
|
130
|
+
return json.loads(data)
|
|
131
|
+
|
|
132
|
+
def _read_cache(self) -> bytes | None:
|
|
133
|
+
p = self._cache_path
|
|
134
|
+
if not p.exists():
|
|
135
|
+
return None
|
|
136
|
+
age = time.time() - p.stat().st_mtime
|
|
137
|
+
if age > self._ttl:
|
|
138
|
+
logger.info("Upstox instrument cache stale (%.0fs), refreshing", age)
|
|
139
|
+
return None
|
|
140
|
+
return p.read_bytes()
|
|
141
|
+
|
|
142
|
+
def _write_cache(self, raw: bytes) -> None:
|
|
143
|
+
# Atomic write: temp file in the same dir + os.replace, so a
|
|
144
|
+
# crash mid-write never leaves a truncated cache behind.
|
|
145
|
+
try:
|
|
146
|
+
self._cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
tmp = self._cache_path.with_suffix(self._cache_path.suffix + f".tmp.{os.getpid()}")
|
|
148
|
+
tmp.write_bytes(raw)
|
|
149
|
+
os.replace(tmp, self._cache_path)
|
|
150
|
+
except OSError as e: # cache is best-effort
|
|
151
|
+
logger.warning("Could not write instrument cache: %s", e)
|
|
152
|
+
|
|
153
|
+
def _download(self) -> bytes:
|
|
154
|
+
logger.info("Downloading Upstox NSE instrument master from %s", self._url)
|
|
155
|
+
req = urllib.request.Request( # noqa: S310
|
|
156
|
+
self._url, headers={"User-Agent": _UA, "Accept-Encoding": "gzip"}
|
|
157
|
+
)
|
|
158
|
+
try:
|
|
159
|
+
with urllib.request.urlopen(req, timeout=60) as resp: # noqa: S310
|
|
160
|
+
raw = resp.read(_MAX_DOWNLOAD_BYTES + 1)
|
|
161
|
+
except (URLError, TimeoutError, OSError) as e:
|
|
162
|
+
# Surface as ProviderError so the price-feed chain treats it
|
|
163
|
+
# as a provider outage (→ falls back to the next provider,
|
|
164
|
+
# and it's logged) rather than a silent "unknown symbol".
|
|
165
|
+
raise ProviderError(f"instrument master download failed: {e}") from e
|
|
166
|
+
if len(raw) > _MAX_DOWNLOAD_BYTES:
|
|
167
|
+
raise ProviderError("instrument master exceeds download size limit")
|
|
168
|
+
return raw
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
__all__ = ["UpstoxInstrumentMaster"]
|