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,1360 @@
1
+ from datetime import datetime
2
+ from decimal import Decimal
3
+ from typing import Any, ClassVar, Optional
4
+
5
+ from pydantic import BaseModel, Field, computed_field, model_validator
6
+ from trading_engine_interface.common.enums import Asset, StrValueEnum, TimeInterval
7
+ from trading_engine_interface.common.models.base_api_model import BaseApiModel
8
+ from trading_engine_interface.trading_engine.enums import (
9
+ ExecutionMode,
10
+ StrategyErrorReason,
11
+ StrategyStatus,
12
+ StrategyStatusSource,
13
+ Symbol,
14
+ VenueName,
15
+ )
16
+ from trading_engine_interface.trading_engine.models.accounting_models import Balance
17
+ from trading_engine_interface.trading_engine.models.market_models import Kline, OrderBook, PublicTrade
18
+ from trading_engine_interface.trading_engine.models.order_models import (
19
+ AmendStopRequest,
20
+ BracketOrderRequest,
21
+ CancelOrderRequest,
22
+ CreateOrderRequest,
23
+ Order,
24
+ ReplaceOrderRequest,
25
+ )
26
+ from trading_engine_interface.trading_engine.models.position_breakdown_models import StrategyVenueBreakdown
27
+ from trading_engine_interface.trading_engine.models.position_models import PositionGroup
28
+ from typing_extensions import Self
29
+
30
+
31
+ class AccountPermissionConfig(BaseModel):
32
+ """Trading account permissions with granular symbol-venue control.
33
+
34
+ Two distinct scopes:
35
+ - `symbol_to_venues`: trading authorization (order routing consults this)
36
+ - `observable_venues`: read-only market data access (no trading authorization)
37
+
38
+ Use `observable_venues` when a strategy needs cross-venue market data (e.g. cross-venue
39
+ true-value signals, spread-aware routing reference) without granting trading access.
40
+ """
41
+
42
+ symbol_to_venues: dict[Symbol, list[VenueName]] = Field(
43
+ default_factory=dict, description="Mapping of symbols to allowed TRADING venues"
44
+ )
45
+ observable_venues: list[VenueName] = Field(
46
+ default_factory=list,
47
+ description="Read-only venues for market data access (no trading authorization)",
48
+ )
49
+ # Assume spot account only; add this if we need to differentiate account types
50
+ # account_types: list[AccountType]
51
+
52
+ @classmethod
53
+ def from_venues_symbols(
54
+ cls,
55
+ venues: list[VenueName],
56
+ symbols: list[Symbol],
57
+ observable_venues: Optional[list[VenueName]] = None,
58
+ ) -> Self:
59
+ """Create config allowing all symbols on all trading venues (Cartesian product).
60
+
61
+ Optionally adds read-only `observable_venues` for market data access without
62
+ granting trading permission on those venues.
63
+ """
64
+ return cls(
65
+ symbol_to_venues={symbol: venues.copy() for symbol in symbols},
66
+ observable_venues=observable_venues or [],
67
+ )
68
+
69
+ @model_validator(mode="after")
70
+ def validate_non_empty_venues(self) -> Self:
71
+ """Ensure each symbol has at least one venue."""
72
+ for symbol, venues in self.symbol_to_venues.items():
73
+ if not venues:
74
+ raise ValueError(f"Symbol {symbol} must have at least one venue")
75
+ return self
76
+
77
+ @property
78
+ def venues(self) -> list[VenueName]:
79
+ """All trading venues that appear in any symbol's venue list."""
80
+ return sorted(list(set().union(*self.symbol_to_venues.values()))) if self.symbol_to_venues else []
81
+
82
+ @property
83
+ def symbols(self) -> list[Symbol]:
84
+ """All symbols configured for trading."""
85
+ return sorted(list(self.symbol_to_venues.keys()))
86
+
87
+ def allows_trading(self, symbol: Symbol, venue: VenueName) -> bool:
88
+ """Check if trading is allowed for a specific symbol-venue combination."""
89
+ return venue in self.symbol_to_venues.get(symbol, [])
90
+
91
+ @property
92
+ def symbol_to_data_venues(self) -> dict[Symbol, list[VenueName]]:
93
+ """Trading + observable venues per symbol. For market data gathering only.
94
+
95
+ NEVER consult this for order routing — trading-authorized venues live in
96
+ `symbol_to_venues`. Use this only to decide which venues' order books /
97
+ klines to collect for strategy inputs.
98
+ """
99
+ if not self.observable_venues:
100
+ return self.symbol_to_venues # fast path, no copy
101
+ base = {sym: list(venues) for sym, venues in self.symbol_to_venues.items()}
102
+ for sym in base:
103
+ for venue in self.observable_venues:
104
+ if venue not in base[sym]:
105
+ base[sym].append(venue)
106
+ return base
107
+
108
+
109
+ class RiskLimitConfig(BaseModel):
110
+ """Risk limits that trigger kill switch."""
111
+
112
+ # Kill switch limits
113
+ max_total_loss: float = Field(default=0, ge=0)
114
+ max_drawdown_pct: float = Field(default=0, ge=0, le=100)
115
+
116
+ # Per-order limits
117
+ max_order_value: float = Field(default=0, ge=0)
118
+
119
+ # Position exposure limits
120
+ max_position_value: float = Field(default=0, ge=0)
121
+
122
+ # Gross (per-venue) exposure cap. Binds on
123
+ # Σ per-venue COST-BASIS exposure across the strategy's symbols — the measure
124
+ # a delta-neutral cross-venue book keeps large while its NET exposure (what
125
+ # max_position_value sees) sits at ~0. Enforcement is reduce-only suppression:
126
+ # decisions containing gross-INCREASING orders are blocked once the cap is
127
+ # reached; pure reduce-side decisions always pass, so the book can only work
128
+ # back down (never the one-sided pin a full block would cause). 0 = disabled.
129
+ max_gross_exposure_value: float = Field(
130
+ default=0, ge=0, description="Max Σ per-venue cost-basis exposure USD (0 = unlimited)"
131
+ )
132
+
133
+ # Capital allocation limits (position + locked balance)
134
+ max_capital_allocation_usd: float = Field(
135
+ default=0, ge=0, description="Maximum USD capital this strategy can allocate (0 = unlimited)"
136
+ )
137
+ max_capital_allocation_pct: float = Field(
138
+ default=0, ge=0, le=100, description="Maximum % of total account NAV this strategy can use (0 = unlimited)"
139
+ )
140
+
141
+ # Asset usage limits (prevents asset exhaustion)
142
+ max_asset_usage_pct: float = Field(
143
+ default=0, # 0 = unlimited
144
+ ge=0,
145
+ le=100,
146
+ description="Max % of any asset's free balance that can be locked/used",
147
+ )
148
+
149
+ # DEPRECATED — ignored. Was the HWM arming floor for the fraction-of-PnL-peak
150
+ # drawdown; drawdown is now measured on allocated capital and needs no floor. Kept so
151
+ # stored strategy configs that carry the key still validate.
152
+ min_peak_threshold_pct: float = Field(
153
+ default=0.5,
154
+ ge=0,
155
+ le=100,
156
+ description="Deprecated: ignored — drawdown is measured on allocated capital with no HWM floor",
157
+ )
158
+
159
+ # Per-strategy override for the order flow velocity check in RiskService.
160
+ # The check caps gross order notional per symbol in a rolling 60s window at
161
+ # (max_position_value × multiplier). It exists as a safety net against runaway
162
+ # order submission caused by position pipeline lag (fills arrive but position
163
+ # state hasn't refreshed before the next decision cycle).
164
+ #
165
+ # The check is calibrated for positional strategies. Continuous-submission
166
+ # strategies (market making) legitimately post far above 3× max_position per
167
+ # minute by design; they rely on other defenses (position cap, SETTLING status,
168
+ # open-order gating) for runaway protection.
169
+ order_flow_velocity_multiplier: Optional[float] = Field(
170
+ default=None,
171
+ ge=0,
172
+ description=(
173
+ "Override for order flow velocity threshold multiplier. "
174
+ "None = use RiskService default (3.0). "
175
+ "0 = disable the check entirely (use for market-making / high-frequency "
176
+ "quoting strategies where continuous order submission is normal)."
177
+ ),
178
+ )
179
+ # Consider adding these
180
+ # max_daily_loss: float = Field(default=0, ge=0)
181
+ # error_threshold: int = Field(default=0, ge=0)
182
+ # max_reject_number: int = Field(default=10, gt=0, description="Maximum number of rejected orders")
183
+ # max_reject_rate: float = Field(default=0.5, gt=0, description="Maximum rate of rejected orders")
184
+ # min_fill_rate_maker: float = Field(default=0.5, gt=0, description="Minimum fill rate for maker orders")
185
+ # min_fill_rate_taker: float = Field(default=0.5, gt=0, description="Minimum fill rate for taker orders")
186
+
187
+ # Fields declared in source code (strategy class-level policy), not user-tunable
188
+ # at runtime. On boot, these are always taken from the source config even when
189
+ # the DB has a stale value — protects MM-style opt-outs from being silently
190
+ # discarded when a strategy row predates the override.
191
+ CLASS_LEVEL_FIELDS: ClassVar[frozenset[str]] = frozenset({"order_flow_velocity_multiplier"})
192
+
193
+ def merge_class_level_from(self, source: "RiskLimitConfig") -> "RiskLimitConfig":
194
+ """Return a copy with CLASS_LEVEL_FIELDS replaced by the values from `source`."""
195
+ overrides = {name: getattr(source, name) for name in self.CLASS_LEVEL_FIELDS}
196
+ return self.model_copy(update=overrides)
197
+
198
+
199
+ class RuntimeConfig(BaseModel):
200
+ """Runtime execution controls."""
201
+
202
+ # Execution mode
203
+ execution_mode: ExecutionMode = Field(
204
+ default=ExecutionMode.TIMER, description="Strategy execution mode (TIMER or MARKET_DRIVEN)"
205
+ )
206
+ # TODO: for backward compatibility, make run_interval required for now; in the future this can be optional for ExecutionMode.MARKET_DRIVEN
207
+ run_interval: float = Field(
208
+ default=..., gt=0, description="Execution interval in seconds (required for TIMER mode)"
209
+ )
210
+
211
+ # Execution guard parameters
212
+ min_execution_interval: float = Field(
213
+ default=0.0, ge=0, description="Minimum seconds between executions (rate limiting)"
214
+ )
215
+ max_concurrent_orders: int = Field(default=10, gt=0, description="Maximum open orders before pausing execution")
216
+ wait_for_fills: bool = Field(default=False, description="Wait for open orders to fill before next execution")
217
+
218
+ @model_validator(mode="after")
219
+ def validate_execution_mode(self) -> Self:
220
+ """Validate that run_interval is set for TIMER mode."""
221
+ if self.execution_mode == ExecutionMode.TIMER and self.run_interval is None:
222
+ raise ValueError("run_interval is required when execution_mode is TIMER")
223
+ return self
224
+
225
+
226
+ class PositionParams(BaseModel):
227
+ """Position sizing parameters in USD"""
228
+
229
+ # Close postion conditions
230
+ take_profit_pct: float = Field(default=2.0, gt=0, le=100)
231
+ stop_loss_pct: float = Field(default=1.0, gt=0, le=100)
232
+
233
+ # USD values for consistent cross-symbol sizing
234
+ min_position_value: float = Field(default=20, gt=0)
235
+ max_position_value: float = Field(default=100, gt=0)
236
+
237
+ # Add more parameters if needed
238
+ # Multiplier for scaling positions
239
+ # position_increment_multiplier: Decimal = Field(default=1, gt=0)
240
+
241
+
242
+ class TechnicalIndicatorConfig(BaseModel):
243
+ """Technical indicator data requirements and common configuration."""
244
+
245
+ # Data requirements
246
+ intervals: list[TimeInterval] = Field(
247
+ default_factory=list, description="Time intervals required for technical analysis"
248
+ )
249
+ min_klines_num: int = Field(default=200, ge=1, description="Minimum number of klines required for calculations")
250
+
251
+ # Other common parameters to consider
252
+ # # Data freshness requirements
253
+ # max_kline_age_seconds: float = Field(
254
+ # default=300.0,
255
+ # gt=0.0,
256
+ # description="Maximum age of latest kline data in seconds"
257
+ # )
258
+ #
259
+ # # Calculation preferences
260
+ # preferred_venue: Optional[VenueName] = Field(
261
+ # default=None,
262
+ # description="Preferred venue for kline data (uses first available if None)"
263
+ # )
264
+ #
265
+ # # Performance optimization
266
+ # enable_caching: bool = Field(
267
+ # default=True,
268
+ # description="Enable caching of calculated indicator values"
269
+ # )
270
+ # cache_ttl_seconds: float = Field(
271
+ # default=60.0,
272
+ # gt=0.0,
273
+ # description="Time-to-live for cached indicator values in seconds"
274
+ # )
275
+
276
+
277
+ class PredictionConfig(BaseModel):
278
+ """ML prediction configuration with multi-endpoint support."""
279
+
280
+ # Endpoint configuration - each endpoint supports one symbol
281
+ endpoints: list[str] = Field(min_length=1, description="List of ML endpoints to use")
282
+
283
+ # Prediction usage configuration - moved from prediction models
284
+ confidence_threshold: float = Field(
285
+ default=0.6, ge=0.0, le=1.0, description="Minimum confidence threshold to act on predictions"
286
+ )
287
+ max_prediction_age_seconds: float = 300.0 # Maximum age of prediction to use
288
+ history_bars: int = Field(
289
+ default=0,
290
+ ge=0,
291
+ le=1000,
292
+ description=(
293
+ "Bar intervals of persisted prediction history to attach per served (symbol, endpoint) as "
294
+ "StrategyPredictions.history — oldest first, including the current bar. Time-bounded: at most "
295
+ "N bars, none older than the last N intervals (plus one of grace for the bar about to land), "
296
+ "so a generation gap yields fewer than N bars. "
297
+ "0 = none. Served by the engine, so a rolling window is warm immediately after a strategy "
298
+ "reload or engine restart."
299
+ ),
300
+ )
301
+
302
+ @property
303
+ def primary_endpoint(self) -> str:
304
+ """Get the first endpoint as primary."""
305
+ return self.endpoints[0]
306
+
307
+ @property
308
+ def is_ensemble(self) -> bool:
309
+ """Check if this config uses multiple endpoints."""
310
+ return len(self.endpoints) > 1
311
+
312
+
313
+ class PublicTradeConfig(BaseModel):
314
+ """Public-trade data requirements.
315
+
316
+ Opt-in: set ``BaseStrategyConfig.public_trade`` to a ``PublicTradeConfig`` instance
317
+ to have the engine pre-load recent trades into ``StrategyInput.market_data.public_trades``
318
+ on every ``decide()`` cycle. Leave as ``None`` to skip pre-loading entirely.
319
+
320
+ Reads from the engine's per-(venue, symbol) ring buffer
321
+ (``MarketDataService.list_recent_public_trades``) — sync, sub-ms, no REST call.
322
+ Pre-loads for every venue in ``BaseStrategyConfig.symbol_to_data_venues`` (i.e.
323
+ trading + observable venues), same scope as the kline pre-load.
324
+ """
325
+
326
+ lookback_seconds: float = Field(
327
+ default=30.0,
328
+ gt=0.0,
329
+ description="Rolling time window of recent trades to pre-load per (symbol, venue).",
330
+ )
331
+ limit: int = Field(
332
+ default=1000,
333
+ ge=1,
334
+ description="Maximum trades returned per (symbol, venue). Engine buffer cap is currently 1000.",
335
+ )
336
+
337
+
338
+ class StrategyConfigUpdate(BaseModel):
339
+ """Partial config update — only set the fields you want to change.
340
+
341
+ Single stop/restart cycle instead of one per field.
342
+ """
343
+
344
+ position: Optional[PositionParams] = None
345
+ risk_limit: Optional[RiskLimitConfig] = None
346
+ account_permission: Optional[AccountPermissionConfig] = None
347
+ runtime: Optional[RuntimeConfig] = None
348
+ prediction: Optional[PredictionConfig] = None
349
+ public_trade: Optional[PublicTradeConfig] = None
350
+ custom: Optional[dict[str, Any]] = None
351
+
352
+
353
+ class BaseStrategyConfig(BaseModel):
354
+ """Base configuration for trading strategies.
355
+
356
+ Note: version is NOT part of config — it lives on the strategy class (Strategy.VERSION).
357
+ Strategy naming (with version) is handled by the strategy service at registration time.
358
+ """
359
+
360
+ # Identity
361
+ class_type: str
362
+ instance_name: Optional[str] = Field(
363
+ default=None, description="Optional instance identifier (overrides auto-naming)"
364
+ )
365
+
366
+ # Core configs
367
+ account_permission: AccountPermissionConfig
368
+ risk_limit: RiskLimitConfig
369
+ runtime: RuntimeConfig
370
+ position: PositionParams
371
+ technical_indicator: Optional[TechnicalIndicatorConfig] = None
372
+ prediction: Optional[PredictionConfig] = None
373
+ public_trade: Optional[PublicTradeConfig] = None
374
+
375
+ trading_symbols: list[Symbol] = Field(default_factory=list, description="List of trading symbols for the strategy")
376
+
377
+ # Deployment control: initial status for newly created strategies (ignored for existing)
378
+ initial_status: StrategyStatus = Field(
379
+ default=StrategyStatus.INACTIVE,
380
+ description="Initial status when strategy is first created (e.g., DISABLED to deploy without auto-start)",
381
+ )
382
+
383
+ @property
384
+ def config_key(self) -> str:
385
+ """Config-level identifier (without version). Used for logging and as the
386
+ base for the DB-row name (see ``StrategyService.strategy_name`` in the
387
+ engine — which prepends ``v{VERSION}``).
388
+
389
+ Naming priority:
390
+ 1. If instance_name set: {class_type}_{instance_name}
391
+ 2. If single trading_symbol: {class_type}_{symbol}
392
+ 3. Otherwise: {class_type}
393
+
394
+ Known limitation: when ``instance_name`` is set, ``trading_symbols`` is
395
+ ignored. Two configs that share ``instance_name`` but differ in symbol
396
+ (e.g. per-symbol A/B variants like ``instance_name="ctrl"`` for both
397
+ BTC and ETH) produce the same ``config_key``. Strategies-repo convention
398
+ works around this by encoding the symbol in ``instance_name``
399
+ (``ctrl_btc`` / ``ctrl_eth``). For dedup detection — which catches
400
+ violations of that convention — use :attr:`dedup_key` instead.
401
+ """
402
+ if self.instance_name:
403
+ return f"{self.class_type}_{self.instance_name}"
404
+ elif len(self.trading_symbols) == 1:
405
+ # Auto-derive from single symbol: BTC-USDT -> BTCUSDT
406
+ symbol_short = self.trading_symbols[0].value.replace("-", "")
407
+ return f"{self.class_type}_{symbol_short}"
408
+ return self.class_type
409
+
410
+ @property
411
+ def dedup_key(self) -> str:
412
+ """Symbol-aware uniqueness key for dedup detection at the configs-list level.
413
+
414
+ Unlike :attr:`config_key`, this property **always** incorporates
415
+ ``trading_symbols`` when set, regardless of whether ``instance_name`` is
416
+ also set. Used by the engine's config-list dedup validation to detect
417
+ strategies-repo bugs where two per-symbol variants share the same
418
+ ``instance_name`` (e.g. ``instance_name="ctrl"`` for both BTC and ETH —
419
+ a known regression class, observed twice).
420
+
421
+ Format: ``{class_type}[_{instance_name}][_{symbols_short}]``
422
+
423
+ The strategies-repo convention to encode the symbol in
424
+ ``instance_name`` (``<name>_btc`` / ``<name>_eth``) is still required
425
+ for ``config_key`` and ``strategy_name`` (DB-row name) to be unique;
426
+ ``dedup_key`` exists to surface violations of that convention early
427
+ and accurately — the engine's dedup-error message previously claimed
428
+ it checked "instance_name + trading_symbols" but only checked
429
+ ``instance_name``. ``dedup_key`` makes the message truthful.
430
+ """
431
+ parts = [self.class_type]
432
+ if self.instance_name:
433
+ parts.append(self.instance_name)
434
+ if self.trading_symbols:
435
+ symbols_short = "_".join(s.value.replace("-", "") for s in self.trading_symbols)
436
+ parts.append(symbols_short)
437
+ return "_".join(parts)
438
+
439
+ @property
440
+ def symbols(self) -> list[Symbol]:
441
+ if self.trading_symbols:
442
+ return self.trading_symbols
443
+ else:
444
+ return self.account_permission.symbols
445
+
446
+ @property
447
+ def venues(self) -> list[VenueName]:
448
+ return self.account_permission.venues
449
+
450
+ @property
451
+ def symbol_to_venues(self) -> dict[Symbol, list[VenueName]]:
452
+ return self.account_permission.symbol_to_venues
453
+
454
+ @property
455
+ def symbol_to_data_venues(self) -> dict[Symbol, list[VenueName]]:
456
+ """Trading + observable venues per symbol. For market data gathering only.
457
+ NEVER use for order routing — see AccountPermissionConfig.symbol_to_data_venues.
458
+ """
459
+ return self.account_permission.symbol_to_data_venues
460
+
461
+ @property
462
+ def run_interval(self) -> float:
463
+ return self.runtime.run_interval
464
+
465
+
466
+ # --- State & Metrics --- #
467
+
468
+
469
+ class StrategyErrorEntry(BaseModel):
470
+ """One entry in a strategy's bounded error history (`StrategyState.recent_errors`).
471
+
472
+ Records a terminal error transition (status → ERROR/KILLED) so operators can
473
+ see the recent error timeline via `GET /strategies/{id}` without grepping
474
+ logs. Routine per-order execution errors are NOT recorded here — those live
475
+ in the execution history (`GET /strategies/{id}/executions`, the `errors`
476
+ field). This captures the high-value 'what killed this strategy' sequence.
477
+ """
478
+
479
+ at: datetime = Field(description="When the error transition was recorded")
480
+ error: str = Field(description="Error message")
481
+ error_reason: Optional[StrategyErrorReason] = Field(
482
+ default=None, description="Classification of the error (risk quarantine, rejection, unknown, ...)"
483
+ )
484
+ from_status: Optional[str] = Field(
485
+ default=None, description="Strategy status immediately before this error transition"
486
+ )
487
+
488
+
489
+ class StrategyState(BaseModel):
490
+ # Decision
491
+ decisions_count: int = Field(default=0, ge=0)
492
+
493
+ # Order & Fill
494
+ total_orders_count: int = Field(default=0, ge=0)
495
+ open_orders_count: int = Field(default=0, ge=0)
496
+ # Add filled_order_count, cancelled_order_count, rejected_order_count if needed
497
+ fills_count: int = Field(default=0, ge=0)
498
+ fills_volume: Decimal = Field(default=Decimal(0), ge=0)
499
+
500
+ # Timestamps
501
+ last_decision_at: Optional[datetime] = None
502
+ last_order_at: Optional[datetime] = None
503
+ last_fill_at: Optional[datetime] = None
504
+
505
+ # Error tracking
506
+ error_count: int = Field(default=0, ge=0)
507
+ last_error: Optional[str] = None
508
+ last_error_at: Optional[datetime] = None
509
+ # Classification for auto-resume gating — set when status transitions to ERROR,
510
+ # cleared on transition away from ERROR.
511
+ error_reason: Optional[StrategyErrorReason] = None
512
+ # Bounded error history (most-recent-first), capped engine-side. Lets operators
513
+ # query the recent terminal-error timeline without log-grepping. Routine
514
+ # per-order errors stay in execution history, not here.
515
+ recent_errors: list[StrategyErrorEntry] = Field(default_factory=list)
516
+
517
+
518
+ class Strategy(BaseApiModel):
519
+ # Strategy identification - name is the unique identifier
520
+ name: str # Canonical: {class_type}_v{version}_{symbol|instance_name}
521
+ class_type: str
522
+ version: int # From strategy class VERSION, not config
523
+ config: dict[str, Any]
524
+
525
+ # Strategy status and data
526
+ status: StrategyStatus
527
+ # Who last set `status`. OPERATOR = explicit live decision
528
+ # (kill/disable/enable) — config-driven reconciliation must never RAISE such
529
+ # a status (resurrect a killed strategy); demoting it pages. CONFIG =
530
+ # engine-derived from the wheel's production configs. Defaults CONFIG so
531
+ # pre-existing rows and older writers are unchanged.
532
+ status_source: StrategyStatusSource = StrategyStatusSource.CONFIG
533
+ state: StrategyState
534
+
535
+ @model_validator(mode="after")
536
+ def validate_config(self) -> Self:
537
+ config_model = BaseStrategyConfig.model_validate(self.config)
538
+ if self.class_type != config_model.class_type:
539
+ raise ValueError(f"Class type mismatch: {self.class_type} != {config_model.class_type}")
540
+ return self
541
+
542
+ @computed_field # type: ignore[prop-decorator]
543
+ @property
544
+ def last_active_at(self) -> Optional[datetime]:
545
+ """Denormalized last-activity timestamp: the most recent of the state's
546
+ last fill/order/decision, floored at created_at.
547
+
548
+ Derived from state (not an independently-maintained field) so it is always
549
+ consistent — no write-path bookkeeping. Because it is included in
550
+ ``model_dump``, the DB layer persists it to the top-level, indexed
551
+ ``strategies.last_active_at`` column on every write, which is what lets the
552
+ History query filter/order/paginate by activity in SQL instead of cracking
553
+ the state JSON. ``None`` only for a never-persisted, never-active strategy.
554
+ """
555
+ candidates = [
556
+ t
557
+ for t in (
558
+ self.created_at,
559
+ self.state.last_fill_at,
560
+ self.state.last_order_at,
561
+ self.state.last_decision_at,
562
+ )
563
+ if t is not None
564
+ ]
565
+ return max(candidates) if candidates else None
566
+
567
+ @property
568
+ def is_active(self) -> bool:
569
+ return self.status == StrategyStatus.ACTIVE
570
+
571
+ @property
572
+ def base_config(self) -> BaseStrategyConfig:
573
+ return BaseStrategyConfig(**self.config)
574
+
575
+
576
+ # --- Execution --- #
577
+
578
+
579
+ class StrategyMarketData(BaseModel):
580
+ order_books: dict[Symbol, dict[VenueName, Optional[OrderBook]]]
581
+ klines: dict[Symbol, dict[VenueName, dict[TimeInterval, list[Kline]]]] = {}
582
+ # Per (symbol, venue) snapshot of recent public trades pre-loaded by the engine
583
+ # when ``BaseStrategyConfig.public_trade`` is set. Empty dict when the strategy
584
+ # has not opted in. Buffer source: ``MarketDataService.list_recent_public_trades``
585
+ # (sync, sub-ms, no REST call).
586
+ public_trades: dict[Symbol, dict[VenueName, list[PublicTrade]]] = {}
587
+
588
+ def get_klines(self, symbol: Symbol, venue: VenueName, interval: TimeInterval) -> list[Kline]:
589
+ """Get klines for a specific symbol, venue, and interval."""
590
+ return self.klines.get(symbol, {}).get(venue, {}).get(interval, [])
591
+
592
+ def has_klines(self, symbol: Symbol, venue: VenueName, interval: TimeInterval) -> bool:
593
+ """Check if klines are available for the specified parameters."""
594
+ return bool(self.get_klines(symbol, venue, interval))
595
+
596
+ def get_public_trades(self, symbol: Symbol, venue: VenueName) -> list[PublicTrade]:
597
+ """Get pre-loaded recent public trades for a (symbol, venue).
598
+
599
+ Returns ``[]`` when the strategy has not opted into ``PublicTradeConfig``
600
+ OR when the engine ring buffer is empty for that (venue, symbol).
601
+ """
602
+ return self.public_trades.get(symbol, {}).get(venue, [])
603
+
604
+ def has_public_trades(self, symbol: Symbol, venue: VenueName) -> bool:
605
+ """Check if pre-loaded recent public trades are available for the specified parameters."""
606
+ return bool(self.get_public_trades(symbol, venue))
607
+
608
+
609
+ class StrategyInput(BaseModel):
610
+ """
611
+ Input data for strategy decision-making.
612
+
613
+ Contains market data (order books, klines), positions, open orders, and
614
+ per-venue account balances. Predictions are passed separately via
615
+ StrategyPredictions to maintain clean separation between market data and ML
616
+ predictions.
617
+ """
618
+
619
+ market_data: StrategyMarketData
620
+ position_group: PositionGroup
621
+ open_orders: list[Order]
622
+ # Per-(venue, asset) SPOT account balances for the strategy's order venues.
623
+ # SPOT only — that is the account the engine reserves against
624
+ # (AccountingService.reserve_balance), so `free` here is exactly what gates
625
+ # an order at reservation time. Lets the venue-selection layer skip a venue
626
+ # that can't fund the order BEFORE emitting it (2026-06-10 incident: a strategy
627
+ # routed a buy-back to a venue with 0 USDT free → 10 rejections →
628
+ # quarantine). Empty dict for callers that don't populate it (e.g. backtest
629
+ # before its population gap is closed); accessors degrade to 0/None.
630
+ balances: dict[VenueName, dict[Asset, Balance]] = {}
631
+
632
+ # Per-venue position slices derived from fills. The venue
633
+ # dimension the NET position_group hides: a delta-neutral cross-venue book
634
+ # nets to ~0 while per-venue gross stays large. None when
635
+ # the engine (or backtest) didn't populate it — strategies must degrade to
636
+ # net-position behavior, mirroring the `balances` contract above.
637
+ venue_breakdown: Optional[StrategyVenueBreakdown] = None
638
+
639
+ # How much of each (venue, asset) THIS strategy may consume right now
640
+ # — the shared pool converted into a per-strategy allowance. The
641
+ # tighter of the strategy's `max_asset_usage_pct` budget and the pool's free
642
+ # balance, i.e. exactly what both RiskService's asset-usage check and
643
+ # `reserve_balance` will gate the order on. `balances` above is the SHARED
644
+ # pool: every sibling sees the same `free` and each concludes it may use all
645
+ # of it (first-come-first-served starvation) — which is why
646
+ # shipping raw balances did not stop the identical rejection cascade
647
+ # from recurring on 2026-07-15. Size against this, not `free`.
648
+ #
649
+ # Empty dict for callers that don't populate it (e.g. backtest); accessors
650
+ # degrade to the free balance, mirroring the `balances` contract above.
651
+ balance_allowances: dict[VenueName, dict[Asset, Decimal]] = {}
652
+
653
+ def get_balance(self, venue: VenueName, asset: Asset) -> Optional[Balance]:
654
+ """SPOT balance for a (venue, asset), or None if the engine didn't populate it."""
655
+ return self.balances.get(venue, {}).get(asset)
656
+
657
+ def get_free_balance(self, venue: VenueName, asset: Asset) -> Decimal:
658
+ """Free SPOT balance the engine will reserve against; 0 when absent.
659
+
660
+ BUY orders reserve quote_asset, SELL orders reserve base_asset — compare
661
+ the order notional against this to predict a reservation rejection.
662
+ """
663
+ balance = self.get_balance(venue, asset)
664
+ return balance.free if balance else Decimal(0)
665
+
666
+ def get_allowance(self, venue: VenueName, asset: Asset) -> Decimal:
667
+ """How much of (venue, asset) this strategy may consume now; 0 when none.
668
+
669
+ BUY consumes quote_asset (quantity x price), SELL consumes base_asset
670
+ (quantity) — keep an order at or under this and it passes both the
671
+ asset-usage check and balance reservation. 0 means reduce-only: the
672
+ strategy is at its budget or the pool is dry.
673
+
674
+ Degrades to `get_free_balance` when the engine didn't populate
675
+ allowances, so a caller written against this reads the shared pool
676
+ rather than silently seeing 0 (backtest, older engines).
677
+ """
678
+ per_venue = self.balance_allowances.get(venue)
679
+ if per_venue is None or asset not in per_venue:
680
+ return self.get_free_balance(venue, asset)
681
+ return per_venue[asset]
682
+
683
+
684
+ class StrategyRegistryEntry(BaseModel):
685
+ """Metadata for a strategy class registered in the engine's strategy registry.
686
+
687
+ Exposed via ``GET /strategies/registry``. Lets operators and the frontend see
688
+ which strategy classes are available for instantiation, where they came from,
689
+ and which version of the algorithm is loaded.
690
+ """
691
+
692
+ name: str = Field(..., description="Class name used as the registry key.")
693
+ module: str = Field(..., description="Python module path where the class is defined.")
694
+ source: str = Field(
695
+ ...,
696
+ description=(
697
+ "Where the strategy code came from. 'builtin' = bundled with the engine; "
698
+ "'external' = loaded from an external wheel/plugin source (Phase 3)."
699
+ ),
700
+ )
701
+ version: int = Field(
702
+ ...,
703
+ description="Class-level VERSION attribute (BaseStrategy.VERSION) — algorithm-level version.",
704
+ )
705
+ registered_at: datetime = Field(..., description="When the class was registered (engine boot time).")
706
+
707
+
708
+ class WheelInstallInfo(BaseModel):
709
+ """Snapshot of the strategies wheel install that's currently active.
710
+
711
+ Populated by ``app.strategies._wheel_loader`` after each successful install
712
+ (or cache-hit on a known target dir). Operators use this to verify the
713
+ engine is running the wheel they expected — for example, confirm that a
714
+ hot-reload actually picked up a new release rather than serving the cached
715
+ wheel from a prior install.
716
+ """
717
+
718
+ requested_url: str = Field(
719
+ ...,
720
+ description=(
721
+ "Original URL passed to the install pipeline — the operator-facing form. "
722
+ "Examples: 'github://owner/repo@stable', 'github://owner/repo@v1.4.0', "
723
+ "'file:///opt/strategies/'."
724
+ ),
725
+ )
726
+ resolved_url: str = Field(
727
+ ...,
728
+ description=(
729
+ "Canonical URL after mutable-tag resolution. Mutable tags like ``@latest`` "
730
+ "and ``@stable`` get rewritten by ``_canonicalize_wheel_url`` so the "
731
+ "per-URL cache key tracks actual content. For ``@latest`` this is the "
732
+ "immutable version tag (e.g. 'github://owner/repo@v1.4.0'); for "
733
+ "``@stable`` named releases it carries a ``#asset={id}`` fragment that "
734
+ "uniquely identifies the installed wheel. Immutable URLs (specific "
735
+ "version tags, ``file://``) pass through unchanged."
736
+ ),
737
+ )
738
+ install_target_dir: str = Field(
739
+ ...,
740
+ description=(
741
+ "Absolute path of the per-version install directory. Same directory "
742
+ "across cache hits at the same resolved URL; new directory each time "
743
+ "the resolved URL advances."
744
+ ),
745
+ )
746
+ installed_at: datetime = Field(
747
+ ...,
748
+ description=(
749
+ "When this install record was created (UTC). For a fresh install this "
750
+ "is when ``pip install`` completed; for a cache hit it's when the "
751
+ "loader noticed the cache was warm. Compare to engine restart time "
752
+ "to tell which case."
753
+ ),
754
+ )
755
+ source: str = Field(
756
+ ...,
757
+ description="What triggered the install: 'boot' (engine startup) or 'hot_reload' (operator API call).",
758
+ )
759
+
760
+ # --- Resolution metadata (Phase: post-canonicalization, pre-install) --- #
761
+ # Cheaply derived during install — surfaced so operators don't need to grep
762
+ # CloudWatch to answer "what did @stable resolve to at this moment?".
763
+
764
+ resolved_tag: Optional[str] = Field(
765
+ None,
766
+ description=(
767
+ "Canonical tag the wheel URL resolved to (e.g. ``@stable`` → ``v1.13.0``). "
768
+ "Populated for mutable tags whose ``tag_name`` differs from the requested tag. "
769
+ "``None`` if the URL was already immutable (specific version tag, ``file://``) "
770
+ "or if the tag resolves to itself (e.g. ``@stable`` named release — see "
771
+ "``resolved_asset_id`` instead)."
772
+ ),
773
+ )
774
+ resolved_asset_id: Optional[int] = Field(
775
+ None,
776
+ description=(
777
+ "GitHub Releases asset id of the installed wheel. The disambiguator for "
778
+ "``@stable``-style tags that resolve to themselves: distinct asset_ids for the "
779
+ "same tag indicate the release was deleted + recreated (e.g. across promote "
780
+ "workflow runs). ``None`` for ``file://`` installs or when the GitHub API "
781
+ "didn't return an asset id."
782
+ ),
783
+ )
784
+ wheel_sha256: Optional[str] = Field(
785
+ None,
786
+ description=(
787
+ "SHA-256 of the installed wheel file. The single field that proves two installs "
788
+ "of the same resolved tag carried bytewise-identical content. ``None`` on cache "
789
+ "hit (the wheel file was not re-read this install) or for local-source-tree "
790
+ "installs (no wheel file to hash)."
791
+ ),
792
+ )
793
+ cache_hit: bool = Field(
794
+ False,
795
+ description=(
796
+ "True if ``install_target_dir`` already contained the unpacked wheel — the "
797
+ "install step skipped both download and ``pip install``. With a fresh "
798
+ "``resolved_asset_id`` this means the engine has seen this exact asset before "
799
+ "(prior boot or prior reload at the same content)."
800
+ ),
801
+ )
802
+
803
+
804
+ class StrategyRegistryStatus(BaseModel):
805
+ """Snapshot of the strategy registry — class entries + wheel install metadata.
806
+
807
+ Returned by ``GET /strategies/registry/status``. Complements
808
+ :class:`StrategyRegistryEntry` (per-class info via ``GET /strategies/registry``)
809
+ and :class:`StrategyRegistryReloadReport` (one-shot reload diff via
810
+ ``POST /strategies/registry/reload``) by exposing the *current* state of the
811
+ registry — which wheel is loaded, when, from where, and whether the
812
+ production-configs hook is registered.
813
+ """
814
+
815
+ entries: list[StrategyRegistryEntry] = Field(
816
+ default_factory=list,
817
+ description="All strategy classes currently registered in ``STRATEGY_REGISTRY``.",
818
+ )
819
+ wheel: Optional[WheelInstallInfo] = Field(
820
+ None,
821
+ description=(
822
+ "The most recent successful wheel install — ``None`` only when the "
823
+ "engine is running with ``STRATEGY_LOCAL_PATH`` (dev source tree) or "
824
+ "the bundled-only fallback."
825
+ ),
826
+ )
827
+ production_configs_registered: bool = Field(
828
+ ...,
829
+ description=(
830
+ "Whether the wheel's ``@register_production_configs`` decorator has "
831
+ "fired. False means the engine has no production-config payload to "
832
+ "instantiate strategies from — typically a wheel-load defect."
833
+ ),
834
+ )
835
+ production_configs_module: Optional[str] = Field(
836
+ None,
837
+ description=(
838
+ "``__module__`` of the registered ``configs_for`` function. "
839
+ "Typically ``'strategies.production'`` when the wheel is healthy. "
840
+ "``None`` when ``production_configs_registered`` is False."
841
+ ),
842
+ )
843
+
844
+
845
+ class StrategyRegistryReloadRequest(BaseModel):
846
+ """Body for ``POST /strategies/registry/reload``.
847
+
848
+ Triggers a re-install of the strategies wheel at ``wheel_url`` and re-walks
849
+ the strategy packages so newly-added classes and version bumps are picked up
850
+ without restarting the engine. Existing strategy instances continue running
851
+ on the class objects they were constructed with; new instances created after
852
+ the reload pick up the latest registered versions.
853
+ """
854
+
855
+ wheel_url: str = Field(
856
+ ...,
857
+ description=(
858
+ "Wheel URL accepted by the engine's loader. Supported forms: "
859
+ "`file://path`, `file://dir/`, `github://owner/repo@tag`, and "
860
+ "`github://owner/repo@latest` (resolved via /releases/latest). "
861
+ "Same scheme as the engine's STRATEGY_WHEEL_URL bootstrap variable."
862
+ ),
863
+ )
864
+
865
+
866
+ class StrategyRegistryReloadChange(BaseModel):
867
+ """One strategy whose registry entry changed across a reload."""
868
+
869
+ name: str = Field(..., description="Strategy registry key (class name).")
870
+ module: str = Field(..., description="Python module path where the class is defined.")
871
+ old_version: Optional[int] = Field(
872
+ None,
873
+ description="Class VERSION before reload. ``None`` if the strategy is newly added.",
874
+ )
875
+ new_version: int = Field(..., description="Class VERSION after reload.")
876
+
877
+
878
+ class StrategyInstanceChange(BaseModel):
879
+ """One strategy instance whose ``Strategy`` row changed during reload reconciliation.
880
+
881
+ A single shape is used across the three buckets in :class:`InstanceReconcileReport`
882
+ (``created`` / ``updated`` / ``orphaned``) with different fields populated per bucket:
883
+
884
+ - ``created``: new row materialized from a config that had no prior instance.
885
+ ``previous_name``/``previous_version``/``previous_status`` are ``None``.
886
+ - ``updated``: existing row matched by identity (``class_type`` + ``instance_name``
887
+ + ``trading_symbols``) and rebound to the latest class version. ``previous_name``
888
+ and ``previous_version`` are set when the version bump renamed the row;
889
+ ``status`` is preserved (``previous_status == status``).
890
+ - ``orphaned``: existing row whose identity is no longer in the configs list.
891
+ Demoted to ``DISABLED`` (or another terminal status per past-strategy rules);
892
+ ``previous_status`` is the pre-demotion status.
893
+ """
894
+
895
+ strategy_id: int = Field(..., description="DB primary key of the strategy row.")
896
+ name: str = Field(..., description="Current name (post-reconciliation).")
897
+ class_type: str = Field(..., description="Strategy class name (e.g. ``TouchBidStrategy``).")
898
+ new_version: int = Field(..., description="Class VERSION the row is now bound to.")
899
+ status: StrategyStatus = Field(..., description="Current status (post-reconciliation).")
900
+ previous_name: Optional[str] = Field(
901
+ None,
902
+ description="Prior name when a version bump caused a rename. ``None`` if unchanged or newly created.",
903
+ )
904
+ previous_version: Optional[int] = Field(
905
+ None,
906
+ description="Prior class VERSION when bumped. ``None`` if unchanged or newly created.",
907
+ )
908
+ previous_status: Optional[StrategyStatus] = Field(
909
+ None,
910
+ description="Prior status (only populated for orphans whose status was demoted).",
911
+ )
912
+
913
+
914
+ class InstanceReconcileReport(BaseModel):
915
+ """Per-instance reconciliation diff applied during reload (phase 2).
916
+
917
+ Phase 1 of reload refreshes the strategy-class table (see ``classes``-level
918
+ fields on :class:`StrategyRegistryReloadReport`). Phase 2 re-invokes
919
+ ``configs_for(...)`` and reconciles the resulting config list against the
920
+ running ``Strategy`` rows. Identity match key is
921
+ ``(class_type, instance_name, trading_symbols)``.
922
+ """
923
+
924
+ created: list[StrategyInstanceChange] = Field(
925
+ default_factory=list,
926
+ description="Configs that had no matching DB row pre-reload; new rows materialized at ``initial_status``.",
927
+ )
928
+ updated: list[StrategyInstanceChange] = Field(
929
+ default_factory=list,
930
+ description="Existing rows rebound to the latest class version (potentially renamed). Status preserved.",
931
+ )
932
+ orphaned: list[StrategyInstanceChange] = Field(
933
+ default_factory=list,
934
+ description="Existing rows not in the new configs list; demoted to ``DISABLED`` (or terminal status).",
935
+ )
936
+ errors: list[str] = Field(
937
+ default_factory=list,
938
+ description="Per-instance errors encountered during reconciliation (DB write failure, instantiation error, etc).",
939
+ )
940
+
941
+
942
+ class StrategyRegistryReloadReport(BaseModel):
943
+ """Result of ``POST /strategies/registry/reload``.
944
+
945
+ Two-phase diff:
946
+
947
+ - **Phase 1 (class registry):** ``added`` is strategies registered post-reload
948
+ that didn't exist before; ``updated`` is strategies whose VERSION changed;
949
+ ``unchanged`` is strategies whose VERSION matches pre-reload. ``errors``
950
+ collects per-module import failures during re-discovery (the reload itself
951
+ succeeded overall — partial failures don't roll back).
952
+ - **Phase 2 (instance reconciliation, ``instances``):** new instance rows
953
+ materialized from the refreshed ``configs_for(...)`` output, existing rows
954
+ rebound to the new class version (with name + config updates and status
955
+ preservation), and orphan rows whose config disappeared from the new list
956
+ (demoted to ``DISABLED``).
957
+
958
+ Engine-bundled sandbox strategies (``app.strategies.sandbox.*``) are NOT
959
+ touched by reload and never appear in any of the diff arrays. Only modules
960
+ under ``_WHEEL_PACKAGE_PREFIXES`` (currently ``("strategies",)``) are
961
+ reloaded; the sandbox stays on its boot-time class objects.
962
+ """
963
+
964
+ wheel_url: str = Field(..., description="The wheel URL that was reloaded (as the caller requested it).")
965
+ before_count: int = Field(..., description="Number of registry entries before reload.")
966
+ after_count: int = Field(..., description="Number of registry entries after reload.")
967
+ added: list[StrategyRegistryReloadChange] = Field(
968
+ default_factory=list,
969
+ description="Strategies registered post-reload that did not exist pre-reload (phase 1 — class registry).",
970
+ )
971
+ updated: list[StrategyRegistryReloadChange] = Field(
972
+ default_factory=list,
973
+ description="Strategies whose VERSION changed across the reload (phase 1 — class registry).",
974
+ )
975
+ unchanged: list[str] = Field(
976
+ default_factory=list,
977
+ description="Names of strategies whose VERSION matches pre-reload (phase 1 — class registry).",
978
+ )
979
+ errors: list[str] = Field(
980
+ default_factory=list,
981
+ description="Per-module import errors encountered during phase 1 re-discovery.",
982
+ )
983
+ instances: InstanceReconcileReport = Field(
984
+ default_factory=InstanceReconcileReport,
985
+ description="Phase 2 instance reconciliation diff — created / updated / orphaned strategy rows.",
986
+ )
987
+ duration_ms: int = Field(..., description="Wall-clock duration of the full reload operation (phase 1 + phase 2).")
988
+
989
+ # --- Install + load instrumentation --- #
990
+ # Self-describing reload report: callers don't need to grep CloudWatch to
991
+ # answer "what wheel did `@stable` actually install" or "did importlib.reload
992
+ # pick up the freshly installed files".
993
+
994
+ wheel_install: Optional[WheelInstallInfo] = Field(
995
+ None,
996
+ description=(
997
+ "Install-side resolution snapshot — what ``wheel_url`` actually resolved to and "
998
+ "where it landed on disk. Same shape as the record returned from "
999
+ "``GET /strategies/registry/status``. ``None`` only if the install step itself "
1000
+ "didn't run (shouldn't happen for a successful reload)."
1001
+ ),
1002
+ )
1003
+ module_file_paths: dict[str, str] = Field(
1004
+ default_factory=dict,
1005
+ description=(
1006
+ "Map of ``{module_name: __file__}`` captured AFTER ``importlib.reload`` for every "
1007
+ "wheel-sourced module. Pairs with ``wheel_install.install_target_dir`` to surface "
1008
+ "stale-reload bugs: if any value doesn't start with the fresh install dir, "
1009
+ "``importlib.reload`` re-read from a prior install path instead of the freshly "
1010
+ "installed one — modules actually loaded into memory are stale relative to what's "
1011
+ "on disk."
1012
+ ),
1013
+ )
1014
+
1015
+
1016
+ class StrategyPredictionMeta(BaseModel):
1017
+ """Provenance for a consumed prediction, carried alongside its value.
1018
+
1019
+ Populated by the engine's pull path (``read_prediction_latest``): ``bar_time``
1020
+ lets a strategy act at most once per bar; ``ml_model_version`` + ``generated_at``
1021
+ let live performance be attributed across model retrains. A prediction only
1022
+ reaches a strategy if the server reported it fresh (``stale=false``) for the
1023
+ latest closed bar, so no ``stale`` field is carried — presence implies freshness.
1024
+ """
1025
+
1026
+ bar_time: datetime = Field(..., description="Close time (UTC) of the last input bar the prediction was from")
1027
+ generated_at: datetime = Field(..., description="When the ML service generated and persisted the prediction")
1028
+ ml_model_version: Optional[str] = Field(default=None, description="Model version that produced the prediction")
1029
+
1030
+
1031
+ class StrategyPredictionRecord(BaseModel):
1032
+ """One bar of prediction history: the prediction ML persisted for the bar closing at ``bar_time``."""
1033
+
1034
+ bar_time: datetime = Field(..., description="Close time (UTC) of the last input bar the prediction was from")
1035
+ prediction: Any = Field(..., description="Prediction value, same shape as StrategyPredictions.data entries")
1036
+
1037
+
1038
+ class StrategyPredictions(BaseModel):
1039
+ """
1040
+ Container for ML predictions, passed separately from StrategyInput.
1041
+
1042
+ Separates market data concerns from ML predictions for cleaner architecture.
1043
+ Predictions are organized as: symbol -> endpoint_name -> prediction value.
1044
+
1045
+ Using ``Any`` for the prediction value to avoid coupling this interface to
1046
+ any specific ML model schema.
1047
+
1048
+ ``meta`` carries per-prediction provenance (bar_time / model version /
1049
+ generated_at) in a parallel map keyed the same way. It is optional and
1050
+ defaults empty, so this stays backward-compatible with callers that only
1051
+ read prediction values via ``get`` / ``get_all``.
1052
+
1053
+ ``history`` carries the last ``PredictionConfig.history_bars`` bars per
1054
+ served prediction (oldest first, including the current bar), keyed the same
1055
+ way. Empty unless the strategy declares ``history_bars``.
1056
+ """
1057
+
1058
+ data: dict[Symbol, dict[str, Any]] = Field(
1059
+ default_factory=dict, description="Predictions organized by symbol and endpoint"
1060
+ )
1061
+ meta: dict[Symbol, dict[str, StrategyPredictionMeta]] = Field(
1062
+ default_factory=dict, description="Per-prediction provenance, keyed by symbol and endpoint (parallel to data)"
1063
+ )
1064
+ history: dict[Symbol, dict[str, list[StrategyPredictionRecord]]] = Field(
1065
+ default_factory=dict,
1066
+ description="Recent bars per prediction, oldest first incl. the current bar (parallel to data)",
1067
+ )
1068
+
1069
+ def get(self, symbol: Symbol, endpoint_name: Optional[str] = None) -> Optional[Any]:
1070
+ """
1071
+ Get prediction for symbol from a specific endpoint, or the first available.
1072
+
1073
+ Args:
1074
+ symbol: Symbol to get prediction for.
1075
+ endpoint_name: Specific endpoint name. If None, returns first available.
1076
+
1077
+ Returns:
1078
+ Prediction if available, None otherwise.
1079
+ """
1080
+ symbol_predictions = self.data.get(symbol, {})
1081
+ if not symbol_predictions:
1082
+ return None
1083
+ if endpoint_name:
1084
+ return symbol_predictions.get(endpoint_name)
1085
+ # First available (backward-compatible default).
1086
+ return next(iter(symbol_predictions.values()))
1087
+
1088
+ def get_all(self, symbol: Symbol) -> dict[str, Any]:
1089
+ """Return all predictions for a symbol across endpoints."""
1090
+ return self.data.get(symbol, {})
1091
+
1092
+ def get_meta(self, symbol: Symbol, endpoint_name: Optional[str] = None) -> Optional[StrategyPredictionMeta]:
1093
+ """Get provenance for a prediction, mirroring ``get``'s selection.
1094
+
1095
+ With no ``endpoint_name``, returns the meta for the first available
1096
+ endpoint — the same one ``get`` returns — so value and meta stay aligned.
1097
+ Returns None when no meta was attached (e.g. backtest push path).
1098
+ """
1099
+ symbol_meta = self.meta.get(symbol, {})
1100
+ if not symbol_meta:
1101
+ return None
1102
+ if endpoint_name:
1103
+ return symbol_meta.get(endpoint_name)
1104
+ return next(iter(symbol_meta.values()))
1105
+
1106
+ def get_history(self, symbol: Symbol, endpoint_name: Optional[str] = None) -> list[StrategyPredictionRecord]:
1107
+ """Get recent bars for a prediction (oldest first), mirroring ``get``'s selection.
1108
+
1109
+ Returns an empty list when no history was attached (``history_bars`` = 0).
1110
+ """
1111
+ symbol_history = self.history.get(symbol, {})
1112
+ if not symbol_history:
1113
+ return []
1114
+ if endpoint_name:
1115
+ return symbol_history.get(endpoint_name, [])
1116
+ return next(iter(symbol_history.values()))
1117
+
1118
+ def has(self, symbol: Symbol, endpoint_name: Optional[str] = None) -> bool:
1119
+ """Check whether a prediction is available."""
1120
+ if endpoint_name:
1121
+ return endpoint_name in self.data.get(symbol, {})
1122
+ return bool(self.data.get(symbol, {}))
1123
+
1124
+ @property
1125
+ def is_empty(self) -> bool:
1126
+ """``True`` when no predictions are stored."""
1127
+ return not self.data
1128
+
1129
+
1130
+ class SkipReason(StrValueEnum):
1131
+ """Why a strategy decide() returned no actions.
1132
+
1133
+ Strategies populate `StrategyOutput.skip_reason` to explain quiet cycles.
1134
+ A `WindowedSkipAggregator` in StrategyService aggregates these per
1135
+ strategy over a rolling time window and emits structured summary lines
1136
+ so silent strategies leave a diagnostic trail (CloudWatch log + backtest
1137
+ BacktestResultDetail.skip_summaries).
1138
+
1139
+ Strategies that don't set skip_reason are recorded as UNATTRIBUTED, which is
1140
+ deliberately NOT a reason — it says the strategy never reported one. OTHER is
1141
+ the different, explicit answer "none of the listed reasons fits". Phase 1 ships
1142
+ the plumbing; Phase 2 migrates strategy paths to set specific reasons, and its
1143
+ progress is readable as the UNATTRIBUTED share falling.
1144
+ """
1145
+
1146
+ NO_DATA = "no_data" # missing OB / klines / prediction
1147
+ SIGNAL_BELOW_THRESHOLD = "signal_weak" # deviation / z-score / strength gated out
1148
+ REGIME_FILTER = "regime_filter" # macro regime / vol gate rejected
1149
+ COOLDOWN = "cooldown" # post-exit, consecutive-loss pause
1150
+ OPEN_ORDERS = "open_orders_inflight" # open-order gate
1151
+ POSITION_LIMIT = "position_limit" # max position / capital allocation
1152
+ FEE_GATE = "fee_gate" # estimated profit < fees
1153
+ HOLD_OPEN = "hold_open" # have position, no exit signal
1154
+ OTHER = "other" # strategy DECIDED none of the above fits — an explicit answer
1155
+ # The strategy set no skip_reason at all. NOT a reason: an instrumentation gap.
1156
+ # Distinct from OTHER, which is a deliberate "none of the above" — conflating the
1157
+ # two makes "this strategy has no edge" and "this strategy was never wired to tell
1158
+ # us" read identically, which is exactly the misread a silent-strategy diagnostic
1159
+ # exists to prevent. Never set by a strategy; only ever stamped by the aggregator.
1160
+ UNATTRIBUTED = "unattributed"
1161
+
1162
+
1163
+ class StrategyOutput(BaseModel):
1164
+ create_orders: list[CreateOrderRequest] = []
1165
+ cancel_orders: list[CancelOrderRequest] = []
1166
+ replace_orders: list[ReplaceOrderRequest] = []
1167
+ # Venue-side stop emission. A bracket is ONE exit intent mapped to the
1168
+ # venue's native OCO (maker TP + stop, one inventory lock, sibling auto-cancelled);
1169
+ # only the strategy knows two exits are mutually exclusive, so exclusivity is
1170
+ # declared here, never inferred from separate orders. amend_stops moves a resting
1171
+ # stop's trigger atomically on venues that support it (OKX amend-algos).
1172
+ bracket_orders: list[BracketOrderRequest] = []
1173
+ amend_stops: list[AmendStopRequest] = []
1174
+ logs: list[str] = []
1175
+
1176
+ # Phase 1 observability fields. Optional in Phase 1 (default None / empty)
1177
+ # so existing strategies need no migration. The aggregator attributes
1178
+ # actionless cycles with skip_reason=None to SkipReason.UNATTRIBUTED.
1179
+ skip_reason: Optional[SkipReason] = Field(
1180
+ default=None,
1181
+ description=(
1182
+ "Why this decide() returned no actions. None = unmigrated path, which the "
1183
+ "aggregator records as UNATTRIBUTED — NOT as OTHER. Leaving it None means "
1184
+ "the diagnostic cannot say why this strategy is quiet, and a window of "
1185
+ "nothing-but-UNATTRIBUTED is flagged UNINSTRUMENTED rather than being "
1186
+ "reported as 'found no opportunity'. Set this in every early-return branch."
1187
+ ),
1188
+ )
1189
+ skip_metrics: dict[str, float] = Field(
1190
+ default_factory=dict,
1191
+ description=(
1192
+ "Small diagnostic numbers attached to a skip (e.g. "
1193
+ "{'signal_strength': 0.32, 'deviation_pct': 0.18}). Capped at 10 "
1194
+ "keys by the aggregator — meant for windowed observability, not "
1195
+ "exhaustive state dump."
1196
+ ),
1197
+ )
1198
+
1199
+ @property
1200
+ def has_actions(self) -> bool:
1201
+ return (
1202
+ bool(self.create_orders)
1203
+ or bool(self.cancel_orders)
1204
+ or bool(self.replace_orders)
1205
+ or bool(self.bracket_orders)
1206
+ or bool(self.amend_stops)
1207
+ )
1208
+
1209
+
1210
+ class SkipSummary(BaseModel):
1211
+ """Per-strategy windowed summary of decide() outcomes.
1212
+
1213
+ Emitted live as a log line and persisted on BacktestResultDetail. Lets
1214
+ silent strategies leave a structured trace: how many iterations ran in
1215
+ the window, how many produced actions, and the reason distribution for
1216
+ the rest.
1217
+ """
1218
+
1219
+ strategy_id: int
1220
+ window_start: datetime
1221
+ window_end: datetime
1222
+ iterations: int = Field(ge=0, description="Total decide() calls in this window")
1223
+ actions: int = Field(ge=0, description="Iterations where has_actions=True")
1224
+ skip_counts: dict[SkipReason, int] = Field(
1225
+ default_factory=dict,
1226
+ description="Count of each skip reason across iterations in the window",
1227
+ )
1228
+ last_metrics: dict[str, float] = Field(
1229
+ default_factory=dict,
1230
+ description="Most recent non-empty skip_metrics seen in the window (small dict, ≤10 keys)",
1231
+ )
1232
+
1233
+
1234
+ class StrategyExecution(BaseApiModel):
1235
+ """
1236
+ Complete record of a strategy execution.
1237
+
1238
+ Storage-optimized: 2-10 KB per execution (vs 20-200 KB with full market data).
1239
+
1240
+ Contains:
1241
+ - Intent: What strategy wanted to do (requests)
1242
+ - Results: What actually happened (created/cancelled orders, errors)
1243
+ - Context: What strategy saw (positions, order references, order book timestamps)
1244
+ """
1245
+
1246
+ # === Identity ===
1247
+ strategy_id: int
1248
+ timestamp: datetime
1249
+ duration_seconds: float
1250
+
1251
+ # === Strategy Decisions (Intent) ===
1252
+ create_order_requests: list[CreateOrderRequest] = Field(
1253
+ default_factory=list, description="Order creation requests made by strategy"
1254
+ )
1255
+ cancel_order_requests: list[CancelOrderRequest] = Field(
1256
+ default_factory=list, description="Order cancellation requests made by strategy"
1257
+ )
1258
+ logs: list[str] = Field(default_factory=list, description="Strategy decision logs")
1259
+
1260
+ # === Execution Results (Actual) ===
1261
+ created_orders: list[int] = Field(default_factory=list, description="Order IDs that were successfully created")
1262
+ cancelled_orders: list[int] = Field(default_factory=list, description="Order IDs that were successfully cancelled")
1263
+ errors: list[str] = Field(default_factory=list, description="Execution errors")
1264
+
1265
+ # === Context Snapshots (What Strategy Saw) ===
1266
+ position_group: PositionGroup = Field(description="Position snapshot at decision time")
1267
+ open_order_ids: list[int] = Field(
1268
+ default_factory=list, description="Order IDs that were open when decision was made"
1269
+ )
1270
+ order_book_timestamps: dict[Symbol, dict[VenueName, datetime]] = Field(
1271
+ default_factory=dict, description="Order book timestamps used in decision (Symbol -> VenueName -> timestamp)"
1272
+ )
1273
+
1274
+ # === Metadata ===
1275
+ has_actions: bool = Field(default=False, description="Whether execution had any actions (orders or errors)")
1276
+
1277
+ @model_validator(mode="after")
1278
+ def compute_has_actions(self) -> Self:
1279
+ """Auto-compute has_actions flag for efficient querying."""
1280
+ self.has_actions = bool(self.created_orders or self.cancelled_orders or self.errors)
1281
+ return self
1282
+
1283
+ # === Analysis Properties ===
1284
+ @property
1285
+ def create_success_rate(self) -> float:
1286
+ """Percentage of create requests that succeeded."""
1287
+ if not self.create_order_requests:
1288
+ return 1.0
1289
+ return len(self.created_orders) / len(self.create_order_requests)
1290
+
1291
+ @property
1292
+ def cancel_success_rate(self) -> float:
1293
+ """Percentage of cancel requests that succeeded."""
1294
+ if not self.cancel_order_requests:
1295
+ return 1.0
1296
+ return len(self.cancelled_orders) / len(self.cancel_order_requests)
1297
+
1298
+ @property
1299
+ def has_failures(self) -> bool:
1300
+ """Whether any requests failed."""
1301
+ return (
1302
+ len(self.created_orders) < len(self.create_order_requests)
1303
+ or len(self.cancelled_orders) < len(self.cancel_order_requests)
1304
+ or bool(self.errors)
1305
+ )
1306
+
1307
+
1308
+ # --- Unused Models --- #
1309
+
1310
+
1311
+ # class StrategyResourceLimitV1(BaseModel):
1312
+ # """
1313
+ # Resource limits a strategy cannot exceed within a certain time period.
1314
+ # """
1315
+ #
1316
+ # time_interval: TimeInterval
1317
+ # max_decisions: Optional[int]
1318
+ # max_orders: Optional[int]
1319
+ # max_fills: Optional[int]
1320
+ #
1321
+ # # Additional fields can be added for account/position limits
1322
+ # # max_account_value: Optional[float]
1323
+ # # max_position_value: Optional[float]
1324
+ #
1325
+ #
1326
+ # class StrategyConvergenceCriteriaV1(BaseModel):
1327
+ # """
1328
+ # Conditions indicating the strategy has "stabilized" in terms of its expected behavior.
1329
+ # - It uses specific statistical properties of time series data.
1330
+ # - It's more of a verification tool.
1331
+ # - It requires deep statistical analysis and might not always be instantaneous in real-time scenarios
1332
+ # """
1333
+ #
1334
+ # # Here are some examples should we decide to use them
1335
+ # pnl_variance_threshold: float
1336
+ # consecutive_days_below_threshold: int
1337
+ #
1338
+ #
1339
+ # class StrategyExpectedOutcomeV1(BaseModel):
1340
+ # """
1341
+ # Expected outcome of running a strategy.
1342
+ # - Expected Metrics after resources limit are reached or certain conditions are met
1343
+ # - Convergence Criteria that can be used as checks to stop a strategy
1344
+ #
1345
+ # To extend this model and support more use cases:
1346
+ # - Add the attribute directly to the StrategyExpectedOutcome model like pnl_range
1347
+ # - Or add additional_expected_metrics for more generic usage.
1348
+ # - If the attribute is common across strategies, provide default values.
1349
+ # """
1350
+ #
1351
+ # strategy_id: str
1352
+ # # Directly define the most essential expected metrics
1353
+ # pnl_range: tuple[float, float] # (-min, max)
1354
+ #
1355
+ # # A more flexible config using Dict of Enums and values
1356
+ # # E.g., {"OrderNumber": 500, "DecisionNumber": 1000, "TradeVolume": 10000}
1357
+ # additional_expected_metrics: dict
1358
+ #
1359
+ # # Add convergence criteria when using it
1360
+ # convergence_criteria: Optional[StrategyConvergenceCriteriaV1] = None