Files
listik efd4e1dcf4
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
linux
2026-10-23 21:36:08 +03:00

397 lines
19 KiB
Python

"""Shared strategy formulas used by simulation, live trading and the historical backtest.
Keeping these rules in one place prevents the three modes from drifting apart.
"""
from __future__ import annotations
import math
# Approximate maintenance-margin rate for Bybit USDT perpetuals at the lowest risk tier.
MAINTENANCE_MARGIN_RATE_PCT = 0.5
def fee_cover_pct(fee_pct: float) -> float:
"""Minimum gross price rise that offsets taker fees on entry and exit fills."""
fee = max(0.0, fee_pct) / 100
return ((1 + fee) / (1 - fee) - 1) * 100 if fee < 1 else math.inf
def effective_take_profit_pct(take_profit_pct: float, fee_pct: float) -> float:
"""TP percentage raised to cover round-trip fees; 0 keeps TP disabled."""
if take_profit_pct <= 0:
return 0.0
return max(take_profit_pct, fee_cover_pct(fee_pct))
def take_profit_price(avg_entry: float, take_profit_pct: float, fee_pct: float) -> float | None:
pct = effective_take_profit_pct(take_profit_pct, fee_pct)
return avg_entry * (1 + pct / 100) if pct > 0 else None
def stop_loss_price(avg_entry: float, stop_loss_pct: float) -> float | None:
return avg_entry * (1 - stop_loss_pct / 100) if stop_loss_pct > 0 else None
def entry_level(baseline_close: float, trigger_pct: float) -> float:
return baseline_close * (1 + trigger_pct / 100)
def add_level(last_add_price: float, add_step_pct: float) -> float | None:
return last_add_price * (1 - add_step_pct / 100) if add_step_pct > 0 else None
def can_add(add_count: int, max_adds: int, add_step_pct: float, averaging_frozen: bool = False) -> bool:
return add_step_pct > 0 and add_count < max_adds and not averaging_frozen
def liquidation_price(avg_entry: float, leverage: float,
mmr_pct: float = MAINTENANCE_MARGIN_RATE_PCT, side: str = "long") -> float | None:
"""Approximate isolated-margin liquidation price; None when leverage <= 1 for a LONG.
With leverage 1 a LONG cannot lose more than its margin before price reaches 0,
so liquidation is not modelled. For higher leverage the LONG price is
entry * (1 - 1/leverage + MMR) and the SHORT price is entry * (1 + 1/leverage - MMR).
A 1x SHORT is liquidated near a doubling of the price.
"""
if side == "short":
return avg_entry * (1 + 1 / max(leverage, 1.0) - mmr_pct / 100)
if leverage <= 1:
return None
return max(0.0, avg_entry * (1 - 1 / leverage + mmr_pct / 100))
# ---------------------------------------------------------------------------
# Strategy modes.
#
# "classic" — the original rule: entry on a rise above the previous 1-minute close,
# averaging down, TP/stop from the average price (settings per currency).
# "breakout" — mode A: LONG on a close above the N-hour high with a volume spike,
# ATR stop, partial take-profit, breakeven and ATR trailing stop.
# "fade" — mode B: SHORT after a pump stalls (24h growth, high funding, close back
# under the turnover-weighted average price and below the recent high).
# Modes A and B share one exit engine and one parameter set for all currencies.
# ---------------------------------------------------------------------------
STRATEGY_CLASSIC = "classic"
STRATEGY_BREAKOUT = "breakout"
STRATEGY_FADE = "fade"
STRATEGY_MODES = (STRATEGY_CLASSIC, STRATEGY_BREAKOUT, STRATEGY_FADE)
STRATEGY_TITLES = {
STRATEGY_CLASSIC: "Классика: пробой 1-мин свечи + усреднение",
STRATEGY_BREAKOUT: "A: пробой N-часового максимума (ATR)",
STRATEGY_FADE: "B: шорт затухающего пампа",
}
STRATEGY_DESCRIPTIONS = {
STRATEGY_CLASSIC: (
"LONG при росте от закрытия прошлой минутной свечи, доливки при снижении, TP и стоп от средней "
"цены. Настройки задаются для каждой валюты отдельно; здесь — шаблон, который применяется ко всем."
),
STRATEGY_BREAKOUT: (
"LONG, когда закрытие свечи таймфрейма выше максимума за N часов и оборот свечи в K раз выше "
"среднего. Стоп = вход − ATR × множитель, без усреднения. Часть позиции фиксируется на заданном R "
"(R — расстояние до стопа), стоп переносится в безубыток, остаток ведётся трейлинг-стопом по ATR. "
"Фильтры: BTC выше EMA на часовом графике и funding не выше порога."
),
STRATEGY_FADE: (
"SHORT монеты после пампа: рост за 24 ч выше порога, funding не ниже порога, максимум за "
"последние часы уже позади, закрытие ниже него на заданный процент и ниже средней цены по "
"обороту (VWAP). Стоп — над максимумом + ATR × буфер; сделка пропускается, если стоп дальше "
"заданного процента. Выход: частичная фиксация на R, безубыток, трейлинг по ATR. "
"Funding при положительной ставке получают шорты."
),
}
# (key, label, minimum, maximum, integer?) — minimum 0 usually means "0 = выключено".
_COMMON_RISK_FIELDS = (
("stake_pct", "Ставка, % депозита", 0.01, 100.0, False),
("leverage", "Плечо", 1.0, 100.0, False),
("timeframe_min", "Таймфрейм сигнала, мин (5/15/30/60)", 5.0, 60.0, True),
("atr_period", "Период ATR, свечей", 2.0, 200.0, True),
)
_COMMON_EXIT_FIELDS = (
("partial_r", "Частичная фиксация на R (0 = выкл.)", 0.0, 50.0, False),
("partial_pct", "Доля частичной фиксации, %", 0.0, 100.0, False),
("breakeven", "Безубыток после частичной (1/0)", 0.0, 1.0, True),
("trail_atr", "Трейлинг-стоп, ATR (0 = выкл.)", 0.0, 50.0, False),
("take_profit_r", "Финальный TP на R (0 = выкл.)", 0.0, 100.0, False),
("max_hold_hours", "Макс. удержание, ч (0 = выкл.)", 0.0, 10000.0, False),
)
MODE_FIELDS: dict[str, tuple[tuple[str, str, float, float, bool], ...]] = {
STRATEGY_BREAKOUT: _COMMON_RISK_FIELDS + (
("breakout_hours", "Пробой максимума за, ч", 0.25, 168.0, False),
("volume_mult", "Оборот свечи × среднего (0 = выкл.)", 0.0, 100.0, False),
("stop_atr", "Стоп, ATR от входа", 0.1, 50.0, False),
("btc_filter", "Фильтр BTC выше EMA 1ч (1/0)", 0.0, 1.0, True),
("btc_ema", "Период EMA BTC, часов", 2.0, 900.0, True),
("max_funding_pct", "Не входить при funding выше, % (0 = выкл.)", 0.0, 10.0, False),
) + _COMMON_EXIT_FIELDS,
STRATEGY_FADE: _COMMON_RISK_FIELDS + (
("min_growth_24h", "Рост за 24 ч, не меньше %", 0.0, 10000.0, False),
("min_funding_pct", "Funding не ниже, % (0 = выкл.)", 0.0, 10.0, False),
("high_lookback_hours", "Максимум пампа за последние, ч", 0.5, 72.0, False),
("pullback_pct", "Закрытие ниже максимума на, %", 0.0, 90.0, False),
("vwap_hours", "VWAP по обороту за, ч", 0.5, 72.0, False),
("stop_buffer_atr", "Стоп над максимумом, ATR", 0.0, 20.0, False),
("max_stop_pct", "Макс. расстояние до стопа, %", 0.1, 100.0, False),
) + _COMMON_EXIT_FIELDS,
}
MODE_DEFAULTS: dict[str, dict[str, float]] = {
STRATEGY_BREAKOUT: {
"stake_pct": 5.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0,
"breakout_hours": 4.0, "volume_mult": 2.0, "stop_atr": 2.0,
"btc_filter": 1.0, "btc_ema": 200.0, "max_funding_pct": 0.05,
"partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0,
"take_profit_r": 0.0, "max_hold_hours": 48.0,
},
STRATEGY_FADE: {
"stake_pct": 3.0, "leverage": 1.0, "timeframe_min": 15.0, "atr_period": 14.0,
"min_growth_24h": 30.0, "min_funding_pct": 0.03, "high_lookback_hours": 6.0,
"pullback_pct": 3.0, "vwap_hours": 6.0, "stop_buffer_atr": 0.5, "max_stop_pct": 15.0,
"partial_r": 1.5, "partial_pct": 50.0, "breakeven": 1.0, "trail_atr": 3.0,
"take_profit_r": 0.0, "max_hold_hours": 24.0,
},
}
ALLOWED_TIMEFRAMES = (5, 15, 30, 60)
def parse_mode_params(mode: str, raw: dict[str, object]) -> dict[str, float]:
"""Validate the text values of a mode's settings; raises ValueError with a readable message."""
params: dict[str, float] = {}
for key, label, minimum, maximum, integer in MODE_FIELDS[mode]:
value = raw.get(key, MODE_DEFAULTS[mode][key])
try:
number = float(str(value).strip().replace(",", "."))
except ValueError as exc:
raise ValueError(f"Проверьте значение «{label}».") from exc
if not math.isfinite(number) or not minimum <= number <= maximum:
raise ValueError(f"«{label}» должно быть от {minimum:g} до {maximum:g}.")
if integer and not number.is_integer():
raise ValueError(f"«{label}» должно быть целым числом.")
params[key] = number
if int(params["timeframe_min"]) not in ALLOWED_TIMEFRAMES:
raise ValueError("Таймфрейм сигнала: 5, 15, 30 или 60 минут.")
if params["partial_pct"] > 0 and params["partial_r"] <= 0:
raise ValueError("Для частичной фиксации укажите R больше 0 или долю 0%.")
if (params["trail_atr"] <= 0 and params["take_profit_r"] <= 0
and not (params["partial_r"] > 0 and params["partial_pct"] >= 100)
and params["max_hold_hours"] <= 0):
raise ValueError("Задайте выход по прибыли: трейлинг, финальный TP, 100% частичную фиксацию "
"или максимальное удержание.")
return params
def side_sign(side: str) -> float:
return -1.0 if side == "short" else 1.0
def unrealized_pnl(side: str, entry: float, mark: float, qty: float) -> float:
return side_sign(side) * (mark - entry) * qty
def bars_for_hours(hours: float, timeframe_min: float) -> int:
return max(1, int(round(hours * 60 / timeframe_min)))
def aggregate_candles(rows: list[list[float]], timeframe_min: int) -> list[list[float]]:
"""Group minute rows [start_ms, o, h, l, c, (turnover)] into timeframe candles."""
step = int(timeframe_min) * 60_000
output: list[list[float]] = []
for row in rows:
bucket = (int(row[0]) // step) * step
turnover = float(row[5]) if len(row) > 5 and row[5] is not None else 0.0
if output and output[-1][0] == bucket:
candle = output[-1]
candle[2] = max(candle[2], float(row[2]))
candle[3] = min(candle[3], float(row[3]))
candle[4] = float(row[4])
candle[5] += turnover
else:
output.append([bucket, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover])
return output
def average_true_range(candles: list[list[float]], period: int) -> float | None:
"""Simple average of the true range over the last ``period`` candles."""
period = int(period)
if period < 1 or len(candles) < period + 1:
return None
ranges = []
for previous, current in zip(candles[-period - 1:-1], candles[-period:]):
high, low, prev_close = float(current[2]), float(current[3]), float(previous[4])
ranges.append(max(high - low, abs(high - prev_close), abs(low - prev_close)))
value = sum(ranges) / len(ranges)
return value if value > 0 else None
def turnover_vwap(candles: list[list[float]]) -> float | None:
"""Average typical price weighted by turnover (falls back to an equal-weight mean)."""
if not candles:
return None
typical = [(float(c[2]) + float(c[3]) + float(c[4])) / 3 for c in candles]
weights = [float(c[5]) if len(c) > 5 and c[5] else 0.0 for c in candles]
total = sum(weights)
if total > 0:
return sum(price * weight for price, weight in zip(typical, weights)) / total
return sum(typical) / len(typical)
def ema(values: list[float], period: int) -> float | None:
period = int(period)
if period < 1 or len(values) < period:
return None
alpha = 2 / (period + 1)
value = sum(values[:period]) / period
for item in values[period:]:
value = alpha * item + (1 - alpha) * value
return value
def btc_regime_ok(hourly_closes: list[float], ema_period: int) -> bool | None:
"""True when the last closed BTC hour is above its EMA; None without enough data."""
average = ema(hourly_closes, ema_period)
if average is None:
return None
return hourly_closes[-1] > average
def required_bars(mode: str, params: dict[str, float]) -> int:
"""Closed timeframe candles the signal needs (oldest to the just-closed one)."""
tf = params["timeframe_min"]
atr_bars = int(params["atr_period"]) + 1
if mode == STRATEGY_BREAKOUT:
return max(bars_for_hours(params["breakout_hours"], tf) + 1, atr_bars)
return max(bars_for_hours(24, tf) + 1, bars_for_hours(params["high_lookback_hours"], tf),
bars_for_hours(params["vwap_hours"], tf), atr_bars)
def evaluate_breakout(candles: list[list[float]], params: dict[str, float],
funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None:
"""Mode A signal on closed candles [start, o, h, l, c, turnover]; the last one has just closed."""
if len(candles) < required_bars(STRATEGY_BREAKOUT, params):
return None
lookback = bars_for_hours(params["breakout_hours"], params["timeframe_min"])
last = candles[-1]
prior = candles[-lookback - 1:-1]
level = max(float(c[2]) for c in prior)
close = float(last[4])
if close <= level:
return None
if params["volume_mult"] > 0:
average = sum(float(c[5]) if len(c) > 5 else 0.0 for c in prior) / len(prior)
turnover = float(last[5]) if len(last) > 5 else 0.0
if average > 0 and turnover < params["volume_mult"] * average:
return None
if params["btc_filter"] >= 1 and btc_ok is not True:
return None
if (params["max_funding_pct"] > 0 and funding_rate_pct is not None
and funding_rate_pct > params["max_funding_pct"]):
return None
atr = average_true_range(candles, int(params["atr_period"]))
if atr is None:
return None
return {"side": "long", "atr": atr, "level": level, "close": close, "candle_start": int(last[0])}
def evaluate_fade(candles: list[list[float]], params: dict[str, float],
funding_rate_pct: float | None = None) -> dict | None:
"""Mode B signal on closed candles; returns the planned SHORT stop above the pump high."""
if len(candles) < required_bars(STRATEGY_FADE, params):
return None
tf = params["timeframe_min"]
last = candles[-1]
close = float(last[4])
day_ago = float(candles[-bars_for_hours(24, tf) - 1][4])
if day_ago <= 0:
return None
growth = (close / day_ago - 1) * 100
if growth < params["min_growth_24h"]:
return None
if params["min_funding_pct"] > 0 and (funding_rate_pct is None
or funding_rate_pct < params["min_funding_pct"]):
return None
window = candles[-bars_for_hours(params["high_lookback_hours"], tf):]
high_index = max(range(len(window)), key=lambda index: float(window[index][2]))
high = float(window[high_index][2])
if high_index == len(window) - 1:
return None # the pump is still printing new highs
if close > high * (1 - params["pullback_pct"] / 100):
return None
vwap = turnover_vwap(candles[-bars_for_hours(params["vwap_hours"], tf):])
if vwap is None or close >= vwap:
return None
atr = average_true_range(candles, int(params["atr_period"]))
if atr is None:
return None
return {"side": "short", "atr": atr, "high": high, "stop": high + params["stop_buffer_atr"] * atr,
"vwap": vwap, "growth": growth, "close": close, "candle_start": int(last[0])}
def evaluate_signal(mode: str, candles: list[list[float]], params: dict[str, float],
funding_rate_pct: float | None = None, btc_ok: bool | None = True) -> dict | None:
if mode == STRATEGY_BREAKOUT:
return evaluate_breakout(candles, params, funding_rate_pct, btc_ok)
if mode == STRATEGY_FADE:
return evaluate_fade(candles, params, funding_rate_pct)
return None
def entry_plan(signal: dict, entry_price: float, params: dict[str, float]) -> dict | None:
"""Stop and targets for an entry at ``entry_price``; None when the signal is no longer valid."""
side = signal["side"]
if entry_price <= 0:
return None
if side == "long":
if entry_price <= signal["level"]:
return None # price fell back under the breakout level before the fill
stop = entry_price - params["stop_atr"] * signal["atr"]
if stop <= 0:
return None
else:
stop = signal["stop"]
if entry_price >= stop or (stop / entry_price - 1) * 100 > params["max_stop_pct"]:
return None
risk = abs(entry_price - stop)
sign = side_sign(side)
partial = (entry_price + sign * params["partial_r"] * risk
if params["partial_r"] > 0 and params["partial_pct"] > 0 else None)
final = entry_price + sign * params["take_profit_r"] * risk if params["take_profit_r"] > 0 else None
if final is not None and final <= 0:
final = None
if partial is not None and partial <= 0:
partial = None
return {"side": side, "stop": stop, "risk": risk, "atr": signal["atr"],
"partial_target": partial, "final_target": final}
def breakeven_price(side: str, entry: float, fee_pct: float) -> float:
cover = fee_cover_pct(fee_pct) / 100
return entry * (1 + cover) if side == "long" else entry * (1 - cover)
def tighten_stop(side: str, stop: float, candidate: float) -> float:
"""Stops only move in the trade's favour."""
return max(stop, candidate) if side == "long" else min(stop, candidate)
def trailing_stop(side: str, stop: float, extreme: float, atr: float, trail_atr: float) -> float:
if trail_atr <= 0 or atr <= 0:
return stop
candidate = extreme - trail_atr * atr if side == "long" else extreme + trail_atr * atr
return tighten_stop(side, stop, candidate)
def trailing_active(partial_done: bool, params: dict[str, float]) -> bool:
"""Trail from the start without a partial exit, otherwise only after it."""
return params["trail_atr"] > 0 and (partial_done or params["partial_r"] <= 0 or params["partial_pct"] <= 0)
def stop_hit(side: str, price: float, stop: float) -> bool:
return price <= stop if side == "long" else price >= stop
def target_hit(side: str, price: float, target: float | None) -> bool:
if target is None or target <= 0:
return False
return price >= target if side == "long" else price <= target