Новый пакет `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>
200 lines
6.2 KiB
Python
200 lines
6.2 KiB
Python
"""Integration test: FuturesExecutor + BybitEmulator.
|
|
|
|
Proves that FuturesExecutor works identically with BybitEmulator
|
|
as it does with ccxt.bybit — all public methods exercised.
|
|
"""
|
|
|
|
import numpy as np
|
|
import pytest
|
|
from remizov_trader.emulator import BybitEmulator, FillModel
|
|
from remizov_trader.core.futures import FuturesExecutor
|
|
from remizov_trader.config import ExchangeConfig
|
|
|
|
|
|
# ── Helpers ──────────────────────────────────────────────────────
|
|
|
|
def make_ohlcv(n=200, start_price=10.0, volatility=0.02,
|
|
start_ts=1700000000000):
|
|
rows = []
|
|
price = start_price
|
|
for i in range(n):
|
|
ts = start_ts + i * 4 * 3600 * 1000
|
|
change = np.random.uniform(-volatility, volatility)
|
|
o = price
|
|
h = price * (1 + abs(change) + 0.005)
|
|
l = price * (1 - abs(change) - 0.005)
|
|
c = price * (1 + change)
|
|
vol = np.random.uniform(1000, 5000)
|
|
rows.append([ts, o, h, l, c, vol])
|
|
price = c
|
|
return np.array(rows)
|
|
|
|
|
|
SYM = "UNI/USDT:USDT"
|
|
|
|
|
|
@pytest.fixture
|
|
def setup():
|
|
"""Create FuturesExecutor backed by BybitEmulator."""
|
|
np.random.seed(42)
|
|
ohlcv = {SYM: make_ohlcv(200, start_price=8.0)}
|
|
fm = FillModel(spread=0.0003, stop_slippage=0.002,
|
|
commission=0.00055, funding_rate=0.0001)
|
|
emu = BybitEmulator(ohlcv, initial_usdt=500.0, fill_model=fm)
|
|
|
|
# Advance to bar 50 so we have a "current price"
|
|
first_ts = int(ohlcv[SYM][0][0])
|
|
emu.fetch_ohlcv(SYM, "4h", since=first_ts, limit=50)
|
|
|
|
cfg = ExchangeConfig(
|
|
api_key="test", api_secret="test", testnet=False,
|
|
)
|
|
executor = FuturesExecutor(cfg, leverage=1, exchange=emu)
|
|
|
|
return executor, emu
|
|
|
|
|
|
# ── Tests ────────────────────────────────────────────────────────
|
|
|
|
class TestGetBalance:
|
|
def test_returns_float(self, setup):
|
|
executor, _ = setup
|
|
bal = executor.get_balance("USDT")
|
|
assert isinstance(bal, float)
|
|
assert bal == 500.0
|
|
|
|
|
|
class TestGetPrice:
|
|
def test_returns_current_price(self, setup):
|
|
executor, emu = setup
|
|
price = executor.get_price(SYM)
|
|
assert price is not None
|
|
assert price > 0
|
|
# Should match emulator's current price
|
|
ticker = emu.fetch_ticker(SYM)
|
|
assert price == ticker["last"]
|
|
|
|
|
|
class TestGetPosition:
|
|
def test_no_position(self, setup):
|
|
executor, _ = setup
|
|
pos = executor.get_position(SYM)
|
|
assert pos is None
|
|
|
|
def test_position_after_open(self, setup):
|
|
executor, _ = setup
|
|
executor.open_long(SYM, 50.0)
|
|
pos = executor.get_position(SYM)
|
|
assert isinstance(pos, dict)
|
|
assert pos["side"] == "long"
|
|
assert pos["size"] > 0
|
|
assert pos["entryPrice"] > 0
|
|
|
|
|
|
class TestOpenLong:
|
|
def test_opens_successfully(self, setup):
|
|
executor, _ = setup
|
|
order = executor.open_long(SYM, 50.0)
|
|
assert order is not None
|
|
assert order["status"] == "closed"
|
|
assert float(order["filled"]) > 0
|
|
|
|
def test_balance_reduced(self, setup):
|
|
executor, _ = setup
|
|
before = executor.get_balance("USDT")
|
|
executor.open_long(SYM, 50.0)
|
|
after = executor.get_balance("USDT")
|
|
assert after < before
|
|
|
|
|
|
class TestOpenShort:
|
|
def test_opens_successfully(self, setup):
|
|
executor, _ = setup
|
|
order = executor.open_short(SYM, 50.0)
|
|
assert order is not None
|
|
pos = executor.get_position(SYM)
|
|
assert pos["side"] == "short"
|
|
|
|
|
|
class TestClosePosition:
|
|
def test_close_long(self, setup):
|
|
executor, _ = setup
|
|
executor.open_long(SYM, 50.0)
|
|
order = executor.close_position(SYM, "long")
|
|
assert order is not None
|
|
pos = executor.get_position(SYM)
|
|
assert pos is None
|
|
|
|
def test_close_short(self, setup):
|
|
executor, _ = setup
|
|
executor.open_short(SYM, 50.0)
|
|
order = executor.close_position(SYM, "short")
|
|
assert order is not None
|
|
pos = executor.get_position(SYM)
|
|
assert pos is None
|
|
|
|
|
|
class TestPlaceSafetyStop:
|
|
def test_sets_position_sl(self, setup):
|
|
executor, emu = setup
|
|
executor.open_long(SYM, 50.0)
|
|
pos = executor.get_position(SYM)
|
|
trigger = pos["entryPrice"] * 0.95
|
|
result = executor.place_safety_stop(SYM, "long", pos["size"], trigger)
|
|
assert result is not None
|
|
assert result["stopLoss"] > 0
|
|
# Verify SL is set on emulator position
|
|
emu_pos = emu.account.positions[SYM]
|
|
assert abs(emu_pos.stop_loss - trigger) < 0.01
|
|
|
|
|
|
class TestGetClosedPnl:
|
|
def test_after_close(self, setup):
|
|
executor, _ = setup
|
|
executor.open_long(SYM, 50.0)
|
|
executor.close_position(SYM, "long")
|
|
pnl = executor.get_closed_pnl(SYM)
|
|
assert pnl is not None
|
|
assert "closedPnl" in pnl
|
|
assert "exitPrice" in pnl
|
|
assert "entryPrice" in pnl
|
|
|
|
def test_no_pnl_without_close(self, setup):
|
|
executor, _ = setup
|
|
pnl = executor.get_closed_pnl(SYM)
|
|
assert pnl is None
|
|
|
|
|
|
class TestFullTradeFlow:
|
|
def test_open_advance_close(self, setup):
|
|
"""Simulate full lifecycle: open → advance bars → close."""
|
|
executor, emu = setup
|
|
# Open long
|
|
initial_bal = executor.get_balance("USDT")
|
|
order = executor.open_long(SYM, 100.0)
|
|
assert order is not None
|
|
|
|
# Verify position exists
|
|
pos = executor.get_position(SYM)
|
|
assert pos is not None
|
|
assert pos["side"] == "long"
|
|
|
|
# Advance a few bars (simulating time passing)
|
|
for i in range(50, 55):
|
|
emu.advance_to_bar(SYM, i)
|
|
|
|
# Close position
|
|
close_order = executor.close_position(SYM, "long")
|
|
assert close_order is not None
|
|
|
|
# Position gone
|
|
assert executor.get_position(SYM) is None
|
|
|
|
# PnL recorded
|
|
pnl = executor.get_closed_pnl(SYM)
|
|
assert pnl is not None
|
|
|
|
# Balance changed (profit or loss)
|
|
final_bal = executor.get_balance("USDT")
|
|
assert final_bal != initial_bal
|