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,210 @@
|
|
|
1
|
+
"""Limit order queueing and fill execution.
|
|
2
|
+
|
|
3
|
+
Two entry points:
|
|
4
|
+
|
|
5
|
+
- :func:`queue` — persist a new PENDING limit order and optionally
|
|
6
|
+
prime its book-queue position.
|
|
7
|
+
- :func:`fill` — called by :class:`LimitOrderWatcher` when the market
|
|
8
|
+
crosses the limit price; handles partial fills, bracket OCO, and
|
|
9
|
+
settlement.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import uuid
|
|
16
|
+
from typing import TYPE_CHECKING
|
|
17
|
+
|
|
18
|
+
from ..domain.exceptions import OrderNoLongerPending
|
|
19
|
+
from ..domain.models import Order, OrderSide, OrderStatus, OrderType, ProductType
|
|
20
|
+
from ..execution.slippage import apply_slippage
|
|
21
|
+
from . import state as _state
|
|
22
|
+
from .book_helpers import maybe_join_book_queue
|
|
23
|
+
from .market import _maybe_settle_trade
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
26
|
+
from .._context import BrokerContext
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def queue(
|
|
32
|
+
ctx: BrokerContext,
|
|
33
|
+
symbol: str,
|
|
34
|
+
qty: float,
|
|
35
|
+
side: OrderSide,
|
|
36
|
+
limit_price: float,
|
|
37
|
+
time_in_force: str,
|
|
38
|
+
product_type: ProductType = ProductType.DELIVERY,
|
|
39
|
+
) -> Order:
|
|
40
|
+
"""Persist a new PENDING limit order."""
|
|
41
|
+
order_id = uuid.uuid4().hex[:12]
|
|
42
|
+
now = ctx.now_iso()
|
|
43
|
+
|
|
44
|
+
with ctx.persistence.transaction() as conn:
|
|
45
|
+
_state.record(
|
|
46
|
+
ctx, conn,
|
|
47
|
+
order_id=order_id, symbol=symbol, side=side, qty=qty,
|
|
48
|
+
order_type=OrderType.LIMIT, status=OrderStatus.PENDING,
|
|
49
|
+
filled_qty=0.0, filled_avg_price=None, limit_price=limit_price,
|
|
50
|
+
fees_paid=0.0, realized_pl=0.0, time_in_force=time_in_force,
|
|
51
|
+
created_at=now, filled_at=None, product_type=product_type,
|
|
52
|
+
)
|
|
53
|
+
ctx.emit(conn, event_type="order_submitted", order_id=order_id,
|
|
54
|
+
payload={"symbol": symbol, "side": side.value, "qty": qty,
|
|
55
|
+
"order_type": OrderType.LIMIT.value,
|
|
56
|
+
"limit_price": limit_price,
|
|
57
|
+
"product_type": product_type.value})
|
|
58
|
+
|
|
59
|
+
if ctx.book_sim.config.enabled:
|
|
60
|
+
maybe_join_book_queue(ctx, symbol, side, limit_price)
|
|
61
|
+
|
|
62
|
+
ctx.drain_pending_events()
|
|
63
|
+
logger.info("QUEUE LIMIT %s %s %s @ ₹%.2f",
|
|
64
|
+
side.value.upper(), qty, symbol, limit_price)
|
|
65
|
+
|
|
66
|
+
with ctx.persistence.read() as conn:
|
|
67
|
+
row = conn.execute(
|
|
68
|
+
"SELECT * FROM orders WHERE id = ? AND account_id = ?",
|
|
69
|
+
(order_id, ctx.account_id),
|
|
70
|
+
).fetchone()
|
|
71
|
+
assert row is not None
|
|
72
|
+
return _state.row_to_order(row)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def fill(
|
|
76
|
+
ctx: BrokerContext,
|
|
77
|
+
order: Order,
|
|
78
|
+
fill_price: float,
|
|
79
|
+
fill_qty: float | None = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
"""Called by :class:`LimitOrderWatcher` when market crosses limit price.
|
|
82
|
+
|
|
83
|
+
Race-safety: claims the order first (UPDATE WHERE status IN
|
|
84
|
+
pending/partially_filled); raises :class:`OrderNoLongerPending` on
|
|
85
|
+
a lost race so the watcher can skip and move on.
|
|
86
|
+
|
|
87
|
+
Slippage on limit fills is opt-in (``SlippageConfig.apply_to_limits``).
|
|
88
|
+
Default behavior fills at the supplied ``fill_price``.
|
|
89
|
+
|
|
90
|
+
Partial fills: ``fill_qty`` (if provided and < remaining qty) marks
|
|
91
|
+
the order as ``PARTIALLY_FILLED`` and updates ``filled_qty`` rather
|
|
92
|
+
than transitioning to ``FILLED``.
|
|
93
|
+
"""
|
|
94
|
+
adjusted_price = apply_slippage(
|
|
95
|
+
ctx.slippage_config,
|
|
96
|
+
side=order.side,
|
|
97
|
+
order_type=OrderType.LIMIT,
|
|
98
|
+
last_price=fill_price,
|
|
99
|
+
limit_price=order.limit_price,
|
|
100
|
+
symbol=order.symbol,
|
|
101
|
+
)
|
|
102
|
+
now = ctx.now_iso()
|
|
103
|
+
fee_engine = ctx.fee_engine_for(now)
|
|
104
|
+
|
|
105
|
+
remaining = order.qty - order.filled_qty
|
|
106
|
+
if fill_qty is None or fill_qty >= remaining:
|
|
107
|
+
slice_qty = remaining
|
|
108
|
+
terminal = True
|
|
109
|
+
else:
|
|
110
|
+
slice_qty = fill_qty
|
|
111
|
+
terminal = False
|
|
112
|
+
|
|
113
|
+
if slice_qty <= 0:
|
|
114
|
+
return
|
|
115
|
+
|
|
116
|
+
fees = fee_engine.calculate(order.side, slice_qty, adjusted_price,
|
|
117
|
+
order.exchange)
|
|
118
|
+
|
|
119
|
+
new_filled_qty = order.filled_qty + slice_qty
|
|
120
|
+
prior_total = order.filled_qty * (order.filled_avg_price or 0.0)
|
|
121
|
+
new_avg_fill = (prior_total + slice_qty * adjusted_price) / new_filled_qty
|
|
122
|
+
new_status = OrderStatus.FILLED if terminal else OrderStatus.PARTIALLY_FILLED
|
|
123
|
+
cumulative_fees = order.fees_paid + fees.total
|
|
124
|
+
|
|
125
|
+
with ctx.persistence.transaction() as conn:
|
|
126
|
+
cur = conn.execute(
|
|
127
|
+
"UPDATE orders SET status = ?, filled_qty = ?, "
|
|
128
|
+
"filled_avg_price = ?, fees_paid = ?, realized_pl = ?, "
|
|
129
|
+
"filled_at = ? "
|
|
130
|
+
"WHERE id = ? AND account_id = ? AND status IN (?, ?)",
|
|
131
|
+
(
|
|
132
|
+
new_status.value, new_filled_qty, new_avg_fill,
|
|
133
|
+
cumulative_fees, 0.0,
|
|
134
|
+
now if terminal else None,
|
|
135
|
+
order.id, ctx.account_id,
|
|
136
|
+
OrderStatus.PENDING.value, OrderStatus.PARTIALLY_FILLED.value,
|
|
137
|
+
),
|
|
138
|
+
)
|
|
139
|
+
if cur.rowcount == 0:
|
|
140
|
+
raise OrderNoLongerPending(
|
|
141
|
+
f"Order {order.id} is no longer pending; skip"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
position_existed_before = (
|
|
145
|
+
_state.symbol_position_qty(ctx, conn, order.symbol) > 0
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
if order.side == OrderSide.BUY:
|
|
149
|
+
_state.apply_buy(ctx, conn, order.symbol, slice_qty, adjusted_price,
|
|
150
|
+
fees.total, now, order_id=order.id)
|
|
151
|
+
slice_realized_pl = 0.0
|
|
152
|
+
else:
|
|
153
|
+
slice_realized_pl = _state.apply_sell(
|
|
154
|
+
ctx, conn, order.symbol, slice_qty, adjusted_price,
|
|
155
|
+
fees.total, now, order_id=order.id,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
cumulative_realized_pl = order.realized_pl + slice_realized_pl
|
|
159
|
+
if cumulative_realized_pl != 0.0:
|
|
160
|
+
conn.execute(
|
|
161
|
+
"UPDATE orders SET realized_pl = ? WHERE id = ? AND account_id = ?",
|
|
162
|
+
(cumulative_realized_pl, order.id, ctx.account_id),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
_state.record_trade(
|
|
166
|
+
ctx, conn, order_id=order.id, symbol=order.symbol,
|
|
167
|
+
side=order.side, qty=slice_qty, price=adjusted_price,
|
|
168
|
+
fees=fees.total, realized_pl=slice_realized_pl, executed_at=now,
|
|
169
|
+
)
|
|
170
|
+
_maybe_settle_trade(
|
|
171
|
+
ctx, conn, side=order.side, symbol=order.symbol, qty=slice_qty,
|
|
172
|
+
cash_credit=slice_qty * adjusted_price - fees.total,
|
|
173
|
+
product_type=order.product_type, now=now,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
position_qty_after = _state.symbol_position_qty(ctx, conn, order.symbol)
|
|
177
|
+
_state.emit_position_events(ctx, conn, order,
|
|
178
|
+
position_existed_before, position_qty_after)
|
|
179
|
+
|
|
180
|
+
if order.parent_order_id is not None:
|
|
181
|
+
_state.rebalance_bracket_sibling_qty(ctx, conn, order, new_filled_qty)
|
|
182
|
+
if terminal:
|
|
183
|
+
_state.cancel_bracket_siblings(ctx, conn, order)
|
|
184
|
+
|
|
185
|
+
if terminal:
|
|
186
|
+
ctx.emit(conn, event_type="order_filled", order_id=order.id,
|
|
187
|
+
payload={"symbol": order.symbol, "side": order.side.value,
|
|
188
|
+
"qty": new_filled_qty, "fill_price": adjusted_price,
|
|
189
|
+
"fees_paid": cumulative_fees})
|
|
190
|
+
else:
|
|
191
|
+
ctx.emit(conn, event_type="order_partially_filled", order_id=order.id,
|
|
192
|
+
payload={"symbol": order.symbol, "side": order.side.value,
|
|
193
|
+
"slice_qty": slice_qty, "filled_qty": new_filled_qty,
|
|
194
|
+
"remaining_qty": order.qty - new_filled_qty,
|
|
195
|
+
"slice_price": adjusted_price})
|
|
196
|
+
|
|
197
|
+
ctx.drain_pending_events()
|
|
198
|
+
|
|
199
|
+
if terminal:
|
|
200
|
+
logger.info("LIMIT FILL %s %s %s @ ₹%.2f (limit was ₹%.2f)",
|
|
201
|
+
order.side.value.upper(), order.qty, order.symbol,
|
|
202
|
+
adjusted_price, order.limit_price)
|
|
203
|
+
else:
|
|
204
|
+
logger.info("LIMIT PARTIAL %s %s/%s %s @ ₹%.2f (limit was ₹%.2f)",
|
|
205
|
+
order.side.value.upper(),
|
|
206
|
+
slice_qty, order.qty - new_filled_qty + slice_qty,
|
|
207
|
+
order.symbol, adjusted_price, order.limit_price)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
__all__ = ["queue", "fill"]
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""Market order execution.
|
|
2
|
+
|
|
3
|
+
A market order fills immediately at the slippage-adjusted (and
|
|
4
|
+
optionally book-impact-adjusted) price. This module owns the full
|
|
5
|
+
execution path: quote fetch → price adjustment → fee calculation →
|
|
6
|
+
position update → ledger → settlement → events.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from ..domain.models import Order, OrderSide, OrderStatus, OrderType, ProductType
|
|
16
|
+
from ..execution.slippage import apply_slippage
|
|
17
|
+
from . import state as _state
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
20
|
+
from .._context import BrokerContext
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def execute(
|
|
26
|
+
ctx: BrokerContext,
|
|
27
|
+
symbol: str,
|
|
28
|
+
qty: float,
|
|
29
|
+
side: OrderSide,
|
|
30
|
+
time_in_force: str,
|
|
31
|
+
product_type: ProductType = ProductType.DELIVERY,
|
|
32
|
+
) -> Order:
|
|
33
|
+
"""Fill immediately at slippage-adjusted market price."""
|
|
34
|
+
from .book_helpers import maybe_apply_book_impact # noqa: PLC0415
|
|
35
|
+
|
|
36
|
+
quote = _get_fill_quote(ctx, symbol)
|
|
37
|
+
last_price = quote.price
|
|
38
|
+
price = apply_slippage(
|
|
39
|
+
ctx.slippage_config,
|
|
40
|
+
side=side,
|
|
41
|
+
order_type=OrderType.MARKET,
|
|
42
|
+
last_price=last_price,
|
|
43
|
+
symbol=symbol,
|
|
44
|
+
)
|
|
45
|
+
if ctx.book_sim.config.enabled:
|
|
46
|
+
price = maybe_apply_book_impact(ctx, symbol=symbol, qty=qty,
|
|
47
|
+
side=side, last_price=last_price)
|
|
48
|
+
|
|
49
|
+
order_id = uuid.uuid4().hex[:12]
|
|
50
|
+
now = ctx.now_iso()
|
|
51
|
+
fee_engine = ctx.fee_engine_for(now)
|
|
52
|
+
fees = fee_engine.calculate(side, qty, price, ctx.default_exchange)
|
|
53
|
+
|
|
54
|
+
with ctx.persistence.transaction() as conn:
|
|
55
|
+
position_existed_before = _state.symbol_position_qty(ctx, conn, symbol) > 0
|
|
56
|
+
if side == OrderSide.BUY:
|
|
57
|
+
_state.apply_buy(ctx, conn, symbol, qty, price, fees.total, now,
|
|
58
|
+
order_id=order_id)
|
|
59
|
+
realized_pl = 0.0
|
|
60
|
+
else:
|
|
61
|
+
realized_pl = _state.apply_sell(ctx, conn, symbol, qty, price,
|
|
62
|
+
fees.total, now, order_id=order_id)
|
|
63
|
+
|
|
64
|
+
_state.record(
|
|
65
|
+
ctx, conn,
|
|
66
|
+
order_id=order_id, symbol=symbol, side=side, qty=qty,
|
|
67
|
+
order_type=OrderType.MARKET, status=OrderStatus.FILLED,
|
|
68
|
+
filled_qty=qty, filled_avg_price=price, limit_price=None,
|
|
69
|
+
fees_paid=fees.total, realized_pl=realized_pl,
|
|
70
|
+
time_in_force=time_in_force, created_at=now, filled_at=now,
|
|
71
|
+
product_type=product_type,
|
|
72
|
+
)
|
|
73
|
+
_state.record_trade(
|
|
74
|
+
ctx, conn, order_id=order_id, symbol=symbol, side=side,
|
|
75
|
+
qty=qty, price=price, fees=fees.total,
|
|
76
|
+
realized_pl=realized_pl, executed_at=now,
|
|
77
|
+
)
|
|
78
|
+
_maybe_settle_trade(ctx, conn, side=side, symbol=symbol, qty=qty,
|
|
79
|
+
cash_credit=qty * price - fees.total,
|
|
80
|
+
product_type=product_type, now=now)
|
|
81
|
+
|
|
82
|
+
ctx.emit(conn, event_type="order_submitted", order_id=order_id,
|
|
83
|
+
payload={"symbol": symbol, "side": side.value, "qty": qty,
|
|
84
|
+
"order_type": OrderType.MARKET.value})
|
|
85
|
+
ctx.emit(conn, event_type="order_filled", order_id=order_id,
|
|
86
|
+
payload={"symbol": symbol, "side": side.value, "qty": qty,
|
|
87
|
+
"fill_price": price, "fees_paid": fees.total})
|
|
88
|
+
|
|
89
|
+
qty_after = _state.symbol_position_qty(ctx, conn, symbol)
|
|
90
|
+
order_for_events = Order(
|
|
91
|
+
id=order_id, symbol=symbol, exchange=ctx.default_exchange,
|
|
92
|
+
side=side, qty=qty, order_type=OrderType.MARKET,
|
|
93
|
+
status=OrderStatus.FILLED, filled_qty=qty,
|
|
94
|
+
filled_avg_price=price, limit_price=None,
|
|
95
|
+
fees_paid=fees.total, realized_pl=realized_pl,
|
|
96
|
+
)
|
|
97
|
+
_state.emit_position_events(ctx, conn, order_for_events,
|
|
98
|
+
position_existed_before, qty_after)
|
|
99
|
+
|
|
100
|
+
ctx.drain_pending_events()
|
|
101
|
+
|
|
102
|
+
if side == OrderSide.SELL:
|
|
103
|
+
logger.info("FILL %s %s %s @ ₹%.2f (fees ₹%.2f, realized P&L ₹%.2f)",
|
|
104
|
+
side.value.upper(), qty, symbol, price, fees.total, realized_pl)
|
|
105
|
+
else:
|
|
106
|
+
logger.info("FILL %s %s %s @ ₹%.2f (fees ₹%.2f)",
|
|
107
|
+
side.value.upper(), qty, symbol, price, fees.total)
|
|
108
|
+
|
|
109
|
+
with ctx.persistence.read() as conn:
|
|
110
|
+
row = conn.execute(
|
|
111
|
+
"SELECT * FROM orders WHERE id = ? AND account_id = ?",
|
|
112
|
+
(order_id, ctx.account_id),
|
|
113
|
+
).fetchone()
|
|
114
|
+
assert row is not None, "order disappeared after commit"
|
|
115
|
+
return _state.row_to_order(row)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def fill_pending_market(ctx: BrokerContext, order_id: str) -> None:
|
|
119
|
+
"""Fill a PENDING market order (bracket parent or AMO) at current price.
|
|
120
|
+
|
|
121
|
+
Reuses the standard execution path so fees/ledger/events flow
|
|
122
|
+
through canonical code.
|
|
123
|
+
"""
|
|
124
|
+
from .book_helpers import maybe_apply_book_impact # noqa: PLC0415
|
|
125
|
+
|
|
126
|
+
with ctx.persistence.read() as conn:
|
|
127
|
+
row = conn.execute(
|
|
128
|
+
"SELECT * FROM orders WHERE id = ? AND account_id = ?",
|
|
129
|
+
(order_id, ctx.account_id),
|
|
130
|
+
).fetchone()
|
|
131
|
+
if row is None:
|
|
132
|
+
return
|
|
133
|
+
order = _state.row_to_order(row)
|
|
134
|
+
if order.status != OrderStatus.PENDING:
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
quote = _get_fill_quote(ctx, order.symbol)
|
|
138
|
+
last_price = quote.price
|
|
139
|
+
price = apply_slippage(
|
|
140
|
+
ctx.slippage_config,
|
|
141
|
+
side=order.side,
|
|
142
|
+
order_type=OrderType.MARKET,
|
|
143
|
+
last_price=last_price,
|
|
144
|
+
symbol=order.symbol,
|
|
145
|
+
)
|
|
146
|
+
if ctx.book_sim.config.enabled:
|
|
147
|
+
price = maybe_apply_book_impact(ctx, symbol=order.symbol,
|
|
148
|
+
qty=order.qty, side=order.side,
|
|
149
|
+
last_price=last_price)
|
|
150
|
+
|
|
151
|
+
now = ctx.now_iso()
|
|
152
|
+
fee_engine = ctx.fee_engine_for(now)
|
|
153
|
+
fees = fee_engine.calculate(order.side, order.qty, price, ctx.default_exchange)
|
|
154
|
+
|
|
155
|
+
with ctx.persistence.transaction() as conn:
|
|
156
|
+
cur = conn.execute(
|
|
157
|
+
"UPDATE orders SET status = ?, filled_qty = ?, "
|
|
158
|
+
"filled_avg_price = ?, fees_paid = ?, filled_at = ? "
|
|
159
|
+
"WHERE id = ? AND account_id = ? AND status = ?",
|
|
160
|
+
(
|
|
161
|
+
OrderStatus.FILLED.value, order.qty, price,
|
|
162
|
+
fees.total, now, order_id, ctx.account_id,
|
|
163
|
+
OrderStatus.PENDING.value,
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
if cur.rowcount == 0:
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
position_existed = _state.symbol_position_qty(ctx, conn, order.symbol) > 0
|
|
170
|
+
if order.side == OrderSide.BUY:
|
|
171
|
+
_state.apply_buy(ctx, conn, order.symbol, order.qty, price,
|
|
172
|
+
fees.total, now, order_id=order_id)
|
|
173
|
+
realized_pl = 0.0
|
|
174
|
+
else:
|
|
175
|
+
realized_pl = _state.apply_sell(ctx, conn, order.symbol, order.qty,
|
|
176
|
+
price, fees.total, now,
|
|
177
|
+
order_id=order_id)
|
|
178
|
+
if realized_pl != 0.0:
|
|
179
|
+
conn.execute(
|
|
180
|
+
"UPDATE orders SET realized_pl = ? WHERE id = ?",
|
|
181
|
+
(realized_pl, order_id),
|
|
182
|
+
)
|
|
183
|
+
_state.record_trade(
|
|
184
|
+
ctx, conn, order_id=order_id, symbol=order.symbol,
|
|
185
|
+
side=order.side, qty=order.qty, price=price,
|
|
186
|
+
fees=fees.total, realized_pl=realized_pl, executed_at=now,
|
|
187
|
+
)
|
|
188
|
+
_maybe_settle_trade(ctx, conn, side=order.side, symbol=order.symbol,
|
|
189
|
+
qty=order.qty,
|
|
190
|
+
cash_credit=order.qty * price - fees.total,
|
|
191
|
+
product_type=order.product_type, now=now)
|
|
192
|
+
|
|
193
|
+
qty_after = _state.symbol_position_qty(ctx, conn, order.symbol)
|
|
194
|
+
ctx.emit(conn, event_type="order_filled", order_id=order_id,
|
|
195
|
+
payload={"symbol": order.symbol, "side": order.side.value,
|
|
196
|
+
"qty": order.qty, "fill_price": price,
|
|
197
|
+
"fees_paid": fees.total,
|
|
198
|
+
"is_bracket_parent": True})
|
|
199
|
+
_state.emit_position_events(ctx, conn, order, position_existed, qty_after)
|
|
200
|
+
|
|
201
|
+
if order.parent_order_id is not None:
|
|
202
|
+
_state.cancel_bracket_siblings(ctx, conn, order)
|
|
203
|
+
|
|
204
|
+
ctx.drain_pending_events()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ── Helpers ───────────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _get_fill_quote(ctx: BrokerContext, symbol: str): # type: ignore[return]
|
|
211
|
+
"""Fetch a quote and apply the stale-price guard."""
|
|
212
|
+
from ..domain.exceptions import StalePriceRejected # noqa: PLC0415
|
|
213
|
+
|
|
214
|
+
quote = ctx.price_feed.get_quote(symbol)
|
|
215
|
+
if ctx.enforce_fresh_prices and quote.is_stale:
|
|
216
|
+
raise StalePriceRejected(
|
|
217
|
+
f"Refusing to fill {symbol} at stale cached price "
|
|
218
|
+
f"₹{quote.price:.2f} (fetched {quote.fetched_at.isoformat()}). "
|
|
219
|
+
f"Disable enforce_fresh_prices=False to allow stale fills."
|
|
220
|
+
)
|
|
221
|
+
if ctx.enforce_real_time and not quote.is_real_time:
|
|
222
|
+
raise StalePriceRejected(
|
|
223
|
+
f"Refusing to fill {symbol} on a delayed feed "
|
|
224
|
+
f"(source {quote.source!r}, fetched {quote.fetched_at.isoformat()}). "
|
|
225
|
+
f"Use a real-time provider (kite/dhan/upstox/finnhub) or set "
|
|
226
|
+
f"enforce_real_time=False to allow delayed fills."
|
|
227
|
+
)
|
|
228
|
+
return quote
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _maybe_settle_trade(
|
|
232
|
+
ctx: BrokerContext,
|
|
233
|
+
conn,
|
|
234
|
+
side: OrderSide,
|
|
235
|
+
symbol: str,
|
|
236
|
+
qty: float,
|
|
237
|
+
cash_credit: float,
|
|
238
|
+
product_type: ProductType,
|
|
239
|
+
now: str,
|
|
240
|
+
) -> None:
|
|
241
|
+
"""Enqueue a T+1 row for delivery trades; no-op for intraday/T+0."""
|
|
242
|
+
from datetime import datetime as _dt # noqa: PLC0415
|
|
243
|
+
|
|
244
|
+
from ..execution.settlement import SettlementMode # noqa: PLC0415
|
|
245
|
+
|
|
246
|
+
if product_type != ProductType.DELIVERY:
|
|
247
|
+
return
|
|
248
|
+
if ctx.settlement.mode != SettlementMode.T_PLUS_1:
|
|
249
|
+
return
|
|
250
|
+
trade_date = _dt.fromisoformat(now).date()
|
|
251
|
+
now_dt = _dt.fromisoformat(now)
|
|
252
|
+
if side == OrderSide.SELL:
|
|
253
|
+
ctx.settlement.enqueue_sell(
|
|
254
|
+
conn, account_id=ctx.account_id, symbol=symbol, qty=qty,
|
|
255
|
+
cash_credit=cash_credit, trade_date=trade_date, now=now_dt,
|
|
256
|
+
)
|
|
257
|
+
else:
|
|
258
|
+
ctx.settlement.enqueue_buy(
|
|
259
|
+
conn, account_id=ctx.account_id, symbol=symbol, qty=qty,
|
|
260
|
+
trade_date=trade_date, now=now_dt,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
__all__ = ["execute", "fill_pending_market"]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Configurable partial-fill model.
|
|
2
|
+
|
|
3
|
+
Honest framing: real partial fills require an order-book and per-symbol
|
|
4
|
+
liquidity. We don't have that — we have last-traded price.
|
|
5
|
+
|
|
6
|
+
What we model instead is a **configurable per-tick fill cap**: when the
|
|
7
|
+
limit-order watcher would fill a 1000-share order, the cap says "fill at
|
|
8
|
+
most N shares this tick; the rest stays PENDING." Across multiple ticks
|
|
9
|
+
the order eventually fills.
|
|
10
|
+
|
|
11
|
+
This isn't real bid/ask depth, but it's a useful knob for stress-testing
|
|
12
|
+
strategies that assume infinite liquidity. Tune ``PartialFillConfig``
|
|
13
|
+
to your beliefs about per-symbol average ticket size.
|
|
14
|
+
|
|
15
|
+
Configuration
|
|
16
|
+
-------------
|
|
17
|
+
- ``enabled``: master switch. False = legacy all-or-nothing fills.
|
|
18
|
+
- ``max_per_tick``: absolute share cap per watcher tick. ``None`` = no cap.
|
|
19
|
+
- ``max_pct_per_tick``: cap as a fraction of the order's qty. e.g. 0.25 =
|
|
20
|
+
fill ~25% per tick. ``None`` = no cap.
|
|
21
|
+
- ``min_fill_qty``: smallest slice we'll fill. Acts as a floor: the
|
|
22
|
+
effective per-tick cap is ``max(computed_cap, min_fill_qty)``, so
|
|
23
|
+
the order always makes forward progress instead of stalling on a
|
|
24
|
+
cap that rounds below the floor.
|
|
25
|
+
|
|
26
|
+
The effective cap per tick is roughly
|
|
27
|
+
``min(max_per_tick, qty * max_pct_per_tick)``, lifted to at least
|
|
28
|
+
``min_fill_qty`` so we never return zero when there's still work to do.
|
|
29
|
+
|
|
30
|
+
Market orders
|
|
31
|
+
-------------
|
|
32
|
+
Market orders still fill in one shot. Partial fills are limit-only —
|
|
33
|
+
they're a watcher-tick concept. (A market order that can't fully fill
|
|
34
|
+
in one print would, in reality, hit the order book at multiple price
|
|
35
|
+
levels — that needs a real LOB simulator.)
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import math
|
|
41
|
+
from dataclasses import dataclass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class PartialFillConfig:
|
|
46
|
+
"""Configuration for partial-fill simulation."""
|
|
47
|
+
|
|
48
|
+
enabled: bool = False
|
|
49
|
+
max_per_tick: int | None = None
|
|
50
|
+
max_pct_per_tick: float | None = None
|
|
51
|
+
min_fill_qty: int = 1
|
|
52
|
+
|
|
53
|
+
def fill_qty(self, remaining_qty: float) -> float:
|
|
54
|
+
"""Compute how many shares to fill on this tick.
|
|
55
|
+
|
|
56
|
+
Returns 0 (no fill this tick) or a value in
|
|
57
|
+
``[min_fill_qty, remaining_qty]``, with one exception: when
|
|
58
|
+
``remaining_qty <= min_fill_qty``, we fill ``remaining_qty``
|
|
59
|
+
in a single shot. Otherwise small orders (or the last sliver
|
|
60
|
+
of a large order) would never fill.
|
|
61
|
+
|
|
62
|
+
When the percentage cap rounds below ``min_fill_qty``, we lift
|
|
63
|
+
the cap *up* to ``min_fill_qty`` rather than truncating to 0 —
|
|
64
|
+
otherwise a 5-share order with 25% cap and ``min_fill_qty=1``
|
|
65
|
+
would stall after filling 2 shares (remaining 3 × 0.25 = 0.75,
|
|
66
|
+
floors to 0). The whole point of ``min_fill_qty`` is to
|
|
67
|
+
guarantee forward progress.
|
|
68
|
+
"""
|
|
69
|
+
if not self.enabled or remaining_qty <= 0:
|
|
70
|
+
return remaining_qty # disabled = full fill (legacy)
|
|
71
|
+
|
|
72
|
+
# Whole-order-fits-in-one-tick: don't bother slicing.
|
|
73
|
+
if remaining_qty <= self.min_fill_qty:
|
|
74
|
+
return float(remaining_qty)
|
|
75
|
+
|
|
76
|
+
candidates: list[float] = [remaining_qty]
|
|
77
|
+
if self.max_per_tick is not None:
|
|
78
|
+
candidates.append(float(self.max_per_tick))
|
|
79
|
+
if self.max_pct_per_tick is not None:
|
|
80
|
+
candidates.append(remaining_qty * self.max_pct_per_tick)
|
|
81
|
+
|
|
82
|
+
# Truncate to whole shares (Indian equity is whole-share-only,
|
|
83
|
+
# except for fractional MF units which are out of scope here).
|
|
84
|
+
cap = math.floor(min(candidates))
|
|
85
|
+
|
|
86
|
+
# Guarantee forward progress: a cap that rounds below
|
|
87
|
+
# ``min_fill_qty`` is lifted up to it. The earlier "remaining
|
|
88
|
+
# <= min_fill_qty" shortcut handles the small-order case, so
|
|
89
|
+
# by here we know remaining > min_fill_qty and lifting is safe.
|
|
90
|
+
if cap < self.min_fill_qty:
|
|
91
|
+
cap = min(self.min_fill_qty, int(remaining_qty))
|
|
92
|
+
return float(cap)
|