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,213 @@
|
|
|
1
|
+
"""Indian fee engine.
|
|
2
|
+
|
|
3
|
+
A real Indian paper broker must simulate fees properly. P&L without fees
|
|
4
|
+
is misleading and an agent will systematically over-estimate returns.
|
|
5
|
+
|
|
6
|
+
Default ``FeeConfig`` matches a typical Indian discount broker (Zerodha-style)
|
|
7
|
+
for equity *delivery* in 2026:
|
|
8
|
+
|
|
9
|
+
- Brokerage: ₹0 for delivery
|
|
10
|
+
- STT: 0.1% on both buy and sell
|
|
11
|
+
- Exchange charges: 0.00322% (NSE), 0.00375% (BSE)
|
|
12
|
+
- GST: 18% on (brokerage + exchange charges)
|
|
13
|
+
- SEBI turnover charges: ₹10 per crore
|
|
14
|
+
- Stamp duty: 0.015% on buy only
|
|
15
|
+
- DP charge: ₹13.5 per sell order
|
|
16
|
+
|
|
17
|
+
References used (paraphrased and rephrased for compliance with licensing):
|
|
18
|
+
public Indian broker fee structures from Zerodha, Upstox, Groww and Angel
|
|
19
|
+
One published in 2025–2026.
|
|
20
|
+
|
|
21
|
+
Pass a custom ``FeeConfig`` to model a different broker's schedule.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from datetime import date # noqa: F401 — used in FeeSchedule type hints
|
|
28
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
29
|
+
|
|
30
|
+
from ..domain.models import Exchange, OrderSide
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class FeeBreakdown:
|
|
35
|
+
"""Per-order fee breakdown, all amounts in INR."""
|
|
36
|
+
|
|
37
|
+
brokerage: float
|
|
38
|
+
stt: float
|
|
39
|
+
exchange_charge: float
|
|
40
|
+
gst: float
|
|
41
|
+
sebi_charges: float
|
|
42
|
+
stamp_duty: float
|
|
43
|
+
dp_charges: float
|
|
44
|
+
total: float
|
|
45
|
+
|
|
46
|
+
def __str__(self) -> str:
|
|
47
|
+
return (
|
|
48
|
+
f"Brokerage: ₹{self.brokerage:.2f}, STT: ₹{self.stt:.2f}, "
|
|
49
|
+
f"Exchange: ₹{self.exchange_charge:.2f}, GST: ₹{self.gst:.2f}, "
|
|
50
|
+
f"SEBI: ₹{self.sebi_charges:.2f}, Stamp: ₹{self.stamp_duty:.2f}, "
|
|
51
|
+
f"DP: ₹{self.dp_charges:.2f}, Total: ₹{self.total:.2f}"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class FeeConfig:
|
|
57
|
+
"""Configurable fee schedule.
|
|
58
|
+
|
|
59
|
+
Defaults model a discount-broker delivery account in 2026. Override
|
|
60
|
+
fields to model intraday, full-service brokers, or custom contracts.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
# Brokerage. Discount-broker delivery is ₹0. For intraday or full-service:
|
|
64
|
+
# - ``brokerage_flat`` charges a fixed amount per order
|
|
65
|
+
# - ``brokerage_pct`` charges a percentage of turnover
|
|
66
|
+
# - ``brokerage_max`` caps the percentage charge
|
|
67
|
+
# If ``brokerage_max`` is set (>0), brokerage = min(turnover * pct, max).
|
|
68
|
+
# Otherwise, brokerage = ``brokerage_flat``.
|
|
69
|
+
brokerage_flat: float = 0.0
|
|
70
|
+
brokerage_pct: float = 0.0
|
|
71
|
+
brokerage_max: float = 0.0
|
|
72
|
+
|
|
73
|
+
# Statutory taxes/charges (rarely change)
|
|
74
|
+
stt_pct_buy: float = 0.001 # 0.1% on buy
|
|
75
|
+
stt_pct_sell: float = 0.001 # 0.1% on sell
|
|
76
|
+
exchange_charge_nse: float = 0.0000322
|
|
77
|
+
exchange_charge_bse: float = 0.0000375
|
|
78
|
+
gst_pct: float = 0.18 # 18% on brokerage + exchange charge
|
|
79
|
+
sebi_charges_pct: float = 0.000001 # ₹10 per crore
|
|
80
|
+
stamp_duty_pct: float = 0.00015 # 0.015% on buy only
|
|
81
|
+
|
|
82
|
+
# DP charge: in reality ~₹13.5–20 per scrip per day on sells. We apply
|
|
83
|
+
# it per sell order in the simulator (very slightly conservative if a
|
|
84
|
+
# user sells the same symbol multiple times in one day).
|
|
85
|
+
dp_charge_per_sell: float = 13.5
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class FeeSchedule:
|
|
90
|
+
"""Date-versioned fee schedule.
|
|
91
|
+
|
|
92
|
+
Maps an effective-from date (inclusive) to a ``FeeConfig``. The
|
|
93
|
+
correct config is picked by the order's *trade date* — useful when
|
|
94
|
+
statutory rates change mid-year (the government regularly tweaks
|
|
95
|
+
STT, GST, stamp duty in the union budget).
|
|
96
|
+
|
|
97
|
+
Usage::
|
|
98
|
+
|
|
99
|
+
schedule = FeeSchedule(
|
|
100
|
+
default=FeeConfig(), # pre-history
|
|
101
|
+
effective_from={
|
|
102
|
+
date(2025, 4, 1): FeeConfig(stt_pct_buy=0.001),
|
|
103
|
+
date(2026, 4, 1): FeeConfig(stt_pct_buy=0.00125), # hike
|
|
104
|
+
},
|
|
105
|
+
)
|
|
106
|
+
cfg = schedule.config_on(date(2025, 9, 1)) # → 2025 config
|
|
107
|
+
cfg = schedule.config_on(date(2026, 5, 1)) # → 2026 config
|
|
108
|
+
|
|
109
|
+
A bare ``FeeConfig`` keeps working — the broker wraps it in a
|
|
110
|
+
``FeeSchedule(default=cfg)``.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
default: FeeConfig
|
|
114
|
+
effective_from: dict[date, FeeConfig] = field(default_factory=dict)
|
|
115
|
+
|
|
116
|
+
def config_on(self, when: date) -> FeeConfig:
|
|
117
|
+
"""Pick the fee config in effect on ``when``.
|
|
118
|
+
|
|
119
|
+
Walks effective-from dates in descending order and returns the
|
|
120
|
+
first one ``<= when``. Falls back to ``default``.
|
|
121
|
+
"""
|
|
122
|
+
if not self.effective_from:
|
|
123
|
+
return self.default
|
|
124
|
+
for eff_date in sorted(self.effective_from, reverse=True):
|
|
125
|
+
if eff_date <= when:
|
|
126
|
+
return self.effective_from[eff_date]
|
|
127
|
+
return self.default
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _round_paise(x: float) -> float:
|
|
131
|
+
"""Round to paise (2 decimals) using half-up."""
|
|
132
|
+
return float(
|
|
133
|
+
Decimal(str(x)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class IndianFeeEngine:
|
|
138
|
+
"""Computes Indian-specific brokerage and statutory fees."""
|
|
139
|
+
|
|
140
|
+
def __init__(self, config: FeeConfig | None = None) -> None:
|
|
141
|
+
self.config = config or FeeConfig()
|
|
142
|
+
|
|
143
|
+
def calculate(
|
|
144
|
+
self,
|
|
145
|
+
side: OrderSide,
|
|
146
|
+
qty: float,
|
|
147
|
+
price: float,
|
|
148
|
+
exchange: Exchange,
|
|
149
|
+
) -> FeeBreakdown:
|
|
150
|
+
"""Compute the full fee breakdown for an executed leg."""
|
|
151
|
+
if qty <= 0 or price <= 0:
|
|
152
|
+
# Zero-fee, zero-everything — keeps callers from special-casing.
|
|
153
|
+
zero = _round_paise(0.0)
|
|
154
|
+
return FeeBreakdown(
|
|
155
|
+
brokerage=zero, stt=zero, exchange_charge=zero, gst=zero,
|
|
156
|
+
sebi_charges=zero, stamp_duty=zero, dp_charges=zero,
|
|
157
|
+
total=zero,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
turnover = qty * price
|
|
161
|
+
cfg = self.config
|
|
162
|
+
|
|
163
|
+
# Brokerage: percentage with cap, or flat if no percentage configured.
|
|
164
|
+
if cfg.brokerage_max > 0 and cfg.brokerage_pct > 0:
|
|
165
|
+
brokerage = min(turnover * cfg.brokerage_pct, cfg.brokerage_max)
|
|
166
|
+
elif cfg.brokerage_pct > 0:
|
|
167
|
+
brokerage = turnover * cfg.brokerage_pct
|
|
168
|
+
else:
|
|
169
|
+
brokerage = cfg.brokerage_flat
|
|
170
|
+
brokerage = max(0.0, brokerage)
|
|
171
|
+
|
|
172
|
+
# STT — symmetric on buy/sell for delivery
|
|
173
|
+
stt_pct = cfg.stt_pct_buy if side == OrderSide.BUY else cfg.stt_pct_sell
|
|
174
|
+
stt = turnover * stt_pct
|
|
175
|
+
|
|
176
|
+
# Exchange charges (depend on venue)
|
|
177
|
+
exch_pct = (
|
|
178
|
+
cfg.exchange_charge_nse if exchange == Exchange.NSE
|
|
179
|
+
else cfg.exchange_charge_bse
|
|
180
|
+
)
|
|
181
|
+
exchange_charge = turnover * exch_pct
|
|
182
|
+
|
|
183
|
+
# GST is on (brokerage + exchange charge), not on STT/stamp/SEBI.
|
|
184
|
+
gst = (brokerage + exchange_charge) * cfg.gst_pct
|
|
185
|
+
|
|
186
|
+
# SEBI turnover charges
|
|
187
|
+
sebi_charges = turnover * cfg.sebi_charges_pct
|
|
188
|
+
|
|
189
|
+
# Stamp duty applies to buys only (in delivery).
|
|
190
|
+
stamp_duty = (
|
|
191
|
+
turnover * cfg.stamp_duty_pct if side == OrderSide.BUY else 0.0
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# DP charge applies to sells only.
|
|
195
|
+
dp_charges = (
|
|
196
|
+
cfg.dp_charge_per_sell if side == OrderSide.SELL else 0.0
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
total = (
|
|
200
|
+
brokerage + stt + exchange_charge + gst
|
|
201
|
+
+ sebi_charges + stamp_duty + dp_charges
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
return FeeBreakdown(
|
|
205
|
+
brokerage=_round_paise(brokerage),
|
|
206
|
+
stt=_round_paise(stt),
|
|
207
|
+
exchange_charge=_round_paise(exchange_charge),
|
|
208
|
+
gst=_round_paise(gst),
|
|
209
|
+
sebi_charges=_round_paise(sebi_charges),
|
|
210
|
+
stamp_duty=_round_paise(stamp_duty),
|
|
211
|
+
dp_charges=_round_paise(dp_charges),
|
|
212
|
+
total=_round_paise(total),
|
|
213
|
+
)
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""T+1 settlement and intraday auto-square-off.
|
|
2
|
+
|
|
3
|
+
India moved to T+1 settlement in 2023 (full rollout by Jan 2024). The
|
|
4
|
+
practical effect on a retail trader:
|
|
5
|
+
|
|
6
|
+
- A SELL credits proceeds to ``cash`` on T+1, not T+0. Until then the
|
|
7
|
+
cash exists but isn't withdrawable to the bank — though for most
|
|
8
|
+
paper-trading purposes you can still re-buy with it.
|
|
9
|
+
- A BUY debits cash immediately but the shares aren't deliverable until
|
|
10
|
+
T+1. You cannot sell what you don't have, even if your limit order
|
|
11
|
+
filled this morning.
|
|
12
|
+
- INTRADAY (MIS) trades sidestep both: the broker squares off any open
|
|
13
|
+
MIS position at 15:15 IST, no demat involvement, no DP charge, no
|
|
14
|
+
delivery.
|
|
15
|
+
|
|
16
|
+
Real-world deviations we don't model:
|
|
17
|
+
- BTST (Buy Today Sell Tomorrow) using auctioned shares — too edge-case.
|
|
18
|
+
- T+0 settlement pilot for a small subset of scrips — opt-in to the
|
|
19
|
+
pilot is per-broker.
|
|
20
|
+
- T+2 leftovers in BSE for a few weeks during transitions.
|
|
21
|
+
|
|
22
|
+
This module provides:
|
|
23
|
+
|
|
24
|
+
- :class:`SettlementMode` — picks the broker's settlement style.
|
|
25
|
+
- :class:`SettlementConfig` — one knob: ``auto_square_off_intraday_at``
|
|
26
|
+
(minutes since midnight IST, 15:15 by default).
|
|
27
|
+
- :class:`PendingSettlement` — a single row in the queue.
|
|
28
|
+
- :class:`SettlementEngine` — drives the queue against the broker.
|
|
29
|
+
|
|
30
|
+
The broker hosts an instance and calls :meth:`settle_due` on each tick
|
|
31
|
+
and at session close. Persistence lives in a new ``pending_settlements``
|
|
32
|
+
table added in migration v2.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import logging
|
|
38
|
+
import sqlite3
|
|
39
|
+
import uuid
|
|
40
|
+
from dataclasses import dataclass
|
|
41
|
+
from datetime import date, datetime, time, timedelta
|
|
42
|
+
from enum import Enum
|
|
43
|
+
|
|
44
|
+
from ..infrastructure.market_hours import IST
|
|
45
|
+
|
|
46
|
+
logger = logging.getLogger(__name__)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SettlementMode(str, Enum):
|
|
50
|
+
"""How the simulator settles cash and shares.
|
|
51
|
+
|
|
52
|
+
- ``T_PLUS_1``: realistic Indian settlement (default since v0.2).
|
|
53
|
+
Sells produce a pending-cash row that converts to spendable cash
|
|
54
|
+
on the next trading day. Buys reduce ``deliverable_qty`` until
|
|
55
|
+
T+1 — you can't sell what you bought today on a delivery account.
|
|
56
|
+
- ``T_PLUS_0``: legacy mode. Cash settles instantly. Use this for
|
|
57
|
+
backtests that pre-date T+1 (NSE's T+1 rollout was Jan 2024) or
|
|
58
|
+
when you want the simpler "money is fungible immediately" model.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
T_PLUS_0 = "T+0"
|
|
62
|
+
T_PLUS_1 = "T+1"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class SettlementConfig:
|
|
67
|
+
"""Runtime knobs for the settlement engine.
|
|
68
|
+
|
|
69
|
+
``mode`` controls the cash-settlement timing. Default is
|
|
70
|
+
:attr:`SettlementMode.T_PLUS_1` to match real Indian retail
|
|
71
|
+
behavior — a fresh delivery buy isn't sellable the same day.
|
|
72
|
+
Pass ``SettlementMode.T_PLUS_0`` for the legacy "instant
|
|
73
|
+
settlement" simplification that was the v0.1.x default.
|
|
74
|
+
|
|
75
|
+
``auto_square_off_at`` is the wall-clock time-of-day in IST when
|
|
76
|
+
intraday positions get forcibly closed (15:15 IST is the
|
|
77
|
+
conventional broker default — NSE itself trades until 15:30, but
|
|
78
|
+
most brokers force-close at 15:15 so any market-impact slack is
|
|
79
|
+
absorbed before close).
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
mode: SettlementMode = SettlementMode.T_PLUS_1
|
|
83
|
+
auto_square_off_at: time = time(15, 15)
|
|
84
|
+
auto_square_off_enabled: bool = True
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class PendingSettlement:
|
|
89
|
+
"""A pending T+1 cash settlement.
|
|
90
|
+
|
|
91
|
+
Fields
|
|
92
|
+
------
|
|
93
|
+
id:
|
|
94
|
+
UUID hex.
|
|
95
|
+
account_id, symbol:
|
|
96
|
+
Account scope and the underlying symbol.
|
|
97
|
+
side:
|
|
98
|
+
``"buy"`` or ``"sell"`` — determines whether shares or cash is
|
|
99
|
+
the pending side.
|
|
100
|
+
qty:
|
|
101
|
+
Number of shares involved (informational; cash deltas are
|
|
102
|
+
already in ``account.cash``).
|
|
103
|
+
cash_delta:
|
|
104
|
+
Cash to credit (sells, positive) or debit (buys, usually 0
|
|
105
|
+
because buys debit immediately) when the row settles.
|
|
106
|
+
settle_on:
|
|
107
|
+
ISO date the row becomes ``"settled"``.
|
|
108
|
+
status:
|
|
109
|
+
``"pending"`` until the engine settles it.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
id: str
|
|
113
|
+
account_id: str
|
|
114
|
+
symbol: str
|
|
115
|
+
side: str
|
|
116
|
+
qty: float
|
|
117
|
+
cash_delta: float
|
|
118
|
+
trade_date: date
|
|
119
|
+
settle_on: date
|
|
120
|
+
status: str
|
|
121
|
+
created_at: datetime
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ── DDL ──────────────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
SETTLEMENT_TABLE_SQL = """
|
|
128
|
+
CREATE TABLE IF NOT EXISTS pending_settlements (
|
|
129
|
+
id TEXT PRIMARY KEY,
|
|
130
|
+
account_id TEXT NOT NULL,
|
|
131
|
+
symbol TEXT NOT NULL,
|
|
132
|
+
side TEXT NOT NULL CHECK(side IN ('buy','sell')),
|
|
133
|
+
qty REAL NOT NULL,
|
|
134
|
+
cash_delta REAL NOT NULL DEFAULT 0,
|
|
135
|
+
trade_date TEXT NOT NULL,
|
|
136
|
+
settle_on TEXT NOT NULL,
|
|
137
|
+
status TEXT NOT NULL DEFAULT 'pending'
|
|
138
|
+
CHECK(status IN ('pending','settled','cancelled')),
|
|
139
|
+
created_at TEXT NOT NULL,
|
|
140
|
+
FOREIGN KEY (account_id) REFERENCES account(account_id) ON DELETE CASCADE
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
CREATE INDEX IF NOT EXISTS idx_pending_settlements_due
|
|
144
|
+
ON pending_settlements(account_id, status, settle_on);
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ── Engine ───────────────────────────────────────────────────────────
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class SettlementEngine:
|
|
152
|
+
"""Drives the T+1 queue and intraday auto-square-off.
|
|
153
|
+
|
|
154
|
+
Stateless — all state lives in ``pending_settlements``. Inject one
|
|
155
|
+
into the broker; the broker calls :meth:`enqueue_sell`,
|
|
156
|
+
:meth:`enqueue_buy`, and :meth:`settle_due` at the right moments.
|
|
157
|
+
|
|
158
|
+
Square-off is *initiated* here (we identify positions to close);
|
|
159
|
+
the actual broker.sell call happens in the broker so fees, ledger,
|
|
160
|
+
and events flow through the canonical execution path. Keeping the
|
|
161
|
+
engine free of the broker's internals avoids a circular import and
|
|
162
|
+
makes the engine unit-testable.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(self, config: SettlementConfig | None = None) -> None:
|
|
166
|
+
self.config = config or SettlementConfig()
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def mode(self) -> SettlementMode:
|
|
170
|
+
return self.config.mode
|
|
171
|
+
|
|
172
|
+
# ── Enqueue ──────────────────────────────────────────────────────
|
|
173
|
+
|
|
174
|
+
def enqueue_sell(
|
|
175
|
+
self,
|
|
176
|
+
conn: sqlite3.Connection,
|
|
177
|
+
account_id: str,
|
|
178
|
+
symbol: str,
|
|
179
|
+
qty: float,
|
|
180
|
+
cash_credit: float,
|
|
181
|
+
trade_date: date,
|
|
182
|
+
now: datetime,
|
|
183
|
+
) -> str | None:
|
|
184
|
+
"""Record a pending T+1 sell. Returns the row id, or ``None``
|
|
185
|
+
when the engine is in T+0 mode (no row needed).
|
|
186
|
+
|
|
187
|
+
``cash_credit`` is the *additional* cash that will land on T+1
|
|
188
|
+
beyond what's already been credited. In our default model,
|
|
189
|
+
sells already credit cash on T+0 (so the user can buy back),
|
|
190
|
+
and ``cash_credit`` records the bookkeeping rather than another
|
|
191
|
+
movement. Callers can pass 0 when they want shares-only tracking.
|
|
192
|
+
"""
|
|
193
|
+
if self.config.mode != SettlementMode.T_PLUS_1:
|
|
194
|
+
return None
|
|
195
|
+
sid = uuid.uuid4().hex[:12]
|
|
196
|
+
settle_on = _next_business_day(trade_date)
|
|
197
|
+
conn.execute(
|
|
198
|
+
"INSERT INTO pending_settlements "
|
|
199
|
+
"(id, account_id, symbol, side, qty, cash_delta, "
|
|
200
|
+
"trade_date, settle_on, status, created_at) "
|
|
201
|
+
"VALUES (?, ?, ?, 'sell', ?, ?, ?, ?, 'pending', ?)",
|
|
202
|
+
(
|
|
203
|
+
sid, account_id, symbol, qty, cash_credit,
|
|
204
|
+
trade_date.isoformat(), settle_on.isoformat(),
|
|
205
|
+
now.isoformat(),
|
|
206
|
+
),
|
|
207
|
+
)
|
|
208
|
+
return sid
|
|
209
|
+
|
|
210
|
+
def enqueue_buy(
|
|
211
|
+
self,
|
|
212
|
+
conn: sqlite3.Connection,
|
|
213
|
+
account_id: str,
|
|
214
|
+
symbol: str,
|
|
215
|
+
qty: float,
|
|
216
|
+
trade_date: date,
|
|
217
|
+
now: datetime,
|
|
218
|
+
) -> str | None:
|
|
219
|
+
"""Record a pending T+1 buy.
|
|
220
|
+
|
|
221
|
+
Tracks ``qty`` shares as undeliverable until T+1. The broker
|
|
222
|
+
uses the ``deliverable_qty(...)`` query to enforce "you can't
|
|
223
|
+
sell shares you bought earlier today on a delivery account."
|
|
224
|
+
Returns the row id (or ``None`` in T+0 mode).
|
|
225
|
+
"""
|
|
226
|
+
if self.config.mode != SettlementMode.T_PLUS_1:
|
|
227
|
+
return None
|
|
228
|
+
sid = uuid.uuid4().hex[:12]
|
|
229
|
+
settle_on = _next_business_day(trade_date)
|
|
230
|
+
conn.execute(
|
|
231
|
+
"INSERT INTO pending_settlements "
|
|
232
|
+
"(id, account_id, symbol, side, qty, cash_delta, "
|
|
233
|
+
"trade_date, settle_on, status, created_at) "
|
|
234
|
+
"VALUES (?, ?, ?, 'buy', ?, 0, ?, ?, 'pending', ?)",
|
|
235
|
+
(
|
|
236
|
+
sid, account_id, symbol, qty,
|
|
237
|
+
trade_date.isoformat(), settle_on.isoformat(),
|
|
238
|
+
now.isoformat(),
|
|
239
|
+
),
|
|
240
|
+
)
|
|
241
|
+
return sid
|
|
242
|
+
|
|
243
|
+
# ── Daily roll ────────────────────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
def settle_due(
|
|
246
|
+
self,
|
|
247
|
+
conn: sqlite3.Connection,
|
|
248
|
+
account_id: str,
|
|
249
|
+
as_of: date,
|
|
250
|
+
) -> int:
|
|
251
|
+
"""Mark all rows with ``settle_on <= as_of`` as ``settled``.
|
|
252
|
+
|
|
253
|
+
Returns the count rolled. Cash already moved at trade time, so
|
|
254
|
+
no further account.cash mutation is needed; this just retires
|
|
255
|
+
the bookkeeping. For deliverable-qty tracking it's the moment
|
|
256
|
+
a buy turns "free for sale."
|
|
257
|
+
"""
|
|
258
|
+
cur = conn.execute(
|
|
259
|
+
"UPDATE pending_settlements "
|
|
260
|
+
"SET status = 'settled' "
|
|
261
|
+
"WHERE account_id = ? AND status = 'pending' AND settle_on <= ?",
|
|
262
|
+
(account_id, as_of.isoformat()),
|
|
263
|
+
)
|
|
264
|
+
if cur.rowcount:
|
|
265
|
+
logger.info(
|
|
266
|
+
"Settled %d row(s) for account=%s as_of=%s",
|
|
267
|
+
cur.rowcount, account_id, as_of.isoformat(),
|
|
268
|
+
)
|
|
269
|
+
return cur.rowcount
|
|
270
|
+
|
|
271
|
+
# ── Deliverable-qty query ────────────────────────────────────────
|
|
272
|
+
|
|
273
|
+
def deliverable_qty(
|
|
274
|
+
self,
|
|
275
|
+
conn: sqlite3.Connection,
|
|
276
|
+
account_id: str,
|
|
277
|
+
symbol: str,
|
|
278
|
+
position_qty: float,
|
|
279
|
+
as_of: date,
|
|
280
|
+
) -> float:
|
|
281
|
+
"""Shares of ``symbol`` that are sellable today on a delivery
|
|
282
|
+
account.
|
|
283
|
+
|
|
284
|
+
Sellable = position - (sum of unsettled buys still in flight).
|
|
285
|
+
In T+0 mode, unsettled buys is always 0, so this returns
|
|
286
|
+
``position_qty`` unchanged.
|
|
287
|
+
"""
|
|
288
|
+
if self.config.mode != SettlementMode.T_PLUS_1:
|
|
289
|
+
return position_qty
|
|
290
|
+
row = conn.execute(
|
|
291
|
+
"SELECT COALESCE(SUM(qty), 0) AS in_flight "
|
|
292
|
+
"FROM pending_settlements "
|
|
293
|
+
"WHERE account_id = ? AND symbol = ? AND side = 'buy' "
|
|
294
|
+
"AND status = 'pending' AND settle_on > ?",
|
|
295
|
+
(account_id, symbol, as_of.isoformat()),
|
|
296
|
+
).fetchone()
|
|
297
|
+
in_flight = float(row["in_flight"]) if row else 0.0
|
|
298
|
+
return max(0.0, position_qty - in_flight)
|
|
299
|
+
|
|
300
|
+
# ── Auto square-off helper ───────────────────────────────────────
|
|
301
|
+
|
|
302
|
+
def is_square_off_time(self, now: datetime) -> bool:
|
|
303
|
+
"""True when ``now`` (IST) has passed the configured square-off time."""
|
|
304
|
+
if not self.config.auto_square_off_enabled:
|
|
305
|
+
return False
|
|
306
|
+
# Compare time-of-day in IST. ``now`` may be naive (broker uses
|
|
307
|
+
# IST internally) or aware; we treat naive as IST.
|
|
308
|
+
local = now.astimezone(IST) if now.tzinfo else now.replace(tzinfo=IST)
|
|
309
|
+
return local.time() >= self.config.auto_square_off_at
|
|
310
|
+
|
|
311
|
+
# ── Reads ────────────────────────────────────────────────────────
|
|
312
|
+
|
|
313
|
+
def list_pending(
|
|
314
|
+
self,
|
|
315
|
+
conn: sqlite3.Connection,
|
|
316
|
+
account_id: str,
|
|
317
|
+
limit: int = 100,
|
|
318
|
+
) -> list[PendingSettlement]:
|
|
319
|
+
"""All pending rows for an account, oldest first."""
|
|
320
|
+
rows = conn.execute(
|
|
321
|
+
"SELECT * FROM pending_settlements "
|
|
322
|
+
"WHERE account_id = ? AND status = 'pending' "
|
|
323
|
+
"ORDER BY settle_on ASC, created_at ASC LIMIT ?",
|
|
324
|
+
(account_id, limit),
|
|
325
|
+
).fetchall()
|
|
326
|
+
return [_row_to_pending(r) for r in rows]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ── Helpers ──────────────────────────────────────────────────────────
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _next_business_day(d: date) -> date:
|
|
333
|
+
"""Naive next-business-day: skip weekends.
|
|
334
|
+
|
|
335
|
+
We deliberately don't import the NSE holiday calendar here — the
|
|
336
|
+
settlement engine is a low-level component and the calendar lives
|
|
337
|
+
one layer up in the broker. In practice "settle on Monday after
|
|
338
|
+
a Friday trade" is the common case and weekend skipping is enough
|
|
339
|
+
for paper-trading; users who care about Diwali settlement quirks
|
|
340
|
+
can subclass and override.
|
|
341
|
+
"""
|
|
342
|
+
nxt = d + timedelta(days=1)
|
|
343
|
+
while nxt.weekday() >= 5: # Sat=5, Sun=6
|
|
344
|
+
nxt += timedelta(days=1)
|
|
345
|
+
return nxt
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _row_to_pending(row: sqlite3.Row) -> PendingSettlement:
|
|
349
|
+
return PendingSettlement(
|
|
350
|
+
id=row["id"],
|
|
351
|
+
account_id=row["account_id"],
|
|
352
|
+
symbol=row["symbol"],
|
|
353
|
+
side=row["side"],
|
|
354
|
+
qty=float(row["qty"]),
|
|
355
|
+
cash_delta=float(row["cash_delta"]),
|
|
356
|
+
trade_date=date.fromisoformat(row["trade_date"]),
|
|
357
|
+
settle_on=date.fromisoformat(row["settle_on"]),
|
|
358
|
+
status=row["status"],
|
|
359
|
+
created_at=datetime.fromisoformat(row["created_at"]),
|
|
360
|
+
)
|