Files
remizov-trader/tests/test_integration_run_cycle.py
anorandClaude Opus 4.6 377d682c0f feat: Bybit exchange emulator + per-coin 1h оптимизация (+$862, 17/17 profitable)
Новый пакет `emulator/`:
- BybitEmulator: drop-in ccxt.bybit mock (13 методов, duck typing)
- FillModel: реалистичные косты (spread 0.03%, slippage 0.2%, funding 0.01%)
- MatchingEngine: bar-by-bar stops по high/low, funding каждые 8h
- AccountState: позиции, ордера, баланс, PnL
- runner.py: standalone backtest с True ATR и per-coin параметрами
- integration.py: прогон реального run_cycle() через эмулятор

Исправления:
- FuturesExecutor: dependency injection (exchange= параметр)
- optimize-windows: добавлены realistic costs (spread, slippage), true ATR,
  убран longs-only фильтр
- compute_atr (close-only) даёт стопы в 2.5x теснее True ATR — задокументировано

Per-coin оптимизация 1h (data/1h_optimal_params.json):
- 17/17 монет прибыльны, total +$862, ROI 86% за 17 мес
- Паттерн: shift 42-48, SM 4.0-6.0, K 2-5

146 тестов проходят.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 00:48:50 +10:00

75 lines
2.5 KiB
Python

"""Integration test: run_cycle() driven by BybitEmulator.
Tests that the real bot code works end-to-end with emulated exchange.
Uses cached OHLCV data (skips if not available).
"""
import pickle
import numpy as np
import pytest
from remizov_trader.emulator.integration import run_integrated
from remizov_trader.emulator.matching import FillModel
CACHE_DIR = "/tmp/ohlcv_cache"
def _load_ohlcv(symbol: str):
"""Load cached OHLCV. Returns (ohlcv_array, dates) or (None, None)."""
safe = symbol.replace("/", "_").replace(":", "_")
path = f"{CACHE_DIR}/{safe}_4h.pkl"
try:
with open(path, "rb") as f:
ohlcv, dates = pickle.load(f)
return ohlcv, dates
except FileNotFoundError:
return None, None
@pytest.mark.slow
class TestIntegrationRunCycle:
"""Run real run_cycle() through emulator with cached OHLCV."""
def test_uni_produces_trades(self):
"""UNI/USDT:USDT should produce trades via run_cycle()."""
ohlcv, dates = _load_ohlcv("UNI/USDT:USDT")
if ohlcv is None:
pytest.skip("No cached OHLCV for UNI")
fm = FillModel() # realistic defaults
result = run_integrated(
"UNI/USDT:USDT", ohlcv, cap=59.0, fill_model=fm, dates=dates,
)
assert result["trades"] > 0, "Should produce at least 1 trade"
assert len(result["equity_curve"]) > 1
# Verify equity changed from initial
assert result["equity_curve"][-1] != result["equity_curve"][0]
def test_doge_produces_trades(self):
ohlcv, dates = _load_ohlcv("DOGE/USDT:USDT")
if ohlcv is None:
pytest.skip("No cached OHLCV for DOGE")
result = run_integrated("DOGE/USDT:USDT", ohlcv, cap=59.0, dates=dates)
assert result["trades"] > 0
def test_no_crash_on_empty_signals(self):
"""Short data should not crash, just produce 0 trades."""
np.random.seed(42)
# Very short data — not enough for model training to work well
n = 200
rows = []
price = 10.0
for i in range(n):
ts = 1700000000000 + i * 4 * 3600 * 1000
c = price * (1 + np.random.uniform(-0.02, 0.02))
rows.append([ts, price, price * 1.01, price * 0.99, c, 1000])
price = c
ohlcv = np.array(rows)
result = run_integrated("TEST/USDT:USDT", ohlcv, cap=59.0)
# Should not crash; may or may not produce trades
assert "pnl" in result
assert "trades" in result