trading-engine-interface 0.56.25__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.
- trading_engine_interface/__init__.py +334 -0
- trading_engine_interface/common/__init__.py +0 -0
- trading_engine_interface/common/enums.py +163 -0
- trading_engine_interface/common/errors.py +259 -0
- trading_engine_interface/common/models/__init__.py +3 -0
- trading_engine_interface/common/models/base_api_model.py +14 -0
- trading_engine_interface/common/utils.py +20 -0
- trading_engine_interface/domain/__init__.py +8 -0
- trading_engine_interface/domain/fill_simulator.py +114 -0
- trading_engine_interface/domain/maker_fill.py +138 -0
- trading_engine_interface/domain/position_math.py +386 -0
- trading_engine_interface/examples/__init__.py +1 -0
- trading_engine_interface/examples/touch_bid_strategy.py +131 -0
- trading_engine_interface/py.typed +0 -0
- trading_engine_interface/runtime/__init__.py +32 -0
- trading_engine_interface/runtime/registry.py +298 -0
- trading_engine_interface/runtime/strategy.py +94 -0
- trading_engine_interface/trading_engine/__init__.py +0 -0
- trading_engine_interface/trading_engine/enums.py +284 -0
- trading_engine_interface/trading_engine/models/__init__.py +0 -0
- trading_engine_interface/trading_engine/models/accounting_models.py +412 -0
- trading_engine_interface/trading_engine/models/backtest_models.py +200 -0
- trading_engine_interface/trading_engine/models/market_models.py +452 -0
- trading_engine_interface/trading_engine/models/order_models.py +520 -0
- trading_engine_interface/trading_engine/models/position_breakdown_models.py +130 -0
- trading_engine_interface/trading_engine/models/position_models.py +230 -0
- trading_engine_interface/trading_engine/models/strategy_metrics_models.py +204 -0
- trading_engine_interface/trading_engine/models/strategy_models.py +1360 -0
- trading_engine_interface/trading_engine/order_rules.py +209 -0
- trading_engine_interface-0.56.25.dist-info/LICENSE +21 -0
- trading_engine_interface-0.56.25.dist-info/METADATA +112 -0
- trading_engine_interface-0.56.25.dist-info/RECORD +33 -0
- trading_engine_interface-0.56.25.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
from uuid import uuid4
|
|
5
|
+
|
|
6
|
+
from pydantic import Field, model_validator
|
|
7
|
+
from trading_engine_interface.common.enums import Asset, Symbol, VenueName
|
|
8
|
+
from trading_engine_interface.common.models.base_api_model import BaseApiModel
|
|
9
|
+
from trading_engine_interface.trading_engine.enums import AccountType, LiquidityType, OrderStatus, OrderType, Side
|
|
10
|
+
from typing_extensions import Self
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def gen_id() -> str:
|
|
14
|
+
return uuid4().hex
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CreateOrderRequest(BaseApiModel):
|
|
18
|
+
venue: VenueName
|
|
19
|
+
symbol: Symbol
|
|
20
|
+
order_type: OrderType
|
|
21
|
+
side: Side
|
|
22
|
+
quantity: Decimal = Field(gt=0)
|
|
23
|
+
price: Decimal = Field(ge=0)
|
|
24
|
+
|
|
25
|
+
# Venue-side trigger orders: price at which a resting STOP_LOSS /
|
|
26
|
+
# STOP_LOSS_LIMIT converts at the venue. Required for those types, forbidden
|
|
27
|
+
# otherwise. For STOP_LOSS_LIMIT, ``price`` is the post-trigger limit price;
|
|
28
|
+
# for STOP_LOSS, ``price`` stays 0 (market on trigger, like MARKET).
|
|
29
|
+
trigger_price: Optional[Decimal] = Field(default=None, gt=0)
|
|
30
|
+
|
|
31
|
+
client_order_id: str = Field(default_factory=gen_id, max_length=36)
|
|
32
|
+
strategy_id: Optional[int] = None
|
|
33
|
+
|
|
34
|
+
# Strategy-defined business context (TV, signals, regime, etc.). Engine round-trips opaquely;
|
|
35
|
+
# strategies own schema discipline. Convention:
|
|
36
|
+
# {"strategy_class": "MMv12", "schema_version": 1, "context": {...}}
|
|
37
|
+
# Named `strategy_context` to distinguish from engine-owned `metrics`/`failure_details`
|
|
38
|
+
# and to avoid SQLAlchemy's reserved `metadata` attribute on declarative bases.
|
|
39
|
+
strategy_context: Optional[dict[str, Any]] = Field(
|
|
40
|
+
default=None,
|
|
41
|
+
description="Strategy-defined business context attached at order creation. Opaque to engine.",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
@model_validator(mode="after")
|
|
45
|
+
def validate_trigger(self) -> Self:
|
|
46
|
+
is_stop = self.order_type in (OrderType.STOP_LOSS, OrderType.STOP_LOSS_LIMIT)
|
|
47
|
+
if is_stop and self.trigger_price is None:
|
|
48
|
+
raise ValueError(f"{self.order_type.value} order requires trigger_price: {self}")
|
|
49
|
+
if not is_stop and self.trigger_price is not None:
|
|
50
|
+
raise ValueError(f"trigger_price is only valid for STOP_LOSS/STOP_LOSS_LIMIT orders: {self}")
|
|
51
|
+
if self.order_type == OrderType.STOP_LOSS_LIMIT and self.price <= 0:
|
|
52
|
+
raise ValueError(f"STOP_LOSS_LIMIT order requires a post-trigger limit price: {self}")
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def __str__(self) -> str:
|
|
56
|
+
trigger = f" trigger@{self.trigger_price}" if self.trigger_price is not None else ""
|
|
57
|
+
return (
|
|
58
|
+
f"strategy-{self.strategy_id} "
|
|
59
|
+
f"{self.symbol.value} {self.side.value} {self.quantity}@{self.price} {self.order_type.value}"
|
|
60
|
+
f"{trigger} {self.venue.value} {self.client_order_id}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class BracketOrderRequest(BaseApiModel):
|
|
65
|
+
"""One exit intent, two venue legs: a maker take-profit + a venue-side stop.
|
|
66
|
+
|
|
67
|
+
Only the STRATEGY knows two exits are mutually exclusive (the engine cannot infer
|
|
68
|
+
a bracket from two separate orders — a scale-out ladder looks identical), so
|
|
69
|
+
exclusivity is declared here and the gateway maps it to the venue's native
|
|
70
|
+
one-cancels-the-other primitive (Binance ``POST /api/v3/order/oco``). Measured on
|
|
71
|
+
both venues: the pair locks 1x the inventory and the venue auto-cancels the
|
|
72
|
+
sibling when either leg executes.
|
|
73
|
+
|
|
74
|
+
The engine returns the two legs as ordinary ``Order`` rows sharing
|
|
75
|
+
``venue_algo_id`` (the venue's grouping id — Binance ``orderListId``); each leg
|
|
76
|
+
fills/cancels through the existing lifecycle. ``side`` is the EXIT side (SELL
|
|
77
|
+
closes a long): the TP leg rests as a maker limit at ``tp_price``, the stop leg
|
|
78
|
+
trigger-watches ``stop_trigger_price`` and converts to a limit at
|
|
79
|
+
``stop_limit_price`` (venue-side stops are limit-on-trigger on some venues — plain
|
|
80
|
+
STOP_LOSS is not enabled on all of them).
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
venue: VenueName
|
|
84
|
+
symbol: Symbol
|
|
85
|
+
side: Side
|
|
86
|
+
quantity: Decimal = Field(gt=0)
|
|
87
|
+
|
|
88
|
+
tp_price: Decimal = Field(gt=0)
|
|
89
|
+
stop_trigger_price: Decimal = Field(gt=0)
|
|
90
|
+
stop_limit_price: Decimal = Field(gt=0)
|
|
91
|
+
|
|
92
|
+
# Base id: legs derive "<id>-tp" / "<id>-sl" (<=36 chars each, venue limit).
|
|
93
|
+
client_order_id: str = Field(default_factory=gen_id, max_length=32)
|
|
94
|
+
strategy_id: Optional[int] = None
|
|
95
|
+
strategy_context: Optional[dict[str, Any]] = Field(default=None)
|
|
96
|
+
|
|
97
|
+
@model_validator(mode="after")
|
|
98
|
+
def validate_bracket(self) -> Self:
|
|
99
|
+
# Venue price rules: the TP must sit on the profitable side of the trigger for
|
|
100
|
+
# the exit direction, or the venue rejects the pair ("breaking the Price rules").
|
|
101
|
+
if self.side == Side.SELL and not self.tp_price > self.stop_trigger_price:
|
|
102
|
+
raise ValueError(f"SELL bracket requires tp_price > stop_trigger_price: {self}")
|
|
103
|
+
if self.side == Side.BUY and not self.tp_price < self.stop_trigger_price:
|
|
104
|
+
raise ValueError(f"BUY bracket requires tp_price < stop_trigger_price: {self}")
|
|
105
|
+
return self
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def tp_client_order_id(self) -> str:
|
|
109
|
+
return f"{self.client_order_id}-tp"
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def stop_client_order_id(self) -> str:
|
|
113
|
+
return f"{self.client_order_id}-sl"
|
|
114
|
+
|
|
115
|
+
def __str__(self) -> str:
|
|
116
|
+
return (
|
|
117
|
+
f"strategy-{self.strategy_id} BRACKET {self.symbol.value} {self.side.value} {self.quantity} "
|
|
118
|
+
f"tp@{self.tp_price} stop@{self.stop_trigger_price}/{self.stop_limit_price} "
|
|
119
|
+
f"{self.venue.value} {self.client_order_id}"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class CancelOrderRequest(BaseApiModel):
|
|
124
|
+
order_id: int
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class AmendStopRequest(BaseApiModel):
|
|
128
|
+
"""Move a RESTING venue-side stop's trigger (and, for limit-on-trigger stops, its
|
|
129
|
+
post-trigger limit) atomically at the venue.
|
|
130
|
+
|
|
131
|
+
A strategy's stop is not static — breakeven activation and ATR updates move it.
|
|
132
|
+
Cancel+create has a naked window (cancel lands, create fails -> no stop resting,
|
|
133
|
+
in exactly the fast market stops exist for) and the safe ordering is impossible
|
|
134
|
+
anyway (both stops would lock the same inventory). Venues with a native
|
|
135
|
+
amend (OKX ``amend-algos``) move the stop in ONE call; venues without one report
|
|
136
|
+
no support and the caller owns an explicit cancel+create fallback.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
order_id: int
|
|
140
|
+
new_trigger_price: Decimal = Field(gt=0)
|
|
141
|
+
# Required when the stop is limit-on-trigger (STOP_LOSS_LIMIT keeps its old limit
|
|
142
|
+
# if omitted). Ignored for market-on-trigger stops.
|
|
143
|
+
new_limit_price: Optional[Decimal] = Field(default=None, gt=0)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class ReplaceOrderRequest(BaseApiModel):
|
|
147
|
+
"""Reprice and/or resize a live (NEW / PARTIALLY_FILLED) order — the request the
|
|
148
|
+
engine turns into a venue cancel-replace.
|
|
149
|
+
|
|
150
|
+
``new_quantity`` is the desired RESTING (live) quantity after the replace — the
|
|
151
|
+
size of the working quote, NOT the total including already-filled. The engine
|
|
152
|
+
cancels the original and places a fresh order of size ``new_quantity`` on venues
|
|
153
|
+
with an atomic cancel-replace (e.g. Binance ``cancelReplace``); venues without it
|
|
154
|
+
report no support and the caller falls back to cancel + create. Either way the
|
|
155
|
+
economic state is the same — already-filled banked, ``new_quantity`` resting.
|
|
156
|
+
Expressing resting (not total) is fill-race-robust (it is relative to current
|
|
157
|
+
fills).
|
|
158
|
+
|
|
159
|
+
In-place modify (the original design) was removed — it raced the
|
|
160
|
+
venue's fills and WS pushes, producing un-cancellable orders and orphaned
|
|
161
|
+
reservations.
|
|
162
|
+
|
|
163
|
+
At least one of ``new_price`` / ``new_quantity`` must be set.
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
order_id: int
|
|
167
|
+
new_price: Optional[Decimal] = Field(default=None, gt=0)
|
|
168
|
+
new_quantity: Optional[Decimal] = Field(
|
|
169
|
+
default=None, gt=0, description="Desired resting (live) quantity after the replace; the engine cancel-replaces."
|
|
170
|
+
)
|
|
171
|
+
# On a venue with native cancel-replace, the replacement is placed atomically with
|
|
172
|
+
# the cancel. True (default) — the MM requote case: the drifted
|
|
173
|
+
# quote was going to be cancelled anyway, so a failed replace degrades to flat,
|
|
174
|
+
# repost next cycle, with no extra request. Set False to keep the original order
|
|
175
|
+
# resting on failure (caller owns the cancel+create fallback explicitly).
|
|
176
|
+
cancel_on_fail: bool = True
|
|
177
|
+
|
|
178
|
+
@model_validator(mode="after")
|
|
179
|
+
def validate_replace(self) -> Self:
|
|
180
|
+
if self.new_price is None and self.new_quantity is None:
|
|
181
|
+
raise ValueError(f"ReplaceOrderRequest requires at least one of new_price / new_quantity: {self}")
|
|
182
|
+
return self
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class Order(BaseApiModel):
|
|
186
|
+
# Order details
|
|
187
|
+
venue: VenueName
|
|
188
|
+
symbol: Symbol
|
|
189
|
+
order_type: OrderType
|
|
190
|
+
side: Side
|
|
191
|
+
quantity: Decimal = Field(gt=0)
|
|
192
|
+
price: Decimal = Field(ge=0)
|
|
193
|
+
|
|
194
|
+
# Account info
|
|
195
|
+
venue_user_id: str
|
|
196
|
+
account_type: AccountType
|
|
197
|
+
|
|
198
|
+
# Order status
|
|
199
|
+
status: OrderStatus
|
|
200
|
+
timestamp: Optional[datetime] = None # remote creation time
|
|
201
|
+
filled_quantity: Decimal = Field(default=Decimal(0), ge=0)
|
|
202
|
+
avg_fill_price: Optional[Decimal] = Field(default=None, gt=0)
|
|
203
|
+
|
|
204
|
+
# Venue-side trigger orders. A resting stop has ``venue_algo_id`` set (OKX
|
|
205
|
+
# algoId — a separate id namespace from ordId) and no ``venue_order_id`` yet; when
|
|
206
|
+
# the venue triggers it, the spawned regular order's id fills ``venue_order_id``
|
|
207
|
+
# (linked via algoClOrdId == client_order_id) and the normal fill lifecycle applies.
|
|
208
|
+
trigger_price: Optional[Decimal] = Field(default=None, gt=0)
|
|
209
|
+
|
|
210
|
+
# Identifiers
|
|
211
|
+
client_order_id: str
|
|
212
|
+
venue_order_id: Optional[str] = None # optional because local order does not have it when created
|
|
213
|
+
venue_algo_id: Optional[str] = None # set only for venue-side trigger (algo) orders
|
|
214
|
+
strategy_id: Optional[int] = None # optional because remote data source does not have it
|
|
215
|
+
account_id: Optional[int] = None # optional because remote data source does not have it
|
|
216
|
+
|
|
217
|
+
# Failure tracking
|
|
218
|
+
failure_details: Optional[dict[str, Any]] = Field(
|
|
219
|
+
default=None,
|
|
220
|
+
description="Details about order rejection or errors (reason, code, gateway message, etc.)",
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
# Performance metrics
|
|
224
|
+
metrics: Optional[dict[str, Any]] = Field(
|
|
225
|
+
default=None,
|
|
226
|
+
description="Order execution metrics (latencies, timestamps, etc.)",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# Strategy-defined business context (round-tripped from CreateOrderRequest)
|
|
230
|
+
strategy_context: Optional[dict[str, Any]] = Field(
|
|
231
|
+
default=None,
|
|
232
|
+
description="Strategy-defined business context attached at order creation. Opaque to engine.",
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Relationships
|
|
236
|
+
fills: list["Fill"] = []
|
|
237
|
+
|
|
238
|
+
@model_validator(mode="after")
|
|
239
|
+
def validate_order(self) -> Self:
|
|
240
|
+
"""Validate order state and price rules."""
|
|
241
|
+
# Quantity validations
|
|
242
|
+
if self.filled_quantity > self.quantity:
|
|
243
|
+
raise ValueError(f"Filled quantity cannot exceed order quantity: {self}")
|
|
244
|
+
if self.status in (OrderStatus.PENDING_NEW, OrderStatus.NEW) and self.filled_quantity > 0:
|
|
245
|
+
raise ValueError(f"New order cannot have filled quantity > 0: {self}")
|
|
246
|
+
if self.status == OrderStatus.FILLED and self.filled_quantity != self.quantity:
|
|
247
|
+
if self.order_type == OrderType.MARKET:
|
|
248
|
+
# Market orders may have slight quantity mismatch due to exchange lot size rounding.
|
|
249
|
+
# Reject if filled less than 99% -- that indicates a real problem, not rounding.
|
|
250
|
+
if self.filled_quantity < self.quantity * Decimal("0.99"):
|
|
251
|
+
raise ValueError(f"Market order filled quantity too low: {self}")
|
|
252
|
+
else:
|
|
253
|
+
raise ValueError(f"Order cannot be filled without filling the entire quantity: {self}")
|
|
254
|
+
if self.status == OrderStatus.REJECTED and self.filled_quantity > 0:
|
|
255
|
+
raise ValueError(f"Order cannot be rejected with filled quantity: {self}")
|
|
256
|
+
if self.status == OrderStatus.PARTIALLY_FILLED and self.filled_quantity == 0:
|
|
257
|
+
raise ValueError(f"Order cannot be partially filled with 0 filled quantity: {self}")
|
|
258
|
+
if self.status == OrderStatus.SETTLING:
|
|
259
|
+
# SETTLING = a terminal status was decided at the venue but per-fill
|
|
260
|
+
# records are still propagating locally. Two parent cases:
|
|
261
|
+
# - FILLED-with-deficit: filled_quantity == quantity, eventual
|
|
262
|
+
# status FILLED.
|
|
263
|
+
# - CANCELED-with-deficit: filled_quantity < quantity (partial
|
|
264
|
+
# fills accumulated before the cancel completed), eventual
|
|
265
|
+
# status CANCELED.
|
|
266
|
+
# Only the lower bound is universal: SETTLING is meaningless with
|
|
267
|
+
# zero fill activity.
|
|
268
|
+
if self.filled_quantity == 0:
|
|
269
|
+
raise ValueError(f"Settling order must have filled quantity > 0: {self}")
|
|
270
|
+
|
|
271
|
+
# NOTE: the price-vs-fill sanity check (BUY avg_fill <= limit, SELL
|
|
272
|
+
# avg_fill >= limit) used to be a HARD model error here. It was moved to a
|
|
273
|
+
# verify-layer rule (verification_service: `order_fill_within_limit`, WARNING).
|
|
274
|
+
# A model must be able to REPRESENT any state the venue reports — an amended
|
|
275
|
+
# limit can legitimately sit past a pre-amend fill — and one such order must
|
|
276
|
+
# never make `Order` un-constructable, which would 500 every read/cancel/
|
|
277
|
+
# reconcile for the whole account AND crash the gateway on the venue's WS push.
|
|
278
|
+
# The invariant is still enforced and surfaced; just not as a constructor error.
|
|
279
|
+
|
|
280
|
+
return self
|
|
281
|
+
|
|
282
|
+
@model_validator(mode="after")
|
|
283
|
+
def validate_order_fills(self) -> Self:
|
|
284
|
+
"""Validate fill consistency and price calculations.
|
|
285
|
+
|
|
286
|
+
Reconciliation contract: ``filled_quantity`` is the venue-authoritative
|
|
287
|
+
cumulative fill total (e.g. OKX ``accFillSz``); ``fills`` is the set of
|
|
288
|
+
per-fill records the engine has reconstructed locally. The two streams
|
|
289
|
+
often arrive out of order — venues report cumulative fills via the
|
|
290
|
+
order endpoint faster than per-fill records propagate to the fills
|
|
291
|
+
endpoint or the WS fills channel.
|
|
292
|
+
|
|
293
|
+
Hard invariant: ``sum(fills) <= filled_quantity``. The reverse
|
|
294
|
+
(``sum(fills) > filled_quantity``) is structurally impossible and
|
|
295
|
+
signals real corruption.
|
|
296
|
+
|
|
297
|
+
Soft state: ``sum(fills) < filled_quantity`` is the in-flight reconciliation
|
|
298
|
+
window. The polling fallback (``_fill_pending_since`` in OrderService) drives
|
|
299
|
+
recovery; do not reject the update — record what we have and let the
|
|
300
|
+
missing fills be adopted as they arrive. Fill-derived checks (e.g.
|
|
301
|
+
weighted-avg price equality) are skipped while in this state because
|
|
302
|
+
partial-fill data does not represent the true venue-side aggregate.
|
|
303
|
+
"""
|
|
304
|
+
# Remote data source may not include fills in order
|
|
305
|
+
if not self.fills:
|
|
306
|
+
return self
|
|
307
|
+
|
|
308
|
+
if self.filled_quantity > 0 and not self.fills:
|
|
309
|
+
raise ValueError(f"Order with filled quantity must have fills: {self}")
|
|
310
|
+
|
|
311
|
+
if self.fills and self.filled_quantity == 0:
|
|
312
|
+
raise ValueError(f"Order with fills must have filled quantity: {self}")
|
|
313
|
+
|
|
314
|
+
# Verify fills match order
|
|
315
|
+
for fill in self.fills:
|
|
316
|
+
if not all(
|
|
317
|
+
[
|
|
318
|
+
fill.venue == self.venue,
|
|
319
|
+
fill.symbol == self.symbol,
|
|
320
|
+
fill.side == self.side,
|
|
321
|
+
fill.order_id == self.id,
|
|
322
|
+
]
|
|
323
|
+
):
|
|
324
|
+
raise ValueError(f"Order fill does not match: {self}")
|
|
325
|
+
|
|
326
|
+
total_fill_quantity = sum(fill.quantity for fill in self.fills)
|
|
327
|
+
if total_fill_quantity > self.filled_quantity:
|
|
328
|
+
# Structural corruption: more local fills than the venue says were filled.
|
|
329
|
+
raise ValueError(f"Sum of fills exceeds filled quantity: {self}")
|
|
330
|
+
fills_pending = self.filled_quantity - total_fill_quantity
|
|
331
|
+
|
|
332
|
+
# POST_ONLY fills must be maker only
|
|
333
|
+
if self.order_type == OrderType.POST_ONLY:
|
|
334
|
+
if any(f.liquidity_type == LiquidityType.TAKER for f in self.fills):
|
|
335
|
+
raise ValueError("POST_ONLY order cannot have taker fills")
|
|
336
|
+
|
|
337
|
+
# Verify avg_fill_price matches fill prices — only meaningful when fully
|
|
338
|
+
# reconciled. While fills_pending > 0, the local weighted-avg reflects a
|
|
339
|
+
# subset of fills and won't match the venue's true average across all fills.
|
|
340
|
+
if fills_pending == 0 and self.filled_quantity > 0 and self.avg_fill_price is not None:
|
|
341
|
+
weighted_avg = sum(f.quantity * f.price for f in self.fills) / total_fill_quantity
|
|
342
|
+
weighted_avg = Decimal(weighted_avg)
|
|
343
|
+
if abs(weighted_avg - self.avg_fill_price) > Decimal("0.00000001"):
|
|
344
|
+
raise ValueError(
|
|
345
|
+
f"avg_fill_price {self.avg_fill_price} does not match fills weighted average {weighted_avg}"
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
# Sort fills by ID for consistent ordering
|
|
349
|
+
self.fills.sort(key=lambda x: x.id or 0)
|
|
350
|
+
return self
|
|
351
|
+
|
|
352
|
+
@property
|
|
353
|
+
def fills_pending_quantity(self) -> Decimal:
|
|
354
|
+
"""Quantity reported as filled by the venue but not yet recorded as fills locally.
|
|
355
|
+
|
|
356
|
+
Non-zero indicates the order is in the reconciliation window between
|
|
357
|
+
cumulative fill reporting and per-fill record arrival. Polling and the
|
|
358
|
+
WS fills channel close this gap; ``OrderService._fill_pending_since``
|
|
359
|
+
tracks the lag.
|
|
360
|
+
"""
|
|
361
|
+
total_fill_quantity = sum((fill.quantity for fill in self.fills), Decimal(0))
|
|
362
|
+
return self.filled_quantity - total_fill_quantity
|
|
363
|
+
|
|
364
|
+
@property
|
|
365
|
+
def venue_account_id(self) -> str:
|
|
366
|
+
return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
|
|
367
|
+
|
|
368
|
+
@property
|
|
369
|
+
def remaining_quantity(self) -> Decimal:
|
|
370
|
+
return self.quantity - self.filled_quantity
|
|
371
|
+
|
|
372
|
+
@property
|
|
373
|
+
def is_filled(self) -> bool:
|
|
374
|
+
return self.status == OrderStatus.FILLED
|
|
375
|
+
|
|
376
|
+
@property
|
|
377
|
+
def is_canceled(self) -> bool:
|
|
378
|
+
return self.status == OrderStatus.CANCELED
|
|
379
|
+
|
|
380
|
+
@property
|
|
381
|
+
def is_settling(self) -> bool:
|
|
382
|
+
"""Order filled on exchange but fill records not yet received locally."""
|
|
383
|
+
return self.status == OrderStatus.SETTLING
|
|
384
|
+
|
|
385
|
+
@property
|
|
386
|
+
def is_closed(self) -> bool:
|
|
387
|
+
return self.status in [
|
|
388
|
+
OrderStatus.FILLED,
|
|
389
|
+
OrderStatus.CANCELED,
|
|
390
|
+
OrderStatus.REJECTED,
|
|
391
|
+
]
|
|
392
|
+
|
|
393
|
+
@property
|
|
394
|
+
def is_open(self) -> bool:
|
|
395
|
+
return not self.is_closed
|
|
396
|
+
|
|
397
|
+
def __str__(self) -> str:
|
|
398
|
+
return (
|
|
399
|
+
f"Order-{self.id}:{self.status} {self.side} {self.symbol} "
|
|
400
|
+
f"{self.quantity}@{self.price} {self.order_type} {self.venue} "
|
|
401
|
+
f"filled_quantity={self.filled_quantity} avg_fill_price={self.avg_fill_price} fills_count={len(self.fills)}"
|
|
402
|
+
f" {self.client_order_id}"
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class Fill(BaseApiModel):
|
|
407
|
+
# Fill details
|
|
408
|
+
venue: VenueName
|
|
409
|
+
symbol: Symbol
|
|
410
|
+
side: Side
|
|
411
|
+
quantity: Decimal = Field(gt=0)
|
|
412
|
+
price: Decimal = Field(gt=0)
|
|
413
|
+
liquidity_type: LiquidityType
|
|
414
|
+
timestamp: datetime # remote creation time
|
|
415
|
+
|
|
416
|
+
# Account info
|
|
417
|
+
venue_user_id: str
|
|
418
|
+
account_type: AccountType
|
|
419
|
+
|
|
420
|
+
# Fee information
|
|
421
|
+
# Negative fee = rebate (maker rebate earnings)
|
|
422
|
+
# Positive fee = cost (taker fee paid)
|
|
423
|
+
fee: Optional[Decimal] = Field(default=None)
|
|
424
|
+
fee_asset: Optional[Asset] = None
|
|
425
|
+
|
|
426
|
+
# Identifiers
|
|
427
|
+
venue_fill_id: str
|
|
428
|
+
venue_order_id: str
|
|
429
|
+
strategy_id: Optional[int] = None # optional because remote data source does not have it
|
|
430
|
+
account_id: Optional[int] = None # optional because remote data source does not have it
|
|
431
|
+
order_id: Optional[int] = None # optional because remote data source does not have it
|
|
432
|
+
|
|
433
|
+
@model_validator(mode="after")
|
|
434
|
+
def validate_fill(self) -> Self:
|
|
435
|
+
"""Validate fill state and price rules."""
|
|
436
|
+
if self.fee is not None and self.fee_asset is None:
|
|
437
|
+
raise ValueError(f"Fill with fee must have fee asset specified: {self}")
|
|
438
|
+
|
|
439
|
+
if self.fee is None and self.fee_asset is not None:
|
|
440
|
+
raise ValueError(f"Fill with fee asset must have fee specified: {self}")
|
|
441
|
+
|
|
442
|
+
if self.fee_asset and self.fee_asset != self.symbol.base_asset and self.fee_asset != self.symbol.quote_asset:
|
|
443
|
+
raise ValueError(f"Fill fee asset {self.fee_asset} must be base or quote asset of symbol {self.symbol}")
|
|
444
|
+
|
|
445
|
+
return self
|
|
446
|
+
|
|
447
|
+
@property
|
|
448
|
+
def venue_account_id(self) -> str:
|
|
449
|
+
return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
|
|
450
|
+
|
|
451
|
+
@property
|
|
452
|
+
def volume(self) -> Decimal:
|
|
453
|
+
return self.quantity * self.price
|
|
454
|
+
|
|
455
|
+
@property
|
|
456
|
+
def base_amount(self) -> Decimal:
|
|
457
|
+
"""
|
|
458
|
+
Signed base asset amount including fees/rebates.
|
|
459
|
+
|
|
460
|
+
- Positive: Receiving base (BUY)
|
|
461
|
+
- Negative: Sending base (SELL)
|
|
462
|
+
- Positive fee: reduces net amount
|
|
463
|
+
- Negative fee (rebate): increases net amount
|
|
464
|
+
|
|
465
|
+
Example:
|
|
466
|
+
BUY 1 BTC with 0.001 BTC fee → base_amount = 0.999
|
|
467
|
+
BUY 1 BTC with -0.001 BTC rebate → base_amount = 1.001
|
|
468
|
+
SELL 1 BTC with 0.001 BTC fee → base_amount = -1.001
|
|
469
|
+
SELL 1 BTC with -0.001 BTC rebate → base_amount = -0.999
|
|
470
|
+
"""
|
|
471
|
+
base_qty = self.quantity if self.side == Side.BUY else -self.quantity
|
|
472
|
+
|
|
473
|
+
if self.fee and self.fee_asset == self.symbol.base_asset:
|
|
474
|
+
# Positive fee reduces, negative fee (rebate) increases
|
|
475
|
+
base_qty -= self.fee
|
|
476
|
+
|
|
477
|
+
return base_qty
|
|
478
|
+
|
|
479
|
+
@property
|
|
480
|
+
def quote_amount(self) -> Decimal:
|
|
481
|
+
"""
|
|
482
|
+
Signed quote asset amount including fees/rebates.
|
|
483
|
+
|
|
484
|
+
- Negative: Paying quote (BUY)
|
|
485
|
+
- Positive: Receiving quote (SELL)
|
|
486
|
+
- Positive fee: reduces net amount
|
|
487
|
+
- Negative fee (rebate): increases net amount
|
|
488
|
+
|
|
489
|
+
Example:
|
|
490
|
+
BUY 1 BTC @ $50k with $50 USDT fee → quote_amount = -$50,050 (paid more)
|
|
491
|
+
BUY 1 BTC @ $50k with -$5 USDT rebate → quote_amount = -$49,995 (paid less)
|
|
492
|
+
SELL 1 BTC @ $50k with $50 USDT fee → quote_amount = +$49,950 (received less)
|
|
493
|
+
SELL 1 BTC @ $50k with -$5 USDT rebate → quote_amount = +$50,005 (received more)
|
|
494
|
+
"""
|
|
495
|
+
quote_amt = -(self.quantity * self.price) if self.side == Side.BUY else (self.quantity * self.price)
|
|
496
|
+
|
|
497
|
+
if self.fee and self.fee_asset == self.symbol.quote_asset:
|
|
498
|
+
# Positive fee reduces, negative fee (rebate) increases
|
|
499
|
+
quote_amt -= self.fee
|
|
500
|
+
|
|
501
|
+
return quote_amt
|
|
502
|
+
|
|
503
|
+
@property
|
|
504
|
+
def net_price(self) -> Decimal:
|
|
505
|
+
"""
|
|
506
|
+
Effective price after fees/rebates: abs(quote_amount / base_amount)
|
|
507
|
+
|
|
508
|
+
This reflects the true cost/proceeds per unit of base asset after accounting for fees.
|
|
509
|
+
|
|
510
|
+
Example:
|
|
511
|
+
BUY 1 BTC @ $50k with $50 fee → net_price = $50,050 / 1 = $50,050 (paid more)
|
|
512
|
+
BUY 1 BTC @ $50k with -$5 rebate → net_price = $49,995 / 1 = $49,995 (paid less)
|
|
513
|
+
BUY 1 BTC @ $50k with 0.001 BTC fee → net_price = $50,000 / 0.999 = $50,050.05
|
|
514
|
+
"""
|
|
515
|
+
if self.base_amount == 0:
|
|
516
|
+
return self.price
|
|
517
|
+
return abs(self.quote_amount / self.base_amount)
|
|
518
|
+
|
|
519
|
+
def __str__(self) -> str:
|
|
520
|
+
return f"Fill-{self.id}: {self.venue_fill_id} {self.quantity}@{self.price}"
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Per-venue position breakdown — read models.
|
|
2
|
+
|
|
3
|
+
The persisted ``Position`` is a per-(strategy, symbol) NET vector: a cross-venue
|
|
4
|
+
netted book (short venue A / long venue B) folds to base ≈ 0, so net-based
|
|
5
|
+
exposure caps never bind. These models carry the missing venue dimension,
|
|
6
|
+
derived from fills (``Fill.venue`` is ground truth) at read time — they are
|
|
7
|
+
telemetry/read models, never persisted, and deliberately separate from the
|
|
8
|
+
money-path ``Position``/``PositionGroup``.
|
|
9
|
+
|
|
10
|
+
Identity: for each (strategy, symbol), Σ over venues of ``base_amount`` equals
|
|
11
|
+
Σ ``Fill.base_amount`` over all that strategy's fills for the symbol — the same
|
|
12
|
+
quantity the ``position_base_diverges_from_fills`` verification rule pins to the
|
|
13
|
+
net position (base + dust).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from decimal import Decimal
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, Field
|
|
21
|
+
from trading_engine_interface.common.enums import Asset, Symbol, VenueName
|
|
22
|
+
from trading_engine_interface.trading_engine.enums import AccountType
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class VenuePosition(BaseModel):
|
|
26
|
+
"""One venue's slice of a symbol's position: signed fill-sum vectors.
|
|
27
|
+
|
|
28
|
+
``base_amount`` / ``quote_amount`` are Σ ``Fill.base_amount`` /
|
|
29
|
+
Σ ``Fill.quote_amount`` over this (strategy, symbol, venue) — fees/rebates
|
|
30
|
+
already encoded, same conventions as the position vector. ``quote_amount``
|
|
31
|
+
is the net cash flow on the venue (where the money accumulated — the
|
|
32
|
+
rebalance-drift signal), not an open-position cost basis.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
venue: VenueName
|
|
36
|
+
base_amount: Decimal = Field(default=Decimal(0), description="Σ fill base on this venue (signed; fees encoded)")
|
|
37
|
+
quote_amount: Decimal = Field(
|
|
38
|
+
default=Decimal(0), description="Σ fill quote cash flow on this venue (signed; fees encoded)"
|
|
39
|
+
)
|
|
40
|
+
# $-exposure of this venue's OPEN slice at COST basis: the
|
|
41
|
+
# slice is folded through the same update_position math as the net position,
|
|
42
|
+
# so closes reduce it and one-directional slices on netted books accumulate
|
|
43
|
+
# their full entry cost. This is what max_gross_exposure_value binds on —
|
|
44
|
+
# same basis as Position.exposure / max_position_value. Distinct from
|
|
45
|
+
# quote_amount (net cash flow — the drift signal, unchanged from Phase 1).
|
|
46
|
+
cost_basis_exposure: Decimal = Field(
|
|
47
|
+
default=Decimal(0), ge=0, description="Open-slice exposure at cost basis (USD-quote terms)"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class StrategyVenueBreakdown(BaseModel):
|
|
52
|
+
"""Per-venue position slices for one strategy, keyed by symbol.
|
|
53
|
+
|
|
54
|
+
Read model derived from the strategy's fill history. ``gross_base(symbol)``
|
|
55
|
+
is the gross measure — Σ |per-venue base| — which stays large on a
|
|
56
|
+
delta-neutral book whose NET base is ~0.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
strategy_id: int
|
|
60
|
+
timestamp: datetime
|
|
61
|
+
positions: dict[Symbol, list[VenuePosition]] = Field(default_factory=dict)
|
|
62
|
+
|
|
63
|
+
def venue_base(self, symbol: Symbol, venue: VenueName) -> Decimal:
|
|
64
|
+
"""Signed base on one venue; 0 when the venue has no fills for the symbol."""
|
|
65
|
+
for vp in self.positions.get(symbol, []):
|
|
66
|
+
if vp.venue == venue:
|
|
67
|
+
return vp.base_amount
|
|
68
|
+
return Decimal(0)
|
|
69
|
+
|
|
70
|
+
def gross_base(self, symbol: Symbol) -> Decimal:
|
|
71
|
+
"""Σ |per-venue base| — the gross-exposure measure a net position hides."""
|
|
72
|
+
return sum((abs(vp.base_amount) for vp in self.positions.get(symbol, [])), Decimal(0))
|
|
73
|
+
|
|
74
|
+
def net_base(self, symbol: Symbol) -> Decimal:
|
|
75
|
+
"""Σ per-venue base — equals the net position's base (+ dust) by the fill identity."""
|
|
76
|
+
return sum((vp.base_amount for vp in self.positions.get(symbol, [])), Decimal(0))
|
|
77
|
+
|
|
78
|
+
def gross_exposure(self, symbol: Symbol) -> Decimal:
|
|
79
|
+
"""Σ per-venue cost-basis exposure ($) for one symbol."""
|
|
80
|
+
return sum((vp.cost_basis_exposure for vp in self.positions.get(symbol, [])), Decimal(0))
|
|
81
|
+
|
|
82
|
+
def total_gross_exposure(self) -> Decimal:
|
|
83
|
+
"""Σ per-venue cost-basis exposure ($) across ALL symbols — the quantity
|
|
84
|
+
max_gross_exposure_value binds on. Stays large on a delta-neutral book
|
|
85
|
+
whose net exposure is ~0."""
|
|
86
|
+
return sum((self.gross_exposure(symbol) for symbol in self.positions), Decimal(0))
|
|
87
|
+
|
|
88
|
+
def venue_slice(self, symbol: Symbol, venue: VenueName) -> "Optional[VenuePosition]":
|
|
89
|
+
"""The venue's slice for a symbol, or None when it has no fills."""
|
|
90
|
+
for vp in self.positions.get(symbol, []):
|
|
91
|
+
if vp.venue == venue:
|
|
92
|
+
return vp
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class AccountVenueExposureItem(BaseModel):
|
|
97
|
+
"""Aggregated fill vectors for one (venue, symbol) across ALL strategies.
|
|
98
|
+
|
|
99
|
+
Includes strategy-less fills (manual/reconciled), so this is the
|
|
100
|
+
fills-complete account view — what the account actually accumulated,
|
|
101
|
+
independent of strategy attribution.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
venue: VenueName
|
|
105
|
+
symbol: Symbol
|
|
106
|
+
base_amount: Decimal = Field(default=Decimal(0))
|
|
107
|
+
quote_amount: Decimal = Field(default=Decimal(0))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class FundedCapitalItem(BaseModel):
|
|
111
|
+
"""Net funded capital for one (venue, account_type, asset): completed
|
|
112
|
+
deposits − withdrawals. The baseline account balances drift away from."""
|
|
113
|
+
|
|
114
|
+
venue: VenueName
|
|
115
|
+
account_type: AccountType
|
|
116
|
+
asset: Asset
|
|
117
|
+
net_funded: Decimal
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class AccountVenueExposureReport(BaseModel):
|
|
121
|
+
"""Account-level per-venue exposure + the funded baseline.
|
|
122
|
+
|
|
123
|
+
``items`` aggregates fill vectors per (venue, symbol) across all strategies;
|
|
124
|
+
``funded`` is the deposit/withdrawal baseline that current balances
|
|
125
|
+
are compared against to measure rebalance drift.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
timestamp: datetime
|
|
129
|
+
items: list[AccountVenueExposureItem] = Field(default_factory=list)
|
|
130
|
+
funded: list[FundedCapitalItem] = Field(default_factory=list)
|