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,205 @@
|
|
|
1
|
+
"""Yahoo Finance provider.
|
|
2
|
+
|
|
3
|
+
Path of least resistance: no API key, no signup. Yahoo is delayed
|
|
4
|
+
~15 minutes for Indian symbols and the response shape can drift
|
|
5
|
+
without notice — keep it as one provider in a chain, not the only one.
|
|
6
|
+
|
|
7
|
+
Capabilities
|
|
8
|
+
------------
|
|
9
|
+
- LAST_PRICE, QUOTE (bid/ask when ``fast_info`` exposes them), DELAYED.
|
|
10
|
+
- OHLCV_DAILY (via ``ticker.history``).
|
|
11
|
+
- NSE (.NS) by default; pass ``exchange_suffix="BO"`` for BSE.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import logging
|
|
18
|
+
from datetime import date, datetime
|
|
19
|
+
|
|
20
|
+
from .base import (
|
|
21
|
+
OHLCV,
|
|
22
|
+
MarketDataProvider,
|
|
23
|
+
MarketQuote,
|
|
24
|
+
ProviderCapability,
|
|
25
|
+
ProviderError,
|
|
26
|
+
ProviderInfo,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class YFinanceProvider(MarketDataProvider):
|
|
33
|
+
"""Yahoo Finance via the ``yfinance`` package.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
exchange_suffix:
|
|
38
|
+
``"NS"`` for NSE (default), ``"BO"`` for BSE.
|
|
39
|
+
auto_adjust:
|
|
40
|
+
When True (default), ``MarketQuote.adjusted_close`` and the
|
|
41
|
+
history bars are returned with split/dividend adjustments
|
|
42
|
+
applied — the standard backtesting choice. When False, raw
|
|
43
|
+
prices are returned (matching what a real broker contract
|
|
44
|
+
note shows on a non-ex-date day).
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
exchange_suffix: str = "NS",
|
|
50
|
+
auto_adjust: bool = True,
|
|
51
|
+
) -> None:
|
|
52
|
+
self.suffix = exchange_suffix.lstrip(".")
|
|
53
|
+
self.auto_adjust = auto_adjust
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def info(self) -> ProviderInfo:
|
|
57
|
+
caps = (
|
|
58
|
+
ProviderCapability.LAST_PRICE
|
|
59
|
+
| ProviderCapability.QUOTE
|
|
60
|
+
| ProviderCapability.OHLCV_DAILY
|
|
61
|
+
| ProviderCapability.DELAYED
|
|
62
|
+
)
|
|
63
|
+
if self.suffix.upper() == "NS":
|
|
64
|
+
caps |= ProviderCapability.SUPPORTS_NSE
|
|
65
|
+
elif self.suffix.upper() == "BO":
|
|
66
|
+
caps |= ProviderCapability.SUPPORTS_BSE
|
|
67
|
+
return ProviderInfo(
|
|
68
|
+
name="yfinance",
|
|
69
|
+
description="Yahoo Finance via the yfinance Python package.",
|
|
70
|
+
capabilities=caps,
|
|
71
|
+
requires_api_key=False,
|
|
72
|
+
homepage="https://github.com/ranaroussi/yfinance",
|
|
73
|
+
notes="~15 minute delay for Indian symbols.",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def get_quote(self, symbol: str) -> MarketQuote | None:
|
|
77
|
+
try:
|
|
78
|
+
import yfinance as yf # noqa: WPS433 — lazy import is intentional
|
|
79
|
+
except ImportError as e:
|
|
80
|
+
raise ProviderError("yfinance is not installed") from e
|
|
81
|
+
|
|
82
|
+
ticker_sym = f"{symbol}.{self.suffix}"
|
|
83
|
+
try:
|
|
84
|
+
ticker = yf.Ticker(ticker_sym)
|
|
85
|
+
|
|
86
|
+
# ``fast_info`` is volatile across versions; treat any
|
|
87
|
+
# KeyError/AttributeError as "fast path didn't work".
|
|
88
|
+
last: float | None = None
|
|
89
|
+
bid: float | None = None
|
|
90
|
+
ask: float | None = None
|
|
91
|
+
volume: int | None = None
|
|
92
|
+
prev_close: float | None = None
|
|
93
|
+
day_high: float | None = None
|
|
94
|
+
day_low: float | None = None
|
|
95
|
+
day_open: float | None = None
|
|
96
|
+
try:
|
|
97
|
+
fi = ticker.fast_info
|
|
98
|
+
last = (
|
|
99
|
+
_f(fi, "lastPrice")
|
|
100
|
+
or _f(fi, "last_price")
|
|
101
|
+
or _f(fi, "regularMarketPrice")
|
|
102
|
+
)
|
|
103
|
+
bid = _f(fi, "bid")
|
|
104
|
+
ask = _f(fi, "ask")
|
|
105
|
+
volume = _i(fi, "lastVolume") or _i(fi, "regularMarketVolume")
|
|
106
|
+
prev_close = (
|
|
107
|
+
_f(fi, "previousClose") or _f(fi, "regularMarketPreviousClose")
|
|
108
|
+
)
|
|
109
|
+
day_high = _f(fi, "dayHigh") or _f(fi, "regularMarketDayHigh")
|
|
110
|
+
day_low = _f(fi, "dayLow") or _f(fi, "regularMarketDayLow")
|
|
111
|
+
day_open = _f(fi, "open") or _f(fi, "regularMarketOpen")
|
|
112
|
+
except Exception: # noqa: BLE001
|
|
113
|
+
pass
|
|
114
|
+
|
|
115
|
+
if last is None:
|
|
116
|
+
# Fall back to the daily history slot.
|
|
117
|
+
hist = ticker.history(period="1d", auto_adjust=self.auto_adjust)
|
|
118
|
+
if hist is not None and not hist.empty:
|
|
119
|
+
last = float(hist["Close"].iloc[-1])
|
|
120
|
+
if "Volume" in hist.columns:
|
|
121
|
+
with contextlib.suppress(Exception):
|
|
122
|
+
volume = int(hist["Volume"].iloc[-1])
|
|
123
|
+
|
|
124
|
+
if last is None:
|
|
125
|
+
return None # genuinely unknown symbol
|
|
126
|
+
|
|
127
|
+
return MarketQuote(
|
|
128
|
+
last=float(last),
|
|
129
|
+
timestamp=datetime.now(),
|
|
130
|
+
bid=bid,
|
|
131
|
+
ask=ask,
|
|
132
|
+
open=day_open,
|
|
133
|
+
high=day_high,
|
|
134
|
+
low=day_low,
|
|
135
|
+
prev_close=prev_close,
|
|
136
|
+
volume=volume,
|
|
137
|
+
# When auto_adjust is on, last == adjusted close.
|
|
138
|
+
# Otherwise it's the raw print and adjusted_close is
|
|
139
|
+
# not available from this code path.
|
|
140
|
+
adjusted_close=float(last) if self.auto_adjust else None,
|
|
141
|
+
source="yfinance",
|
|
142
|
+
is_real_time=False, # Yahoo is delayed
|
|
143
|
+
)
|
|
144
|
+
except Exception as e: # noqa: BLE001
|
|
145
|
+
logger.warning("yfinance failed for %s: %s", symbol, e)
|
|
146
|
+
raise ProviderError(f"yfinance failed for {symbol}: {e}") from e
|
|
147
|
+
|
|
148
|
+
def get_history(
|
|
149
|
+
self,
|
|
150
|
+
symbol: str,
|
|
151
|
+
start: date,
|
|
152
|
+
end: date,
|
|
153
|
+
interval: str = "1d",
|
|
154
|
+
) -> list[OHLCV]:
|
|
155
|
+
try:
|
|
156
|
+
import yfinance as yf # noqa: WPS433
|
|
157
|
+
except ImportError as e:
|
|
158
|
+
raise ProviderError("yfinance is not installed") from e
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
ticker = yf.Ticker(f"{symbol}.{self.suffix}")
|
|
162
|
+
hist = ticker.history(
|
|
163
|
+
start=str(start), end=str(end), interval=interval,
|
|
164
|
+
auto_adjust=self.auto_adjust,
|
|
165
|
+
)
|
|
166
|
+
except Exception as e: # noqa: BLE001
|
|
167
|
+
raise ProviderError(f"yfinance history failed: {e}") from e
|
|
168
|
+
if hist is None or hist.empty:
|
|
169
|
+
return []
|
|
170
|
+
|
|
171
|
+
out: list[OHLCV] = []
|
|
172
|
+
for ts, row in hist.iterrows():
|
|
173
|
+
try:
|
|
174
|
+
out.append(
|
|
175
|
+
OHLCV(
|
|
176
|
+
timestamp=ts.to_pydatetime() if hasattr(ts, "to_pydatetime") else ts,
|
|
177
|
+
open=float(row["Open"]),
|
|
178
|
+
high=float(row["High"]),
|
|
179
|
+
low=float(row["Low"]),
|
|
180
|
+
close=float(row["Close"]),
|
|
181
|
+
volume=int(row.get("Volume", 0) or 0),
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
except Exception: # noqa: BLE001 — skip malformed rows
|
|
185
|
+
continue
|
|
186
|
+
return out
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _f(obj: object, key: str) -> float | None:
|
|
190
|
+
"""Best-effort float extractor that survives missing keys / Nones."""
|
|
191
|
+
try:
|
|
192
|
+
v = obj.get(key) if hasattr(obj, "get") else getattr(obj, key, None)
|
|
193
|
+
if v is None:
|
|
194
|
+
return None
|
|
195
|
+
v = float(v)
|
|
196
|
+
if v != v or v == float("inf") or v == float("-inf"): # NaN guard
|
|
197
|
+
return None
|
|
198
|
+
return v if v > 0 else None
|
|
199
|
+
except Exception: # noqa: BLE001
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _i(obj: object, key: str) -> int | None:
|
|
204
|
+
f = _f(obj, key)
|
|
205
|
+
return int(f) if f is not None else None
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""One-line factory for the most common configuration.
|
|
2
|
+
|
|
3
|
+
Most first-time users just want a "sane defaults" broker so they can
|
|
4
|
+
play with buy/sell. Hand-picking among 14 constructor parameters is a
|
|
5
|
+
cliff. ``quickstart()`` returns a broker pre-configured for safe
|
|
6
|
+
delivery-style equity trading on NSE:
|
|
7
|
+
|
|
8
|
+
- ₹1,000,000 starting capital
|
|
9
|
+
- Zerodha-style fee schedule (₹0 brokerage delivery)
|
|
10
|
+
- 5 bp slippage on market fills
|
|
11
|
+
- Strict symbol master with the bundled NSE-30 sample loaded
|
|
12
|
+
- Idempotency keys cleaned up automatically every 50 watcher ticks
|
|
13
|
+
(see ``LimitOrderWatcher`` opt-in below)
|
|
14
|
+
- Stale-price hard-reject ON for autonomous safety
|
|
15
|
+
|
|
16
|
+
Override any field by passing it explicitly. The returned broker is
|
|
17
|
+
identical to one constructed by hand — there's no "quickstart mode"
|
|
18
|
+
flag anywhere; it's just an opinionated factory.
|
|
19
|
+
|
|
20
|
+
Example::
|
|
21
|
+
|
|
22
|
+
from papertrade_india import quickstart
|
|
23
|
+
broker = quickstart()
|
|
24
|
+
broker.buy("RELIANCE", 1)
|
|
25
|
+
|
|
26
|
+
Pass overrides to specialize::
|
|
27
|
+
|
|
28
|
+
broker = quickstart(
|
|
29
|
+
initial_capital=500_000,
|
|
30
|
+
symbol_master=None, # disable the strict symbol master
|
|
31
|
+
slippage_bps=10.0,
|
|
32
|
+
)
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import TYPE_CHECKING
|
|
39
|
+
|
|
40
|
+
from .broker import IndiaPaperBroker
|
|
41
|
+
from .domain.models import Exchange
|
|
42
|
+
from .domain.rules.risk import RiskConfig
|
|
43
|
+
from .execution.fees import FeeConfig, FeeSchedule
|
|
44
|
+
from .execution.slippage import SlippageConfig
|
|
45
|
+
from .infrastructure.persistence import PathLike
|
|
46
|
+
from .infrastructure.symbols import SymbolMaster
|
|
47
|
+
from .presets import ZERODHA_DELIVERY
|
|
48
|
+
|
|
49
|
+
if TYPE_CHECKING:
|
|
50
|
+
from .infrastructure.market_hours import NSECalendar
|
|
51
|
+
from .price_feed import PriceFeed
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def quickstart(
|
|
55
|
+
*,
|
|
56
|
+
initial_capital: float = 1_000_000.0,
|
|
57
|
+
db_path: PathLike = "data/india_paper.db",
|
|
58
|
+
account_id: str = "default",
|
|
59
|
+
fee_config: FeeConfig | FeeSchedule | None = None,
|
|
60
|
+
slippage_bps: float = 5.0,
|
|
61
|
+
risk_config: RiskConfig | None = None,
|
|
62
|
+
symbol_master: SymbolMaster | None = "load-bundled-nse",
|
|
63
|
+
enforce_market_hours: bool = True,
|
|
64
|
+
enforce_fresh_prices: bool = True,
|
|
65
|
+
price_feed: PriceFeed | None = None,
|
|
66
|
+
calendar: NSECalendar | None = None,
|
|
67
|
+
) -> IndiaPaperBroker:
|
|
68
|
+
"""Construct an opinionated, safe-by-default broker.
|
|
69
|
+
|
|
70
|
+
Parameters that differ from ``IndiaPaperBroker.__init__`` defaults:
|
|
71
|
+
|
|
72
|
+
- ``slippage_bps`` (vs 0): a realistic 5 bps for liquid NSE names.
|
|
73
|
+
- ``enforce_fresh_prices`` (vs False): hard-reject stale fills.
|
|
74
|
+
- ``symbol_master``: defaults to a strict master pre-loaded with
|
|
75
|
+
the bundled NSE-30 sample. Pass ``None`` to disable, or your own
|
|
76
|
+
``SymbolMaster`` to override.
|
|
77
|
+
- ``fee_config``: defaults to ``ZERODHA_DELIVERY`` (₹0 brokerage,
|
|
78
|
+
full statutory schedule).
|
|
79
|
+
|
|
80
|
+
Other parameters fall through to ``IndiaPaperBroker``.
|
|
81
|
+
"""
|
|
82
|
+
if symbol_master == "load-bundled-nse":
|
|
83
|
+
sm = SymbolMaster(strict=True)
|
|
84
|
+
elif symbol_master is None:
|
|
85
|
+
sm = SymbolMaster(strict=False)
|
|
86
|
+
else:
|
|
87
|
+
sm = symbol_master
|
|
88
|
+
|
|
89
|
+
broker = IndiaPaperBroker(
|
|
90
|
+
initial_capital=initial_capital,
|
|
91
|
+
db_path=db_path,
|
|
92
|
+
account_id=account_id,
|
|
93
|
+
exchange=Exchange.NSE,
|
|
94
|
+
fee_config=fee_config or ZERODHA_DELIVERY,
|
|
95
|
+
slippage_config=SlippageConfig(bps=slippage_bps),
|
|
96
|
+
risk_config=risk_config or RiskConfig(),
|
|
97
|
+
symbol_master=sm,
|
|
98
|
+
enforce_market_hours=enforce_market_hours,
|
|
99
|
+
enforce_fresh_prices=enforce_fresh_prices,
|
|
100
|
+
price_feed=price_feed,
|
|
101
|
+
calendar=calendar,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# Load the NSE-30 sample into the master if we constructed one.
|
|
105
|
+
if symbol_master == "load-bundled-nse":
|
|
106
|
+
sample = Path(__file__).parent / "data" / "nse_universe_sample.csv"
|
|
107
|
+
if sample.exists():
|
|
108
|
+
with broker.persistence.transaction() as conn:
|
|
109
|
+
broker.symbol_master.load_csv(conn, sample, Exchange.NSE)
|
|
110
|
+
|
|
111
|
+
return broker
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Read-only views over the account: cash, equity, ledger, events.
|
|
2
|
+
|
|
3
|
+
Like :mod:`reads.positions`, every helper takes the broker as its first
|
|
4
|
+
argument and never mutates state.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
from ..domain.models import Account, OrderSide, OrderStatus, OrderType
|
|
13
|
+
from ..infrastructure import events as _events
|
|
14
|
+
from ..infrastructure import ledger as _ledger
|
|
15
|
+
from . import positions as _positions
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
18
|
+
from ..broker import IndiaPaperBroker
|
|
19
|
+
from ..infrastructure.market_hours import SessionPhase
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def summary(broker: IndiaPaperBroker) -> Account:
|
|
25
|
+
"""Build an :class:`Account` snapshot.
|
|
26
|
+
|
|
27
|
+
Note on consistency: cash/realized_pl_total and pending-buy notional
|
|
28
|
+
are read from the same connection inside one read context to keep
|
|
29
|
+
the snapshot tight. Mark-to-market on positions still calls out to
|
|
30
|
+
the price feed (network-volatile), so the ``equity`` and
|
|
31
|
+
``unrealized_pl_total`` fields can drift slightly if a fill lands
|
|
32
|
+
mid-call. Acceptable for paper-trading reads.
|
|
33
|
+
"""
|
|
34
|
+
with broker.persistence.read() as conn:
|
|
35
|
+
acct_row = conn.execute(
|
|
36
|
+
"SELECT cash, realized_pl_total FROM account "
|
|
37
|
+
"WHERE account_id = ?",
|
|
38
|
+
(broker.account_id,),
|
|
39
|
+
).fetchone()
|
|
40
|
+
pending_buys = conn.execute(
|
|
41
|
+
"SELECT COALESCE(SUM(qty * limit_price), 0) AS notional "
|
|
42
|
+
"FROM orders WHERE account_id = ? AND status = ? "
|
|
43
|
+
"AND side = ? AND order_type = ?",
|
|
44
|
+
(
|
|
45
|
+
broker.account_id, OrderStatus.PENDING.value,
|
|
46
|
+
OrderSide.BUY.value, OrderType.LIMIT.value,
|
|
47
|
+
),
|
|
48
|
+
).fetchone()["notional"]
|
|
49
|
+
|
|
50
|
+
cash = acct_row["cash"]
|
|
51
|
+
realized = acct_row["realized_pl_total"]
|
|
52
|
+
open_positions = _positions.list_all(broker)
|
|
53
|
+
portfolio_value = sum(p.market_value for p in open_positions)
|
|
54
|
+
unrealized = sum(p.unrealized_pl for p in open_positions)
|
|
55
|
+
|
|
56
|
+
return Account(
|
|
57
|
+
account_id=broker.account_id,
|
|
58
|
+
equity=cash + portfolio_value,
|
|
59
|
+
cash=cash,
|
|
60
|
+
portfolio_value=portfolio_value,
|
|
61
|
+
buying_power=max(0.0, cash - pending_buys),
|
|
62
|
+
realized_pl_total=realized,
|
|
63
|
+
unrealized_pl_total=unrealized,
|
|
64
|
+
currency="INR",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def list_cash_movements(
|
|
69
|
+
broker: IndiaPaperBroker, limit: int = 200,
|
|
70
|
+
) -> list[_ledger.CashMovement]:
|
|
71
|
+
"""Recent cash-ledger rows for this account, newest first."""
|
|
72
|
+
with broker.persistence.read() as conn:
|
|
73
|
+
return _ledger.list_for_account(conn, broker.account_id, limit=limit)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def verify_cash_invariant(
|
|
77
|
+
broker: IndiaPaperBroker, tolerance: float = 0.01,
|
|
78
|
+
) -> bool:
|
|
79
|
+
"""Assert ``account.cash == sum(cash_movements.amount)``.
|
|
80
|
+
|
|
81
|
+
Returns ``True`` if the invariant holds within ``tolerance``
|
|
82
|
+
(₹0.01 absolute by default — paise rounding only).
|
|
83
|
+
|
|
84
|
+
Run this from tests, audits, or a periodic health check. A False
|
|
85
|
+
result means there's a code path mutating ``account.cash`` without
|
|
86
|
+
writing a matching ledger row, which is a bug.
|
|
87
|
+
|
|
88
|
+
On drift (returning False) we also log a structured WARN with the
|
|
89
|
+
magnitude and the most recent ledger rows so the failure is
|
|
90
|
+
debuggable in the wild without needing to re-run with debug flags.
|
|
91
|
+
"""
|
|
92
|
+
with broker.persistence.read() as conn:
|
|
93
|
+
cash = conn.execute(
|
|
94
|
+
"SELECT cash FROM account WHERE account_id = ?",
|
|
95
|
+
(broker.account_id,),
|
|
96
|
+
).fetchone()["cash"]
|
|
97
|
+
ledger_total = _ledger.sum_for_account(conn, broker.account_id)
|
|
98
|
+
|
|
99
|
+
drift = cash - ledger_total
|
|
100
|
+
if abs(drift) <= tolerance:
|
|
101
|
+
return True
|
|
102
|
+
|
|
103
|
+
recent = list_cash_movements(broker, limit=5)
|
|
104
|
+
logger.warning(
|
|
105
|
+
"Cash invariant broken on account=%s: cash=%.4f, "
|
|
106
|
+
"sum(movements)=%.4f, drift=%.4f. Recent movements: %s",
|
|
107
|
+
broker.account_id, cash, ledger_total, drift,
|
|
108
|
+
[(m.recorded_at.isoformat(), m.reason, m.amount) for m in recent],
|
|
109
|
+
)
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def list_events(
|
|
114
|
+
broker: IndiaPaperBroker,
|
|
115
|
+
limit: int = 200,
|
|
116
|
+
event_types: tuple[str, ...] | None = None,
|
|
117
|
+
) -> list[_events.Event]:
|
|
118
|
+
"""Recent events for this account, newest first.
|
|
119
|
+
|
|
120
|
+
``event_types`` filters by types when provided, e.g.
|
|
121
|
+
``event_types=("order_filled", "order_partially_filled")``.
|
|
122
|
+
"""
|
|
123
|
+
with broker.persistence.read() as conn:
|
|
124
|
+
return _events.list_for_account(
|
|
125
|
+
conn, broker.account_id, limit=limit, event_types=event_types,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def current_session_phase(broker: IndiaPaperBroker) -> SessionPhase:
|
|
130
|
+
"""The active NSE session phase at the broker's clock."""
|
|
131
|
+
return broker.calendar.current_phase(broker.clock.now())
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
__all__ = [
|
|
135
|
+
"summary",
|
|
136
|
+
"list_cash_movements",
|
|
137
|
+
"verify_cash_invariant",
|
|
138
|
+
"list_events",
|
|
139
|
+
"current_session_phase",
|
|
140
|
+
]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Read-only views over orders.
|
|
2
|
+
|
|
3
|
+
Like the rest of :mod:`reads`, helpers take the broker as their first
|
|
4
|
+
argument and never mutate state. Row-to-:class:`Order` mapping lives on
|
|
5
|
+
the broker; we delegate to it here.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
from ..domain.models import Order, OrderStatus
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
15
|
+
from ..broker import IndiaPaperBroker
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def list_all(
|
|
19
|
+
broker: IndiaPaperBroker,
|
|
20
|
+
status: OrderStatus | None = None,
|
|
21
|
+
limit: int = 100,
|
|
22
|
+
) -> list[Order]:
|
|
23
|
+
"""Recent orders for this account, newest first.
|
|
24
|
+
|
|
25
|
+
``status`` narrows the query when provided.
|
|
26
|
+
"""
|
|
27
|
+
with broker.persistence.read() as conn:
|
|
28
|
+
if status is not None:
|
|
29
|
+
rows = conn.execute(
|
|
30
|
+
"SELECT * FROM orders WHERE account_id = ? AND status = ? "
|
|
31
|
+
"ORDER BY created_at DESC LIMIT ?",
|
|
32
|
+
(broker.account_id, status.value, limit),
|
|
33
|
+
).fetchall()
|
|
34
|
+
else:
|
|
35
|
+
rows = conn.execute(
|
|
36
|
+
"SELECT * FROM orders WHERE account_id = ? "
|
|
37
|
+
"ORDER BY created_at DESC LIMIT ?",
|
|
38
|
+
(broker.account_id, limit),
|
|
39
|
+
).fetchall()
|
|
40
|
+
|
|
41
|
+
return [broker._row_to_order(r) for r in rows]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def get(broker: IndiaPaperBroker, order_id: str) -> Order | None:
|
|
45
|
+
"""Fetch one order by id, scoped to the broker's account."""
|
|
46
|
+
with broker.persistence.read() as conn:
|
|
47
|
+
row = conn.execute(
|
|
48
|
+
"SELECT * FROM orders WHERE id = ? AND account_id = ?",
|
|
49
|
+
(order_id, broker.account_id),
|
|
50
|
+
).fetchone()
|
|
51
|
+
return broker._row_to_order(row) if row else None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
__all__ = ["list_all", "get"]
|