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.
Files changed (33) hide show
  1. trading_engine_interface/__init__.py +334 -0
  2. trading_engine_interface/common/__init__.py +0 -0
  3. trading_engine_interface/common/enums.py +163 -0
  4. trading_engine_interface/common/errors.py +259 -0
  5. trading_engine_interface/common/models/__init__.py +3 -0
  6. trading_engine_interface/common/models/base_api_model.py +14 -0
  7. trading_engine_interface/common/utils.py +20 -0
  8. trading_engine_interface/domain/__init__.py +8 -0
  9. trading_engine_interface/domain/fill_simulator.py +114 -0
  10. trading_engine_interface/domain/maker_fill.py +138 -0
  11. trading_engine_interface/domain/position_math.py +386 -0
  12. trading_engine_interface/examples/__init__.py +1 -0
  13. trading_engine_interface/examples/touch_bid_strategy.py +131 -0
  14. trading_engine_interface/py.typed +0 -0
  15. trading_engine_interface/runtime/__init__.py +32 -0
  16. trading_engine_interface/runtime/registry.py +298 -0
  17. trading_engine_interface/runtime/strategy.py +94 -0
  18. trading_engine_interface/trading_engine/__init__.py +0 -0
  19. trading_engine_interface/trading_engine/enums.py +284 -0
  20. trading_engine_interface/trading_engine/models/__init__.py +0 -0
  21. trading_engine_interface/trading_engine/models/accounting_models.py +412 -0
  22. trading_engine_interface/trading_engine/models/backtest_models.py +200 -0
  23. trading_engine_interface/trading_engine/models/market_models.py +452 -0
  24. trading_engine_interface/trading_engine/models/order_models.py +520 -0
  25. trading_engine_interface/trading_engine/models/position_breakdown_models.py +130 -0
  26. trading_engine_interface/trading_engine/models/position_models.py +230 -0
  27. trading_engine_interface/trading_engine/models/strategy_metrics_models.py +204 -0
  28. trading_engine_interface/trading_engine/models/strategy_models.py +1360 -0
  29. trading_engine_interface/trading_engine/order_rules.py +209 -0
  30. trading_engine_interface-0.56.25.dist-info/LICENSE +21 -0
  31. trading_engine_interface-0.56.25.dist-info/METADATA +112 -0
  32. trading_engine_interface-0.56.25.dist-info/RECORD +33 -0
  33. trading_engine_interface-0.56.25.dist-info/WHEEL +4 -0
