-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy_runtime.py
More file actions
308 lines (283 loc) · 12.3 KB
/
Copy pathstrategy_runtime.py
File metadata and controls
308 lines (283 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
from __future__ import annotations
import os
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Mapping
from quant_platform_kit import PortfolioSnapshot, Position, build_strategy_evaluation_inputs
from quant_platform_kit.strategy_contracts import (
StrategyContext,
StrategyDecision,
StrategyEntrypoint,
StrategyRuntimeAdapter,
build_strategy_context_from_available_inputs,
resolve_strategy_artifact_contract,
)
from crypto_strategies import get_platform_runtime_adapter
from strategy_loader import load_strategy_entrypoint_for_profile
from strategy_registry import BINANCE_PLATFORM, resolve_strategy_metadata
from trend_pool_support import get_default_live_pool_candidates as tp_get_default_live_pool_candidates
DEFAULT_LOCAL_TREND_POOL_ARTIFACT = Path(__file__).resolve().parent / "artifacts" / "live_pool_legacy.json"
# Ensure artifacts directory exists so local-fallback path never fails with FileNotFoundError
DEFAULT_LOCAL_TREND_POOL_ARTIFACT.parent.mkdir(parents=True, exist_ok=True)
DEFAULT_TREND_POOL_SIZE = 5
COMBO_RUNTIME_ENV_OVERRIDES: tuple[tuple[str, str, str], ...] = (
("BTC_WEIGHT", "btc_weight", "ratio"),
("TREND_WEIGHT", "trend_weight", "ratio"),
("DYNAMIC_MODE", "dynamic_mode", "bool"),
("DYNAMIC_REGIME_MODE", "dynamic_regime_mode", "regime_mode"),
("DYNAMIC_REGIME_OFF_CUT", "dynamic_regime_off_cut", "ratio"),
("DYNAMIC_HARD_SMA200_RATIO", "dynamic_hard_sma200_ratio", "positive_float"),
("DYNAMIC_HARD_MA200_SLOPE", "dynamic_hard_ma200_slope", "float"),
("DYNAMIC_SOFT_SMA200_RATIO", "dynamic_soft_sma200_ratio", "positive_float"),
("DYNAMIC_HARD_BTC_WEIGHT", "dynamic_hard_btc_weight", "ratio"),
("DYNAMIC_HARD_TREND_WEIGHT", "dynamic_hard_trend_weight", "ratio"),
("DYNAMIC_SOFT_BTC_WEIGHT", "dynamic_soft_btc_weight", "ratio"),
("DYNAMIC_SOFT_TREND_WEIGHT", "dynamic_soft_trend_weight", "ratio"),
("ROTATION_TOP_N", "rotation_top_n", "int"),
("TARGET_VOL", "target_vol", "positive_float"),
("CIRCUIT_BREAKER_ENABLED", "circuit_breaker_enabled", "bool"),
("ZSCORE_EXIT_RISK_REDUCED_EXPOSURE", "zscore_exit_risk_reduced_exposure", "ratio"),
("ZSCORE_EXIT_RISK_OFF_EXPOSURE", "zscore_exit_risk_off_exposure", "ratio"),
("ZSCORE_EXIT_ALLOW_OUTSIDE_EXECUTION_WINDOW", "zscore_exit_allow_outside_execution_window", "bool"),
)
def _parse_env_bool(name: str, raw: str) -> bool:
normalized = raw.strip().lower()
if normalized in {"1", "true", "yes", "y", "on"}:
return True
if normalized in {"0", "false", "no", "n", "off"}:
return False
raise ValueError(f"{name} must be boolean-like")
def _parse_runtime_env_value(name: str, raw: str, kind: str) -> Any:
if kind == "bool":
return _parse_env_bool(name, raw)
if kind == "regime_mode":
normalized = raw.strip().lower().replace("-", "_")
if normalized == "legacy":
return "legacy"
if normalized in {"dual", "dual_leg", "tiered", "cash_cap"}:
return "dual_leg"
raise ValueError(f"{name} must be legacy or dual_leg")
if kind == "int":
value = int(raw)
if value < 1:
raise ValueError(f"{name} must be >= 1")
return value
value = float(raw)
if kind == "float":
return value
if kind == "ratio":
if not 0.0 <= value <= 1.0:
raise ValueError(f"{name} must be between 0 and 1")
return value
if kind == "positive_float":
if value <= 0.0:
raise ValueError(f"{name} must be > 0")
return value
raise ValueError(f"unsupported runtime env parser: {kind}")
def _load_combo_runtime_overrides() -> dict[str, Any]:
overrides: dict[str, Any] = {}
for env_name, config_key, kind in COMBO_RUNTIME_ENV_OVERRIDES:
raw = os.getenv(env_name)
if raw is None or not raw.strip():
continue
overrides[config_key] = _parse_runtime_env_value(env_name, raw, kind)
return overrides
@dataclass(frozen=True)
class StrategyEvaluationResult:
decision: StrategyDecision
account_metrics: Mapping[str, Any] = field(default_factory=dict)
metadata: Mapping[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class LoadedStrategyRuntime:
entrypoint: StrategyEntrypoint
runtime_adapter: StrategyRuntimeAdapter
runtime_overrides: Mapping[str, Any] = field(default_factory=dict)
merged_runtime_config: Mapping[str, Any] = field(default_factory=dict)
local_artifact_candidates: tuple[Path, ...] = ()
@property
def profile(self) -> str:
return self.entrypoint.manifest.profile
@property
def trend_pool_size(self) -> int:
return int(self.merged_runtime_config.get("trend_pool_size", DEFAULT_TREND_POOL_SIZE))
@property
def artifact_contract(self) -> dict[str, Any]:
contract = resolve_strategy_artifact_contract(self.runtime_adapter)
return {
"version": str(
contract.snapshot_contract_version
or self.merged_runtime_config.get("artifact_contract_version", "")
),
"max_age_days": int(self.merged_runtime_config.get("artifact_max_age_days", 45)),
"acceptable_modes": tuple(self.merged_runtime_config.get("artifact_acceptable_modes", ())),
"requires_artifacts": bool(contract.requires_snapshot_artifacts),
"requires_manifest": bool(contract.requires_snapshot_manifest_path),
"config_source_policy": str(contract.config_source_policy),
"default_local_candidates": tuple(str(path) for path in self.local_artifact_candidates),
}
@property
def default_local_artifact_path(self) -> Path:
if self.local_artifact_candidates:
return self.local_artifact_candidates[0]
return DEFAULT_LOCAL_TREND_POOL_ARTIFACT
def compute_account_metrics(
self,
runtime_trend_universe,
balances,
prices,
u_total,
fuel_val,
) -> dict[str, float]:
trend_value = sum(float(balances[symbol]) * float(prices[symbol]) for symbol in runtime_trend_universe)
dca_value = float(balances["BTCUSDT"]) * float(prices["BTCUSDT"])
total_equity = float(u_total) + float(fuel_val) + trend_value + dca_value
return {
"cash_usdt": float(u_total),
"trend_value": trend_value,
"dca_value": dca_value,
"total_equity": total_equity,
}
def build_portfolio_snapshot(
self,
*,
account_metrics: Mapping[str, Any],
balances: Mapping[str, Any] | None,
prices: Mapping[str, Any],
trend_universe_symbols: tuple[str, ...],
as_of: datetime,
) -> PortfolioSnapshot:
positions: list[Position] = []
normalized_symbols = ("BTCUSDT",) + tuple(str(symbol) for symbol in trend_universe_symbols)
balances_map = dict(balances or {})
for symbol in normalized_symbols:
quantity = float(balances_map.get(symbol, 0.0) or 0.0)
last_price = float(prices.get(symbol, 0.0) or 0.0)
market_value = quantity * last_price
if quantity <= 0.0 and market_value <= 0.0:
continue
positions.append(
Position(
symbol=symbol,
quantity=quantity,
market_value=market_value,
)
)
return PortfolioSnapshot(
as_of=as_of,
total_equity=float(account_metrics["total_equity"]),
buying_power=float(account_metrics["cash_usdt"]),
cash_balance=float(account_metrics["cash_usdt"]),
positions=tuple(positions),
metadata={
"account_metrics": dict(account_metrics),
"cash_available_for_trading": float(account_metrics["cash_usdt"]),
"trend_value": float(account_metrics["trend_value"]),
"dca_value": float(account_metrics["dca_value"]),
},
)
def evaluate(
self,
*,
prices,
trend_indicators,
btc_snapshot,
account_metrics,
trend_universe_symbols,
state,
translator: Callable[..., str],
balances: Mapping[str, Any] | None = None,
now_utc=None,
allow_new_trend_entries: bool = True,
allow_rotation_refresh: bool = True,
get_symbol_trade_state_fn: Callable[..., Any] | None = None,
set_symbol_trade_state_fn: Callable[..., Any] | None = None,
) -> StrategyEvaluationResult:
runtime_config = dict(self.runtime_overrides)
runtime_config.update(
{
"translator": translator,
"allow_new_trend_entries": bool(allow_new_trend_entries),
"allow_rotation_refresh": bool(allow_rotation_refresh),
"now_utc": now_utc,
}
)
if get_symbol_trade_state_fn is not None:
runtime_config["get_symbol_trade_state_fn"] = get_symbol_trade_state_fn
if set_symbol_trade_state_fn is not None:
runtime_config["set_symbol_trade_state_fn"] = set_symbol_trade_state_fn
runtime_now = now_utc or datetime.now(timezone.utc)
portfolio_snapshot = self.build_portfolio_snapshot(
account_metrics=account_metrics,
balances=balances,
prices=prices,
trend_universe_symbols=tuple(trend_universe_symbols),
as_of=runtime_now,
)
from quant_platform_kit.strategy_lifecycle.live_equity import stamp_consecutive_losses_on_snapshot
portfolio_snapshot = stamp_consecutive_losses_on_snapshot(
portfolio_snapshot,
strategy_profile=self.profile,
domain="crypto",
logger=getattr(self, "logger", None),
)
evaluation_inputs = build_strategy_evaluation_inputs(
available_inputs=self.runtime_adapter.available_inputs,
market_inputs={
"market_prices": prices,
"derived_indicators": trend_indicators,
"benchmark_snapshot": btc_snapshot,
"universe_snapshot": tuple(trend_universe_symbols),
},
portfolio_snapshot=portfolio_snapshot,
)
ctx = build_strategy_context_from_available_inputs(
entrypoint=self.entrypoint,
runtime_adapter=self.runtime_adapter,
as_of=runtime_now,
available_inputs=evaluation_inputs,
state=state,
runtime_config=runtime_config,
capabilities={"platform": BINANCE_PLATFORM},
)
ctx = StrategyContext(
as_of=ctx.as_of,
market_data=ctx.market_data,
portfolio=ctx.portfolio,
state=ctx.state,
runtime_config=ctx.runtime_config,
capabilities=ctx.capabilities,
artifacts={"trend_pool_contract": self.artifact_contract},
)
decision = self.entrypoint.evaluate(ctx)
return StrategyEvaluationResult(
decision=decision,
account_metrics=dict(account_metrics),
metadata={
"strategy_profile": self.profile,
"strategy_display_name": resolve_strategy_metadata(
self.profile,
platform_id=BINANCE_PLATFORM,
).display_name,
},
)
def load_strategy_runtime(raw_profile: str | None) -> LoadedStrategyRuntime:
entrypoint = load_strategy_entrypoint_for_profile(raw_profile)
runtime_adapter = get_platform_runtime_adapter(
entrypoint.manifest.profile,
platform_id=BINANCE_PLATFORM,
)
merged_runtime_config = dict(entrypoint.manifest.default_config)
runtime_overrides: dict[str, Any] = {}
if entrypoint.manifest.profile == "crypto_equity_combo":
runtime_overrides.update(_load_combo_runtime_overrides())
local_artifact_candidates = tuple(
Path(path) for path in tp_get_default_live_pool_candidates(DEFAULT_LOCAL_TREND_POOL_ARTIFACT)
)
return LoadedStrategyRuntime(
entrypoint=entrypoint,
runtime_adapter=runtime_adapter,
runtime_overrides=runtime_overrides,
merged_runtime_config=merged_runtime_config,
local_artifact_candidates=local_artifact_candidates,
)