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,386 @@
|
|
|
1
|
+
"""Pure position-vector math — the domain-tier home for these functions.
|
|
2
|
+
|
|
3
|
+
These functions were originally ported into `app/backtest/in_memory_portfolio.py`
|
|
4
|
+
(the lightweight backtest portfolio) and `PositionService` imported them back from
|
|
5
|
+
there — a live→backtest dependency inversion (the live money-path reaching into a
|
|
6
|
+
backtest module). They now live in the domain tier (`app/domain/`), which sits
|
|
7
|
+
below both the live engine (`app/services`) and the backtest harness, so neither
|
|
8
|
+
depends "up" into the other. `PositionService` imports from here, and
|
|
9
|
+
`in_memory_portfolio` re-exports from here until the backtest portfolio moves into
|
|
10
|
+
its own package, at which point the backtest package will
|
|
11
|
+
carry its own copy.
|
|
12
|
+
|
|
13
|
+
Pure functions over interface models — `trading_engine_interface` is the only
|
|
14
|
+
dependency. No service state, no I/O.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from decimal import Decimal
|
|
20
|
+
from typing import Optional
|
|
21
|
+
|
|
22
|
+
from trading_engine_interface.common.enums import Symbol
|
|
23
|
+
from trading_engine_interface.trading_engine.enums import Side
|
|
24
|
+
from trading_engine_interface.trading_engine.models.order_models import Fill
|
|
25
|
+
from trading_engine_interface.trading_engine.models.position_models import Position
|
|
26
|
+
from trading_engine_interface.trading_engine.models.strategy_metrics_models import (
|
|
27
|
+
StrategyPositionMetrics,
|
|
28
|
+
StrategyTrade,
|
|
29
|
+
)
|
|
30
|
+
from trading_engine_interface.trading_engine.order_rules import ORDER_RULES
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _is_effectively_flat(symbol: Symbol, base_amount: Decimal) -> bool:
|
|
34
|
+
"""True when |base_amount| rounds below the symbol's min tradeable size.
|
|
35
|
+
|
|
36
|
+
A position reduced to a sub-min residual is economically flat even though
|
|
37
|
+
base_amount is rarely exactly 0 (fees + multi-partial fills almost never
|
|
38
|
+
land on zero). It is the single source of the engine's flatness semantics
|
|
39
|
+
(Position.is_flat is min-aware via the same rule). Falls back to an
|
|
40
|
+
exact-zero check for symbols without an ORDER_RULES entry.
|
|
41
|
+
"""
|
|
42
|
+
if base_amount == 0:
|
|
43
|
+
return True
|
|
44
|
+
if symbol not in ORDER_RULES:
|
|
45
|
+
return False
|
|
46
|
+
rule = ORDER_RULES[symbol]
|
|
47
|
+
return round(abs(base_amount), rule.quantity_precision) < rule.min_quantity
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def update_position(position: Position, fill: Fill) -> None:
|
|
51
|
+
"""Update position using vector arithmetic.
|
|
52
|
+
|
|
53
|
+
Ported from PositionService._update_position (app/services/position_service.py:335).
|
|
54
|
+
Uses fill.base_amount and fill.quote_amount which already include fees.
|
|
55
|
+
"""
|
|
56
|
+
fill_base = fill.base_amount
|
|
57
|
+
fill_quote = fill.quote_amount
|
|
58
|
+
|
|
59
|
+
prev_base = position.base_amount
|
|
60
|
+
prev_quote = position.quote_amount
|
|
61
|
+
|
|
62
|
+
is_closing = (prev_base > 0 > fill_base) or (prev_base < 0 < fill_base)
|
|
63
|
+
|
|
64
|
+
# === 1. Update base_amount, quote_amount, realized_pnl ===
|
|
65
|
+
if prev_base == 0 or not is_closing:
|
|
66
|
+
# Opening or increasing position: simple vector addition
|
|
67
|
+
position.base_amount += fill_base
|
|
68
|
+
position.quote_amount += fill_quote
|
|
69
|
+
else:
|
|
70
|
+
# Closing or reversing: calculate realized PnL
|
|
71
|
+
closing_qty = min(abs(fill_base), abs(prev_base))
|
|
72
|
+
|
|
73
|
+
pos_closed_quote = prev_quote * (closing_qty / abs(prev_base))
|
|
74
|
+
fill_closed_quote = fill_quote * (closing_qty / abs(fill_base))
|
|
75
|
+
|
|
76
|
+
realized_pnl = pos_closed_quote + fill_closed_quote
|
|
77
|
+
position.realized_pnl += realized_pnl
|
|
78
|
+
|
|
79
|
+
position.base_amount += fill_base
|
|
80
|
+
position.quote_amount += fill_quote - realized_pnl
|
|
81
|
+
|
|
82
|
+
# === 2. Update unrealized_pnl ===
|
|
83
|
+
if position.base_amount != 0:
|
|
84
|
+
current_value = position.base_amount * fill.price
|
|
85
|
+
cost_basis = -position.quote_amount
|
|
86
|
+
position.unrealized_pnl = current_value - cost_basis
|
|
87
|
+
else:
|
|
88
|
+
position.unrealized_pnl = Decimal(0)
|
|
89
|
+
|
|
90
|
+
# === 3. Update entry_time ===
|
|
91
|
+
# Reset on the ECONOMIC open/close of a position, treating a sub-min residual
|
|
92
|
+
# as flat. Keying on exact base==0 here pinned entry_time to the original entry
|
|
93
|
+
# whenever a position was reduced to dust and re-entered same-direction (base
|
|
94
|
+
# rarely lands on exactly 0 after fees/partials), so every later partial close
|
|
95
|
+
# re-measured holding from a stale anchor — avg_holding_time then summed
|
|
96
|
+
# overlapping intervals far past wall-clock (2026-06-08: holding-days exceeded
|
|
97
|
+
# the strategy's age). entry_time is
|
|
98
|
+
# metrics-only (holding time); this touches neither base/quote nor realized_pnl,
|
|
99
|
+
# so trade_count and PnL are unchanged.
|
|
100
|
+
prev_flat = _is_effectively_flat(position.symbol, prev_base)
|
|
101
|
+
now_flat = _is_effectively_flat(position.symbol, position.base_amount)
|
|
102
|
+
if prev_flat and not now_flat:
|
|
103
|
+
position.entry_time = fill.timestamp
|
|
104
|
+
elif now_flat:
|
|
105
|
+
position.entry_time = None
|
|
106
|
+
elif prev_base * position.base_amount < 0:
|
|
107
|
+
position.entry_time = fill.timestamp
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def group_fills_by_order(fills: list[Fill]) -> list[list[Fill]]:
|
|
111
|
+
"""Group consecutive fills by order_id, preserving chronological order.
|
|
112
|
+
|
|
113
|
+
Ported from PositionService._group_fills_by_order (app/services/position_service.py:498).
|
|
114
|
+
"""
|
|
115
|
+
order_groups: list[list[Fill]] = []
|
|
116
|
+
current_order_id: Optional[int] = None
|
|
117
|
+
current_group: list[Fill] = []
|
|
118
|
+
|
|
119
|
+
for fill in fills:
|
|
120
|
+
fill_order_id = fill.order_id
|
|
121
|
+
if fill_order_id is not None and fill_order_id == current_order_id:
|
|
122
|
+
current_group.append(fill)
|
|
123
|
+
else:
|
|
124
|
+
if current_group:
|
|
125
|
+
order_groups.append(current_group)
|
|
126
|
+
current_order_id = fill_order_id
|
|
127
|
+
current_group = [fill]
|
|
128
|
+
if current_group:
|
|
129
|
+
order_groups.append(current_group)
|
|
130
|
+
|
|
131
|
+
return order_groups
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass
|
|
135
|
+
class _Episode:
|
|
136
|
+
"""An in-flight round-trip: a position's life from open to close/flip."""
|
|
137
|
+
|
|
138
|
+
start: datetime
|
|
139
|
+
realized: Decimal
|
|
140
|
+
notional: Decimal
|
|
141
|
+
side: Side = Side.BUY # BUY = long round-trip, SELL = short
|
|
142
|
+
fill_count: int = 1
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class MetricsFold:
|
|
146
|
+
"""Incremental left-fold over a strategy's fill stream producing StrategyPositionMetrics.
|
|
147
|
+
|
|
148
|
+
A "trade" is a per-leg ROUND-TRIP episode: the life of a position from open
|
|
149
|
+
(flat -> non-flat) to close (non-flat -> flat) or flip (sign reversal). One
|
|
150
|
+
trade is booked per episode, aggregating any partial closes into a single
|
|
151
|
+
realized P/L, holding interval, and notional. This is NOT one-trade-per-order:
|
|
152
|
+
a position closed across three partial orders is ONE round-trip, and a
|
|
153
|
+
multi-leg strategy counts each leg's round-trips separately.
|
|
154
|
+
|
|
155
|
+
Episode boundaries are exactly update_position's entry_time resets (open /
|
|
156
|
+
close-to-flat / flip), where "flat" means a sub-min residual (fees + partial
|
|
157
|
+
fills rarely land base on exactly 0 — see _is_effectively_flat).
|
|
158
|
+
|
|
159
|
+
PnL identity is preserved: total_profit + total_loss == the full realized PnL
|
|
160
|
+
== the cash-flow PnL. Realized booked while no episode is open (sub-min dust
|
|
161
|
+
churn) or inside a still-open episode at snapshot time is folded into the
|
|
162
|
+
profit/loss totals by sign but does NOT count as a completed trade — so the
|
|
163
|
+
headline PnL is unchanged while the round-trip count stays honest.
|
|
164
|
+
|
|
165
|
+
The fold is strictly per-fill with no lookahead, so feeding fills one at a
|
|
166
|
+
time (or in any chunking) yields the same state as one batch pass — this is
|
|
167
|
+
what lets PositionService cache fold state per strategy and fold only the
|
|
168
|
+
fill-table tail on each read instead of replaying the full history (the
|
|
169
|
+
unbounded replay on every /summary poll was the dominant steady-state
|
|
170
|
+
event-loop + GC load). Fills are append-only, so a fold cursor
|
|
171
|
+
keyed on Fill.id never needs invalidation.
|
|
172
|
+
|
|
173
|
+
snapshot() is non-mutating: it can be taken at any point and folding can
|
|
174
|
+
continue afterwards.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
def __init__(self, risk_free_rate: float = 0.0, collect_trades: bool = False) -> None:
|
|
178
|
+
self._risk_free_rate = risk_free_rate
|
|
179
|
+
# Per-round-trip trade records (StrategyTrade), only kept when
|
|
180
|
+
# collect_trades=True. Default OFF: the retained per-strategy folds
|
|
181
|
+
# (the metrics cache) must stay O(1) memory for the process lifetime
|
|
182
|
+
# (an unbounded per-trade list here is exactly what an earlier fix
|
|
183
|
+
# removed). Collect-on folds are for transient, request-scoped
|
|
184
|
+
# derivation (the /strategies/{id}/trades endpoint), where the list
|
|
185
|
+
# dies with the request.
|
|
186
|
+
self._collect_trades = collect_trades
|
|
187
|
+
self._trades: list[StrategyTrade] = []
|
|
188
|
+
self._positions: dict[Symbol, Position] = {}
|
|
189
|
+
self._open_episodes: dict[Symbol, Optional[_Episode]] = {}
|
|
190
|
+
# Realized that is real cash flow but not part of a completed round-trip
|
|
191
|
+
# (sub-min dust churn) — kept in the PnL totals, excluded from the count.
|
|
192
|
+
self._residual_pnl = Decimal(0)
|
|
193
|
+
self._last_closed_at: Optional[datetime] = None
|
|
194
|
+
# Accumulators over completed round-trips.
|
|
195
|
+
self._trade_count = 0
|
|
196
|
+
self._profitable_count = 0
|
|
197
|
+
self._total_profit = Decimal(0)
|
|
198
|
+
self._total_loss = Decimal(0)
|
|
199
|
+
self._largest_profit = Decimal(0)
|
|
200
|
+
self._largest_loss = Decimal(0)
|
|
201
|
+
self._total_profit_ratio = Decimal(0)
|
|
202
|
+
self._total_loss_ratio = Decimal(0)
|
|
203
|
+
self._total_value = Decimal(0)
|
|
204
|
+
self._total_holding_time = 0.0
|
|
205
|
+
# Running mean / sum-of-squared-deviations (Welford) over per-round-trip
|
|
206
|
+
# returns — O(1) state for the Sharpe stddev. Replaces an unbounded
|
|
207
|
+
# list[float] that grew one entry per closed trade for the process lifetime
|
|
208
|
+
# (the fold is retained per strategy by the metrics cache), leaking the live
|
|
209
|
+
# heap and growing gen2 GC pause time with uptime. Welford is used
|
|
210
|
+
# over a sum/sum-of-squares accumulator because trade returns cluster
|
|
211
|
+
# tightly near zero, where sumsq - sum^2/n catastrophically cancels.
|
|
212
|
+
self._returns_mean = 0.0
|
|
213
|
+
self._returns_m2 = 0.0
|
|
214
|
+
|
|
215
|
+
def fold(self, fill: Fill) -> None:
|
|
216
|
+
"""Advance the fold by one fill. Fills must arrive in fill-table order."""
|
|
217
|
+
symbol = fill.symbol
|
|
218
|
+
if symbol not in self._positions:
|
|
219
|
+
self._positions[symbol] = Position(symbol=symbol)
|
|
220
|
+
position = self._positions[symbol]
|
|
221
|
+
|
|
222
|
+
prev_base = position.base_amount
|
|
223
|
+
prev_quote = position.quote_amount
|
|
224
|
+
prev_realized = position.realized_pnl
|
|
225
|
+
|
|
226
|
+
update_position(position, fill)
|
|
227
|
+
# Realized PnL comes purely from update_position's closing logic — the
|
|
228
|
+
# cash-flow PnL (for a flat strategy, Sum(fill.quote_amount)). A leftover
|
|
229
|
+
# sub-min residue is an open untradeable position whose value is unrealized,
|
|
230
|
+
# never booked into realized (the dust bucket and its per-fill
|
|
231
|
+
# mark-as-realized are gone).
|
|
232
|
+
|
|
233
|
+
realized_delta = position.realized_pnl - prev_realized
|
|
234
|
+
if realized_delta != 0 and prev_base != 0:
|
|
235
|
+
closing_qty = min(abs(fill.base_amount), abs(prev_base))
|
|
236
|
+
fill_notional = abs(prev_quote * (closing_qty / abs(prev_base)))
|
|
237
|
+
else:
|
|
238
|
+
fill_notional = Decimal(0)
|
|
239
|
+
|
|
240
|
+
prev_flat = _is_effectively_flat(symbol, prev_base)
|
|
241
|
+
now_flat = _is_effectively_flat(symbol, position.base_amount)
|
|
242
|
+
opened = prev_flat and not now_flat
|
|
243
|
+
closed = not prev_flat and now_flat
|
|
244
|
+
flipped = not prev_flat and not now_flat and prev_base * position.base_amount < 0
|
|
245
|
+
episode = self._open_episodes.get(symbol)
|
|
246
|
+
|
|
247
|
+
if opened:
|
|
248
|
+
# A fresh round-trip owns this fill's realized/notional. (not prev_flat
|
|
249
|
+
# below guarantees an open episode, so no else-branch is reachable.)
|
|
250
|
+
side = Side.BUY if position.base_amount > 0 else Side.SELL
|
|
251
|
+
self._open_episodes[symbol] = _Episode(fill.timestamp, realized_delta, fill_notional, side)
|
|
252
|
+
elif episode is not None:
|
|
253
|
+
# Mid-episode fill: accumulate into the open round-trip.
|
|
254
|
+
episode.realized += realized_delta
|
|
255
|
+
episode.notional += fill_notional
|
|
256
|
+
episode.fill_count += 1
|
|
257
|
+
if closed or flipped:
|
|
258
|
+
holding = max(0.0, (fill.timestamp - episode.start).total_seconds())
|
|
259
|
+
self._complete_round_trip(episode.realized, episode.notional, holding)
|
|
260
|
+
self._last_closed_at = fill.timestamp
|
|
261
|
+
if self._collect_trades:
|
|
262
|
+
self._trades.append(
|
|
263
|
+
StrategyTrade(
|
|
264
|
+
symbol=symbol,
|
|
265
|
+
side=episode.side,
|
|
266
|
+
opened_at=episode.start,
|
|
267
|
+
closed_at=fill.timestamp,
|
|
268
|
+
realized_pnl=episode.realized,
|
|
269
|
+
notional=episode.notional,
|
|
270
|
+
return_ratio=episode.realized / episode.notional if episode.notional > 0 else Decimal(0),
|
|
271
|
+
holding_seconds=holding,
|
|
272
|
+
fill_count=episode.fill_count,
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
# A flip immediately opens the opposite-side round-trip here.
|
|
276
|
+
if flipped:
|
|
277
|
+
side = Side.BUY if position.base_amount > 0 else Side.SELL
|
|
278
|
+
self._open_episodes[symbol] = _Episode(fill.timestamp, Decimal(0), Decimal(0), side)
|
|
279
|
+
else:
|
|
280
|
+
self._open_episodes[symbol] = None
|
|
281
|
+
else:
|
|
282
|
+
# Churn while flat (sub-min dust): real cash flow, not a round-trip.
|
|
283
|
+
self._residual_pnl += realized_delta
|
|
284
|
+
|
|
285
|
+
def _complete_round_trip(self, realized: Decimal, notional: Decimal, holding_seconds: float) -> None:
|
|
286
|
+
self._trade_count += 1
|
|
287
|
+
self._total_value += notional
|
|
288
|
+
self._total_holding_time += holding_seconds
|
|
289
|
+
# Welford online update; sample count is self._trade_count (incremented above),
|
|
290
|
+
# one return per completed round-trip — same population the old list held.
|
|
291
|
+
ret = float(realized / notional) if notional > 0 else 0.0
|
|
292
|
+
delta = ret - self._returns_mean
|
|
293
|
+
self._returns_mean += delta / self._trade_count
|
|
294
|
+
self._returns_m2 += delta * (ret - self._returns_mean)
|
|
295
|
+
if realized > 0:
|
|
296
|
+
self._profitable_count += 1
|
|
297
|
+
self._total_profit += realized
|
|
298
|
+
self._largest_profit = max(self._largest_profit, realized)
|
|
299
|
+
self._total_profit_ratio += realized / notional if notional > 0 else Decimal(0)
|
|
300
|
+
else:
|
|
301
|
+
self._total_loss += realized
|
|
302
|
+
self._largest_loss = min(self._largest_loss, realized)
|
|
303
|
+
self._total_loss_ratio += realized / notional if notional > 0 else Decimal(0)
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def collected_trades(self) -> list[StrategyTrade]:
|
|
307
|
+
"""Completed round-trip trade records, in close order (fold order).
|
|
308
|
+
|
|
309
|
+
Only populated when the fold was constructed with collect_trades=True;
|
|
310
|
+
empty otherwise. Same episode boundaries as the aggregate metrics, so
|
|
311
|
+
len(collected_trades) == snapshot().trade_count by construction. Named
|
|
312
|
+
to avoid colliding with the backtest ``_TradeCollectingFold.trades``.
|
|
313
|
+
"""
|
|
314
|
+
return self._trades
|
|
315
|
+
|
|
316
|
+
def snapshot(self) -> StrategyPositionMetrics:
|
|
317
|
+
"""Build the metrics model from the current fold state, without mutating it."""
|
|
318
|
+
total_profit = self._total_profit
|
|
319
|
+
total_loss = self._total_loss
|
|
320
|
+
|
|
321
|
+
# Still-open episodes haven't completed a round-trip; their realized stays
|
|
322
|
+
# in the PnL totals (cash flow) but is not counted as a trade. Folded here
|
|
323
|
+
# (not into the accumulators) so continuing the fold stays correct.
|
|
324
|
+
residual_pnl = self._residual_pnl
|
|
325
|
+
for episode in self._open_episodes.values():
|
|
326
|
+
if episode is not None:
|
|
327
|
+
residual_pnl += episode.realized
|
|
328
|
+
# A leftover sub-min residue is NOT booked into realized (no absorb mark):
|
|
329
|
+
# it is an open untradeable position whose value is unrealized, on
|
|
330
|
+
# the live Position, not here. Metrics realized is pure closing logic, equal to
|
|
331
|
+
# the reconcile recompute by construction (closes an earlier special-case).
|
|
332
|
+
# Fold non-round-trip realized into the totals so total_profit + total_loss
|
|
333
|
+
# equals the full realized (cash-flow) PnL while the trade count stays honest.
|
|
334
|
+
if residual_pnl > 0:
|
|
335
|
+
total_profit += residual_pnl
|
|
336
|
+
elif residual_pnl < 0:
|
|
337
|
+
total_loss += residual_pnl
|
|
338
|
+
|
|
339
|
+
trade_count = self._trade_count
|
|
340
|
+
profitable_count = self._profitable_count
|
|
341
|
+
avg_profit_ratio = self._total_profit_ratio / profitable_count if profitable_count > 0 else Decimal(0)
|
|
342
|
+
loss_count = trade_count - profitable_count
|
|
343
|
+
avg_loss_ratio = self._total_loss_ratio / loss_count if loss_count > 0 else Decimal(0)
|
|
344
|
+
avg_trade_value = self._total_value / trade_count if trade_count > 0 else Decimal(0)
|
|
345
|
+
avg_holding_time = self._total_holding_time / trade_count if trade_count > 0 else 0.0
|
|
346
|
+
|
|
347
|
+
sharpe_ratio: Optional[Decimal] = None
|
|
348
|
+
if self._trade_count > 1:
|
|
349
|
+
# Sample variance (n-1), matching the prior statistics.stdev.
|
|
350
|
+
variance = self._returns_m2 / (self._trade_count - 1)
|
|
351
|
+
if variance > 0:
|
|
352
|
+
std_dev = variance**0.5
|
|
353
|
+
sharpe_ratio = Decimal(str((self._returns_mean - self._risk_free_rate) / std_dev))
|
|
354
|
+
|
|
355
|
+
return StrategyPositionMetrics(
|
|
356
|
+
trade_count=trade_count,
|
|
357
|
+
profitable_count=profitable_count,
|
|
358
|
+
total_profit=total_profit,
|
|
359
|
+
total_loss=total_loss,
|
|
360
|
+
largest_profit=self._largest_profit,
|
|
361
|
+
largest_loss=self._largest_loss,
|
|
362
|
+
avg_profit_ratio=avg_profit_ratio,
|
|
363
|
+
avg_loss_ratio=avg_loss_ratio,
|
|
364
|
+
sharpe_ratio=sharpe_ratio,
|
|
365
|
+
trades_volume=self._total_value,
|
|
366
|
+
avg_trade_value=avg_trade_value,
|
|
367
|
+
avg_holding_time=avg_holding_time,
|
|
368
|
+
last_closed_at=self._last_closed_at,
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def compute_position_metrics(fills: list[Fill], risk_free_rate: float = 0.0) -> StrategyPositionMetrics:
|
|
373
|
+
"""Compute strategy position metrics from a complete fill history (batch form).
|
|
374
|
+
|
|
375
|
+
Thin wrapper over MetricsFold — see its docstring for the trade definition
|
|
376
|
+
(per-leg round-trip episodes) and the PnL identity. Folding fills one batch at
|
|
377
|
+
a time through a held MetricsFold yields the identical result; this helper is
|
|
378
|
+
for callers that have the whole history in hand (backtest, tests).
|
|
379
|
+
"""
|
|
380
|
+
if not fills:
|
|
381
|
+
return StrategyPositionMetrics()
|
|
382
|
+
|
|
383
|
+
fold = MetricsFold(risk_free_rate)
|
|
384
|
+
for fill in fills:
|
|
385
|
+
fold.fold(fill)
|
|
386
|
+
return fold.snapshot()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Example strategies written against the contract."""
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Quickstart: one strategy written against the published contract.
|
|
2
|
+
|
|
3
|
+
Rests one limit buy at the best bid on every trading venue the config allows,
|
|
4
|
+
and does nothing while an order is already open. It is the smallest class that
|
|
5
|
+
satisfies ``StrategyProtocol``; a real strategy replaces ``decide``.
|
|
6
|
+
|
|
7
|
+
Run it once against a hand-built order book:
|
|
8
|
+
|
|
9
|
+
python -m trading_engine_interface.examples.touch_bid_strategy
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from typing import Any, Optional
|
|
17
|
+
|
|
18
|
+
from trading_engine_interface import (
|
|
19
|
+
AccountPermissionConfig,
|
|
20
|
+
BaseStrategyConfig,
|
|
21
|
+
CreateOrderRequest,
|
|
22
|
+
OrderBook,
|
|
23
|
+
OrderType,
|
|
24
|
+
Position,
|
|
25
|
+
PositionParams,
|
|
26
|
+
RiskLimitConfig,
|
|
27
|
+
RuntimeConfig,
|
|
28
|
+
Side,
|
|
29
|
+
SkipReason,
|
|
30
|
+
StrategyInput,
|
|
31
|
+
StrategyOutput,
|
|
32
|
+
StrategyPredictions,
|
|
33
|
+
Symbol,
|
|
34
|
+
TradeFee,
|
|
35
|
+
VenueName,
|
|
36
|
+
)
|
|
37
|
+
from trading_engine_interface.runtime import StrategyProtocol, register_strategy
|
|
38
|
+
from trading_engine_interface.trading_engine.models.market_models import OrderBookEntry
|
|
39
|
+
from trading_engine_interface.trading_engine.models.position_models import PositionGroup
|
|
40
|
+
from trading_engine_interface.trading_engine.models.strategy_models import StrategyMarketData
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TouchBidConfig(BaseStrategyConfig):
|
|
44
|
+
# A config names its strategy class and carries its own defaults, so a runner
|
|
45
|
+
# can build it from the venues, symbols and limits alone.
|
|
46
|
+
class_type: str = "TouchBidStrategy"
|
|
47
|
+
position: PositionParams = PositionParams()
|
|
48
|
+
quantity: Decimal = Decimal("0.001")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@register_strategy(config=TouchBidConfig)
|
|
52
|
+
class TouchBidStrategy:
|
|
53
|
+
VERSION: int = 1
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
config: BaseStrategyConfig,
|
|
58
|
+
order_permissions: Optional[dict[Symbol, dict[VenueName, list[OrderType]]]] = None,
|
|
59
|
+
fees: Optional[dict[Symbol, dict[VenueName, TradeFee]]] = None,
|
|
60
|
+
**kwargs: Any,
|
|
61
|
+
) -> None:
|
|
62
|
+
assert isinstance(config, TouchBidConfig)
|
|
63
|
+
self.config = config
|
|
64
|
+
self.fees: dict[Symbol, dict[VenueName, TradeFee]] = fees or {}
|
|
65
|
+
self._output = StrategyOutput()
|
|
66
|
+
|
|
67
|
+
def decide(self, input_data: StrategyInput, predictions: Optional[StrategyPredictions] = None) -> StrategyOutput:
|
|
68
|
+
if input_data.open_orders:
|
|
69
|
+
return self.flush_output(skip_reason=SkipReason.OPEN_ORDERS)
|
|
70
|
+
for symbol, venues in self.config.symbol_to_venues.items():
|
|
71
|
+
for venue in venues:
|
|
72
|
+
book = input_data.market_data.order_books.get(symbol, {}).get(venue)
|
|
73
|
+
bid = book.best_bid_price if book else None
|
|
74
|
+
if bid is None:
|
|
75
|
+
continue
|
|
76
|
+
self._output.create_orders.append(
|
|
77
|
+
CreateOrderRequest(
|
|
78
|
+
venue=venue,
|
|
79
|
+
symbol=symbol,
|
|
80
|
+
order_type=OrderType.LIMIT,
|
|
81
|
+
side=Side.BUY,
|
|
82
|
+
quantity=self.config.quantity,
|
|
83
|
+
price=bid,
|
|
84
|
+
)
|
|
85
|
+
)
|
|
86
|
+
return self.flush_output(skip_reason=None if self._output.create_orders else SkipReason.NO_DATA)
|
|
87
|
+
|
|
88
|
+
def close_position(
|
|
89
|
+
self,
|
|
90
|
+
position: Position,
|
|
91
|
+
order_book: OrderBook,
|
|
92
|
+
input_data: Optional[StrategyInput] = None,
|
|
93
|
+
exit_type: Any = None,
|
|
94
|
+
) -> bool:
|
|
95
|
+
return False # never holds a position long enough to need the engine's close path
|
|
96
|
+
|
|
97
|
+
def flush_output(self, skip_reason: Optional[Any] = None, **skip_metrics: float) -> StrategyOutput:
|
|
98
|
+
output = self._output
|
|
99
|
+
if not output.has_actions:
|
|
100
|
+
output.skip_reason = skip_reason
|
|
101
|
+
output.skip_metrics = dict(skip_metrics)
|
|
102
|
+
self._output = StrategyOutput()
|
|
103
|
+
return output
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def demo() -> StrategyOutput:
|
|
107
|
+
config = TouchBidConfig(
|
|
108
|
+
account_permission=AccountPermissionConfig.from_venues_symbols([VenueName.OKX], [Symbol.BTC_USDT]),
|
|
109
|
+
risk_limit=RiskLimitConfig(),
|
|
110
|
+
runtime=RuntimeConfig(run_interval=2.0),
|
|
111
|
+
trading_symbols=[Symbol.BTC_USDT],
|
|
112
|
+
)
|
|
113
|
+
strategy: StrategyProtocol = TouchBidStrategy(config)
|
|
114
|
+
book = OrderBook(
|
|
115
|
+
venue=VenueName.OKX,
|
|
116
|
+
symbol=Symbol.BTC_USDT,
|
|
117
|
+
timestamp=datetime.now(timezone.utc),
|
|
118
|
+
bids=[OrderBookEntry(price=Decimal("100000"), quantity=Decimal("1"))],
|
|
119
|
+
asks=[OrderBookEntry(price=Decimal("100001"), quantity=Decimal("1"))],
|
|
120
|
+
)
|
|
121
|
+
input_data = StrategyInput(
|
|
122
|
+
market_data=StrategyMarketData(order_books={Symbol.BTC_USDT: {VenueName.OKX: book}}),
|
|
123
|
+
position_group=PositionGroup(strategy_id=1),
|
|
124
|
+
open_orders=[],
|
|
125
|
+
)
|
|
126
|
+
return strategy.decide(input_data)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
if __name__ == "__main__":
|
|
130
|
+
for order in demo().create_orders:
|
|
131
|
+
print(order)
|
|
File without changes
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Strategy runtime contract — shared by engine and strategies.
|
|
2
|
+
|
|
3
|
+
The runtime submodule holds:
|
|
4
|
+
- The ``Strategy`` Protocol (the type the engine enforces).
|
|
5
|
+
- The strategy registry (``STRATEGY_REGISTRY``, ``StrategyRegistry``,
|
|
6
|
+
``RegistryEntry``) and the ``@register_strategy`` decorator strategies use
|
|
7
|
+
to opt in.
|
|
8
|
+
|
|
9
|
+
Engine code imports from here; strategies decorate themselves with
|
|
10
|
+
``@register_strategy`` from here. Neither side imports the other.
|
|
11
|
+
|
|
12
|
+
Discovery (walking packages to trigger registration) stays in engine code
|
|
13
|
+
because it knows engine-side package namespaces.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from trading_engine_interface.runtime.registry import (
|
|
17
|
+
STRATEGY_REGISTRY,
|
|
18
|
+
RegistryEntry,
|
|
19
|
+
StrategyRegistry,
|
|
20
|
+
register_production_configs,
|
|
21
|
+
register_strategy,
|
|
22
|
+
)
|
|
23
|
+
from trading_engine_interface.runtime.strategy import StrategyProtocol
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"StrategyProtocol",
|
|
27
|
+
"STRATEGY_REGISTRY",
|
|
28
|
+
"StrategyRegistry",
|
|
29
|
+
"RegistryEntry",
|
|
30
|
+
"register_strategy",
|
|
31
|
+
"register_production_configs",
|
|
32
|
+
]
|