Fix trade recovery, local web isolation and backtest risk accounting
This commit is contained in:
1 parent
5c6b0dc54a
commit
6aa76064dc
29 files changed
+2662
-1693
No files matched your search
+36
-25
@@ -495,6 +495,24 @@ def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_
|
||||
return windows, sorted(failed)
|
||||
|
||||
|
||||
def _track_risk(risk: dict[str, float], equity: float) -> None:
|
||||
risk["peak"] = max(risk["peak"], equity)
|
||||
drawdown = risk["peak"] - equity
|
||||
drawdown_pct = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
|
||||
# The largest dollar loss and largest percentage loss may follow different peaks.
|
||||
risk["max_dd_usdt"] = max(risk["max_dd_usdt"], drawdown)
|
||||
risk["max_dd_pct"] = max(risk["max_dd_pct"], drawdown_pct)
|
||||
risk["min_equity"] = min(risk["min_equity"], equity)
|
||||
|
||||
|
||||
def _equity_floor_crossing(start: float, end: float, start_equity: float,
|
||||
end_equity: float, floor: float) -> float | None:
|
||||
"""Price where linearly marked equity first reaches the floor on this segment."""
|
||||
if start_equity > floor >= end_equity:
|
||||
return start + (end - start) * (floor - start_equity) / (end_equity - start_equity)
|
||||
return None
|
||||
|
||||
|
||||
def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
|
||||
strategies: dict[str, dict[str, float]], initial_capital: float,
|
||||
fee_pct: float = TAKER_FEE_PCT,
|
||||
@@ -560,21 +578,12 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
|
||||
equity += unrealized - estimated_exit_fee
|
||||
return equity
|
||||
|
||||
def track_risk(equity: float) -> None:
|
||||
if equity > risk["peak"]:
|
||||
risk["peak"] = equity
|
||||
drawdown = risk["peak"] - equity
|
||||
if drawdown > risk["max_dd_usdt"]:
|
||||
risk["max_dd_usdt"] = drawdown
|
||||
risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
|
||||
risk["min_equity"] = min(risk["min_equity"], equity)
|
||||
|
||||
def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool:
|
||||
if equity_stop["triggered"]:
|
||||
return True
|
||||
marks[symbol] = price
|
||||
equity = equity_at()
|
||||
track_risk(equity)
|
||||
_track_risk(risk, equity)
|
||||
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12):
|
||||
equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
|
||||
return True
|
||||
@@ -742,12 +751,10 @@ def run_backtest(candles_by_symbol: dict[str, list[list[float]]],
|
||||
# Add the precise capital-floor crossing as an event so a later rebound
|
||||
# inside the same candle cannot hide a drawdown breach.
|
||||
if min_equity_pct > 0 and end < current:
|
||||
current_equity = equity_at(symbol, current)
|
||||
end_equity = equity_at(symbol, end)
|
||||
if current_equity > equity_floor >= end_equity and current_equity != end_equity:
|
||||
stop_level = current + (end - current) * (
|
||||
(equity_floor - current_equity) / (end_equity - current_equity)
|
||||
)
|
||||
stop_level = _equity_floor_crossing(
|
||||
current, end, equity_at(symbol, current), equity_at(symbol, end), equity_floor,
|
||||
)
|
||||
if stop_level is not None:
|
||||
candidates.append((stop_level, "EQUITY_STOP"))
|
||||
_tp, stop_level, liq_level = exit_levels(symbol, pos)
|
||||
if stop_level is not None and end <= stop_level < current:
|
||||
@@ -1118,10 +1125,11 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
|
||||
def iso(stamp: int) -> str:
|
||||
return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat()
|
||||
|
||||
def equity_at() -> float:
|
||||
def equity_at(symbol: str | None = None, price: float | None = None) -> float:
|
||||
equity = cash
|
||||
for position_symbol, pos in positions.items():
|
||||
mark = marks.get(position_symbol, pos.entry_price)
|
||||
mark = (price if position_symbol == symbol and price is not None
|
||||
else marks.get(position_symbol, pos.entry_price))
|
||||
equity += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
|
||||
- mark * pos.qty * fee_pct / 100)
|
||||
return equity
|
||||
@@ -1131,13 +1139,7 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
|
||||
return True
|
||||
marks[symbol] = price
|
||||
equity = equity_at()
|
||||
if equity > risk["peak"]:
|
||||
risk["peak"] = equity
|
||||
drawdown = risk["peak"] - equity
|
||||
if drawdown > risk["max_dd_usdt"]:
|
||||
risk["max_dd_usdt"] = drawdown
|
||||
risk["max_dd_pct"] = drawdown / risk["peak"] * 100 if risk["peak"] > 0 else 0.0
|
||||
risk["min_equity"] = min(risk["min_equity"], equity)
|
||||
_track_risk(risk, equity)
|
||||
if min_equity_pct > 0 and equity <= equity_floor + max(1e-9, abs(equity_floor) * 1e-12):
|
||||
equity_stop.update(triggered=True, timestamp=stamp, equity=equity)
|
||||
return True
|
||||
@@ -1296,6 +1298,12 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
|
||||
return
|
||||
liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side)
|
||||
candidates = []
|
||||
if min_equity_pct > 0:
|
||||
floor_price = _equity_floor_crossing(
|
||||
start, end, equity_at(symbol, start), equity_at(symbol, end), equity_floor,
|
||||
)
|
||||
if floor_price is not None:
|
||||
candidates.append((floor_price, "EQUITY_STOP"))
|
||||
lo, hi = min(start, end), max(start, end)
|
||||
if lo <= pos.stop <= hi:
|
||||
candidates.append((pos.stop, "STOP"))
|
||||
@@ -1307,6 +1315,9 @@ def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str
|
||||
# The first level crossed on the way from ``start`` is the nearest one.
|
||||
level, event = min(candidates, key=lambda item: abs(item[0] - start))
|
||||
marks[symbol] = level
|
||||
if event == "EQUITY_STOP":
|
||||
mark_and_check_stop(symbol, level, stamp)
|
||||
return
|
||||
if event == "LIQ":
|
||||
close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True)
|
||||
else:
|
||||
|
||||
Reference in new issue
Block a user