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,139 @@
|
|
|
1
|
+
"""Tick-size, lot-size, and daily price-band validation rules.
|
|
2
|
+
|
|
3
|
+
These are pure domain rules. They take a price (or a quantity, or a
|
|
4
|
+
prev close) and either return silently or raise a domain exception. No
|
|
5
|
+
I/O, no state, no infrastructure dependencies.
|
|
6
|
+
|
|
7
|
+
Three rules live here, one per axis the real exchange enforces:
|
|
8
|
+
|
|
9
|
+
1. **Tick size** — limit / stop prices must be a multiple of the
|
|
10
|
+
scrip's tick (₹0.05 is the NSE default for cash equity).
|
|
11
|
+
2. **Lot size** — orders must be a whole multiple of the lot. Cash
|
|
12
|
+
equities are mostly lot=1; F&O contracts use real lots.
|
|
13
|
+
3. **Daily price band** — orders that would fill outside ``prev_close ×
|
|
14
|
+
(1 ± band_pct)`` are rejected. NSE bands are 2/5/10/20% per scrip,
|
|
15
|
+
set by the exchange; this module just enforces whatever the broker
|
|
16
|
+
passes in.
|
|
17
|
+
|
|
18
|
+
Configuration knobs and per-symbol overrides live with the broker; this
|
|
19
|
+
module is intentionally stateless.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
26
|
+
|
|
27
|
+
from ..exceptions import (
|
|
28
|
+
LotSizeViolation,
|
|
29
|
+
PriceBandViolation,
|
|
30
|
+
TickSizeViolation,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class MicrostructureConfig:
|
|
36
|
+
"""Toggles for tick / lot / band enforcement.
|
|
37
|
+
|
|
38
|
+
All three default to ``True`` because rejecting them is what makes
|
|
39
|
+
fills land where a real broker would land them. Set the field to
|
|
40
|
+
``False`` if you have a backtest that pre-dates a band change and
|
|
41
|
+
you want to suppress the check.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
enforce_tick_size: bool = True
|
|
45
|
+
enforce_lot_size: bool = True
|
|
46
|
+
enforce_price_band: bool = True
|
|
47
|
+
|
|
48
|
+
# Default tick size / band when the symbol master has no override.
|
|
49
|
+
# NSE cash equity is ₹0.05 across nearly all scrips; band defaults
|
|
50
|
+
# to a permissive 20% so the legacy "anything fills" tests don't
|
|
51
|
+
# break.
|
|
52
|
+
default_tick_size: float = 0.05
|
|
53
|
+
default_lot_size: int = 1
|
|
54
|
+
default_band_pct: float = 0.20 # ±20%
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def round_to_tick(price: float, tick: float) -> float:
|
|
58
|
+
"""Round ``price`` to the nearest multiple of ``tick``.
|
|
59
|
+
|
|
60
|
+
Uses ``Decimal`` to avoid the binary-float traps that put 2940.05 at
|
|
61
|
+
2940.0499999999999. Returns ``0.0`` when ``tick`` is ``0`` or the
|
|
62
|
+
input is non-positive (callers should validate before calling).
|
|
63
|
+
"""
|
|
64
|
+
if tick <= 0 or price <= 0:
|
|
65
|
+
return 0.0
|
|
66
|
+
p = Decimal(str(price))
|
|
67
|
+
t = Decimal(str(tick))
|
|
68
|
+
n = (p / t).quantize(Decimal("1"), rounding=ROUND_HALF_UP)
|
|
69
|
+
return float(n * t)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def is_aligned_to_tick(price: float, tick: float, atol: float = 1e-6) -> bool:
|
|
73
|
+
"""True when ``price`` is within ``atol`` paise of a tick boundary."""
|
|
74
|
+
if tick <= 0:
|
|
75
|
+
return True # tick disabled
|
|
76
|
+
rounded = round_to_tick(price, tick)
|
|
77
|
+
return abs(price - rounded) <= atol
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def validate_tick(price: float | None, tick: float, label: str) -> None:
|
|
81
|
+
"""Raise :class:`TickSizeViolation` if a price isn't tick-aligned."""
|
|
82
|
+
if price is None or tick <= 0:
|
|
83
|
+
return
|
|
84
|
+
if not is_aligned_to_tick(price, tick):
|
|
85
|
+
raise TickSizeViolation(
|
|
86
|
+
f"{label} ₹{price:.6f} is not aligned to tick size ₹{tick:.4f}. "
|
|
87
|
+
f"Nearest valid: ₹{round_to_tick(price, tick):.4f}",
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def validate_lot(qty: float, lot: int) -> None:
|
|
92
|
+
"""Raise :class:`LotSizeViolation` if ``qty`` isn't a multiple of ``lot``."""
|
|
93
|
+
if lot <= 1:
|
|
94
|
+
return
|
|
95
|
+
# Reject fractional qty up front (we don't model MF units here).
|
|
96
|
+
if abs(qty - round(qty)) > 1e-9:
|
|
97
|
+
raise LotSizeViolation(
|
|
98
|
+
f"qty {qty} is fractional; lot size {lot} requires whole shares.",
|
|
99
|
+
)
|
|
100
|
+
rounded_qty = int(round(qty))
|
|
101
|
+
if rounded_qty % lot != 0:
|
|
102
|
+
nearest_down = (rounded_qty // lot) * lot
|
|
103
|
+
nearest_up = nearest_down + lot
|
|
104
|
+
raise LotSizeViolation(
|
|
105
|
+
f"qty {rounded_qty} is not a multiple of lot size {lot}. "
|
|
106
|
+
f"Use {nearest_down} or {nearest_up}.",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def validate_band(
|
|
111
|
+
price: float,
|
|
112
|
+
prev_close: float | None,
|
|
113
|
+
band_pct: float,
|
|
114
|
+
) -> None:
|
|
115
|
+
"""Raise :class:`PriceBandViolation` if ``price`` is outside the band.
|
|
116
|
+
|
|
117
|
+
``prev_close=None`` skips the check (e.g. first-day listing or the
|
|
118
|
+
simulator hasn't seen a close yet).
|
|
119
|
+
"""
|
|
120
|
+
if prev_close is None or prev_close <= 0 or band_pct <= 0:
|
|
121
|
+
return
|
|
122
|
+
upper = prev_close * (1.0 + band_pct)
|
|
123
|
+
lower = prev_close * (1.0 - band_pct)
|
|
124
|
+
if price > upper or price < lower:
|
|
125
|
+
raise PriceBandViolation(
|
|
126
|
+
f"Price ₹{price:.4f} is outside the daily band "
|
|
127
|
+
f"[₹{lower:.4f}, ₹{upper:.4f}] (prev close ₹{prev_close:.4f}, "
|
|
128
|
+
f"band ±{band_pct * 100:.1f}%).",
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
__all__ = [
|
|
133
|
+
"MicrostructureConfig",
|
|
134
|
+
"round_to_tick",
|
|
135
|
+
"is_aligned_to_tick",
|
|
136
|
+
"validate_tick",
|
|
137
|
+
"validate_lot",
|
|
138
|
+
"validate_band",
|
|
139
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.infrastructure.events`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.events is deprecated; "
|
|
14
|
+
"import from papertrade_india.infrastructure.events instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.infrastructure.events as _src # noqa: E402
|
|
20
|
+
from papertrade_india.infrastructure.events import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Deprecated re-export shim — module moved to :mod:`papertrade_india.domain.exceptions`.
|
|
2
|
+
|
|
3
|
+
Importing from here still works during the deprecation window but emits
|
|
4
|
+
a :class:`DeprecationWarning`. Update imports to the new path; this
|
|
5
|
+
shim will be removed in v0.3.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import warnings as _warnings
|
|
11
|
+
|
|
12
|
+
_warnings.warn(
|
|
13
|
+
"papertrade_india.exceptions is deprecated; "
|
|
14
|
+
"import from papertrade_india.domain.exceptions instead.",
|
|
15
|
+
DeprecationWarning,
|
|
16
|
+
stacklevel=2,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
import papertrade_india.domain.exceptions as _src # noqa: E402
|
|
20
|
+
from papertrade_india.domain.exceptions import * # noqa: E402, F401, F403
|
|
21
|
+
|
|
22
|
+
# Re-export every attribute defined on the new module — including
|
|
23
|
+
# underscore-prefixed names — so callers that imported private symbols
|
|
24
|
+
# during the refactor window keep working. Dunders are skipped.
|
|
25
|
+
globals().update(
|
|
26
|
+
{name: getattr(_src, name) for name in dir(_src) if not name.startswith("__")}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
del _src, _warnings
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""Synthetic L2 order-book simulator.
|
|
2
|
+
|
|
3
|
+
A parametric L2 book derived from the provider's
|
|
4
|
+
``MarketQuote.bid``/``ask``/``volume``. Market orders walk the book
|
|
5
|
+
(price impact = volume-weighted average), and limit orders get a queue
|
|
6
|
+
position so they don't fill against ghost liquidity.
|
|
7
|
+
|
|
8
|
+
Why parametric (vs. a real LOB simulator)?
|
|
9
|
+
------------------------------------------
|
|
10
|
+
A real LOB needs every market order, cancel, and replace from every
|
|
11
|
+
participant in the day's tape — terabytes of data per day. The
|
|
12
|
+
parametric book here gets you 80% of the realism with 0% of the data
|
|
13
|
+
infrastructure: you tell the simulator "depth at the touch is roughly
|
|
14
|
+
0.5% of ADV" and it builds a realistic-shape book on the fly. Tune
|
|
15
|
+
``OrderBookConfig.depth_pct_of_adv`` and ``shape_decay`` to match the
|
|
16
|
+
liquidity profile of the names you trade.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
import math
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
|
|
25
|
+
from ..domain.models import OrderSide
|
|
26
|
+
from ..domain.rules.tick_lot_band import round_to_tick
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class OrderBookConfig:
|
|
33
|
+
"""Knobs for the parametric L2 book.
|
|
34
|
+
|
|
35
|
+
The book has ``levels`` price levels on each side. The size at the
|
|
36
|
+
top of book is ``adv * depth_pct_of_adv``; sizes at deeper levels
|
|
37
|
+
decay geometrically by ``shape_decay`` (0.6 = each next level holds
|
|
38
|
+
60% of the previous). Spreads come from the provider's bid/ask when
|
|
39
|
+
available; with no real bid/ask the broker skips book impact and
|
|
40
|
+
defers to the slippage model so we don't double-charge.
|
|
41
|
+
|
|
42
|
+
Defaults are tuned for liquid Indian large-caps (RELIANCE, TCS,
|
|
43
|
+
HDFCBANK). For a small-cap, drop ``depth_pct_of_adv`` to ~0.0005 and
|
|
44
|
+
raise ``default_spread_bps`` to ~25.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
enabled: bool = True # default ON for active development
|
|
48
|
+
levels: int = 10
|
|
49
|
+
depth_pct_of_adv: float = 0.005 # 0.5% of ADV at the touch
|
|
50
|
+
shape_decay: float = 0.6 # geometric decay per level
|
|
51
|
+
default_spread_bps: float = 5.0 # fallback when bid/ask unknown
|
|
52
|
+
default_adv: float = 100_000.0 # fallback ADV for unknown symbols
|
|
53
|
+
# Almgren impact coefficient: extra slippage on a market order is
|
|
54
|
+
# ``coeff * (qty / adv) ** exponent`` (in bps). 50 bps for 100% of
|
|
55
|
+
# ADV is a reasonable starting point for Indian large-caps.
|
|
56
|
+
almgren_coeff_bps: float = 50.0
|
|
57
|
+
almgren_exponent: float = 0.5 # square-root impact
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class BookLevel:
|
|
62
|
+
"""One side of one level of the synthetic L2 book."""
|
|
63
|
+
|
|
64
|
+
price: float
|
|
65
|
+
size: int
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class OrderBook:
|
|
70
|
+
"""A point-in-time snapshot of the synthetic book."""
|
|
71
|
+
|
|
72
|
+
symbol: str
|
|
73
|
+
bids: list[BookLevel] # descending price (best bid first)
|
|
74
|
+
asks: list[BookLevel] # ascending price (best ask first)
|
|
75
|
+
last: float
|
|
76
|
+
tick_size: float
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def best_bid(self) -> float | None:
|
|
80
|
+
return self.bids[0].price if self.bids else None
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def best_ask(self) -> float | None:
|
|
84
|
+
return self.asks[0].price if self.asks else None
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def mid(self) -> float | None:
|
|
88
|
+
if self.best_bid is None or self.best_ask is None:
|
|
89
|
+
return None
|
|
90
|
+
return (self.best_bid + self.best_ask) / 2.0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class FillSlice:
|
|
95
|
+
"""A piece of a market-order fill against one book level."""
|
|
96
|
+
|
|
97
|
+
price: float
|
|
98
|
+
qty: int
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class MarketFill:
|
|
103
|
+
"""The aggregated fill produced by walking the book."""
|
|
104
|
+
|
|
105
|
+
avg_price: float
|
|
106
|
+
filled_qty: int
|
|
107
|
+
slices: list[FillSlice]
|
|
108
|
+
impact_bps: float # extra cost vs. mid, in bps
|
|
109
|
+
fully_filled: bool # False when the book ran out of size
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class OrderBookSimulator:
|
|
113
|
+
"""Parametric L2 book + queue position bookkeeping.
|
|
114
|
+
|
|
115
|
+
Stateful only as far as queue position is concerned: each pending
|
|
116
|
+
limit order reserves a "shares-ahead" slot at its price level. As
|
|
117
|
+
the simulator observes trades at that level, ahead-of-me size
|
|
118
|
+
decreases until the order fills.
|
|
119
|
+
|
|
120
|
+
For market orders, the simulator walks the synthesized book to
|
|
121
|
+
produce a realistic VWAP fill plus an impact cost in bps.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, config: OrderBookConfig | None = None) -> None:
|
|
125
|
+
self.config = config or OrderBookConfig()
|
|
126
|
+
# Per-symbol queue tracking: {(symbol, side, price): shares_ahead}.
|
|
127
|
+
self._queue: dict[tuple[str, str, float], int] = {}
|
|
128
|
+
|
|
129
|
+
# ── Book synthesis ────────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
def synthesize(
|
|
132
|
+
self,
|
|
133
|
+
symbol: str,
|
|
134
|
+
last: float,
|
|
135
|
+
bid: float | None,
|
|
136
|
+
ask: float | None,
|
|
137
|
+
adv: float | None,
|
|
138
|
+
tick_size: float,
|
|
139
|
+
) -> OrderBook:
|
|
140
|
+
"""Build a synthetic L2 book from the provider's spot data.
|
|
141
|
+
|
|
142
|
+
Parameters
|
|
143
|
+
----------
|
|
144
|
+
symbol:
|
|
145
|
+
The scrip.
|
|
146
|
+
last:
|
|
147
|
+
Last traded price (the anchor when bid/ask unknown).
|
|
148
|
+
bid, ask:
|
|
149
|
+
Real top-of-book quotes when the provider supplies them.
|
|
150
|
+
``None`` falls back to ``last × (1 ± spread/2)``.
|
|
151
|
+
adv:
|
|
152
|
+
Average daily volume in shares. Drives sizing across levels.
|
|
153
|
+
``None`` uses :attr:`OrderBookConfig.default_adv`.
|
|
154
|
+
tick_size:
|
|
155
|
+
Per-symbol tick. Levels are spaced one tick apart, like NSE.
|
|
156
|
+
"""
|
|
157
|
+
cfg = self.config
|
|
158
|
+
adv_val = adv if adv and adv > 0 else cfg.default_adv
|
|
159
|
+
|
|
160
|
+
if bid is None or ask is None or bid >= ask or bid <= 0:
|
|
161
|
+
half_spread = last * (cfg.default_spread_bps / 10000.0) / 2.0
|
|
162
|
+
bid = last - max(half_spread, tick_size / 2.0)
|
|
163
|
+
ask = last + max(half_spread, tick_size / 2.0)
|
|
164
|
+
# Snap each side to the tick grid so levels are realistic.
|
|
165
|
+
bid = round_to_tick(bid, tick_size) or bid
|
|
166
|
+
ask = round_to_tick(ask, tick_size) or ask
|
|
167
|
+
|
|
168
|
+
top_size = max(1, int(round(adv_val * cfg.depth_pct_of_adv)))
|
|
169
|
+
bids: list[BookLevel] = []
|
|
170
|
+
asks: list[BookLevel] = []
|
|
171
|
+
for i in range(cfg.levels):
|
|
172
|
+
size = max(1, int(round(top_size * (cfg.shape_decay ** i))))
|
|
173
|
+
bid_price = bid - i * tick_size
|
|
174
|
+
if bid_price > 0: # never synthesize a non-positive bid (penny stocks)
|
|
175
|
+
bids.append(BookLevel(price=bid_price, size=size))
|
|
176
|
+
asks.append(BookLevel(price=ask + i * tick_size, size=size))
|
|
177
|
+
|
|
178
|
+
return OrderBook(
|
|
179
|
+
symbol=symbol,
|
|
180
|
+
bids=bids,
|
|
181
|
+
asks=asks,
|
|
182
|
+
last=last,
|
|
183
|
+
tick_size=tick_size,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def book_from_levels(
|
|
187
|
+
self,
|
|
188
|
+
symbol: str,
|
|
189
|
+
last: float,
|
|
190
|
+
bids: list[tuple[float, int]] | tuple[tuple[float, int], ...],
|
|
191
|
+
asks: list[tuple[float, int]] | tuple[tuple[float, int], ...],
|
|
192
|
+
tick_size: float,
|
|
193
|
+
) -> OrderBook:
|
|
194
|
+
"""Build a book from a provider's REAL depth ladder.
|
|
195
|
+
|
|
196
|
+
Uses the actual ``(price, size)`` levels the provider gave us
|
|
197
|
+
(Upstox delivers 5). If an order can consume more than the real
|
|
198
|
+
depth, we extend past the deepest real level with a synthetic
|
|
199
|
+
geometric tail (seeded from the last real size, spaced one tick
|
|
200
|
+
apart) so large orders still fill with a modeled cost instead of
|
|
201
|
+
hitting a wall. Everything up to the real depth is ground truth.
|
|
202
|
+
"""
|
|
203
|
+
cfg = self.config
|
|
204
|
+
|
|
205
|
+
def build(levels: list[tuple[float, int]], descending: bool) -> list[BookLevel]:
|
|
206
|
+
out = [BookLevel(price=p, size=s) for p, s in levels if p and p > 0]
|
|
207
|
+
if not out:
|
|
208
|
+
return out
|
|
209
|
+
# Extend with a synthetic tail up to cfg.levels.
|
|
210
|
+
step = -tick_size if descending else tick_size
|
|
211
|
+
last_price = out[-1].price
|
|
212
|
+
last_size = max(1, out[-1].size)
|
|
213
|
+
for i in range(1, cfg.levels - len(out) + 1):
|
|
214
|
+
price = last_price + step * i
|
|
215
|
+
if price <= 0:
|
|
216
|
+
break
|
|
217
|
+
size = max(1, int(round(last_size * (cfg.shape_decay ** i))))
|
|
218
|
+
out.append(BookLevel(price=price, size=size))
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
return OrderBook(
|
|
222
|
+
symbol=symbol,
|
|
223
|
+
bids=build(list(bids), descending=True),
|
|
224
|
+
asks=build(list(asks), descending=False),
|
|
225
|
+
last=last,
|
|
226
|
+
tick_size=tick_size,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def walk_book(
|
|
230
|
+
self,
|
|
231
|
+
book: OrderBook,
|
|
232
|
+
side: OrderSide,
|
|
233
|
+
qty: int,
|
|
234
|
+
) -> MarketFill:
|
|
235
|
+
"""Consume size from the appropriate side until ``qty`` is filled.
|
|
236
|
+
|
|
237
|
+
Returns a :class:`MarketFill`. If the book runs dry,
|
|
238
|
+
``fully_filled`` is False and ``filled_qty < qty``; the caller
|
|
239
|
+
decides whether to retry or partial-fill the order.
|
|
240
|
+
|
|
241
|
+
Impact cost is reported in bps off the mid (positive cost on
|
|
242
|
+
both sides — buys pay above mid, sells receive below).
|
|
243
|
+
"""
|
|
244
|
+
levels = book.asks if side == OrderSide.BUY else book.bids
|
|
245
|
+
slices: list[FillSlice] = []
|
|
246
|
+
remaining = int(qty)
|
|
247
|
+
spent = 0.0
|
|
248
|
+
filled = 0
|
|
249
|
+
|
|
250
|
+
for level in levels:
|
|
251
|
+
if remaining <= 0:
|
|
252
|
+
break
|
|
253
|
+
take = min(remaining, level.size)
|
|
254
|
+
slices.append(FillSlice(price=level.price, qty=take))
|
|
255
|
+
spent += level.price * take
|
|
256
|
+
filled += take
|
|
257
|
+
remaining -= take
|
|
258
|
+
|
|
259
|
+
# Almgren add-on for orders that try to clear more than ADV.
|
|
260
|
+
# Caller-supplied ADV would let us scale, but the book already
|
|
261
|
+
# reflects ADV; we surface the impact rather than charging again.
|
|
262
|
+
if filled == 0:
|
|
263
|
+
return MarketFill(
|
|
264
|
+
avg_price=0.0,
|
|
265
|
+
filled_qty=0,
|
|
266
|
+
slices=[],
|
|
267
|
+
impact_bps=0.0,
|
|
268
|
+
fully_filled=False,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
avg = spent / filled
|
|
272
|
+
mid = book.mid or book.last
|
|
273
|
+
if side == OrderSide.BUY:
|
|
274
|
+
impact_bps = (avg - mid) / mid * 10000.0
|
|
275
|
+
else:
|
|
276
|
+
impact_bps = (mid - avg) / mid * 10000.0
|
|
277
|
+
return MarketFill(
|
|
278
|
+
avg_price=avg,
|
|
279
|
+
filled_qty=filled,
|
|
280
|
+
slices=slices,
|
|
281
|
+
impact_bps=max(0.0, impact_bps),
|
|
282
|
+
fully_filled=remaining <= 0,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
def almgren_impact_bps(
|
|
286
|
+
self,
|
|
287
|
+
qty: int,
|
|
288
|
+
adv: float | None,
|
|
289
|
+
) -> float:
|
|
290
|
+
"""Stand-alone Almgren impact estimate in bps, for sizing tools.
|
|
291
|
+
|
|
292
|
+
``cost = coeff * (qty / adv) ** exponent`` (bps). Returns 0 when
|
|
293
|
+
``adv`` is ``None`` or non-positive.
|
|
294
|
+
"""
|
|
295
|
+
if not adv or adv <= 0 or qty <= 0:
|
|
296
|
+
return 0.0
|
|
297
|
+
ratio = qty / adv
|
|
298
|
+
return self.config.almgren_coeff_bps * (ratio ** self.config.almgren_exponent)
|
|
299
|
+
|
|
300
|
+
# ── Queue position bookkeeping ────────────────────────────────────
|
|
301
|
+
|
|
302
|
+
def join_queue(
|
|
303
|
+
self,
|
|
304
|
+
symbol: str,
|
|
305
|
+
side: OrderSide,
|
|
306
|
+
price: float,
|
|
307
|
+
book: OrderBook,
|
|
308
|
+
) -> int:
|
|
309
|
+
"""Record that a new limit order is joining the back of the queue
|
|
310
|
+
at ``(symbol, side, price)``. Returns its initial shares-ahead.
|
|
311
|
+
|
|
312
|
+
We use the synthesized depth at that level as the ahead-of-me
|
|
313
|
+
seed. Subsequent orders at the same price level stack behind us
|
|
314
|
+
(their ahead = ours + our_qty).
|
|
315
|
+
"""
|
|
316
|
+
levels = book.bids if side == OrderSide.BUY else book.asks
|
|
317
|
+
ahead = 0
|
|
318
|
+
for level in levels:
|
|
319
|
+
if math.isclose(level.price, price, rel_tol=0.0, abs_tol=1e-6):
|
|
320
|
+
ahead = level.size
|
|
321
|
+
break
|
|
322
|
+
key = (symbol, side.value, round_to_tick(price, book.tick_size) or price)
|
|
323
|
+
# Stack behind any existing orders we've already queued at this level.
|
|
324
|
+
existing = self._queue.get(key, 0)
|
|
325
|
+
total = ahead + existing
|
|
326
|
+
self._queue[key] = total
|
|
327
|
+
return total
|
|
328
|
+
|
|
329
|
+
def observe_trade(
|
|
330
|
+
self,
|
|
331
|
+
symbol: str,
|
|
332
|
+
side: OrderSide,
|
|
333
|
+
price: float,
|
|
334
|
+
qty: int,
|
|
335
|
+
) -> None:
|
|
336
|
+
"""Tell the simulator that ``qty`` shares traded at ``price``.
|
|
337
|
+
|
|
338
|
+
Decreases the "ahead of me" counter for any of our queued
|
|
339
|
+
limits sitting at that price level. Trade is on the *opposite*
|
|
340
|
+
side from the resting limit, so a buyer hitting the ask reduces
|
|
341
|
+
the ask queue.
|
|
342
|
+
"""
|
|
343
|
+
# A buy print eats ask-side queue; a sell print eats bid-side.
|
|
344
|
+
resting_side = "sell" if side == OrderSide.BUY else "buy"
|
|
345
|
+
# Walk all keys at this price for the resting side.
|
|
346
|
+
for key in list(self._queue.keys()):
|
|
347
|
+
sym, ks, p = key
|
|
348
|
+
if sym != symbol or ks != resting_side:
|
|
349
|
+
continue
|
|
350
|
+
if not math.isclose(p, price, rel_tol=0.0, abs_tol=1e-4):
|
|
351
|
+
continue
|
|
352
|
+
self._queue[key] = max(0, self._queue[key] - qty)
|
|
353
|
+
|
|
354
|
+
def queue_position(
|
|
355
|
+
self,
|
|
356
|
+
symbol: str,
|
|
357
|
+
side: OrderSide,
|
|
358
|
+
price: float,
|
|
359
|
+
tick_size: float,
|
|
360
|
+
) -> int | None:
|
|
361
|
+
"""Current shares-ahead count for a limit at ``(symbol, side, price)``.
|
|
362
|
+
|
|
363
|
+
Returns ``None`` if we never recorded a join at that level.
|
|
364
|
+
"""
|
|
365
|
+
key = (symbol, side.value, round_to_tick(price, tick_size) or price)
|
|
366
|
+
return self._queue.get(key)
|
|
367
|
+
|
|
368
|
+
def clear_queue(self, symbol: str | None = None) -> None:
|
|
369
|
+
"""Drop queue state. Optionally narrow to one symbol."""
|
|
370
|
+
if symbol is None:
|
|
371
|
+
self._queue.clear()
|
|
372
|
+
return
|
|
373
|
+
for key in list(self._queue):
|
|
374
|
+
if key[0] == symbol:
|
|
375
|
+
del self._queue[key]
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
__all__ = [
|
|
379
|
+
"OrderBookConfig",
|
|
380
|
+
"BookLevel",
|
|
381
|
+
"OrderBook",
|
|
382
|
+
"FillSlice",
|
|
383
|
+
"MarketFill",
|
|
384
|
+
"OrderBookSimulator",
|
|
385
|
+
]
|