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,230 @@
|
|
|
1
|
+
from datetime import datetime, timezone
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
from typing import ClassVar, Optional
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field, model_validator
|
|
6
|
+
from trading_engine_interface.common.enums import Symbol
|
|
7
|
+
from trading_engine_interface.common.models.base_api_model import BaseApiModel
|
|
8
|
+
from trading_engine_interface.trading_engine.order_rules import ORDER_RULES
|
|
9
|
+
from typing_extensions import Self
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Position(BaseModel):
|
|
13
|
+
"""
|
|
14
|
+
Position tracking using vector arithmetic approach.
|
|
15
|
+
|
|
16
|
+
Primary storage uses (base_amount, quote_amount) as signed vector components:
|
|
17
|
+
- base_amount: Signed quantity of base asset (+ = long, - = short)
|
|
18
|
+
- quote_amount: Signed cost basis in quote asset (- = paid, + = received)
|
|
19
|
+
|
|
20
|
+
Traditional quantity/price are computed properties derived from these components.
|
|
21
|
+
This enables simple vector addition for position updates with automatic fee handling.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
symbol: Symbol
|
|
25
|
+
|
|
26
|
+
# PRIMARY STORAGE: Vector components
|
|
27
|
+
base_amount: Decimal = Field(
|
|
28
|
+
default=Decimal(0), description="Signed base asset quantity (+ = long, - = short, 0 = flat)"
|
|
29
|
+
)
|
|
30
|
+
quote_amount: Decimal = Field(
|
|
31
|
+
default=Decimal(0), description="Signed quote asset cost basis (- = cost for long, + = proceeds for short)"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# PnL tracking
|
|
35
|
+
unrealized_pnl: Decimal = Field(default=Decimal(0))
|
|
36
|
+
realized_pnl: Decimal = Field(default=Decimal(0))
|
|
37
|
+
|
|
38
|
+
entry_time: Optional[datetime] = Field(
|
|
39
|
+
default=None, description="Time when position was first opened (for holding time calculation)"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
def holding_time(self, current_time: Optional[datetime] = None) -> Optional[float]:
|
|
43
|
+
"""Calculate holding time in seconds. Returns None if entry_time not set."""
|
|
44
|
+
if not self.entry_time:
|
|
45
|
+
return None
|
|
46
|
+
end_time = current_time or datetime.now(timezone.utc)
|
|
47
|
+
return (end_time - self.entry_time).total_seconds()
|
|
48
|
+
|
|
49
|
+
def __str__(self) -> str:
|
|
50
|
+
side = "Long" if self.is_long else "Short" if self.is_short else "Flat"
|
|
51
|
+
return f"{self.symbol}: {side} ({self.quantity} @ {self.price}), PnL: {self.total_pnl}"
|
|
52
|
+
|
|
53
|
+
@model_validator(mode="after")
|
|
54
|
+
def validate_base_quote_consistency(self) -> Self:
|
|
55
|
+
"""Validate that base_amount and quote_amount are consistent."""
|
|
56
|
+
if self.base_amount == 0 and self.quote_amount != 0:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
f"Position with zero base_amount should have zero quote_amount: "
|
|
59
|
+
f"base={self.base_amount}, quote={self.quote_amount}"
|
|
60
|
+
)
|
|
61
|
+
return self
|
|
62
|
+
|
|
63
|
+
# COMPUTED PROPERTIES: Traditional fields derived from vector components
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def quantity(self) -> Decimal:
|
|
67
|
+
"""
|
|
68
|
+
Signed quantity (same as base_amount).
|
|
69
|
+
|
|
70
|
+
- Positive: Long position
|
|
71
|
+
- Negative: Short position
|
|
72
|
+
- Zero: Flat/no position
|
|
73
|
+
"""
|
|
74
|
+
return self.base_amount
|
|
75
|
+
|
|
76
|
+
# Sub-precision threshold for treating |base_amount| as "effectively zero".
|
|
77
|
+
# The smallest tradeable unit across supported venues is 1e-5 (BTC perp;
|
|
78
|
+
# ETH is 1e-4, others coarser). |base| strictly less than this can't be
|
|
79
|
+
# the result of a real venue trade — it's a sub-precision residual from
|
|
80
|
+
# imprecise close arithmetic.
|
|
81
|
+
#
|
|
82
|
+
# Without this guard, `quote_amount / base_amount` produces nonsense
|
|
83
|
+
# values like $46M for a -2.16e-6 ETH residual that retained a $100
|
|
84
|
+
# quote_amount (2026-04-30 incident dashboard symptom). The threshold is
|
|
85
|
+
# global rather than per-symbol because Position doesn't know venue
|
|
86
|
+
# min-tick rules; using the strictest precision (1e-5) is a safe lower
|
|
87
|
+
# bound — it never returns None for legitimately-sized positions.
|
|
88
|
+
_BASE_DUST_THRESHOLD: ClassVar[Decimal] = Decimal("0.00001")
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def price(self) -> Optional[Decimal]:
|
|
92
|
+
"""
|
|
93
|
+
Average entry price computed from cost basis.
|
|
94
|
+
|
|
95
|
+
Calculated as: abs(quote_amount / base_amount)
|
|
96
|
+
|
|
97
|
+
Returns None when:
|
|
98
|
+
- Position is flat (base_amount == 0)
|
|
99
|
+
- |base_amount| is sub-precision (< 1e-7) — the residual is below any
|
|
100
|
+
venue's smallest tradeable unit, so the quote/base ratio is a
|
|
101
|
+
mathematical artifact rather than an economic average price. Indicates
|
|
102
|
+
state corruption — a sub-precision residue that is not a real venue
|
|
103
|
+
position. The verification rule `position_dust_residual_misclassified`
|
|
104
|
+
surfaces this case for operator action.
|
|
105
|
+
|
|
106
|
+
Example:
|
|
107
|
+
Long 2 BTC with quote_amount = -$100,000 → price = $50,000
|
|
108
|
+
Short 2 BTC with quote_amount = +$100,000 → price = $50,000
|
|
109
|
+
Long 1e-8 BTC with quote_amount = -$50 → price = None (sub-precision)
|
|
110
|
+
"""
|
|
111
|
+
if self.base_amount == 0:
|
|
112
|
+
return None
|
|
113
|
+
if abs(self.base_amount) < self._BASE_DUST_THRESHOLD:
|
|
114
|
+
return None
|
|
115
|
+
return abs(self.quote_amount / self.base_amount)
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def total_pnl(self) -> Decimal:
|
|
119
|
+
return self.unrealized_pnl + self.realized_pnl
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def exposure(self) -> Decimal:
|
|
123
|
+
"""Current position exposure (quantity * current_price)."""
|
|
124
|
+
if self.is_flat or self.price is None:
|
|
125
|
+
return Decimal(0)
|
|
126
|
+
return abs(self.price * self.base_amount)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def is_flat(self) -> bool:
|
|
130
|
+
"""True when flat OR a sub-min residue that cannot be traded.
|
|
131
|
+
|
|
132
|
+
Min-aware: a residual that rounds below the venue's
|
|
133
|
+
min_quantity is untradeable, so it is treated as flat for every decision —
|
|
134
|
+
strategies (which gate manage/close on is_open), risk, and exposure.
|
|
135
|
+
Deciding flatness here keeps the residue as cost-basis-carrying base, so
|
|
136
|
+
realized PnL never picks up a per-fill mark. Falls back to exact-zero for
|
|
137
|
+
symbols without an ORDER_RULES entry (no min to compare against).
|
|
138
|
+
"""
|
|
139
|
+
if self.base_amount == 0:
|
|
140
|
+
return True
|
|
141
|
+
rule = ORDER_RULES.get(self.symbol)
|
|
142
|
+
if rule is None:
|
|
143
|
+
return False
|
|
144
|
+
return round(abs(self.base_amount), rule.quantity_precision) < rule.min_quantity
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def is_long(self) -> bool:
|
|
148
|
+
return self.base_amount > 0 and not self.is_flat
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def is_short(self) -> bool:
|
|
152
|
+
return self.base_amount < 0 and not self.is_flat
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def is_open(self) -> bool:
|
|
156
|
+
return not self.is_flat
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class PositionGroup(BaseApiModel):
|
|
160
|
+
strategy_id: int
|
|
161
|
+
positions: list[Position] = []
|
|
162
|
+
fills_count: int = 0
|
|
163
|
+
fills_volume: Decimal = Decimal(0)
|
|
164
|
+
|
|
165
|
+
def __str__(self) -> str:
|
|
166
|
+
"""Return readable string representation of position group."""
|
|
167
|
+
open_pos = self.open_positions
|
|
168
|
+
if not open_pos:
|
|
169
|
+
return (
|
|
170
|
+
f"PositionGroup(strategy={self.strategy_id}, "
|
|
171
|
+
f"positions=0, fills={self.fills_count}, "
|
|
172
|
+
f"PnL={self.total_pnl:.2f})"
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
positions_str = ", ".join(
|
|
176
|
+
[f"{p.symbol.value}:{('Long' if p.is_long else 'Short')}({p.quantity}@{p.price})" for p in open_pos]
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
return (
|
|
180
|
+
f"PositionGroup(strategy={self.strategy_id}, "
|
|
181
|
+
f"positions=[{positions_str}], "
|
|
182
|
+
f"fills={self.fills_count}, volume={self.fills_volume:.2f}, "
|
|
183
|
+
f"PnL={self.total_pnl:.2f} (R={self.total_realized_pnl:.2f}, U={self.total_unrealized_pnl:.2f}), "
|
|
184
|
+
f"exposure={self.total_exposure:.2f})"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# NOTE: A `validate_pnl` model_validator used to live here that asserted
|
|
188
|
+
# total_pnl == total_realized_pnl + total_unrealized_pnl
|
|
189
|
+
# That check was mathematically tautological — total_pnl is defined as
|
|
190
|
+
# sum((p.unrealized_pnl + p.realized_pnl) for p in positions)
|
|
191
|
+
# which by commutative addition equals
|
|
192
|
+
# sum(p.unrealized_pnl for p) + sum(p.realized_pnl for p)
|
|
193
|
+
# i.e. total_unrealized_pnl + total_realized_pnl. So the invariant can never
|
|
194
|
+
# be violated by position data — only by Pydantic/runtime edge cases during
|
|
195
|
+
# model_dump → reconstruct roundtrips. When such a spurious violation fired
|
|
196
|
+
# on staging (Apr 22, 2026), it crashed PositionService mid-fill-processing
|
|
197
|
+
# and halted all subsequent fills until restart + reconciliation. The check
|
|
198
|
+
# cannot detect real data inconsistency, so it was removed rather than
|
|
199
|
+
# softened — it added operational fragility without protective value.
|
|
200
|
+
|
|
201
|
+
def get_position_by_symbol(self, symbol: Symbol) -> Optional[Position]:
|
|
202
|
+
return next((p for p in self.positions if p.symbol == symbol), None)
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def symbols(self) -> set[Symbol]:
|
|
206
|
+
return {position.symbol for position in self.positions}
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def open_positions(self) -> list[Position]:
|
|
210
|
+
return [position for position in self.positions if position.is_open]
|
|
211
|
+
|
|
212
|
+
@property
|
|
213
|
+
def total_pnl(self) -> Decimal:
|
|
214
|
+
res = sum(position.total_pnl for position in self.positions)
|
|
215
|
+
return Decimal(res)
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def total_unrealized_pnl(self) -> Decimal:
|
|
219
|
+
res = sum(position.unrealized_pnl for position in self.positions)
|
|
220
|
+
return Decimal(res)
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def total_realized_pnl(self) -> Decimal:
|
|
224
|
+
res = sum(position.realized_pnl for position in self.positions)
|
|
225
|
+
return Decimal(res)
|
|
226
|
+
|
|
227
|
+
@property
|
|
228
|
+
def total_exposure(self) -> Decimal:
|
|
229
|
+
res = sum(position.exposure for position in self.positions)
|
|
230
|
+
return Decimal(res)
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field, model_validator
|
|
6
|
+
from trading_engine_interface.common.enums import Symbol
|
|
7
|
+
from trading_engine_interface.common.models.base_api_model import BaseApiModel
|
|
8
|
+
from trading_engine_interface.trading_engine.enums import Side
|
|
9
|
+
from typing_extensions import Self
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class StrategyTrade(BaseModel):
|
|
13
|
+
"""One completed round-trip trade: a position's life from open (flat -> non-flat)
|
|
14
|
+
to close (non-flat -> flat) or flip (sign reversal).
|
|
15
|
+
|
|
16
|
+
The per-record form of StrategyPositionMetrics: summing ``realized_pnl`` over a
|
|
17
|
+
strategy's trades (plus sub-min residual churn not part of any round-trip)
|
|
18
|
+
reproduces the aggregate realized PnL. ``realized_pnl`` is the PnL delta this
|
|
19
|
+
round-trip contributed, fees already encoded in the underlying fills.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
symbol: Symbol
|
|
23
|
+
side: Side = Field(description="BUY = long round-trip, SELL = short")
|
|
24
|
+
opened_at: datetime
|
|
25
|
+
closed_at: datetime
|
|
26
|
+
realized_pnl: Decimal = Field(description="Realized PnL delta booked by this round-trip")
|
|
27
|
+
notional: Decimal = Field(default=Decimal(0), ge=0, description="Closing notional at cost basis")
|
|
28
|
+
return_ratio: Decimal = Field(default=Decimal(0), description="realized_pnl / notional (0 when notional is 0)")
|
|
29
|
+
holding_seconds: float = Field(default=0, ge=0)
|
|
30
|
+
fill_count: int = Field(default=0, ge=0, description="Fills folded into this round-trip")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class StrategyPositionMetrics(BaseModel):
|
|
34
|
+
"""Metrics from closed positions"""
|
|
35
|
+
|
|
36
|
+
# Trade stats
|
|
37
|
+
trade_count: int = Field(default=0, ge=0)
|
|
38
|
+
profitable_count: int = Field(default=0, ge=0)
|
|
39
|
+
|
|
40
|
+
# PnL metrics (profits positive, losses negative)
|
|
41
|
+
total_profit: Decimal = Field(default=Decimal(0), ge=0)
|
|
42
|
+
total_loss: Decimal = Field(default=Decimal(0), le=0)
|
|
43
|
+
largest_profit: Decimal = Field(default=Decimal(0), ge=0)
|
|
44
|
+
largest_loss: Decimal = Field(default=Decimal(0), le=0)
|
|
45
|
+
|
|
46
|
+
# Return rates (as ratios 0.0-1.0, not percentages)
|
|
47
|
+
avg_profit_ratio: Decimal = Field(default=Decimal(0), ge=0, description="Average profit ratio per winning trade")
|
|
48
|
+
avg_loss_ratio: Decimal = Field(default=Decimal(0), le=0, description="Average loss ratio per losing trade")
|
|
49
|
+
|
|
50
|
+
# Sharpe ratio for the closed trades
|
|
51
|
+
sharpe_ratio: Optional[Decimal] = None
|
|
52
|
+
|
|
53
|
+
# Volume & capital usage
|
|
54
|
+
trades_volume: Decimal = Field(default=Decimal(0), ge=0, description="Total notional value of round-trip trades")
|
|
55
|
+
avg_trade_value: Decimal = Field(default=Decimal(0), ge=0, description="Average notional value per trade")
|
|
56
|
+
|
|
57
|
+
# Timing
|
|
58
|
+
avg_holding_time: float = Field(default=0, ge=0)
|
|
59
|
+
last_closed_at: Optional[datetime] = None
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def realized_pnl(self) -> Decimal:
|
|
63
|
+
return self.total_profit + self.total_loss
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def win_ratio(self) -> Decimal:
|
|
67
|
+
"""Ratio of profitable trades (0.0 to 1.0)"""
|
|
68
|
+
res = self.profitable_count / self.trade_count if self.trade_count > 0 else 0
|
|
69
|
+
return Decimal(res)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def loss_ratio(self) -> Decimal:
|
|
73
|
+
"""Ratio of losing trades (0.0 to 1.0)"""
|
|
74
|
+
return 1 - self.win_ratio
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def avg_profit(self) -> Decimal:
|
|
78
|
+
"""Average profit per winning trade"""
|
|
79
|
+
return self.total_profit / self.profitable_count if self.profitable_count > 0 else Decimal(0)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def avg_loss(self) -> Decimal:
|
|
83
|
+
"""Average loss per losing trade (negative)"""
|
|
84
|
+
loss_count = self.trade_count - self.profitable_count
|
|
85
|
+
return self.total_loss / loss_count if loss_count > 0 else Decimal(0)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def expected_pnl(self) -> Decimal:
|
|
89
|
+
"""Expected PnL per trade"""
|
|
90
|
+
return self.win_ratio * self.avg_profit + self.loss_ratio * self.avg_loss
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def expected_return_ratio(self) -> Decimal:
|
|
94
|
+
"""Expected return ratio per trade (can be negative if losses outweigh profits)"""
|
|
95
|
+
return self.win_ratio * self.avg_profit_ratio + self.loss_ratio * self.avg_loss_ratio
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def profit_margin(self) -> Decimal:
|
|
99
|
+
"""Realized PnL per dollar of trade volume (as ratio).
|
|
100
|
+
|
|
101
|
+
Measures capital efficiency: how much profit the strategy extracts per dollar cycled.
|
|
102
|
+
e.g., 0.0005 means 0.5 bps profit per dollar traded.
|
|
103
|
+
"""
|
|
104
|
+
if self.trades_volume == 0:
|
|
105
|
+
return Decimal(0)
|
|
106
|
+
return self.realized_pnl / self.trades_volume
|
|
107
|
+
|
|
108
|
+
def __str__(self) -> str:
|
|
109
|
+
return (
|
|
110
|
+
f"PnL: {self.realized_pnl} "
|
|
111
|
+
f"Trades: {self.trade_count} "
|
|
112
|
+
f"Win: {self.win_ratio:.2%} "
|
|
113
|
+
f"E[PnL]: {self.expected_pnl:.2f} "
|
|
114
|
+
f"E[Return]: {self.expected_return_ratio:.2%} "
|
|
115
|
+
f"Volume: {self.trades_volume:.2f} "
|
|
116
|
+
f"Margin: {self.profit_margin:.4%}"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class StrategyRiskMetrics(BaseModel):
|
|
121
|
+
"""Risk metrics — stateful accumulators only.
|
|
122
|
+
|
|
123
|
+
Exposure, PnL, and per-symbol values are computed at read time from PositionGroup
|
|
124
|
+
(the single source of truth) and live on StrategyMetrics, not here.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
current_drawdown: Decimal = Field(
|
|
128
|
+
default=Decimal(0), ge=0, le=1, description="Current drawdown as decimal (0.0 to 1.0)"
|
|
129
|
+
)
|
|
130
|
+
max_drawdown: Decimal = Field(
|
|
131
|
+
default=Decimal(0), ge=0, le=1, description="Maximum drawdown as decimal (0.0 to 1.0)"
|
|
132
|
+
)
|
|
133
|
+
high_water_mark: Decimal = Field(default=Decimal(0), description="Highest total profit and loss")
|
|
134
|
+
high_water_time: Optional[datetime] = None
|
|
135
|
+
|
|
136
|
+
@model_validator(mode="after")
|
|
137
|
+
def validate_drawdown(self) -> Self:
|
|
138
|
+
if self.current_drawdown > self.max_drawdown:
|
|
139
|
+
raise ValueError("Current drawdown exceeds maximum drawdown")
|
|
140
|
+
return self
|
|
141
|
+
|
|
142
|
+
def __str__(self) -> str:
|
|
143
|
+
return f"Drawdown: {self.current_drawdown}, Max Drawdown: {self.max_drawdown}, HWM: {self.high_water_mark}"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class ReturnDistribution(BaseModel):
|
|
147
|
+
"""Distribution statistics for returns"""
|
|
148
|
+
|
|
149
|
+
mean: float = Field(default=0)
|
|
150
|
+
std_dev: float = Field(default=0)
|
|
151
|
+
skewness: float = Field(default=0)
|
|
152
|
+
kurtosis: float = Field(default=0)
|
|
153
|
+
percentile_95: float = Field(default=0)
|
|
154
|
+
percentile_5: float = Field(default=0)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class StrategyMetrics(BaseApiModel):
|
|
158
|
+
"""Strategy performance metrics"""
|
|
159
|
+
|
|
160
|
+
strategy_id: int
|
|
161
|
+
position_metrics: StrategyPositionMetrics
|
|
162
|
+
risk_metrics: StrategyRiskMetrics
|
|
163
|
+
return_dist: Optional[ReturnDistribution] = None
|
|
164
|
+
|
|
165
|
+
# Position-derived fields — computed at read time from PositionGroup (single source of truth).
|
|
166
|
+
total_pnl: Decimal = Field(default=Decimal(0), description="Total PnL from position_group")
|
|
167
|
+
current_exposure: Decimal = Field(default=Decimal(0), description="Current exposure from position_group")
|
|
168
|
+
open_positions_count: int = Field(default=0, ge=0, description="Open positions from position_group")
|
|
169
|
+
symbol_exposures: dict[str, Decimal] = Field(
|
|
170
|
+
default_factory=dict, description="Per-symbol exposure from position_group"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def __str__(self) -> str:
|
|
174
|
+
return f"Strategy {self.strategy_id} metrics: {self.position_metrics}, {self.risk_metrics}"
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def realized_pnl(self) -> Decimal:
|
|
178
|
+
return self.position_metrics.realized_pnl
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def trades_volume(self) -> Decimal:
|
|
182
|
+
"""Total notional value of round-trip trades."""
|
|
183
|
+
return self.position_metrics.trades_volume
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def profit_margin(self) -> Decimal:
|
|
187
|
+
"""Realized PnL per dollar of trade volume."""
|
|
188
|
+
return self.position_metrics.profit_margin
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def current_drawdown(self) -> Decimal:
|
|
192
|
+
return self.risk_metrics.current_drawdown
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def max_drawdown(self) -> Decimal:
|
|
196
|
+
return self.risk_metrics.max_drawdown
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def win_ratio(self) -> Decimal:
|
|
200
|
+
return self.position_metrics.win_ratio
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def sharpe_ratio(self) -> Optional[Decimal]:
|
|
204
|
+
return self.position_metrics.sharpe_ratio
|