Files
Crypto_Scam/historical_backtest.py
T
2026-10-22 20:19:52 +03:00

1535 lines
78 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import bisect
import csv
import heapq
import itertools
import json
import math
import sqlite3
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Callable
import strategy
TAKER_FEE_PCT = 0.055
API_URL = "https://api.bybit.com/v5/market/kline"
PAGE_TIMEOUT_SECONDS = 20
PAGE_RETRY_DELAYS_SECONDS = (1, 2, 4, 8)
CANDLE_CACHE_DB = Path(__file__).with_name("historical_candles.sqlite3")
_CACHE_INIT_LOCK = threading.Lock()
TOP_N_DEFAULT = 100
class RetryableBybitError(RuntimeError):
"""A temporary Bybit API response that can succeed on a later attempt."""
def _open_candle_cache(path: Path) -> sqlite3.Connection:
path.parent.mkdir(parents=True, exist_ok=True)
with _CACHE_INIT_LOCK:
connection = sqlite3.connect(str(path), timeout=30)
connection.execute("PRAGMA busy_timeout = 30000")
connection.execute(
"CREATE TABLE IF NOT EXISTS candles ("
"symbol TEXT NOT NULL, interval INTEGER NOT NULL, start_ms INTEGER NOT NULL, "
"open REAL NOT NULL, high REAL NOT NULL, low REAL NOT NULL, close REAL NOT NULL, "
"PRIMARY KEY(symbol, interval, start_ms))"
)
connection.execute(
"CREATE TABLE IF NOT EXISTS coverage ("
"symbol TEXT NOT NULL, interval INTEGER NOT NULL, start_ms INTEGER NOT NULL, "
"end_ms INTEGER NOT NULL, PRIMARY KEY(symbol, interval, start_ms))"
)
columns = {row[1] for row in connection.execute("PRAGMA table_info(candles)").fetchall()}
if "turnover" not in columns:
# Older caches stored OHLC only; turnover is needed for the liquidity ranking.
connection.execute("ALTER TABLE candles ADD COLUMN turnover REAL")
connection.execute(
"CREATE TABLE IF NOT EXISTS funding ("
"symbol TEXT NOT NULL, stamp_ms INTEGER NOT NULL, rate REAL NOT NULL, "
"PRIMARY KEY(symbol, stamp_ms))"
)
connection.commit()
return connection
def _missing_ranges(start_ms: int, end_ms: int, coverage: list[tuple[int, int]], step_ms: int
) -> list[tuple[int, int]]:
missing: list[tuple[int, int]] = []
cursor = start_ms
for covered_start, covered_end in coverage:
if covered_end < cursor:
continue
if covered_start > cursor:
gap_end = min(end_ms, covered_start - step_ms)
if cursor <= gap_end:
missing.append((cursor, gap_end))
cursor = max(cursor, covered_end + step_ms)
if cursor > end_ms:
break
if cursor <= end_ms:
missing.append((cursor, end_ms))
return missing
def _cache_page(connection: sqlite3.Connection, symbol: str, interval: int,
page_start: int, page_end: int, rows: list[list[float]], step_ms: int) -> None:
connection.execute("BEGIN IMMEDIATE")
try:
connection.executemany(
"INSERT INTO candles(symbol, interval, start_ms, open, high, low, close, turnover) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
"ON CONFLICT(symbol, interval, start_ms) DO UPDATE SET "
"open=excluded.open, high=excluded.high, low=excluded.low, close=excluded.close, "
"turnover=COALESCE(excluded.turnover, candles.turnover)",
[(symbol, interval, int(row[0]), *map(float, row[1:5]),
float(row[5]) if len(row) > 5 and row[5] is not None else None) for row in rows],
)
coverage_rows = connection.execute(
"SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? "
"AND end_ms >= ? AND start_ms <= ?",
(symbol, interval, page_start - step_ms, page_end + step_ms),
).fetchall()
merged_start, merged_end = page_start, page_end
for old_start, old_end in coverage_rows:
merged_start = min(merged_start, int(old_start))
merged_end = max(merged_end, int(old_end))
connection.executemany(
"DELETE FROM coverage WHERE symbol=? AND interval=? AND start_ms=?",
[(symbol, interval, int(old_start)) for old_start, _ in coverage_rows],
)
connection.execute(
"INSERT OR REPLACE INTO coverage(symbol, interval, start_ms, end_ms) VALUES (?, ?, ?, ?)",
(symbol, interval, merged_start, merged_end),
)
connection.commit()
except Exception:
connection.rollback()
raise
@dataclass
class SimPosition:
symbol: str
entry_price: float
qty: float
margin: float
entry_fees: float
opened_at: int
last_add_price: float
add_count: int = 0
averaging_frozen: bool = False
funding: float = 0.0 # received (+) or paid (−) funding, USDT
FUNDING_URL = "https://api.bybit.com/v5/market/funding/history"
FUNDING_PAGE_LIMIT = 200
# Coverage rows of the funding history use this pseudo-interval in the shared coverage table.
FUNDING_COVERAGE_INTERVAL = -1
def _request_funding_page(symbol: str, start_ms: int, end_ms: int) -> list[tuple[int, float]]:
params = urllib.parse.urlencode({
"category": "linear", "symbol": symbol, "startTime": str(start_ms),
"endTime": str(end_ms), "limit": str(FUNDING_PAGE_LIMIT),
})
request = urllib.request.Request(f"{FUNDING_URL}?{params}", headers={"User-Agent": "RealtimePaperSimulator/1.0"})
with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response:
payload = json.loads(response.read().decode("utf-8"))
ret_code = payload.get("retCode")
if ret_code != 0:
message = f"Bybit funding {symbol}: {ret_code} {payload.get('retMsg', '')}"
if str(ret_code) in {"10006", "10016"}:
raise RetryableBybitError(message)
raise RuntimeError(message)
rows = []
for row in payload.get("result", {}).get("list", []):
try:
rows.append((int(row["fundingRateTimestamp"]), float(row["fundingRate"])))
except (KeyError, TypeError, ValueError):
continue
return rows
def _cache_funding_page(connection: sqlite3.Connection, symbol: str, page_start: int, page_end: int,
rows: list[tuple[int, float]]) -> None:
connection.execute("BEGIN IMMEDIATE")
try:
connection.executemany(
"INSERT OR REPLACE INTO funding(symbol, stamp_ms, rate) VALUES (?, ?, ?)",
[(symbol, stamp, rate) for stamp, rate in rows],
)
coverage_rows = connection.execute(
"SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? "
"AND end_ms >= ? AND start_ms <= ?",
(symbol, FUNDING_COVERAGE_INTERVAL, page_start - 1, page_end + 1),
).fetchall()
merged_start, merged_end = page_start, page_end
for old_start, old_end in coverage_rows:
merged_start = min(merged_start, int(old_start))
merged_end = max(merged_end, int(old_end))
connection.executemany(
"DELETE FROM coverage WHERE symbol=? AND interval=? AND start_ms=?",
[(symbol, FUNDING_COVERAGE_INTERVAL, int(old_start)) for old_start, _ in coverage_rows],
)
connection.execute(
"INSERT OR REPLACE INTO coverage(symbol, interval, start_ms, end_ms) VALUES (?, ?, ?, ?)",
(symbol, FUNDING_COVERAGE_INTERVAL, merged_start, merged_end),
)
connection.commit()
except Exception:
connection.rollback()
raise
def fetch_funding_history(symbol: str, start_ms: int, end_ms: int,
cancel: Callable[[], bool] = lambda: False,
cache_path: Path | None = None) -> dict[int, float]:
"""Settled funding rates {settlement_ms: rate as a fraction}; cached like the candles.
A positive rate means LONG positions pay and SHORT positions receive
``position value × rate`` at the settlement time.
"""
cache = _open_candle_cache(cache_path or CANDLE_CACHE_DB)
try:
coverage = [(int(row[0]), int(row[1])) for row in cache.execute(
"SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? ORDER BY start_ms",
(symbol, FUNDING_COVERAGE_INTERVAL),
).fetchall()]
for gap_start, gap_end in _missing_ranges(start_ms, end_ms, coverage, 1):
cursor = gap_end
while cursor >= gap_start:
if cancel():
raise InterruptedError("Исторический прогон отменён")
page = None
last_error: Exception | None = None
for attempt in range(len(PAGE_RETRY_DELAYS_SECONDS) + 1):
if cancel():
raise InterruptedError("Исторический прогон отменён")
try:
page = _request_funding_page(symbol, gap_start, cursor)
break
except (RetryableBybitError, TimeoutError, urllib.error.URLError,
ConnectionError, OSError) as exc:
last_error = exc
if attempt >= len(PAGE_RETRY_DELAYS_SECONDS):
break
time.sleep(PAGE_RETRY_DELAYS_SECONDS[attempt])
if page is None:
raise RuntimeError(f"Не удалось загрузить funding {symbol}: {last_error}") from last_error
page = [(stamp, rate) for stamp, rate in page if gap_start <= stamp <= cursor]
full_page = len(page) >= FUNDING_PAGE_LIMIT
page_start = min(stamp for stamp, _ in page) if full_page else gap_start
_cache_funding_page(cache, symbol, page_start, cursor, page)
if not full_page:
break
cursor = page_start - 1
time.sleep(0.1)
return {int(row[0]): float(row[1]) for row in cache.execute(
"SELECT stamp_ms, rate FROM funding WHERE symbol=? AND stamp_ms BETWEEN ? AND ? ORDER BY stamp_ms",
(symbol, start_ms, end_ms),
).fetchall()}
finally:
cache.close()
def _request_page(symbol: str, interval: int, start_ms: int, end_ms: int) -> list[list[float]]:
params = urllib.parse.urlencode({
"category": "linear", "symbol": symbol, "interval": str(interval),
"start": str(start_ms), "end": str(end_ms), "limit": "1000",
})
request = urllib.request.Request(f"{API_URL}?{params}", headers={"User-Agent": "RealtimePaperSimulator/1.0"})
with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response:
payload = json.loads(response.read().decode("utf-8"))
ret_code = payload.get("retCode")
if ret_code != 0:
message = f"Bybit {symbol}: {ret_code} {payload.get('retMsg', '')}"
if str(ret_code) in {"10006", "10016"}:
raise RetryableBybitError(message)
raise RuntimeError(message)
output = []
for row in payload.get("result", {}).get("list", []):
stamp = int(row[0])
turnover = float(row[6]) if len(row) > 6 and row[6] not in (None, "") else None
output.append([stamp, float(row[1]), float(row[2]), float(row[3]), float(row[4]), turnover])
return output
def fetch_klines(symbol: str, interval: int, start_ms: int, end_ms: int,
cancel: Callable[[], bool] = lambda: False,
progress: Callable[..., None] = lambda *_: None,
cache_path: Path | None = None, with_turnover: bool = False) -> list[list[float]]:
"""Return cached candles and fetch only uncovered ranges, persisting every API page.
Rows are [start_ms, open, high, low, close] or, with ``with_turnover``,
[start_ms, open, high, low, close, turnover].
"""
step_ms = interval * 60_000
first_open = ((start_ms + step_ms - 1) // step_ms) * step_ms
last_open = (end_ms // step_ms) * step_ms
if last_open < first_open:
raise RuntimeError(f"Пустой диапазон свечей для {symbol}")
estimated_total = (last_open - first_open) // step_ms + 1
cache = _open_candle_cache(cache_path or CANDLE_CACHE_DB)
page_number = 0
try:
coverage = [(int(row[0]), int(row[1])) for row in cache.execute(
"SELECT start_ms, end_ms FROM coverage WHERE symbol=? AND interval=? ORDER BY start_ms",
(symbol, interval),
).fetchall()]
gaps = _missing_ranges(first_open, last_open, coverage, step_ms)
cached_count = int(cache.execute(
"SELECT COUNT(*) FROM candles WHERE symbol=? AND interval=? AND start_ms BETWEEN ? AND ?",
(symbol, interval, first_open, last_open),
).fetchone()[0])
pages_total = sum(math.ceil(((gap_end - gap_start) // step_ms + 1) / 1000)
for gap_start, gap_end in gaps)
progress(symbol, cached_count, estimated_total,
f"локальный кэш: {cached_count:,} свечей; докачать страниц: {pages_total}")
for gap_start, gap_end in gaps:
cursor = gap_end
while cursor >= gap_start:
if cancel():
raise InterruptedError("Исторический прогон отменён")
page_number += 1
# Query a bounded, non-overlapping block of up to 1,000 candle opens.
page_start = max(gap_start, cursor - 999 * step_ms)
progress(symbol, cached_count, estimated_total,
f"страница {page_number}/{pages_total}: запрос Bybit")
page = None
last_error: Exception | None = None
for attempt in range(len(PAGE_RETRY_DELAYS_SECONDS) + 1):
if cancel():
raise InterruptedError("Исторический прогон отменён")
try:
page = _request_page(symbol, interval, page_start, cursor)
break
except (RetryableBybitError, TimeoutError, urllib.error.URLError,
ConnectionError, OSError) as exc:
last_error = exc
if attempt >= len(PAGE_RETRY_DELAYS_SECONDS):
break
progress(symbol, cached_count, estimated_total,
f"страница {page_number}/{pages_total}: повтор {attempt + 2}/5 ({exc})")
time.sleep(PAGE_RETRY_DELAYS_SECONDS[attempt])
if page is None:
raise RuntimeError(
f"Не удалось загрузить страницу свечей {symbol} после "
f"{len(PAGE_RETRY_DELAYS_SECONDS) + 1} попыток: {last_error}"
) from last_error
page_rows = [row for row in page if page_start <= int(row[0]) <= cursor]
_cache_page(cache, symbol, interval, page_start, cursor, page_rows, step_ms)
cached_count += len(page_rows)
progress(symbol, min(cached_count, estimated_total), estimated_total,
f"страница {page_number}/{pages_total} сохранена в кэш")
cursor = page_start - step_ms
if cursor >= gap_start:
time.sleep(0.25)
result = [[int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])]
+ ([float(row[5] or 0.0)] if with_turnover else [])
for row in cache.execute(
"SELECT start_ms, open, high, low, close, turnover FROM candles "
"WHERE symbol=? AND interval=? AND start_ms BETWEEN ? AND ? ORDER BY start_ms",
(symbol, interval, first_open, last_open),
).fetchall()]
finally:
cache.close()
if len(result) < 2:
raise RuntimeError(f"Bybit вернул только {len(result)} закрытых свечей для {symbol}")
return result
INSTRUMENTS_URL = "https://api.bybit.com/v5/market/instruments-info"
UNIVERSE_SCAN_INTERVAL_MINUTES = 60
def _fee_cover_pct(fee_pct: float) -> float:
return strategy.fee_cover_pct(fee_pct)
def fetch_linear_usdt_symbols(end_ms: int | None = None) -> list[str]:
"""Return USDT perpetual tickers, including delisted ones when Bybit still lists them.
Including ``Closed`` contracts reduces survivorship bias: coins that pumped and were
later delisted stay in the historical universe whenever Bybit still serves their candles.
"""
symbols: set[str] = set()
errors: list[str] = []
for status in ("Trading", "Closed"):
cursor = ""
for _ in range(20):
params = {"category": "linear", "limit": "1000", "status": status}
if cursor:
params["cursor"] = cursor
request = urllib.request.Request(
f"{INSTRUMENTS_URL}?{urllib.parse.urlencode(params)}",
headers={"User-Agent": "RealtimePaperSimulator/1.0"},
)
try:
with urllib.request.urlopen(request, timeout=PAGE_TIMEOUT_SECONDS) as response:
payload = json.loads(response.read().decode("utf-8"))
except Exception as exc: # the Closed list is optional
errors.append(f"{status}: {exc}")
break
if payload.get("retCode") != 0:
errors.append(f"{status}: {payload.get('retCode')} {payload.get('retMsg', '')}")
break
result = payload.get("result", {})
for row in result.get("list", []):
symbol = str(row.get("symbol") or "").upper()
if (row.get("quoteCoin") != "USDT" or row.get("contractType") != "LinearPerpetual"
or not symbol.endswith("USDT")):
continue
launch = int(row.get("launchTime") or 0)
if end_ms is not None and launch and launch > end_ms:
continue
symbols.add(symbol)
cursor = result.get("nextPageCursor") or ""
if not cursor:
break
if not symbols:
raise RuntimeError("Bybit не вернул список USDT-контрактов. " + " · ".join(errors))
return sorted(symbols)
def build_universe_windows(hourly_by_symbol: dict[str, list[list[float]]], start_ms: int, end_ms: int,
min_growth_24h_pct: float, top_n: int = 100
) -> dict[str, list[tuple[int, int]]]:
"""Point-in-time replica of the live auto-selection on hourly data.
After each hourly candle closes, every symbol is ranked by its trailing 24-hour turnover;
of the ``top_n`` most liquid ones, those whose 24-hour change is strictly above
``min_growth_24h_pct`` may open new entries during the following hour.
Returns merged ``[from_ms, to_ms)`` entry windows per symbol.
"""
hour_ms = 60 * 60 * 1000
series: dict[str, dict[int, tuple[float, float]]] = {
symbol: {int(row[0]): (float(row[4]), float(row[5]) if len(row) > 5 else 0.0) for row in rows}
for symbol, rows in hourly_by_symbol.items()
}
first_hour = (start_ms // hour_ms) * hour_ms - hour_ms
windows: dict[str, list[tuple[int, int]]] = {}
rolling: dict[str, float] = {symbol: 0.0 for symbol in series}
# Prime trailing turnover sums with the 23 hours before the first decision.
for symbol, rows in series.items():
rolling[symbol] = sum(rows.get(first_hour - k * hour_ms, (0.0, 0.0))[1] for k in range(1, 24))
hour = first_hour
while hour <= end_ms:
decision_from = hour + hour_ms # the candle [hour, hour+1h) has closed
decision_to = decision_from + hour_ms
ranked: list[tuple[float, str, float]] = []
for symbol, rows in series.items():
current = rows.get(hour)
rolling[symbol] += current[1] if current else 0.0
if current:
prior = rows.get(hour - 24 * hour_ms)
if prior and prior[0] > 0 and rolling[symbol] > 0:
ranked.append((rolling[symbol], symbol, (current[0] / prior[0] - 1) * 100))
dropped = rows.get(hour - 23 * hour_ms)
rolling[symbol] -= dropped[1] if dropped else 0.0
ranked.sort(reverse=True)
for _turnover, symbol, change in ranked[:top_n]:
if change > min_growth_24h_pct and decision_to > start_ms and decision_from <= end_ms:
spans = windows.setdefault(symbol, [])
lo = max(decision_from, start_ms)
if spans and spans[-1][1] >= lo:
spans[-1] = (spans[-1][0], decision_to)
else:
spans.append((lo, decision_to))
hour += hour_ms
return windows
def prepare_universe(start_ms: int, end_ms: int, min_growth_24h_pct: float, top_n: int = TOP_N_DEFAULT,
cancel: Callable[[], bool] = lambda: False,
progress: Callable[..., None] = lambda *_: None,
cache_path: Path | None = None, workers: int = 4
) -> tuple[dict[str, list[tuple[int, int]]], list[str]]:
"""Download hourly candles with turnover for every USDT perpetual and build entry windows.
Returns (windows per symbol, symbols that could not be loaded). Hourly data is cached in the
same SQLite file, so later runs only download new hours.
"""
hour_ms = UNIVERSE_SCAN_INTERVAL_MINUTES * 60_000
hourly_start = (start_ms // hour_ms) * hour_ms - 2 * 24 * hour_ms
hourly_end = (end_ms // hour_ms) * hour_ms - 1
symbols = fetch_linear_usdt_symbols(end_ms)
hourly: dict[str, list[list[float]]] = {}
failed: list[str] = []
done = 0
def load(symbol: str) -> list[list[float]]:
return fetch_klines(symbol, UNIVERSE_SCAN_INTERVAL_MINUTES, hourly_start, hourly_end, cancel,
cache_path=cache_path, with_turnover=True)
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
futures = {pool.submit(load, symbol): symbol for symbol in symbols}
for future in as_completed(futures):
symbol = futures[future]
if cancel():
for pending in futures:
pending.cancel()
raise InterruptedError("Исторический прогон отменён")
try:
hourly[symbol] = future.result()
except InterruptedError:
raise
except Exception:
# Contracts listed after the period or with no candles are simply skipped.
failed.append(symbol)
done += 1
progress("Отбор валют", done, len(symbols),
f"часовые свечи и оборот: {done}/{len(symbols)} контрактов")
windows = build_universe_windows(hourly, start_ms, end_ms, min_growth_24h_pct, top_n)
return windows, sorted(failed)
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,
cancel: Callable[[], bool] = lambda: False,
trading_start_ms: int | None = None,
pause_below_24h_pct: float = 30.0,
resume_above_24h_pct: float = 31.0,
min_equity_pct: float = 10.0,
max_open_positions: int | None = None,
universe_windows: dict[str, list[tuple[int, int]]] | None = None,
funding_by_symbol: dict[str, dict[int, float]] | None = None) -> dict:
"""Replay minute OHLC bars; the assumed path is O-L-H-C for green and O-H-L-C for red.
``max_open_positions`` mirrors the live/simulation limit on simultaneous positions.
``universe_windows`` replaces the per-symbol 24-hour filter with the point-in-time
auto-selection: entries are allowed only inside a symbol's windows and averaging is
paused outside them, exactly like a pair waiting for retirement in live mode.
``funding_by_symbol`` holds settled funding rates; an open LONG pays
``qty × open price × rate`` at each settlement minute (receives it when the rate is negative).
"""
symbols = sorted(set(candles_by_symbol) & set(strategies))
if not symbols:
raise ValueError("Нет свечей для прогона")
universe_mode = universe_windows is not None
# Stream candles in (time, ticker) order instead of building a full timeline in memory:
# the live-like selection can involve dozens of pairs with months of minute data.
first_stamp = min(int(candles_by_symbol[symbol][0][0]) for symbol in symbols)
def tagged(symbol: str):
for candle in candles_by_symbol[symbol]:
yield int(candle[0]), symbol, candle
stream = heapq.merge(*(tagged(symbol) for symbol in symbols), key=lambda item: (item[0], item[1]))
grouped = ((stamp, [(symbol, candle) for _stamp, symbol, candle in items])
for stamp, items in itertools.groupby(stream, key=lambda item: item[0]))
# The per-symbol 24-hour lookup is only needed by the classic growth filter.
lookup = ({} if universe_mode else
{symbol: {int(row[0]): row for row in candles_by_symbol[symbol]} for symbol in symbols})
positions: dict[str, SimPosition] = {}
previous_close: dict[str, float] = {}
entry_allowed = {symbol: False for symbol in symbols}
filter_triggered = {symbol: False for symbol in symbols}
window_cursor = {symbol: 0 for symbol in symbols}
marks: dict[str, float] = {}
cash = float(initial_capital)
closed: list[dict] = []
next_id = 1
equity_floor = initial_capital * min_equity_pct / 100 if min_equity_pct > 0 else 0.0
equity_stop: dict[str, object] = {"triggered": False, "timestamp": None, "equity": None}
processed_candles = {symbol: 0 for symbol in symbols}
risk = {"peak": float(initial_capital), "max_dd_usdt": 0.0, "max_dd_pct": 0.0,
"min_equity": float(initial_capital), "max_margin": 0.0, "max_positions": 0,
"skipped_limit": 0, "skipped_margin": 0}
funding_total = {"sum": 0.0, "events": 0}
last_stamp = first_stamp
def equity_at(symbol: str | None = None, price: float | None = None) -> float:
equity = cash
for position_symbol, position in positions.items():
mark = (price if position_symbol == symbol and price is not None
else marks.get(position_symbol, position.entry_price))
unrealized = (mark - position.entry_price) * position.qty
estimated_exit_fee = mark * position.qty * fee_pct / 100
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)
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
return False
def used_margin() -> float:
return sum(p.margin for p in positions.values())
def free_margin() -> float:
# Same definition as simulation/live: equity (cash + unrealized P&L after the
# estimated closing fee) minus margin locked in open positions.
return equity_at() - used_margin()
def note_exposure() -> None:
risk["max_margin"] = max(risk["max_margin"], used_margin())
risk["max_positions"] = max(risk["max_positions"], len(positions))
def open_position(symbol: str, price: float, stamp: int) -> bool:
nonlocal cash, next_id
cfg = strategies[symbol]
stake, leverage = cfg["stake"], cfg["leverage"]
if max_open_positions is not None and len(positions) >= max_open_positions:
risk["skipped_limit"] += 1
return False
if stake > max(0.0, free_margin()):
risk["skipped_margin"] += 1
return False
notional = stake * leverage
qty = notional / price
entry_fee = notional * fee_pct / 100
cash -= entry_fee
positions[symbol] = SimPosition(symbol, price, qty, stake, entry_fee, stamp, price)
positions[symbol]._trade_id = next_id
next_id += 1
note_exposure()
return True
def add_to_position(symbol: str, pos: SimPosition, level: float) -> bool:
nonlocal cash
cfg = strategies[symbol]
cfg_stake = cfg["stake"]
if cfg_stake > max(0.0, free_margin()):
# Skipped for lack of margin; a later, deeper level may still be filled.
risk["skipped_margin"] += 1
return False
notional = cfg_stake * cfg["leverage"]
added_qty = notional / level
fee = notional * fee_pct / 100
total_qty = pos.qty + added_qty
pos.entry_price = (pos.entry_price * pos.qty + level * added_qty) / total_qty
pos.qty = total_qty
pos.margin += cfg_stake
pos.entry_fees += fee
pos.last_add_price = level
pos.add_count += 1
cash -= fee
note_exposure()
return True
def close_position(symbol: str, price: float, stamp: int, reason: str,
liquidation: bool = False) -> None:
nonlocal cash
pos = positions.pop(symbol)
if liquidation:
# Isolated-margin liquidation forfeits the whole margin of the position.
gross = -pos.margin
exit_fee = 0.0
else:
gross = (price - pos.entry_price) * pos.qty
exit_fee = price * pos.qty * fee_pct / 100
fees = pos.entry_fees + exit_fee
# Funding already moved the cash while the position was open.
net = gross - fees + pos.funding
cash += gross - exit_fee
closed.append({
"id": pos._trade_id, "symbol": symbol, "side": "LONG",
"opened_at": datetime.fromtimestamp(pos.opened_at / 1000, timezone.utc).isoformat(),
"closed_at": datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat(),
"entry": pos.entry_price, "exit": price, "entries": pos.add_count + 1,
"margin": pos.margin, "gross_usdt": gross, "fees_usdt": fees, "funding_usdt": pos.funding,
"net_usdt": net, "roi_pct": net / pos.margin * 100 if pos.margin else 0,
"hold_hours": (stamp - pos.opened_at) / 3_600_000,
"reason": reason, "status": "CLOSED",
})
def exit_levels(symbol: str, pos: SimPosition) -> tuple[float | None, float | None, float | None]:
cfg = strategies[symbol]
return (strategy.take_profit_price(pos.entry_price, cfg["take_profit"], fee_pct),
strategy.stop_loss_price(pos.entry_price, cfg["stop_loss"]),
strategy.liquidation_price(pos.entry_price, cfg["leverage"]))
def handle_gap(symbol: str, price: float, stamp: int) -> None:
"""Apply TP/stop/liquidation/adds when a candle opens beyond a level (price gap)."""
cfg = strategies[symbol]
for _ in range(int(cfg["max_adds"]) + 2):
pos = positions.get(symbol)
if pos is None:
return
tp, stop, liq = exit_levels(symbol, pos)
if liq is not None and price <= liq:
close_position(symbol, price, stamp, "Ликвидация (разрыв цены)", liquidation=True)
return
if stop is not None and price <= stop:
loss_pct = (pos.entry_price - price) / pos.entry_price * 100
close_position(symbol, price, stamp, f"Стоп −{loss_pct:.3f}% (разрыв цены)")
return
if tp is not None and price >= tp:
gain_pct = (price / pos.entry_price - 1) * 100
close_position(symbol, price, stamp, f"TP +{gain_pct:.3f}% (разрыв цены)")
return
level = strategy.add_level(pos.last_add_price, cfg["add_step"])
if (level is None or not strategy.can_add(pos.add_count, cfg["max_adds"], cfg["add_step"],
pos.averaging_frozen) or price > level):
return
if not add_to_position(symbol, pos, price):
return
def walk_segment(symbol: str, start: float, end: float, stamp: int,
baseline: float, armed: list[bool], allow_entry: bool) -> None:
cfg = strategies[symbol]
entry_level = strategy.entry_level(baseline, cfg["trigger"])
current = start
rising = end > start
for _ in range(16 + 2 * int(cfg["max_adds"])):
if mark_and_check_stop(symbol, current, stamp):
return
if abs(end - current) <= max(abs(end), 1.0) * 1e-14:
mark_and_check_stop(symbol, end, stamp)
return
pos = positions.get(symbol)
if rising:
if pos is None:
if armed[0] and current < entry_level <= end:
if allow_entry and open_position(symbol, entry_level, stamp):
armed[0] = False
current = entry_level
if mark_and_check_stop(symbol, current, stamp):
return
continue
# Mark the trigger as crossed even when the filter blocks it;
# a new entry then needs a fresh cross or candle.
armed[0] = False
mark_and_check_stop(symbol, end, stamp)
return
tp_level, _stop, _liq = exit_levels(symbol, pos)
if tp_level is not None and current < tp_level <= end:
marks[symbol] = tp_level
tp_pct = strategy.effective_take_profit_pct(cfg["take_profit"], fee_pct)
close_position(symbol, tp_level, stamp, f"TP +{tp_pct:.3f}%")
armed[0] = False
current = tp_level
if mark_and_check_stop(symbol, current, stamp):
return
continue
mark_and_check_stop(symbol, end, stamp)
return
# Falling segment: once price is below the entry threshold, a later rebound may enter.
if pos is None:
if end < entry_level:
armed[0] = True
mark_and_check_stop(symbol, end, stamp)
return
candidates: list[tuple[float, str]] = []
# Equity moves linearly with this symbol's price between strategy events.
# 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)
)
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:
candidates.append((stop_level, "STOP"))
if liq_level is not None and end <= liq_level < current:
candidates.append((liq_level, "LIQ"))
if strategy.can_add(pos.add_count, cfg["max_adds"], cfg["add_step"], pos.averaging_frozen):
add_level = strategy.add_level(pos.last_add_price, cfg["add_step"])
if add_level is not None and end <= add_level < current:
candidates.append((add_level, "ADD"))
if not candidates:
mark_and_check_stop(symbol, end, stamp)
return
level, event = max(candidates, key=lambda item: item[0])
marks[symbol] = level
if event == "EQUITY_STOP":
mark_and_check_stop(symbol, level, stamp)
return
if event in ("STOP", "LIQ"):
if event == "LIQ":
close_position(symbol, level, stamp, f"Ликвидация (плечо {cfg['leverage']:g}x)",
liquidation=True)
else:
loss_pct = (pos.entry_price - level) / pos.entry_price * 100
close_position(symbol, level, stamp, f"Стоп −{loss_pct:.3f}%")
armed[0] = False
current = level
if mark_and_check_stop(symbol, current, stamp):
return
continue
if not add_to_position(symbol, pos, level):
# Not enough free margin: consume this level so the next one is measured from it.
pos.last_add_price = level
current = level
if mark_and_check_stop(symbol, current, stamp):
return
def update_entry_filter(symbol: str, stamp: int, close: float) -> None:
if universe_mode:
return
prior_day = lookup[symbol].get(stamp - 24 * 60 * 60 * 1000)
if not prior_day or prior_day[4] <= 0:
return
change_24h = (close / float(prior_day[4]) - 1) * 100
if change_24h < pause_below_24h_pct:
entry_allowed[symbol] = False
filter_triggered[symbol] = True
# Once the market weakens below the pause threshold, do not increase
# exposure on the existing position while it waits for TP or stop.
position = positions.get(symbol)
if position is not None:
position.averaging_frozen = True
elif change_24h > resume_above_24h_pct:
entry_allowed[symbol] = True
def update_universe(symbol: str, stamp: int) -> None:
spans = universe_windows.get(symbol, []) if universe_windows else []
index = window_cursor[symbol]
while index < len(spans) and spans[index][1] <= stamp:
index += 1
window_cursor[symbol] = index
inside = index < len(spans) and spans[index][0] <= stamp < spans[index][1]
if not inside and entry_allowed[symbol]:
filter_triggered[symbol] = True
entry_allowed[symbol] = inside
position = positions.get(symbol)
if position is not None:
# Outside the selection the pair only manages its position (no averaging),
# and averaging resumes if the pair qualifies again — as in live rotation.
position.averaging_frozen = not inside
for stamp, minute_candles in grouped:
if equity_stop["triggered"]:
break
if cancel():
raise InterruptedError("Исторический прогон отменён")
last_stamp = stamp
for symbol, candle in minute_candles:
if equity_stop["triggered"]:
break
if trading_start_ms is None or stamp >= trading_start_ms:
processed_candles[symbol] += 1
if universe_mode:
update_universe(symbol, stamp)
funded = positions.get(symbol)
if funded is not None and funding_by_symbol:
rate = funding_by_symbol.get(symbol, {}).get(stamp)
if rate:
payment = funded.qty * float(candle[1]) * rate
cash -= payment
funded.funding -= payment
funding_total["sum"] -= payment
funding_total["events"] += 1
previous = previous_close.get(symbol)
if previous is None:
previous_close[symbol] = float(candle[4])
update_entry_filter(symbol, stamp, float(candle[4]))
continue
_, open_price, high, low, close = candle[:5]
open_price, high, low, close = float(open_price), float(high), float(low), float(close)
if symbol not in positions:
allow_entry = entry_allowed[symbol] and (trading_start_ms is None or stamp >= trading_start_ms)
limit_full = max_open_positions is not None and len(positions) >= max_open_positions
if not allow_entry or limit_full:
# Fast path: without a position and with entries impossible this candle
# cannot change cash, equity or any position, so only the baseline moves.
if allow_entry and high >= strategy.entry_level(previous, strategies[symbol]["trigger"]):
risk["skipped_limit"] += 1
previous_close[symbol] = close
update_entry_filter(symbol, stamp, close)
continue
marks[symbol] = open_price
handle_gap(symbol, open_price, stamp)
if mark_and_check_stop(symbol, open_price, stamp):
break
cfg = strategies[symbol]
entry_level = strategy.entry_level(previous, cfg["trigger"])
armed = [True]
allow_entry = entry_allowed[symbol] and (trading_start_ms is None or stamp >= trading_start_ms)
if symbol not in positions and open_price >= entry_level:
if allow_entry:
open_position(symbol, open_price, stamp)
armed[0] = False
if mark_and_check_stop(symbol, open_price, stamp):
break
# Heuristic intrabar ordering from candle direction; OHLC cannot reveal the true path.
path = [open_price, low, high, close] if close >= open_price else [open_price, high, low, close]
for a, b in zip(path, path[1:]):
walk_segment(symbol, a, b, stamp, previous, armed, allow_entry)
if equity_stop["triggered"]:
break
previous_close[symbol] = close
if equity_stop["triggered"]:
break
update_entry_filter(symbol, stamp, close)
end_stamp = int(equity_stop["timestamp"] if equity_stop["triggered"] else last_stamp)
open_rows = []
open_net = 0.0
for symbol, pos in positions.items():
last_candle = candles_by_symbol[symbol][-1]
mark = marks.get(symbol, float(last_candle[4]))
gross = (mark - pos.entry_price) * pos.qty
estimated_exit_fee = mark * pos.qty * fee_pct / 100
net = gross - pos.entry_fees - estimated_exit_fee + pos.funding
open_net += net
open_rows.append({
"id": pos._trade_id, "symbol": symbol, "side": "LONG",
"opened_at": datetime.fromtimestamp(pos.opened_at / 1000, timezone.utc).isoformat(),
"closed_at": "", "entry": pos.entry_price, "exit": mark,
"entries": pos.add_count + 1, "margin": pos.margin, "funding_usdt": pos.funding,
"gross_usdt": gross, "fees_usdt": pos.entry_fees + estimated_exit_fee,
"net_usdt": net, "roi_pct": net / pos.margin * 100 if pos.margin else 0,
"hold_hours": (end_stamp - pos.opened_at) / 3_600_000,
"reason": ("Открытая позиция на момент остановки по порогу капитала; выходная комиссия оценена"
if equity_stop["triggered"] else
"Открытая позиция на конце периода; выходная комиссия оценена"),
"status": "OPEN",
})
realized = sum(row["net_usdt"] for row in closed)
equity_net = realized + open_net
wins = sum(row["net_usdt"] > 0 for row in closed)
all_rows = closed + open_rows
stops = sum(row["reason"].startswith("Стоп") for row in closed)
liquidations = sum(row["reason"].startswith("Ликвидация") for row in closed)
open_losing = sum(row["net_usdt"] < 0 for row in open_rows)
if universe_mode:
filter_text = (
"Отбор валют как в реальном режиме: после каждого закрытого часа валюты ранжируются по "
f"обороту за 24 ч, из топ-{TOP_N_DEFAULT} входы разрешены тем, чей рост за 24 ч выше порога. "
"Вне отбора позиция только сопровождается до TP/стопа, доливки приостанавливаются."
)
else:
filter_text = (
f"При росте за 24 ч ниже {pause_below_24h_pct:g}% новые входы блокируются, а усреднение "
"открытых позиций замораживается до их закрытия по TP/стопу. Новые входы разрешаются снова "
f"только выше {resume_above_24h_pct:g}%."
)
summary = {
"symbols": symbols,
"period_start_utc": datetime.fromtimestamp((trading_start_ms if trading_start_ms is not None else first_stamp) / 1000, timezone.utc).isoformat(),
"period_end_utc": datetime.fromtimestamp(end_stamp / 1000, timezone.utc).isoformat(),
"candles": processed_candles,
"warmup_candles": {symbol: sum(1 for row in candles_by_symbol[symbol]
if trading_start_ms is not None and int(row[0]) < trading_start_ms)
for symbol in symbols},
"initial_capital": initial_capital,
"closed_trades": len(closed),
"wins": wins,
"losses": len(closed) - wins,
"win_rate_pct": wins / len(closed) * 100 if closed else 0.0,
"stops": stops,
"liquidations": liquidations,
"realized_net_usdt": realized,
"open_positions": len(open_rows),
"open_losing_positions": open_losing,
"open_net_estimate_usdt": open_net,
"total_net_including_open_usdt": equity_net,
"ending_equity_estimate": initial_capital + equity_net,
"max_drawdown_pct": risk["max_dd_pct"],
"max_drawdown_usdt": risk["max_dd_usdt"],
"min_equity_usdt": risk["min_equity"],
"peak_equity_usdt": risk["peak"],
"max_margin_used_usdt": risk["max_margin"],
"max_simultaneous_positions": risk["max_positions"],
"max_open_positions_limit": max_open_positions,
"skipped_entries_position_limit": risk["skipped_limit"],
"skipped_orders_margin": risk["skipped_margin"],
"longest_hold_hours": max((row["hold_hours"] for row in all_rows), default=0.0),
"universe_mode": universe_mode,
"equity_stop_pct": min_equity_pct,
"equity_stop_triggered": bool(equity_stop["triggered"]),
"equity_stop_value_usdt": equity_floor if min_equity_pct > 0 else None,
"equity_at_stop_usdt": equity_stop["equity"],
"return_pct": equity_net / initial_capital * 100 if initial_capital else 0.0,
"fees_usdt": sum(row["fees_usdt"] for row in closed) + sum(row["fees_usdt"] for row in open_rows),
"fee_pct_per_side": fee_pct,
"strategy_mode": strategy.STRATEGY_CLASSIC,
"strategy_title": strategy.STRATEGY_TITLES[strategy.STRATEGY_CLASSIC],
"funding_included": funding_by_symbol is not None,
"funding_usdt": funding_total["sum"],
"funding_events": funding_total["events"],
"entry_filter": filter_text,
"filter_was_triggered": filter_triggered,
"entry_allowed_at_end": {symbol: entry_allowed[symbol] for symbol in symbols},
"assumptions": (
("Отбор валют повторяет автоподбор по часовым свечам (в реальном режиме скан каждые 10 мин). "
if universe_mode else
"Рост за 24 ч считается по минутным закрытиям относительно закрытия ровно 1440 минут назад; "
"порог фильтра обновляется после закрытия свечи и действует со следующей. ")
+ "Прогон останавливается при падении капитала (баланс с учётом нереализованного P&L открытых "
"позиций и оценочной комиссии закрытия) до установленного порога; открытые позиции остаются в "
"отчёте по цене остановки. Минутные OHLC; внутри свечи путь O-L-H-C для зелёной и O-H-L-C для "
"красной свечи; разрывы цены на открытии свечи исполняются по цене открытия. Комиссия taker по "
"заданной ставке. При плече выше 1 моделируется ликвидация с потерей всей маржи позиции "
f"(ставка поддерживающей маржи {strategy.MAINTENANCE_MARGIN_RATE_PCT:g}%). "
+ _funding_assumption(funding_by_symbol is not None)
+ "Проскальзывание и очередь исполнения не моделируются. Общий капитал распределяется между "
"сигналами в пределах одной минуты в алфавитном порядке тикеров. Высокий процент прибыльных "
"сделок без стоп-лосса не означает отсутствия убытков: смотрите открытые позиции и максимальную просадку."
),
}
return {"summary": summary, "trades": all_rows}
def _funding_assumption(included: bool) -> str:
if not included:
return "Funding не учитывается (выключен в настройках прогона). "
return ("Funding учитывается по истории ставок Bybit: в минуту расчёта открытая позиция платит "
"(LONG при положительной ставке) или получает (SHORT при положительной ставке) "
"объём × цена открытия минуты × ставка; сумма входит в Net сделки. ")
@dataclass
class ModePosition:
symbol: str
side: str
entry_price: float
qty: float
margin: float
entry_fees: float
opened_at: int
stop: float
atr: float
extreme: float
partial_target: float | None
final_target: float | None
leverage: float
trade_id: int
initial_margin: float = 0.0
initial_stop: float = 0.0
partial_done: bool = False
realized_gross: float = 0.0
realized_fees: float = 0.0
funding: float = 0.0
def _hourly_btc_regime(btc_hourly: list[list[float]] | None, ema_period: int
) -> tuple[list[int], list[bool | None]]:
"""BTC regime per closed hour: (hour end times, close above EMA)."""
if not btc_hourly:
return [], []
ends: list[int] = []
regime: list[bool | None] = []
alpha = 2 / (ema_period + 1)
seed: list[float] = []
value: float | None = None
for row in btc_hourly:
close = float(row[4])
if value is None:
seed.append(close)
if len(seed) == ema_period:
value = sum(seed) / ema_period
else:
value = alpha * close + (1 - alpha) * value
ends.append(int(row[0]) + 3_600_000)
regime.append(None if value is None else close > value)
return ends, regime
def run_mode_backtest(candles_by_symbol: dict[str, list[list[float]]], mode: str,
params: dict[str, float], initial_capital: float,
fee_pct: float = TAKER_FEE_PCT,
cancel: Callable[[], bool] = lambda: False,
trading_start_ms: int | None = None,
min_growth_24h_pct: float | None = None,
min_equity_pct: float = 10.0,
max_open_positions: int | None = None,
universe_windows: dict[str, list[tuple[int, int]]] | None = None,
funding_by_symbol: dict[str, dict[int, float]] | None = None,
btc_hourly: list[list[float]] | None = None) -> dict:
"""Replay minute bars for strategy mode A (breakout) or B (fade).
Minute rows [start, o, h, l, c, turnover] are grouped into signal candles of
``params["timeframe_min"]``. A signal is evaluated when its candle closes and stays valid
until the next candle closes; the entry fills at the open of a later minute (no look-ahead).
Exits share the simulation rules: stop, partial take-profit on R with breakeven,
ATR trailing stop, optional final target and maximum holding time.
Without ``universe_windows`` entries need the 24h growth above ``min_growth_24h_pct``
(when given), measured on closed signal candles.
"""
if mode not in (strategy.STRATEGY_BREAKOUT, strategy.STRATEGY_FADE):
raise ValueError(f"Неизвестный режим стратегии: {mode}")
symbols = sorted(symbol for symbol, rows in candles_by_symbol.items() if rows)
if not symbols:
raise ValueError("Нет свечей для прогона")
universe_mode = universe_windows is not None
tf_ms = int(params["timeframe_min"]) * 60_000
stake = initial_capital * params["stake_pct"] / 100
leverage = params["leverage"]
bars_24h = strategy.bars_for_hours(24, params["timeframe_min"])
history_len = max(strategy.required_bars(mode, params), bars_24h + 1) + 2
btc_ends, btc_regime = _hourly_btc_regime(btc_hourly, int(params.get("btc_ema", 200)))
funding_stamps = {symbol: sorted((funding_by_symbol or {}).get(symbol, {}))
for symbol in symbols}
def tagged(symbol: str):
for candle in candles_by_symbol[symbol]:
yield int(candle[0]), symbol, candle
first_stamp = min(int(candles_by_symbol[symbol][0][0]) for symbol in symbols)
stream = heapq.merge(*(tagged(symbol) for symbol in symbols), key=lambda item: (item[0], item[1]))
grouped = ((stamp, [(symbol, candle) for _stamp, symbol, candle in items])
for stamp, items in itertools.groupby(stream, key=lambda item: item[0]))
positions: dict[str, ModePosition] = {}
marks: dict[str, float] = {}
history: dict[str, list[list[float]]] = {symbol: [] for symbol in symbols}
bucket: dict[str, list[float] | None] = {symbol: None for symbol in symbols}
pending: dict[str, tuple[dict, int, bool]] = {} # signal, valid-until ms, already counted as skipped
entry_allowed = {symbol: not universe_mode and min_growth_24h_pct is None for symbol in symbols}
filter_triggered = {symbol: False for symbol in symbols}
window_cursor = {symbol: 0 for symbol in symbols}
processed_candles = {symbol: 0 for symbol in symbols}
signals_total = {"count": 0, "rejected_at_fill": 0}
cash = float(initial_capital)
closed: list[dict] = []
next_id = 1
equity_floor = initial_capital * min_equity_pct / 100 if min_equity_pct > 0 else 0.0
equity_stop: dict[str, object] = {"triggered": False, "timestamp": None, "equity": None}
risk = {"peak": float(initial_capital), "max_dd_usdt": 0.0, "max_dd_pct": 0.0,
"min_equity": float(initial_capital), "max_margin": 0.0, "max_positions": 0,
"skipped_limit": 0, "skipped_margin": 0}
funding_total = {"sum": 0.0, "events": 0}
last_stamp = first_stamp
def iso(stamp: int) -> str:
return datetime.fromtimestamp(stamp / 1000, timezone.utc).isoformat()
def equity_at() -> float:
equity = cash
for position_symbol, pos in positions.items():
mark = 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
def mark_and_check_stop(symbol: str, price: float, stamp: int) -> bool:
if equity_stop["triggered"]:
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)
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
return False
def free_margin() -> float:
return equity_at() - sum(pos.margin for pos in positions.values())
def funding_rate_pct_at(symbol: str, stamp: int) -> float | None:
stamps = funding_stamps.get(symbol) or []
index = bisect.bisect_right(stamps, stamp) - 1
if index < 0:
return None
return funding_by_symbol[symbol][stamps[index]] * 100
def btc_ok_at(stamp: int) -> bool | None:
index = bisect.bisect_right(btc_ends, stamp) - 1
return btc_regime[index] if index >= 0 else None
def open_position(symbol: str, signal: dict, price: float, stamp: int) -> str:
nonlocal cash, next_id
if max_open_positions is not None and len(positions) >= max_open_positions:
return "limit"
if stake > max(0.0, free_margin()):
return "margin"
plan = strategy.entry_plan(signal, price, params)
if plan is None:
return "invalid"
notional = stake * leverage
qty = notional / price
entry_fee = notional * fee_pct / 100
cash -= entry_fee
positions[symbol] = ModePosition(
symbol, plan["side"], price, qty, stake, entry_fee, stamp, plan["stop"], plan["atr"], price,
plan["partial_target"], plan["final_target"], leverage, next_id,
initial_margin=stake, initial_stop=plan["stop"],
)
next_id += 1
risk["max_margin"] = max(risk["max_margin"], sum(p.margin for p in positions.values()))
risk["max_positions"] = max(risk["max_positions"], len(positions))
return "opened"
def row_for(pos: ModePosition, exit_price: float, stamp: int, gross: float, fees: float,
reason: str, status: str) -> dict:
net = gross - fees + pos.funding
return {
"id": pos.trade_id, "symbol": pos.symbol, "side": pos.side.upper(), "status": status,
"opened_at": iso(pos.opened_at), "closed_at": iso(stamp) if status == "CLOSED" else "",
"entry": pos.entry_price, "exit": exit_price, "entries": 1,
"margin": pos.initial_margin, "gross_usdt": gross, "fees_usdt": fees,
"funding_usdt": pos.funding, "net_usdt": net,
"roi_pct": net / pos.initial_margin * 100 if pos.initial_margin else 0.0,
"hold_hours": (stamp - pos.opened_at) / 3_600_000, "stop_initial": pos.initial_stop,
"reason": reason,
}
def close_position(symbol: str, price: float, stamp: int, reason: str, liquidation: bool = False) -> None:
nonlocal cash
pos = positions.pop(symbol)
if liquidation:
gross_final, exit_fee = -pos.margin, 0.0
else:
gross_final = strategy.unrealized_pnl(pos.side, pos.entry_price, price, pos.qty)
exit_fee = price * pos.qty * fee_pct / 100
cash += gross_final - exit_fee
closed.append(row_for(pos, price, stamp, pos.realized_gross + gross_final,
pos.entry_fees + pos.realized_fees + exit_fee, reason, "CLOSED"))
pending.pop(symbol, None)
def partial_close(pos: ModePosition, price: float) -> None:
nonlocal cash
fraction = min(1.0, params["partial_pct"] / 100)
qty = pos.qty * fraction
gross = strategy.unrealized_pnl(pos.side, pos.entry_price, price, qty)
fee = price * qty * fee_pct / 100
cash += gross - fee
pos.realized_gross += gross
pos.realized_fees += fee
pos.qty -= qty
pos.margin *= 1 - fraction
pos.partial_done = True
if params["breakeven"] >= 1:
pos.stop = strategy.tighten_stop(pos.side, pos.stop,
strategy.breakeven_price(pos.side, pos.entry_price, fee_pct))
def stop_reason(pos: ModePosition) -> str:
if pos.stop != pos.initial_stop:
return "Стоп (трейлинг/безубыток)"
return "Стоп"
def take_target(symbol: str, pos: ModePosition, level: float, stamp: int, gap: bool) -> bool:
"""Apply the nearest profit target at ``level``; True when the position closed."""
suffix = " (разрыв цены)" if gap else ""
if (not pos.partial_done and pos.partial_target is not None
and strategy.target_hit(pos.side, level, pos.partial_target)):
fill = level if gap else pos.partial_target
if params["partial_pct"] >= 100:
close_position(symbol, fill, stamp, f"Частичный TP 100% на {params['partial_r']:g}R{suffix}")
return True
partial_close(pos, fill)
return False
if strategy.target_hit(pos.side, level, pos.final_target):
fill = level if gap else pos.final_target
close_position(symbol, fill, stamp, f"TP на {params['take_profit_r']:g}R{suffix}")
return True
return False
def handle_open(symbol: str, price: float, stamp: int) -> None:
pos = positions.get(symbol)
if pos is None:
return
liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side)
if liq is not None and strategy.stop_hit(pos.side, price, liq):
close_position(symbol, price, stamp, "Ликвидация (разрыв цены)", liquidation=True)
return
if strategy.stop_hit(pos.side, price, pos.stop):
close_position(symbol, price, stamp, stop_reason(pos) + " (разрыв цены)")
return
for _ in range(2):
pos = positions.get(symbol)
if pos is None or not (strategy.target_hit(pos.side, price, pos.partial_target if not pos.partial_done else None)
or strategy.target_hit(pos.side, price, pos.final_target)):
break
if take_target(symbol, pos, price, stamp, gap=True):
return
pos = positions.get(symbol)
if pos is not None and params["max_hold_hours"] > 0 \
and stamp - pos.opened_at >= params["max_hold_hours"] * 3_600_000:
close_position(symbol, price, stamp, f"Время удержания {params['max_hold_hours']:g} ч")
def walk(symbol: str, start: float, end: float, stamp: int) -> None:
pos = positions.get(symbol)
if pos is None or start == end:
mark_and_check_stop(symbol, end, stamp)
return
favourable = (end > start) == (pos.side == "long")
if favourable:
for _ in range(3):
pos = positions.get(symbol)
if pos is None:
break
targets = [t for t in ((pos.partial_target if not pos.partial_done else None), pos.final_target)
if t is not None and (start < t <= end if pos.side == "long" else end <= t < start)]
if not targets:
break
level = min(targets) if pos.side == "long" else max(targets)
marks[symbol] = level
if take_target(symbol, pos, level, stamp, gap=False):
break
pos = positions.get(symbol)
if pos is not None:
pos.extreme = max(pos.extreme, end) if pos.side == "long" else min(pos.extreme, end)
if strategy.trailing_active(pos.partial_done, params):
pos.stop = strategy.trailing_stop(pos.side, pos.stop, pos.extreme, pos.atr, params["trail_atr"])
mark_and_check_stop(symbol, end, stamp)
return
liq = strategy.liquidation_price(pos.entry_price, pos.leverage, side=pos.side)
candidates = []
lo, hi = min(start, end), max(start, end)
if lo <= pos.stop <= hi:
candidates.append((pos.stop, "STOP"))
if liq is not None and lo <= liq <= hi:
candidates.append((liq, "LIQ"))
if not candidates:
mark_and_check_stop(symbol, end, stamp)
return
# 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 == "LIQ":
close_position(symbol, level, stamp, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True)
else:
close_position(symbol, level, stamp, stop_reason(pos))
mark_and_check_stop(symbol, end, stamp)
def update_universe(symbol: str, stamp: int) -> None:
spans = universe_windows.get(symbol, []) if universe_windows else []
index = window_cursor[symbol]
while index < len(spans) and spans[index][1] <= stamp:
index += 1
window_cursor[symbol] = index
inside = index < len(spans) and spans[index][0] <= stamp < spans[index][1]
if not inside and entry_allowed[symbol]:
filter_triggered[symbol] = True
entry_allowed[symbol] = inside
def close_bucket(symbol: str) -> None:
candle = bucket[symbol]
if candle is None:
return
rows = history[symbol]
rows.append(candle)
if len(rows) > history_len:
del rows[:len(rows) - history_len]
decided_at = int(candle[0]) + tf_ms
if not universe_mode and min_growth_24h_pct is not None and len(rows) > bars_24h:
day_ago = float(rows[-bars_24h - 1][4])
if day_ago > 0:
allowed = (float(candle[4]) / day_ago - 1) * 100 > min_growth_24h_pct
if entry_allowed[symbol] and not allowed:
filter_triggered[symbol] = True
entry_allowed[symbol] = allowed
if symbol in positions:
return
signal = strategy.evaluate_signal(mode, rows, params, funding_rate_pct_at(symbol, decided_at),
btc_ok_at(decided_at))
if signal is not None:
signals_total["count"] += 1
pending[symbol] = (signal, decided_at + tf_ms, False)
for stamp, minute_candles in grouped:
if equity_stop["triggered"]:
break
if cancel():
raise InterruptedError("Исторический прогон отменён")
last_stamp = stamp
for symbol, candle in minute_candles:
if equity_stop["triggered"]:
break
trading = trading_start_ms is None or stamp >= trading_start_ms
if trading:
processed_candles[symbol] += 1
if universe_mode:
update_universe(symbol, stamp)
open_price, high, low, close = (float(value) for value in candle[1:5])
turnover = float(candle[5]) if len(candle) > 5 and candle[5] is not None else 0.0
start = (stamp // tf_ms) * tf_ms
current = bucket[symbol]
if current is not None and int(current[0]) != start:
close_bucket(symbol)
current = None
if current is None:
bucket[symbol] = [start, open_price, high, low, close, turnover]
else:
current[2] = max(current[2], high)
current[3] = min(current[3], low)
current[4] = close
current[5] += turnover
pos = positions.get(symbol)
if pos is not None and funding_by_symbol:
rate = funding_by_symbol.get(symbol, {}).get(stamp)
if rate:
payment = -strategy.side_sign(pos.side) * pos.qty * open_price * rate
cash += payment
pos.funding += payment
funding_total["sum"] += payment
funding_total["events"] += 1
if pos is None:
waiting = pending.get(symbol)
if waiting is not None and stamp >= waiting[1]:
pending.pop(symbol, None)
waiting = None
if waiting is None or not trading or not entry_allowed[symbol]:
marks[symbol] = close
continue
signal, valid_until, counted = waiting
outcome = open_position(symbol, signal, open_price, stamp)
if outcome in ("limit", "margin"):
if not counted:
risk["skipped_limit" if outcome == "limit" else "skipped_margin"] += 1
pending[symbol] = (signal, valid_until, True)
marks[symbol] = close
continue
pending.pop(symbol, None)
if outcome == "invalid":
signals_total["rejected_at_fill"] += 1
marks[symbol] = close
continue
else:
marks[symbol] = open_price
handle_open(symbol, open_price, stamp)
if mark_and_check_stop(symbol, open_price, stamp):
break
path = [open_price, low, high, close] if close >= open_price else [open_price, high, low, close]
for a, b in zip(path, path[1:]):
walk(symbol, a, b, stamp)
if equity_stop["triggered"]:
break
if equity_stop["triggered"]:
break
pos = positions.get(symbol)
if pos is not None and params["max_hold_hours"] > 0 \
and stamp + 60_000 - pos.opened_at >= params["max_hold_hours"] * 3_600_000:
close_position(symbol, close, stamp + 60_000, f"Время удержания {params['max_hold_hours']:g} ч")
end_stamp = int(equity_stop["timestamp"] if equity_stop["triggered"] else last_stamp)
open_rows = []
for symbol, pos in positions.items():
mark = marks.get(symbol, float(candles_by_symbol[symbol][-1][4]))
gross = pos.realized_gross + strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
fees = pos.entry_fees + pos.realized_fees + mark * pos.qty * fee_pct / 100
open_rows.append(row_for(pos, mark, end_stamp, gross, fees,
"Открытая позиция на момент остановки по порогу капитала; выходная комиссия оценена"
if equity_stop["triggered"] else
"Открытая позиция на конце периода; выходная комиссия оценена", "OPEN"))
realized = sum(row["net_usdt"] for row in closed)
open_net = sum(row["net_usdt"] for row in open_rows)
equity_net = realized + open_net
wins = sum(row["net_usdt"] > 0 for row in closed)
all_rows = closed + open_rows
gains = [row["net_usdt"] for row in closed if row["net_usdt"] > 0]
losses = [row["net_usdt"] for row in closed if row["net_usdt"] <= 0]
if universe_mode:
filter_text = (
"Отбор валют как в реальном режиме: после каждого закрытого часа валюты ранжируются по "
f"обороту за 24 ч, из топ-{TOP_N_DEFAULT} сигналы режима разрешены тем, чей рост за 24 ч выше порога."
)
elif min_growth_24h_pct is not None:
filter_text = f"Сигналы режима разрешены при росте за 24 ч выше {min_growth_24h_pct:g}%."
else:
filter_text = "Сигналы режима без дополнительного фильтра роста за 24 ч."
summary = {
"symbols": symbols,
"strategy_mode": mode,
"strategy_title": strategy.STRATEGY_TITLES[mode],
"strategy_params": dict(params),
"period_start_utc": iso(trading_start_ms if trading_start_ms is not None else first_stamp),
"period_end_utc": iso(end_stamp),
"candles": processed_candles,
"initial_capital": initial_capital,
"closed_trades": len(closed),
"wins": wins,
"losses": len(closed) - wins,
"win_rate_pct": wins / len(closed) * 100 if closed else 0.0,
"avg_win_usdt": sum(gains) / len(gains) if gains else 0.0,
"avg_loss_usdt": sum(losses) / len(losses) if losses else 0.0,
"profit_factor": (sum(gains) / -sum(losses)) if losses and sum(losses) < 0 else None,
"signals": signals_total["count"],
"signals_rejected_at_fill": signals_total["rejected_at_fill"],
"stops": sum(row["reason"].startswith("Стоп") for row in closed),
"liquidations": sum(row["reason"].startswith("Ликвидация") for row in closed),
"realized_net_usdt": realized,
"open_positions": len(open_rows),
"open_losing_positions": sum(row["net_usdt"] < 0 for row in open_rows),
"open_net_estimate_usdt": open_net,
"total_net_including_open_usdt": equity_net,
"ending_equity_estimate": initial_capital + equity_net,
"max_drawdown_pct": risk["max_dd_pct"],
"max_drawdown_usdt": risk["max_dd_usdt"],
"min_equity_usdt": risk["min_equity"],
"peak_equity_usdt": risk["peak"],
"max_margin_used_usdt": risk["max_margin"],
"max_simultaneous_positions": risk["max_positions"],
"max_open_positions_limit": max_open_positions,
"skipped_entries_position_limit": risk["skipped_limit"],
"skipped_orders_margin": risk["skipped_margin"],
"longest_hold_hours": max((row["hold_hours"] for row in all_rows), default=0.0),
"universe_mode": universe_mode,
"equity_stop_pct": min_equity_pct,
"equity_stop_triggered": bool(equity_stop["triggered"]),
"equity_stop_value_usdt": equity_floor if min_equity_pct > 0 else None,
"equity_at_stop_usdt": equity_stop["equity"],
"return_pct": equity_net / initial_capital * 100 if initial_capital else 0.0,
"fees_usdt": sum(row["fees_usdt"] for row in all_rows),
"fee_pct_per_side": fee_pct,
"funding_included": funding_by_symbol is not None,
"funding_usdt": funding_total["sum"],
"funding_events": funding_total["events"],
"entry_filter": filter_text,
"filter_was_triggered": filter_triggered,
"entry_allowed_at_end": dict(entry_allowed),
"assumptions": (
f"Режим {strategy.STRATEGY_TITLES[mode]}. Сигнальные свечи {int(params['timeframe_min'])} мин "
"собираются из минутных; сигнал считается после закрытия свечи и действует до закрытия следующей, "
"вход — по цене открытия минуты (без заглядывания вперёд). Внутри минуты путь O-L-H-C для зелёной и "
"O-H-L-C для красной свечи; разрывы на открытии исполняются по цене открытия; частичный TP и "
"финальный TP — по своему уровню, стоп — по уровню стопа. "
+ ("Фильтр BTC: закрытие часа BTCUSDT выше EMA. " if mode == strategy.STRATEGY_BREAKOUT
and params.get("btc_filter", 0) >= 1 else "")
+ "Funding-фильтр сигнала использует последнюю расчётную ставку на момент закрытия свечи. "
+ _funding_assumption(funding_by_symbol is not None)
+ f"Комиссия taker {fee_pct:g}% за сторону. Ликвидация при плече выше 1 (у SHORT и при 1x) "
f"с потерей маржи позиции, поддерживающая маржа {strategy.MAINTENANCE_MARGIN_RATE_PCT:g}%. "
"Проскальзывание не моделируется. Капитал распределяется между сигналами одной минуты в "
"алфавитном порядке тикеров."
),
}
return {"summary": summary, "trades": all_rows}
def save_report(result: dict, output_dir: Path) -> tuple[Path, Path]:
output_dir.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_path = output_dir / f"backtest_{stamp}.csv"
json_path = output_dir / f"backtest_{stamp}.json"
columns = ["id", "symbol", "side", "status", "opened_at", "closed_at", "entry", "exit", "entries",
"margin", "gross_usdt", "fees_usdt", "funding_usdt", "net_usdt", "roi_pct", "hold_hours",
"reason"]
with csv_path.open("w", encoding="utf-8-sig", newline="") as file:
writer = csv.DictWriter(file, fieldnames=columns, extrasaction="ignore")
writer.writeheader()
writer.writerows(result["trades"])
json_path.write_text(json.dumps(result["summary"], ensure_ascii=False, indent=2), encoding="utf-8")
return csv_path, json_path