@@ -0,0 +1,412 @@
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 Asset, VenueName
7
+ from trading_engine_interface.common.models.base_api_model import BaseApiModel
8
+ from trading_engine_interface.trading_engine.enums import (
9
+ AccountStatus,
10
+ AccountType,
11
+ TransactionType,
12
+ TransferFlowClass,
13
+ TransferFlowClassSource,
14
+ TransferStatus,
15
+ TransferType,
16
+ )
17
+ from typing_extensions import Self
18
+
19
+
20
+ class Account(BaseApiModel):
21
+ venue: VenueName
22
+ venue_user_id: str
23
+ account_type: AccountType
24
+ status: AccountStatus = AccountStatus.ACTIVE
25
+
26
+ @property
27
+ def is_active(self) -> bool:
28
+ return self.status == AccountStatus.ACTIVE
29
+
30
+ @property
31
+ def venue_account_id(self) -> str:
32
+ return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
33
+
34
+ @property
35
+ def name(self) -> str:
36
+ """Account name based on venue, user, and type"""
37
+ return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
38
+
39
+
40
+ class Balance(BaseApiModel):
41
+ asset: Asset
42
+ free: Decimal
43
+ # `locked` is the runtime view of venue-reported state, NOT a user-supplied
44
+ # input. A Pydantic `ge=0` constraint here was the wrong layer: it conflated
45
+ # "our code should never write a negative" (a runtime write-time invariant)
46
+ # with "negative is unrepresentable" (a type-time invariant). The constraint
47
+ # crashed the engine on boot when a sub-cent negative locked landed in the
48
+ # DB (e.g., OKX cross-margin rounding tail ingested via
49
+ # reconcile_balances(use_remote=True)). The invariant is now enforced at
50
+ # the write chokepoint (`AccountingService._sync_balance_to_db` clamps +
51
+ # warns) and surfaced via the `balance_locked_non_negative` verification
52
+ # rule, so we keep visibility without the boot-time foot-gun.
53
+ locked: Decimal = Field(default=Decimal(0))
54
+ venue: VenueName
55
+ venue_user_id: str
56
+ account_type: AccountType
57
+ account_id: Optional[int] = None
58
+
59
+ @property
60
+ def venue_account_id(self) -> str:
61
+ return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
62
+
63
+ @property
64
+ def total(self) -> Decimal:
65
+ return self.free + self.locked
66
+
67
+
68
+ class UpdateTransferRequest(BaseModel):
69
+ """Operator correction of a transfer's annotation fields — PUT /transfers/{id}.
70
+
71
+ Only the fields actually SENT are applied (``model_fields_set``): sending
72
+ ``paired_transfer_id: null`` unpairs, omitting it leaves the pair alone. Clients
73
+ must therefore serialize with ``exclude_unset=True``.
74
+
75
+ Venue-sourced fields (amount, asset, timestamp, transfer_type, status) are
76
+ deliberately NOT writable: they drive balances, and are corrected by venue
77
+ re-sync or the heal-script route, never by an annotation write.
78
+ """
79
+
80
+ flow_class: Optional[TransferFlowClass] = None
81
+ paired_transfer_id: Optional[int] = None
82
+ fee: Optional[Decimal] = Field(default=None, ge=0)
83
+ fee_asset: Optional[Asset] = None
84
+ note: str = Field(min_length=1, description="Why the correction was made; persisted on every touched leg")
85
+
86
+ @model_validator(mode="after")
87
+ def validate_request(self) -> Self:
88
+ corrections = self.model_fields_set - {"note"}
89
+ if not corrections:
90
+ raise ValueError("Nothing to correct: send at least one of flow_class, paired_transfer_id, fee, fee_asset")
91
+ if "flow_class" in corrections and self.flow_class is None:
92
+ raise ValueError("flow_class cannot be null")
93
+ if ("fee" in corrections) != ("fee_asset" in corrections):
94
+ raise ValueError("fee and fee_asset must be corrected together")
95
+ if (self.fee is None) != (self.fee_asset is None):
96
+ raise ValueError("fee and fee_asset must both be set or both be null")
97
+ return self
98
+
99
+
100
+ class Transfer(BaseApiModel):
101
+ asset: Asset
102
+ amount: Decimal
103
+ transfer_type: TransferType
104
+ status: TransferStatus
105
+ venue: VenueName
106
+ venue_user_id: str
107
+ account_type: AccountType
108
+ external_id: str
109
+ timestamp: datetime
110
+
111
+ fee: Optional[Decimal] = None
112
+ fee_asset: Optional[Asset] = None
113
+ account_id: Optional[int] = None
114
+
115
+ # Purpose, orthogonal to direction. Defaults keep an unclassified row on the
116
+ # earlier semantics (EXTERNAL = counts toward capital_base). Deliberately NO model
117
+ # validator ties flow_class to paired_transfer_id: a persisted row that failed
118
+ # validation would fail to hydrate, and one bad row must never block loading the
119
+ # whole table. Pairing invariants are enforced where they are written.
120
+ flow_class: TransferFlowClass = TransferFlowClass.EXTERNAL
121
+ paired_transfer_id: Optional[int] = None
122
+ flow_class_source: TransferFlowClassSource = TransferFlowClassSource.AUTO
123
+ note: Optional[str] = None
124
+
125
+ @property
126
+ def venue_account_id(self) -> str:
127
+ return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
128
+
129
+ @property
130
+ def is_incoming(self) -> bool:
131
+ return self.amount > 0
132
+
133
+ @property
134
+ def is_outgoing(self) -> bool:
135
+ return self.amount < 0
136
+
137
+ @model_validator(mode="after")
138
+ def validate_transfer(self) -> Self:
139
+ if self.transfer_type == TransferType.DEPOSIT and self.amount <= 0:
140
+ raise ValueError("Deposits must have a positive amount")
141
+ if self.transfer_type == TransferType.WITHDRAWAL and self.amount >= 0:
142
+ raise ValueError("Withdrawals must have a negative amount")
143
+ if self.fee is not None and self.fee_asset is None:
144
+ raise ValueError("If fee is provided, fee_asset must also be provided")
145
+ return self
146
+
147
+ @property
148
+ def from_account_id(self) -> Optional[int]:
149
+ """Source account ID for the transfer"""
150
+ # For withdrawals, source is the current account
151
+ # For deposits, source is external (None)
152
+ return self.account_id if self.transfer_type == TransferType.WITHDRAWAL else None
153
+
154
+ @property
155
+ def to_account_id(self) -> Optional[int]:
156
+ """Destination account ID for the transfer"""
157
+ # For deposits, destination is the current account
158
+ # For withdrawals, destination is external (None)
159
+ return self.account_id if self.transfer_type == TransferType.DEPOSIT else None
160
+
161
+
162
+ # Currently unused — intended to unify trades and transfers into a single ledger view.
163
+ # To activate: source from Fill (trade) and Transfer records, expose via GET /transactions endpoint.
164
+ class Transaction(BaseApiModel):
165
+ asset: Asset
166
+ amount: Decimal
167
+ transaction_type: TransactionType
168
+ reference_id: str
169
+ account_id: int
170
+
171
+
172
+ class BalanceDetail(BaseModel):
173
+ """Account balance snapshot"""
174
+
175
+ venue: VenueName
176
+ venue_user_id: str
177
+ account_type: AccountType
178
+ balances: dict[Asset, Decimal] # Total balance (free + locked) by asset
179
+
180
+ def __str__(self) -> str:
181
+ """Account summary with key balances."""
182
+ balances_str = ", ".join(f"{amount:.8f} {asset}" for asset, amount in self.balances.items())
183
+ return f"{self.venue_account_id}: {balances_str}"
184
+
185
+ @property
186
+ def venue_account_id(self) -> str:
187
+ return f"{self.venue}_{self.venue_user_id}_{self.account_type}"
188
+
189
+
190
+ class RebalancePlanLeg(BaseModel):
191
+ """One transfer in a computed rebalance plan: move ``amount`` of ``asset`` from
192
+ the ``from_`` account to the ``to_`` account.
193
+
194
+ READ-ONLY output of ``GET /rebalance_plan`` — the engine computes the minimal
195
+ transfer set that re-levels each asset evenly across funded accounts, and a
196
+ human executes it (the engine cannot move funds on live; paper applies the same
197
+ plan automatically at boot). ``amount`` is always POSITIVE — direction lives in
198
+ the from/to fields, not the sign, so a consumer can't accidentally invert a leg.
199
+
200
+ The ``*_venue_account_id`` display ids (``VENUE_user_TYPE``) carry venue, user,
201
+ and account type so a leg is actionable without a second account lookup.
202
+ """
203
+
204
+ asset: Asset
205
+ amount: Decimal
206
+ from_account_id: int
207
+ from_venue_account_id: str
208
+ to_account_id: int
209
+ to_venue_account_id: str
210
+
211
+ def __str__(self) -> str:
212
+ return f"{self.amount} {self.asset}: {self.from_venue_account_id} -> {self.to_venue_account_id}"
213
+
214
+
215
+ class BalanceSnapshot(BaseApiModel):
216
+ """
217
+ Snapshot of all balances across accounts.
218
+ Used for calculating ROI and other accounting metrics.
219
+ """
220
+
221
+ timestamp: datetime
222
+ balances: list[BalanceDetail]
223
+ asset_prices: dict[Asset, Decimal] # USD price per unit at snapshot time
224
+
225
+ def __str__(self) -> str:
226
+ """Snapshot summary with NAV and key positions."""
227
+ # Core metrics
228
+ header = f"Balance Snapshot {self.timestamp.isoformat()}\n"
229
+ header += f"NAV: ${self.nav:.2f}\n"
230
+
231
+ # Top assets by USD value (up to 5)
232
+ assets = "\nassets:\n"
233
+ for asset, value in self.asset_usd_values.items():
234
+ weight = self.asset_weights[asset]
235
+ amt = self.asset_balances[asset]
236
+ assets += f"{asset}: {amt:.8f} (${value:.2f}, {weight:.1%})\n"
237
+
238
+ res = header + assets
239
+
240
+ return res
241
+
242
+ # Using @computed_field complicates serialization in database storage:
243
+ # - it requires additional fields on ORM
244
+ # - it may not be assigned back to pydantic because they are properties
245
+ @property
246
+ def nav(self) -> Decimal:
247
+ """Net Asset Value in USD"""
248
+ return Decimal(sum(asset_value for asset_value in self.asset_usd_values.values()))
249
+
250
+ @property
251
+ def asset_balances(self) -> dict[Asset, Decimal]:
252
+ """Total balance by asset across all accounts"""
253
+ totals: dict[Asset, Decimal] = {}
254
+ for account in self.balances:
255
+ for asset, amount in account.balances.items():
256
+ totals[asset] = totals.get(asset, Decimal(0)) + amount
257
+ return totals
258
+
259
+ @property
260
+ def asset_usd_values(self) -> dict[Asset, Decimal]:
261
+ """Total USD value by asset across all accounts"""
262
+ return {asset: amount * self.asset_prices[asset] for asset, amount in self.asset_balances.items()}
263
+
264
+ @property
265
+ def asset_weights(self) -> dict[Asset, Decimal]:
266
+ """Asset weights in portfolio"""
267
+ if self.nav == 0:
268
+ return {}
269
+ return {asset: value / self.nav for asset, value in self.asset_usd_values.items()}
270
+
271
+
272
+ class Portfolio(BaseApiModel):
273
+ """
274
+ Portfolio tracking capital base and current state for ROI calculation.
275
+
276
+ Fields:
277
+ - capital_base: Asset quantities from deposits/withdrawals (persisted in DB)
278
+ - current_balances: Current total balances across accounts (populated at read time)
279
+ - asset_prices: Current asset prices in USD (populated at read time)
280
+
281
+ Computed properties provide metrics like NAV, ROI, PnL.
282
+ """
283
+
284
+ capital_base: dict[Asset, Decimal] = Field(
285
+ default_factory=dict,
286
+ description="Capital base quantities from deposits/withdrawals",
287
+ )
288
+ current_balances: dict[Asset, Decimal] = Field(
289
+ default_factory=dict,
290
+ description="Current total balances across all accounts",
291
+ )
292
+ asset_prices: dict[Asset, Decimal] = Field(
293
+ default_factory=dict,
294
+ description="Current asset prices in USD",
295
+ )
296
+
297
+ def __str__(self) -> str:
298
+ non_zero = {a: q for a, q in self.capital_base.items() if q != 0}
299
+ base = ", ".join(f"{a.value}={q}" for a, q in non_zero.items()) or "empty"
300
+ return f"Portfolio(capital_base=[{base}])"
301
+
302
+ @property
303
+ def capital_base_usd(self) -> Decimal:
304
+ """Capital base value in USD using current prices."""
305
+ if not self.asset_prices:
306
+ return Decimal(0)
307
+ return Decimal(sum(qty * self.asset_prices.get(asset, Decimal(0)) for asset, qty in self.capital_base.items()))
308
+
309
+ @property
310
+ def nav(self) -> Decimal:
311
+ """Net Asset Value - current portfolio value in USD."""
312
+ if not self.asset_prices:
313
+ return Decimal(0)
314
+ return Decimal(
315
+ sum(qty * self.asset_prices.get(asset, Decimal(0)) for asset, qty in self.current_balances.items())
316
+ )
317
+
318
+ @property
319
+ def roi(self) -> Decimal:
320
+ """Return on Investment: (NAV - capital_base) / capital_base."""
321
+ if self.capital_base_usd <= 0:
322
+ return Decimal(0)
323
+ return (self.nav - self.capital_base_usd) / self.capital_base_usd
324
+
325
+ @property
326
+ def pnl(self) -> Decimal:
327
+ """Absolute profit/loss in USD."""
328
+ return self.nav - self.capital_base_usd
329
+
330
+ @property
331
+ def asset_returns(self) -> dict[Asset, Decimal]:
332
+ """Per-asset quantity-based returns (trading performance)."""
333
+ returns: dict[Asset, Decimal] = {}
334
+ for asset, base_qty in self.capital_base.items():
335
+ current_qty = self.current_balances.get(asset, Decimal(0))
336
+ if base_qty > 0:
337
+ returns[asset] = (current_qty - base_qty) / base_qty
338
+ elif current_qty > 0:
339
+ returns[asset] = current_qty # New asset acquired
340
+ return returns
341
+
342
+
343
+ class PortfolioSnapshot(Portfolio):
344
+ """
345
+ Point-in-time snapshot of portfolio state for tracking growth over time.
346
+
347
+ Inherits all fields and computed properties from Portfolio.
348
+ Adds timestamp to mark when the snapshot was taken.
349
+ Created alongside balance snapshots during reconciliation.
350
+ """
351
+
352
+ timestamp: datetime
353
+ # Cumulative position-accounting realized PnL (USD) up to `timestamp`. Populated by
354
+ # the backfill (reconcile_portfolio_snapshots); 0 on legacy rows pre-dating the field.
355
+ realized_pnl: Decimal = Field(default=Decimal(0))
356
+
357
+
358
+ class KpiPoint(BaseApiModel):
359
+ """One point on the portfolio KPI time series (a grid timestamp).
360
+
361
+ `twr` is the cumulative time-weighted return from inception (a fraction, e.g.
362
+ 0.05 = +5%); `drawdown` is the current drawdown from the TWR-index running peak
363
+ (<= 0). `unrealized = pnl - realized_pnl`.
364
+ """
365
+
366
+ timestamp: datetime
367
+ nav: Decimal
368
+ pnl: Decimal
369
+ realized_pnl: Decimal
370
+ unrealized_pnl: Decimal
371
+ twr: Decimal
372
+ drawdown: Decimal
373
+ # Capital movement inside this point's period, (previous grid point, this one],
374
+ # in USD at transfer-time prices. Read flows from here, never from a capital_base_usd
375
+ # delta: capital_base is held in native units, so its USD value moves with price on
376
+ # days with no transfer at all.
377
+ external_flow_usd: Decimal = Field(default=Decimal(0), description="Net external deposits − withdrawals")
378
+ rebalance_cost_usd: Decimal = Field(default=Decimal(0), description="Sent − received over completed rebalances")
379
+ # T-bill benchmark: the same capital held at KpiSeries.risk_free_rate over
380
+ # the same periods. benchmark_nav starts at the first point's NAV and takes the
381
+ # same external flows; excess_twr = twr − benchmark_twr.
382
+ benchmark_nav: Decimal = Field(default=Decimal(0), description="NAV had the capital earned the risk-free rate")
383
+ benchmark_twr: Decimal = Field(default=Decimal(0), description="Cumulative risk-free accrual (fraction)")
384
+ excess_twr: Decimal = Field(default=Decimal(0), description="twr − benchmark_twr")
385
+
386
+
387
+ class KpiSeries(BaseApiModel):
388
+ """Portfolio KPI time series over [start, end] at `interval`, plus summary stats.
389
+
390
+ The per-point curve is `points`; `sharpe`/`max_drawdown` are derived from the
391
+ flow-neutralized TWR index over the series. `total_return_twr` is the final
392
+ cumulative TWR. `sharpe` is None when there are too few points to annualize.
393
+ `sharpe` is on returns in excess of `risk_free_rate` (annual, e.g. 0.038 = 3.8%),
394
+ and `total_excess_return` = `total_return_twr` − `total_benchmark_return`.
395
+ """
396
+
397
+ start: datetime
398
+ end: datetime
399
+ interval: str
400
+ points: list[KpiPoint] = Field(default_factory=list)
401
+ sharpe: Optional[Decimal] = None
402
+ max_drawdown: Decimal = Field(default=Decimal(0))
403
+ total_return_twr: Decimal = Field(default=Decimal(0))
404
+ total_realized_pnl: Decimal = Field(default=Decimal(0))
405
+ total_external_flow_usd: Decimal = Field(default=Decimal(0))
406
+ total_rebalance_cost_usd: Decimal = Field(default=Decimal(0))
407
+ # Σ rebalance_cost_usd keyed "SOURCE->DESTINATION" venue. A route whose cost is
408
+ # implausibly low is a route whose legs are not pairing.
409
+ rebalance_cost_by_route: dict[str, Decimal] = Field(default_factory=dict)
410
+ risk_free_rate: Decimal = Field(default=Decimal(0), description="Annual risk-free rate used for sharpe/benchmark")
411
+ total_benchmark_return: Decimal = Field(default=Decimal(0))
412
+ total_excess_return: Decimal = Field(default=Decimal(0))
@@ -0,0 +1,200 @@
1
+ from datetime import datetime
2
+ from decimal import Decimal
3
+ from typing import Any, Optional
4
+
5
+ from pydantic import BaseModel, Field, model_validator
6
+ from trading_engine_interface import BaseApiModel, TimeInterval
7
+ from trading_engine_interface.common.enums import StrValueEnum
8
+ from trading_engine_interface.trading_engine.models.strategy_metrics_models import StrategyMetrics
9
+ from trading_engine_interface.trading_engine.models.strategy_models import SkipSummary
10
+ from typing_extensions import Self
11
+
12
+
13
+ class BacktestStatus(StrValueEnum):
14
+ """Status of a backtest execution."""
15
+
16
+ PENDING = "PENDING" # Backtest created but not started
17
+ RUNNING = "RUNNING" # Backtest is currently executing
18
+ COMPLETED = "COMPLETED" # Backtest finished successfully
19
+ FAILED = "FAILED" # Backtest encountered an error
20
+ CANCELLED = "CANCELLED" # Backtest was stopped by user
21
+
22
+
23
+ class KlineSource(StrValueEnum):
24
+ """Where backtest klines come from. All sources implement the same
25
+ ``KlineDataSource`` protocol so the runner is source-agnostic. Order books
26
+ are always synthesized from kline closes — there is no historical-OB
27
+ replay path. See ``app/backtest/kline_data_source.py``.
28
+ """
29
+
30
+ GATEWAY = "gateway" # Host exchange gateway (e.g. OKX). Default — matches live data.
31
+ REMOTE = "remote" # A venue's public REST API. CLI / dev use without a host engine.
32
+ DATABASE = "database" # Host postgres historical klines. Reproducible across runs.
33
+ SYNTHETIC = "synthetic" # Random-walk klines. Strategy parameter exploration / tests.
34
+
35
+
36
+ class BacktestRequest(BaseModel):
37
+ """Configuration for starting a backtest simulation."""
38
+
39
+ # Required parameters
40
+ start_time: datetime = Field(description="Start time for historical data range")
41
+ end_time: datetime = Field(description="End time for historical data range")
42
+ strategy_ids: list[int] = Field(min_length=1, description="List of strategy IDs to backtest")
43
+
44
+ # Backtest execution parameters
45
+ initial_capital: Decimal = Field(default=Decimal("10000"), gt=0, description="Initial capital for backtesting")
46
+ maker_fee_bps: int = Field(
47
+ default=0,
48
+ ge=-50,
49
+ description=(
50
+ "Maker fee in bps (default 0). NEGATIVE = maker rebate (e.g. -1 = earn 1bp), "
51
+ "credited per fill. Floor -50 mirrors "
52
+ "BacktestRunConfig so an API-triggered backtest can model the rebate."
53
+ ),
54
+ )
55
+ taker_fee_bps: int = Field(
56
+ default=2, ge=0, description="Taker fee in bps (default 2 = real OKX tier, 1.75 rounded up; was 10 retail)"
57
+ )
58
+ slippage_bps: int = Field(default=5, ge=0, description="Slippage in basis points (default 5 = 0.05%)")
59
+
60
+ # Kline data source
61
+ kline_source: KlineSource = Field(
62
+ default=KlineSource.GATEWAY,
63
+ description=(
64
+ "Where backtest klines come from. Order books are always synthesized "
65
+ "from kline closes — there is no historical-OB replay path. See KlineSource."
66
+ ),
67
+ )
68
+
69
+ # Synthetic-only knobs (ignored unless kline_source=SYNTHETIC)
70
+ synthetic_initial_price: Decimal = Field(default=Decimal("40000"), description="Initial price for synthetic data")
71
+ synthetic_volatility: float = Field(
72
+ default=0.001, gt=0, description="Price volatility for synthetic random walk (e.g., 0.001 = 0.1%)"
73
+ )
74
+ synthetic_spread_bps: int = Field(default=10, gt=0, description="Bid-ask spread in basis points for synthetic data")
75
+ synthetic_interval_seconds: float = Field(
76
+ default=1.0, gt=0, description="Time interval between synthetic order book snapshots in seconds"
77
+ )
78
+ synthetic_kline_interval: TimeInterval = Field(
79
+ default=TimeInterval.MIN_1, description="Time interval for synthetic kline aggregation"
80
+ )
81
+
82
+ @model_validator(mode="after")
83
+ def validate_time_range(self) -> Self:
84
+ """Validate that end_time is after start_time."""
85
+ if self.end_time <= self.start_time:
86
+ raise ValueError(f"end_time ({self.end_time}) must be after start_time ({self.start_time})")
87
+ return self
88
+
89
+
90
+ class BacktestResult(BaseApiModel):
91
+ """Result and status information for a backtest execution."""
92
+
93
+ # Current status
94
+ status: BacktestStatus = Field(description="Current status of the backtest")
95
+ progress_pct: float = Field(default=0.0, ge=0.0, le=100.0, description="Completion percentage (0-100)")
96
+
97
+ # Runtime information
98
+ current_simulated_time: Optional[datetime] = Field(
99
+ default=None, description="Current simulated time during execution"
100
+ )
101
+ error: Optional[str] = Field(default=None, description="Error message if backtest failed")
102
+
103
+ # Timing information
104
+ start_time: Optional[datetime] = Field(default=None, description="Wall clock time when backtest started")
105
+ end_time: Optional[datetime] = Field(default=None, description="Wall clock time when backtest completed")
106
+ duration_seconds: Optional[float] = Field(default=None, ge=0, description="Total execution duration in seconds")
107
+
108
+ # Configuration — flat fields for DB compatibility (replaces simulated_time_range tuple)
109
+ simulated_start_time: Optional[datetime] = Field(default=None, description="Simulated period start time")
110
+ simulated_end_time: Optional[datetime] = Field(default=None, description="Simulated period end time")
111
+ request_config: Optional[dict[str, Any]] = Field(
112
+ default=None, description="Original BacktestRequest config (JSON-serialized)"
113
+ )
114
+
115
+ # Results
116
+ strategy_metrics: Optional[dict[str, StrategyMetrics]] = Field(
117
+ default=None, description="Strategy metrics keyed by strategy name (available when completed)"
118
+ )
119
+ strategy_failures: Optional[dict[str, str]] = Field(
120
+ default=None,
121
+ description="Strategies that failed to initialize, keyed by strategy name → error message",
122
+ )
123
+
124
+ # Aggregated performance metrics (calculated by backend)
125
+ final_capital: Optional[Decimal] = Field(default=None, description="Final capital after backtest")
126
+ roi: Optional[Decimal] = Field(default=None, description="Return on investment as decimal (e.g., 0.15 = 15%)")
127
+
128
+ @property
129
+ def simulated_time_range(self) -> Optional[tuple[datetime, datetime]]:
130
+ """Backwards-compatible property for simulated time range."""
131
+ if self.simulated_start_time and self.simulated_end_time:
132
+ return self.simulated_start_time, self.simulated_end_time
133
+ return None
134
+
135
+ @property
136
+ def is_running(self) -> bool:
137
+ """Check if backtest is currently running."""
138
+ return self.status == BacktestStatus.RUNNING
139
+
140
+ @property
141
+ def is_completed(self) -> bool:
142
+ """Check if backtest completed successfully."""
143
+ return self.status == BacktestStatus.COMPLETED
144
+
145
+ @property
146
+ def is_failed(self) -> bool:
147
+ """Check if backtest failed."""
148
+ return self.status == BacktestStatus.FAILED
149
+
150
+ @property
151
+ def has_results(self) -> bool:
152
+ """Check if backtest has metrics results available."""
153
+ return self.strategy_metrics is not None and len(self.strategy_metrics) > 0
154
+
155
+ @property
156
+ def total_pnl(self) -> Optional[Decimal]:
157
+ """Aggregate total PnL across all strategies."""
158
+ if not self.has_results:
159
+ return None
160
+
161
+ total = Decimal("0")
162
+ for metrics in self.strategy_metrics.values(): # type: ignore
163
+ if metrics.total_pnl:
164
+ total += metrics.total_pnl
165
+ return total
166
+
167
+ @property
168
+ def total_trades(self) -> Optional[int]:
169
+ """Aggregate total number of trades across all strategies."""
170
+ if not self.has_results:
171
+ return None
172
+
173
+ total = 0
174
+ for metrics in self.strategy_metrics.values(): # type: ignore
175
+ if metrics.position_metrics and metrics.position_metrics.trade_count:
176
+ total += metrics.position_metrics.trade_count
177
+ return total
178
+
179
+
180
+ class BacktestResultDetail(BaseApiModel):
181
+ """Detailed backtest results — orders, fills, and strategy executions.
182
+
183
+ Stored separately from BacktestResult for efficient listing (lightweight)
184
+ vs on-demand detail loading (heavy).
185
+ """
186
+
187
+ backtest_result_id: int = Field(description="ID of the parent BacktestResult")
188
+ strategy_executions: list[dict[str, Any]] = Field(
189
+ default_factory=list, description="Strategy executions with actions"
190
+ )
191
+ orders: list[dict[str, Any]] = Field(default_factory=list, description="All orders placed during backtest")
192
+ fills: list[dict[str, Any]] = Field(default_factory=list, description="All fills received during backtest")
193
+ skip_summaries: list[SkipSummary] = Field(
194
+ default_factory=list,
195
+ description=(
196
+ "Per-strategy windowed summaries of decide() outcomes for cycles that "
197
+ "produced no actions. Complements strategy_executions, which only "
198
+ "captures cycles where the strategy submitted orders."
199
+ ),
200
+ )