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,138 @@
|
|
|
1
|
+
"""Live NSE/BSE trading-holiday source (Upstox market-holidays API).
|
|
2
|
+
|
|
3
|
+
Replaces hand-maintained ``nse_holidays_*.json`` with the exchange-
|
|
4
|
+
published calendar. Upstox's ``/v2/market/holidays`` is **public** (no
|
|
5
|
+
auth) and returns every holiday for the year with the list of
|
|
6
|
+
``closed_exchanges`` (NSE, BSE, NFO, ...), so one call covers both NSE
|
|
7
|
+
and BSE.
|
|
8
|
+
|
|
9
|
+
Design:
|
|
10
|
+
- **No network on import or per-query.** Fetched once, cached to disk
|
|
11
|
+
with a TTL (holidays change ~yearly), and served from memory after.
|
|
12
|
+
- **Degrades gracefully.** API down → stale disk cache → empty set. The
|
|
13
|
+
calendar keeps its bundled JSON as the ultimate floor, so a fetch
|
|
14
|
+
failure never leaves the simulator with *no* holidays.
|
|
15
|
+
- Lives in ``infrastructure`` and depends on nothing outward (no
|
|
16
|
+
``providers`` import) to respect the layering rules.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import time
|
|
24
|
+
import urllib.request
|
|
25
|
+
from datetime import date
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from urllib.error import URLError
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
_URL = "https://api.upstox.com/v2/market/holidays"
|
|
32
|
+
_DEFAULT_CACHE = Path("data/upstox_holidays_cache.json")
|
|
33
|
+
# Cloudflare bans the default Python-urllib UA (Error 1010); use ours.
|
|
34
|
+
_UA = "papertrade-india/0.1 (+https://github.com/Mirzabaig313/papertrade-india)"
|
|
35
|
+
_MAX_BYTES = 4 * 1024 * 1024
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class UpstoxHolidayProvider:
|
|
39
|
+
"""Fetches + caches exchange trading holidays from Upstox.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
exchange:
|
|
44
|
+
Which exchange's closures to report — ``"NSE"`` (default) or
|
|
45
|
+
``"BSE"``. A date counts as closed when this exchange is in the
|
|
46
|
+
row's ``closed_exchanges``.
|
|
47
|
+
cache_path:
|
|
48
|
+
Where to cache the raw API rows. Default
|
|
49
|
+
``data/upstox_holidays_cache.json``.
|
|
50
|
+
ttl_seconds:
|
|
51
|
+
Re-fetch when the cache is older than this. Default 7 days.
|
|
52
|
+
rows:
|
|
53
|
+
Inject pre-parsed API rows (for tests) — skips all network/disk.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
exchange: str = "NSE",
|
|
59
|
+
cache_path: Path | str | None = None,
|
|
60
|
+
ttl_seconds: int = 7 * 86_400,
|
|
61
|
+
rows: list[dict] | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
self._exchange = exchange.upper()
|
|
64
|
+
self._cache_path = Path(cache_path) if cache_path else _DEFAULT_CACHE
|
|
65
|
+
self._ttl = int(ttl_seconds)
|
|
66
|
+
self._injected = rows
|
|
67
|
+
|
|
68
|
+
def closed_dates(self) -> set[date]:
|
|
69
|
+
"""Set of dates on which ``exchange`` is closed for trading."""
|
|
70
|
+
out: set[date] = set()
|
|
71
|
+
for row in self._rows():
|
|
72
|
+
if self._exchange not in (row.get("closed_exchanges") or []):
|
|
73
|
+
continue
|
|
74
|
+
raw = row.get("date")
|
|
75
|
+
if not raw:
|
|
76
|
+
continue
|
|
77
|
+
try:
|
|
78
|
+
out.add(date.fromisoformat(raw))
|
|
79
|
+
except ValueError:
|
|
80
|
+
logger.warning("Unparseable holiday date: %r", raw)
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
# ── Internals ─────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
def _rows(self) -> list[dict]:
|
|
86
|
+
if self._injected is not None:
|
|
87
|
+
return self._injected
|
|
88
|
+
cached = self._read_cache()
|
|
89
|
+
if cached is not None:
|
|
90
|
+
return cached
|
|
91
|
+
try:
|
|
92
|
+
rows = self._fetch()
|
|
93
|
+
self._write_cache(rows)
|
|
94
|
+
return rows
|
|
95
|
+
except (URLError, TimeoutError, OSError, ValueError) as e:
|
|
96
|
+
# Fetch failed — fall back to a stale cache if we have one,
|
|
97
|
+
# else empty (the calendar's bundled JSON is the real floor).
|
|
98
|
+
logger.warning("Holiday API fetch failed (%s); using fallback", e)
|
|
99
|
+
stale = self._read_cache(ignore_ttl=True)
|
|
100
|
+
return stale if stale is not None else []
|
|
101
|
+
|
|
102
|
+
def _read_cache(self, ignore_ttl: bool = False) -> list[dict] | None:
|
|
103
|
+
p = self._cache_path
|
|
104
|
+
if not p.exists():
|
|
105
|
+
return None
|
|
106
|
+
if not ignore_ttl and (time.time() - p.stat().st_mtime) > self._ttl:
|
|
107
|
+
return None
|
|
108
|
+
try:
|
|
109
|
+
return json.loads(p.read_text())
|
|
110
|
+
except (OSError, ValueError):
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
def _write_cache(self, rows: list[dict]) -> None:
|
|
114
|
+
import os
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
self._cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
tmp = self._cache_path.with_suffix(f".tmp.{os.getpid()}")
|
|
119
|
+
tmp.write_text(json.dumps(rows))
|
|
120
|
+
os.replace(tmp, self._cache_path)
|
|
121
|
+
except OSError as e: # cache is best-effort
|
|
122
|
+
logger.warning("Could not write holiday cache: %s", e)
|
|
123
|
+
|
|
124
|
+
def _fetch(self) -> list[dict]:
|
|
125
|
+
req = urllib.request.Request( # noqa: S310
|
|
126
|
+
_URL, headers={"User-Agent": _UA, "Accept": "application/json"}
|
|
127
|
+
)
|
|
128
|
+
with urllib.request.urlopen(req, timeout=20) as resp: # noqa: S310
|
|
129
|
+
body = resp.read(_MAX_BYTES).decode("utf-8", errors="replace")
|
|
130
|
+
payload = json.loads(body)
|
|
131
|
+
rows = payload.get("data") if isinstance(payload, dict) else None
|
|
132
|
+
if not isinstance(rows, list):
|
|
133
|
+
raise ValueError("unexpected holidays response shape")
|
|
134
|
+
logger.info("Fetched %d exchange holidays from Upstox", len(rows))
|
|
135
|
+
return rows
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
__all__ = ["UpstoxHolidayProvider"]
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Idempotency-key tracking.
|
|
2
|
+
|
|
3
|
+
Backend convention (per the global steering rules): mutating operations
|
|
4
|
+
should accept an idempotency key, replay the same response on repeat
|
|
5
|
+
delivery, and reject mismatched parameters under the same key.
|
|
6
|
+
|
|
7
|
+
Storage model
|
|
8
|
+
-------------
|
|
9
|
+
Per (account_id, key) we store:
|
|
10
|
+
|
|
11
|
+
- The originating order id (so replays return the same ``Order``).
|
|
12
|
+
- A stable hash of the request parameters (so we can detect mismatched
|
|
13
|
+
replays — that's a client bug we want to surface, not silently allow).
|
|
14
|
+
- A creation timestamp; rows are pruned by ``cleanup_expired`` per a TTL
|
|
15
|
+
(default 24h, matching common backend conventions).
|
|
16
|
+
|
|
17
|
+
Key scope is per-account to prevent cross-client collisions. Same key
|
|
18
|
+
across two different accounts is allowed.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
import sqlite3
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import datetime, timedelta
|
|
27
|
+
|
|
28
|
+
from .market_hours import IST
|
|
29
|
+
|
|
30
|
+
SCHEMA = """
|
|
31
|
+
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
|
32
|
+
account_id TEXT NOT NULL,
|
|
33
|
+
key TEXT NOT NULL,
|
|
34
|
+
-- SHA-256 hex of canonical request params, so a replay with
|
|
35
|
+
-- different params raises IdempotencyConflict instead of silently
|
|
36
|
+
-- returning the first response.
|
|
37
|
+
request_hash TEXT NOT NULL,
|
|
38
|
+
order_id TEXT NOT NULL,
|
|
39
|
+
created_at TEXT NOT NULL,
|
|
40
|
+
PRIMARY KEY (account_id, key),
|
|
41
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE,
|
|
42
|
+
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
|
46
|
+
ON idempotency_keys(created_at);
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class IdempotencyEntry:
|
|
52
|
+
account_id: str
|
|
53
|
+
key: str
|
|
54
|
+
request_hash: str
|
|
55
|
+
order_id: str
|
|
56
|
+
created_at: datetime
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def hash_request(side: str, symbol: str, qty: float,
|
|
60
|
+
order_type: str, limit_price: float | None,
|
|
61
|
+
time_in_force: str) -> str:
|
|
62
|
+
"""Stable hash of the request parameters.
|
|
63
|
+
|
|
64
|
+
Order matters and floats are formatted to a fixed precision so trivial
|
|
65
|
+
representation drift (e.g. ``2500.0`` vs ``2500``) doesn't cause
|
|
66
|
+
spurious conflicts.
|
|
67
|
+
"""
|
|
68
|
+
parts = (
|
|
69
|
+
side,
|
|
70
|
+
symbol,
|
|
71
|
+
f"{qty:.10g}",
|
|
72
|
+
order_type,
|
|
73
|
+
f"{limit_price:.10g}" if limit_price is not None else "-",
|
|
74
|
+
time_in_force,
|
|
75
|
+
)
|
|
76
|
+
return hashlib.sha256("|".join(parts).encode()).hexdigest()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def lookup(
|
|
80
|
+
conn: sqlite3.Connection,
|
|
81
|
+
account_id: str,
|
|
82
|
+
key: str,
|
|
83
|
+
) -> IdempotencyEntry | None:
|
|
84
|
+
row = conn.execute(
|
|
85
|
+
"SELECT account_id, key, request_hash, order_id, created_at "
|
|
86
|
+
"FROM idempotency_keys WHERE account_id = ? AND key = ?",
|
|
87
|
+
(account_id, key),
|
|
88
|
+
).fetchone()
|
|
89
|
+
if row is None:
|
|
90
|
+
return None
|
|
91
|
+
return IdempotencyEntry(
|
|
92
|
+
account_id=row["account_id"],
|
|
93
|
+
key=row["key"],
|
|
94
|
+
request_hash=row["request_hash"],
|
|
95
|
+
order_id=row["order_id"],
|
|
96
|
+
created_at=datetime.fromisoformat(row["created_at"]),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def store(
|
|
101
|
+
conn: sqlite3.Connection,
|
|
102
|
+
account_id: str,
|
|
103
|
+
key: str,
|
|
104
|
+
request_hash: str,
|
|
105
|
+
order_id: str,
|
|
106
|
+
now_iso: str,
|
|
107
|
+
) -> None:
|
|
108
|
+
conn.execute(
|
|
109
|
+
"INSERT INTO idempotency_keys "
|
|
110
|
+
"(account_id, key, request_hash, order_id, created_at) "
|
|
111
|
+
"VALUES (?, ?, ?, ?, ?)",
|
|
112
|
+
(account_id, key, request_hash, order_id, now_iso),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cleanup_expired(
|
|
117
|
+
conn: sqlite3.Connection,
|
|
118
|
+
ttl: timedelta = timedelta(hours=24),
|
|
119
|
+
now: datetime | None = None,
|
|
120
|
+
) -> int:
|
|
121
|
+
"""Delete idempotency rows older than ``ttl``. Returns count deleted.
|
|
122
|
+
|
|
123
|
+
Idempotency keys past their TTL are no longer protected — a replay
|
|
124
|
+
with the same key will be treated as a fresh request. Backend
|
|
125
|
+
convention is 24–48h; we default to 24h.
|
|
126
|
+
"""
|
|
127
|
+
now = now or datetime.now(IST)
|
|
128
|
+
cutoff = (now - ttl).isoformat()
|
|
129
|
+
cur = conn.execute(
|
|
130
|
+
"DELETE FROM idempotency_keys WHERE created_at < ?",
|
|
131
|
+
(cutoff,),
|
|
132
|
+
)
|
|
133
|
+
return cur.rowcount
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Immutable cash-movement ledger.
|
|
2
|
+
|
|
3
|
+
Every mutation of ``account.cash`` is also recorded as an append-only row
|
|
4
|
+
in ``cash_movements``. ``account.cash`` itself stays as a maintained
|
|
5
|
+
running balance — keeping reads O(1) — but the ledger gives us full
|
|
6
|
+
auditability and a strict invariant we can verify any time:
|
|
7
|
+
|
|
8
|
+
sum(amount across all movements for an account) == account.cash
|
|
9
|
+
|
|
10
|
+
Movements are immutable (no UPDATE / DELETE in normal flow). The only
|
|
11
|
+
non-strict path is ``broker.reset()``, which drops the entire account's
|
|
12
|
+
ledger together with positions and orders.
|
|
13
|
+
|
|
14
|
+
Reasons captured on each row
|
|
15
|
+
----------------------------
|
|
16
|
+
- ``buy_principal`` — cash spent on share principal (qty * price)
|
|
17
|
+
- ``buy_fees`` — Indian fees paid on the buy leg
|
|
18
|
+
- ``sell_principal`` — cash received from a sell (qty * price)
|
|
19
|
+
- ``sell_fees`` — Indian fees paid on the sell leg (negative)
|
|
20
|
+
- ``dividend`` — cash dividend received per share held
|
|
21
|
+
- ``adjustment`` — manual one-off adjustments (rare)
|
|
22
|
+
- ``initial_capital`` — opening deposit when the account was created
|
|
23
|
+
|
|
24
|
+
Splitting buy/sell into principal vs fees lets analytics distinguish
|
|
25
|
+
pure-economic flows from broker-imposed costs without re-deriving them
|
|
26
|
+
from the orders table.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import sqlite3
|
|
32
|
+
import uuid
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from datetime import datetime
|
|
35
|
+
|
|
36
|
+
SCHEMA = """
|
|
37
|
+
CREATE TABLE IF NOT EXISTS cash_movements (
|
|
38
|
+
id TEXT PRIMARY KEY,
|
|
39
|
+
account_id TEXT NOT NULL,
|
|
40
|
+
-- Positive = credit, negative = debit. cash + sum(amount) is the
|
|
41
|
+
-- post-movement balance, so a buy_principal is negative.
|
|
42
|
+
amount REAL NOT NULL,
|
|
43
|
+
reason TEXT NOT NULL CHECK(reason IN (
|
|
44
|
+
'buy_principal', 'buy_fees',
|
|
45
|
+
'sell_principal', 'sell_fees',
|
|
46
|
+
'dividend', 'adjustment', 'initial_capital'
|
|
47
|
+
)),
|
|
48
|
+
-- Optional cross-references for audit. NOT a foreign key by design:
|
|
49
|
+
-- ledger writes happen alongside the cash UPDATE in _apply_buy /
|
|
50
|
+
-- _apply_sell, BEFORE the orders row is inserted in the same
|
|
51
|
+
-- transaction, so a hard FK would fail. Keeping this as a soft
|
|
52
|
+
-- reference is fine — orders also have ON DELETE CASCADE on
|
|
53
|
+
-- account_id, so they're swept together with ledger rows on reset.
|
|
54
|
+
order_id TEXT,
|
|
55
|
+
symbol TEXT,
|
|
56
|
+
notes TEXT,
|
|
57
|
+
-- Wall-clock recorded time. Multiple movements in one transaction
|
|
58
|
+
-- can share a timestamp; their PK ``id`` keeps them ordered.
|
|
59
|
+
recorded_at TEXT NOT NULL,
|
|
60
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
CREATE INDEX IF NOT EXISTS idx_cash_movements_account_recorded
|
|
64
|
+
ON cash_movements(account_id, recorded_at DESC);
|
|
65
|
+
|
|
66
|
+
CREATE INDEX IF NOT EXISTS idx_cash_movements_order
|
|
67
|
+
ON cash_movements(order_id);
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class CashMovement:
|
|
73
|
+
id: str
|
|
74
|
+
account_id: str
|
|
75
|
+
amount: float
|
|
76
|
+
reason: str
|
|
77
|
+
order_id: str | None
|
|
78
|
+
symbol: str | None
|
|
79
|
+
notes: str | None
|
|
80
|
+
recorded_at: datetime
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def record(
|
|
84
|
+
conn: sqlite3.Connection,
|
|
85
|
+
account_id: str,
|
|
86
|
+
amount: float,
|
|
87
|
+
reason: str,
|
|
88
|
+
recorded_at_iso: str,
|
|
89
|
+
order_id: str | None = None,
|
|
90
|
+
symbol: str | None = None,
|
|
91
|
+
notes: str | None = None,
|
|
92
|
+
) -> str:
|
|
93
|
+
"""Insert one immutable ledger row. Returns the generated id."""
|
|
94
|
+
movement_id = uuid.uuid4().hex[:12]
|
|
95
|
+
conn.execute(
|
|
96
|
+
"INSERT INTO cash_movements "
|
|
97
|
+
"(id, account_id, amount, reason, order_id, symbol, notes, recorded_at) "
|
|
98
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
99
|
+
(
|
|
100
|
+
movement_id, account_id, amount, reason,
|
|
101
|
+
order_id, symbol, notes, recorded_at_iso,
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
return movement_id
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def list_for_account(
|
|
108
|
+
conn: sqlite3.Connection,
|
|
109
|
+
account_id: str,
|
|
110
|
+
limit: int = 200,
|
|
111
|
+
) -> list[CashMovement]:
|
|
112
|
+
rows = conn.execute(
|
|
113
|
+
"SELECT id, account_id, amount, reason, order_id, symbol, "
|
|
114
|
+
"notes, recorded_at "
|
|
115
|
+
"FROM cash_movements WHERE account_id = ? "
|
|
116
|
+
"ORDER BY recorded_at DESC, id DESC LIMIT ?",
|
|
117
|
+
(account_id, limit),
|
|
118
|
+
).fetchall()
|
|
119
|
+
return [
|
|
120
|
+
CashMovement(
|
|
121
|
+
id=r["id"],
|
|
122
|
+
account_id=r["account_id"],
|
|
123
|
+
amount=r["amount"],
|
|
124
|
+
reason=r["reason"],
|
|
125
|
+
order_id=r["order_id"],
|
|
126
|
+
symbol=r["symbol"],
|
|
127
|
+
notes=r["notes"],
|
|
128
|
+
recorded_at=datetime.fromisoformat(r["recorded_at"]),
|
|
129
|
+
)
|
|
130
|
+
for r in rows
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def sum_for_account(conn: sqlite3.Connection, account_id: str) -> float:
|
|
135
|
+
"""Aggregate of all amounts for an account. Used by verification."""
|
|
136
|
+
row = conn.execute(
|
|
137
|
+
"SELECT COALESCE(SUM(amount), 0) AS total "
|
|
138
|
+
"FROM cash_movements WHERE account_id = ?",
|
|
139
|
+
(account_id,),
|
|
140
|
+
).fetchone()
|
|
141
|
+
return float(row["total"])
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""NSE/BSE trading hours and holiday calendar.
|
|
2
|
+
|
|
3
|
+
We enforce that market orders submitted outside trading hours are rejected
|
|
4
|
+
(or queued, in the case of limit orders). Without this, a caller's
|
|
5
|
+
back-of-the-envelope P&L would silently drift from reality.
|
|
6
|
+
|
|
7
|
+
Hours used:
|
|
8
|
+
- NSE/BSE equity continuous session: 09:15 to 15:30 IST, Mon–Fri,
|
|
9
|
+
excluding holidays.
|
|
10
|
+
- Pre-open auction: 09:00 to 09:08 IST. Limit orders accepted; no
|
|
11
|
+
continuous fills.
|
|
12
|
+
- Closing-session window: 15:40 to 16:00 IST (UCC/AMO accepted).
|
|
13
|
+
|
|
14
|
+
Holiday data ships as JSON in ``data/nse_holidays_*.json``. Each year's
|
|
15
|
+
list can be refreshed independently. The community can keep these files
|
|
16
|
+
current via PR.
|
|
17
|
+
|
|
18
|
+
Time zone: Asia/Kolkata (IST). IST does not observe DST, so this is just
|
|
19
|
+
UTC+5:30 year-round.
|
|
20
|
+
|
|
21
|
+
Session phases
|
|
22
|
+
--------------
|
|
23
|
+
The simulator models four phases per trading day:
|
|
24
|
+
- ``CLOSED``: outside any session window.
|
|
25
|
+
- ``PRE_OPEN``: 09:00–09:08, limit orders queue, no continuous fills.
|
|
26
|
+
- ``REGULAR``: 09:15–15:30, continuous matching (what we simulate).
|
|
27
|
+
- ``POST_CLOSE``: 15:40–16:00, AMO/closing-session window.
|
|
28
|
+
|
|
29
|
+
The broker's market-orders-only-during-REGULAR rule preserves backward
|
|
30
|
+
compatibility (``is_market_open`` returns True only during REGULAR).
|
|
31
|
+
``current_phase`` exposes the full state for callers that care.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import json
|
|
37
|
+
import logging
|
|
38
|
+
from datetime import date, datetime, time, timedelta
|
|
39
|
+
from enum import Enum
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
from typing import TYPE_CHECKING
|
|
42
|
+
|
|
43
|
+
if TYPE_CHECKING:
|
|
44
|
+
from .holidays import UpstoxHolidayProvider
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
from zoneinfo import ZoneInfo
|
|
48
|
+
except ImportError: # pragma: no cover — zoneinfo is std-lib in 3.9+
|
|
49
|
+
from backports.zoneinfo import ZoneInfo # type: ignore
|
|
50
|
+
|
|
51
|
+
logger = logging.getLogger(__name__)
|
|
52
|
+
|
|
53
|
+
IST = ZoneInfo("Asia/Kolkata")
|
|
54
|
+
NSE_OPEN = time(9, 15)
|
|
55
|
+
NSE_CLOSE = time(15, 30)
|
|
56
|
+
|
|
57
|
+
# Session phase boundaries.
|
|
58
|
+
PRE_OPEN_START = time(9, 0)
|
|
59
|
+
PRE_OPEN_END = time(9, 8)
|
|
60
|
+
POST_CLOSE_START = time(15, 40)
|
|
61
|
+
POST_CLOSE_END = time(16, 0)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class SessionPhase(str, Enum):
|
|
65
|
+
"""NSE session phases."""
|
|
66
|
+
|
|
67
|
+
CLOSED = "closed"
|
|
68
|
+
PRE_OPEN = "pre_open"
|
|
69
|
+
REGULAR = "regular"
|
|
70
|
+
POST_CLOSE = "post_close"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class NSECalendar:
|
|
74
|
+
"""NSE trading calendar.
|
|
75
|
+
|
|
76
|
+
Holiday lists are loaded from JSON files in the ``data/`` directory
|
|
77
|
+
(one per year). Loading is lazy-friendly: missing or malformed files
|
|
78
|
+
log a warning but don't break the calendar — weekends and explicit
|
|
79
|
+
weekday holidays are still respected for years that *are* loaded.
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
holidays_dir:
|
|
84
|
+
Override the default data directory (mostly used in tests).
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
holidays_dir: Path | None = None,
|
|
90
|
+
holiday_provider: UpstoxHolidayProvider | None = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
self.holidays_dir = (
|
|
93
|
+
holidays_dir or Path(__file__).resolve().parent.parent / "data"
|
|
94
|
+
)
|
|
95
|
+
self._holidays: set[date] = set()
|
|
96
|
+
self._load_holidays()
|
|
97
|
+
# Optional live source (Upstox published calendar). Augments the
|
|
98
|
+
# bundled JSON — the API's dates are added on top, and the JSON
|
|
99
|
+
# remains the offline floor if the API is unavailable. Default
|
|
100
|
+
# None keeps NSECalendar() fully offline (hermetic tests).
|
|
101
|
+
if holiday_provider is not None:
|
|
102
|
+
try:
|
|
103
|
+
self._holidays |= holiday_provider.closed_dates()
|
|
104
|
+
except Exception as e: # noqa: BLE001 — never break the calendar
|
|
105
|
+
logger.warning("Live holiday provider failed: %s", e)
|
|
106
|
+
|
|
107
|
+
# ── Loading ────────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
def _load_holidays(self) -> None:
|
|
110
|
+
if not self.holidays_dir.exists():
|
|
111
|
+
logger.warning(
|
|
112
|
+
"Holiday dir %s does not exist; no holidays loaded",
|
|
113
|
+
self.holidays_dir,
|
|
114
|
+
)
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
for path in sorted(self.holidays_dir.glob("nse_holidays_*.json")):
|
|
118
|
+
try:
|
|
119
|
+
with open(path) as f:
|
|
120
|
+
data = json.load(f)
|
|
121
|
+
for d in data.get("holidays", []):
|
|
122
|
+
self._holidays.add(date.fromisoformat(d))
|
|
123
|
+
except (OSError, ValueError, json.JSONDecodeError) as e:
|
|
124
|
+
logger.warning("Failed to load holidays from %s: %s", path, e)
|
|
125
|
+
|
|
126
|
+
def reload(self) -> None:
|
|
127
|
+
"""Re-read holiday files from disk (useful after PR-merging updates)."""
|
|
128
|
+
self._holidays.clear()
|
|
129
|
+
self._load_holidays()
|
|
130
|
+
|
|
131
|
+
# ── Queries ────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
def is_holiday(self, d: date) -> bool:
|
|
134
|
+
return d in self._holidays
|
|
135
|
+
|
|
136
|
+
def is_trading_day(self, d: date) -> bool:
|
|
137
|
+
if d.weekday() >= 5: # Saturday=5, Sunday=6
|
|
138
|
+
return False
|
|
139
|
+
return not self.is_holiday(d)
|
|
140
|
+
|
|
141
|
+
def is_market_open(self, dt: datetime | None = None) -> bool:
|
|
142
|
+
"""``True`` if NSE is in the continuous (REGULAR) session at ``dt``.
|
|
143
|
+
|
|
144
|
+
Pre-open and post-close phases return False — they're separate
|
|
145
|
+
windows where market orders shouldn't fill at last price. Use
|
|
146
|
+
``current_phase`` to distinguish them.
|
|
147
|
+
"""
|
|
148
|
+
return self.current_phase(dt) == SessionPhase.REGULAR
|
|
149
|
+
|
|
150
|
+
def current_phase(self, dt: datetime | None = None) -> SessionPhase:
|
|
151
|
+
"""Return the active session phase at ``dt`` (IST).
|
|
152
|
+
|
|
153
|
+
- ``REGULAR`` 09:15–15:30 (continuous matching)
|
|
154
|
+
- ``PRE_OPEN`` 09:00–09:08 (limit orders queue, no fills)
|
|
155
|
+
- ``POST_CLOSE`` 15:40–16:00 (AMO / closing session)
|
|
156
|
+
- ``CLOSED`` anywhere else (incl. weekends and holidays)
|
|
157
|
+
"""
|
|
158
|
+
if dt is None:
|
|
159
|
+
dt = datetime.now(IST)
|
|
160
|
+
elif dt.tzinfo is None:
|
|
161
|
+
dt = dt.replace(tzinfo=IST)
|
|
162
|
+
else:
|
|
163
|
+
dt = dt.astimezone(IST)
|
|
164
|
+
|
|
165
|
+
if not self.is_trading_day(dt.date()):
|
|
166
|
+
return SessionPhase.CLOSED
|
|
167
|
+
|
|
168
|
+
t = dt.time()
|
|
169
|
+
if NSE_OPEN <= t <= NSE_CLOSE:
|
|
170
|
+
return SessionPhase.REGULAR
|
|
171
|
+
if PRE_OPEN_START <= t <= PRE_OPEN_END:
|
|
172
|
+
return SessionPhase.PRE_OPEN
|
|
173
|
+
if POST_CLOSE_START <= t <= POST_CLOSE_END:
|
|
174
|
+
return SessionPhase.POST_CLOSE
|
|
175
|
+
return SessionPhase.CLOSED
|
|
176
|
+
|
|
177
|
+
def next_open(self, dt: datetime | None = None) -> datetime:
|
|
178
|
+
"""Next datetime when the market opens (IST)."""
|
|
179
|
+
if dt is None:
|
|
180
|
+
dt = datetime.now(IST)
|
|
181
|
+
elif dt.tzinfo is None:
|
|
182
|
+
dt = dt.replace(tzinfo=IST)
|
|
183
|
+
else:
|
|
184
|
+
dt = dt.astimezone(IST)
|
|
185
|
+
|
|
186
|
+
candidate = dt.replace(
|
|
187
|
+
hour=NSE_OPEN.hour, minute=NSE_OPEN.minute,
|
|
188
|
+
second=0, microsecond=0,
|
|
189
|
+
)
|
|
190
|
+
# If today's open has already passed, look at tomorrow.
|
|
191
|
+
if dt.time() >= NSE_OPEN:
|
|
192
|
+
candidate += timedelta(days=1)
|
|
193
|
+
# Walk forward over weekends and holidays.
|
|
194
|
+
for _ in range(20): # Bounded loop — ~3 weeks of guard
|
|
195
|
+
if self.is_trading_day(candidate.date()):
|
|
196
|
+
return candidate
|
|
197
|
+
candidate += timedelta(days=1)
|
|
198
|
+
# Shouldn't happen in practice; return the candidate anyway so
|
|
199
|
+
# callers get a deterministic value.
|
|
200
|
+
return candidate
|