Новый пакет `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>
260 lines
10 KiB
Python
260 lines
10 KiB
Python
"""Tests for Bybit exchange emulator."""
|
|
|
|
import numpy as np
|
|
import pytest
|
|
from remizov_trader.emulator import BybitEmulator, FillModel, AccountState
|
|
from remizov_trader.emulator.matching import MatchingEngine
|
|
|
|
|
|
# ── Helpers ──────────────────────────────────────────────────────
|
|
|
|
def make_ohlcv(n=100, start_price=100.0, volatility=0.02, start_ts=1700000000000):
|
|
"""Generate synthetic OHLCV data."""
|
|
rows = []
|
|
price = start_price
|
|
for i in range(n):
|
|
ts = start_ts + i * 4 * 3600 * 1000 # 4h bars
|
|
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)
|
|
|
|
|
|
@pytest.fixture
|
|
def ohlcv_data():
|
|
np.random.seed(42)
|
|
return {"TEST/USDT:USDT": make_ohlcv(200, start_price=10.0)}
|
|
|
|
|
|
@pytest.fixture
|
|
def emulator(ohlcv_data):
|
|
fm = FillModel(spread=0.0003, stop_slippage=0.002,
|
|
commission=0.00055, funding_rate=0.0001)
|
|
return BybitEmulator(ohlcv_data, initial_usdt=1000.0, fill_model=fm)
|
|
|
|
|
|
SYM = "TEST/USDT:USDT"
|
|
|
|
|
|
def _fetch_from_start(emu, n=50):
|
|
"""Fetch first n bars from the beginning (simulates bot startup)."""
|
|
first_ts = int(emu._ohlcv[SYM][0][0])
|
|
return emu.fetch_ohlcv(SYM, "4h", since=first_ts, limit=n)
|
|
|
|
|
|
# ── fetch_ohlcv ─────────────────────────────────────────────────
|
|
|
|
class TestFetchOhlcv:
|
|
def test_returns_list_of_lists(self, emulator):
|
|
bars = emulator.fetch_ohlcv(SYM, "4h", limit=10)
|
|
assert isinstance(bars, list)
|
|
assert len(bars) == 10
|
|
assert len(bars[0]) == 6
|
|
|
|
def test_no_lookahead(self, emulator):
|
|
"""After fetching 50 bars from start, current price = bar 49."""
|
|
bars = _fetch_from_start(emulator, 50)
|
|
assert len(bars) == 50
|
|
ticker = emulator.fetch_ticker(SYM)
|
|
assert ticker["last"] == bars[-1][4]
|
|
|
|
def test_since_pagination(self, emulator):
|
|
first_ts = int(emulator._ohlcv[SYM][0][0])
|
|
bars1 = emulator.fetch_ohlcv(SYM, "4h", since=first_ts, limit=10)
|
|
since = bars1[-1][0] + 1
|
|
bars2 = emulator.fetch_ohlcv(SYM, "4h", since=since, limit=10)
|
|
assert bars2[0][0] > bars1[-1][0]
|
|
|
|
def test_unknown_symbol_raises(self, emulator):
|
|
with pytest.raises(Exception, match="No OHLCV data"):
|
|
emulator.fetch_ohlcv("FAKE/USDT:USDT", "4h")
|
|
|
|
|
|
# ── Market orders ────────────────────────────────────────────────
|
|
|
|
class TestMarketOrders:
|
|
def test_buy_fills_with_spread(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
price = emulator.fetch_ticker(SYM)["last"]
|
|
order = emulator.create_order(SYM, "market", "buy", 10.0)
|
|
assert order["status"] == "closed"
|
|
assert order["filled"] == 10.0
|
|
assert order["average"] > price
|
|
assert order["average"] < price * 1.01
|
|
|
|
def test_sell_fills_with_spread(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
price = emulator.fetch_ticker(SYM)["last"]
|
|
order = emulator.create_order(
|
|
SYM, "market", "sell", 10.0, params={"reduceOnly": True}
|
|
)
|
|
assert order["status"] == "closed"
|
|
assert order["average"] < price
|
|
|
|
def test_fee_charged(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
order = emulator.create_order(SYM, "market", "buy", 10.0)
|
|
assert order["fee"]["cost"] > 0
|
|
assert order["fee"]["currency"] == "USDT"
|
|
|
|
def test_balance_deducted(self, emulator):
|
|
initial = emulator.fetch_balance()["USDT"]["free"]
|
|
_fetch_from_start(emulator, 50)
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
after = emulator.fetch_balance()["USDT"]["free"]
|
|
assert after < initial
|
|
|
|
|
|
# ── Positions ────────────────────────────────────────────────────
|
|
|
|
class TestPositions:
|
|
def test_position_created_on_buy(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
positions = emulator.fetch_positions([SYM])
|
|
assert len(positions) == 1
|
|
assert positions[0]["side"] == "long"
|
|
assert positions[0]["contracts"] == 10.0
|
|
|
|
def test_position_closed_on_reduce(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
emulator.create_order(
|
|
SYM, "market", "sell", 10.0, params={"reduceOnly": True}
|
|
)
|
|
positions = emulator.fetch_positions([SYM])
|
|
assert len(positions) == 0
|
|
|
|
def test_no_positions_initially(self, emulator):
|
|
positions = emulator.fetch_positions([SYM])
|
|
assert len(positions) == 0
|
|
|
|
|
|
# ── Stop loss (position level) ───────────────────────────────────
|
|
|
|
class TestPositionStopLoss:
|
|
def test_set_stop_loss(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
mkt = emulator.market(SYM)
|
|
result = emulator.privatePostV5PositionTradingStop({
|
|
"symbol": mkt["id"],
|
|
"category": "linear",
|
|
"stopLoss": "8.0",
|
|
"slTriggerBy": "LastPrice",
|
|
"tpslMode": "Full",
|
|
"positionIdx": 0,
|
|
})
|
|
assert result["retCode"] == 0
|
|
pos = emulator.account.positions[SYM]
|
|
assert pos.stop_loss == 8.0
|
|
|
|
def test_stop_triggers_on_bar(self, emulator, ohlcv_data):
|
|
_fetch_from_start(emulator, 50) # current_bar = 49
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
# Set stop above next bar's low — guaranteed to trigger
|
|
next_high = float(ohlcv_data[SYM][50][2])
|
|
emulator.account.positions[SYM].stop_loss = next_high
|
|
emulator.advance_to_bar(SYM, 50)
|
|
assert SYM not in emulator.account.positions
|
|
|
|
|
|
# ── Funding ──────────────────────────────────────────────────────
|
|
|
|
class TestFunding:
|
|
def test_funding_charged_after_interval(self, emulator):
|
|
_fetch_from_start(emulator, 10) # current_bar = 9
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
balance_before = emulator.fetch_balance()["USDT"]["free"]
|
|
# Advance 5 bars (20h > 8h funding interval)
|
|
for i in range(10, 15):
|
|
emulator.advance_to_bar(SYM, i)
|
|
balance_after = emulator.fetch_balance()["USDT"]["free"]
|
|
assert balance_after < balance_before
|
|
|
|
|
|
# ── Closed PnL ───────────────────────────────────────────────────
|
|
|
|
class TestClosedPnl:
|
|
def test_closed_pnl_recorded(self, emulator):
|
|
_fetch_from_start(emulator, 50)
|
|
emulator.create_order(SYM, "market", "buy", 10.0)
|
|
emulator.create_order(
|
|
SYM, "market", "sell", 10.0, params={"reduceOnly": True}
|
|
)
|
|
mkt = emulator.market(SYM)
|
|
result = emulator.privateGetV5PositionClosedPnl({
|
|
"symbol": mkt["id"], "category": "linear", "limit": 5
|
|
})
|
|
pnl_list = result["result"]["list"]
|
|
assert len(pnl_list) == 1
|
|
assert "closedPnl" in pnl_list[0]
|
|
assert "avgEntryPrice" in pnl_list[0]
|
|
|
|
|
|
# ── Precision ────────────────────────────────────────────────────
|
|
|
|
class TestPrecision:
|
|
def test_amount_precision(self, emulator):
|
|
result = emulator.amount_to_precision("ETH/USDT:USDT", 1.23456)
|
|
assert result == "1.234"
|
|
|
|
def test_price_precision(self, emulator):
|
|
result = emulator.price_to_precision("ETH/USDT:USDT", 3456.789)
|
|
assert result == "3456.79"
|
|
|
|
|
|
# ── Market metadata ──────────────────────────────────────────────
|
|
|
|
class TestMarket:
|
|
def test_known_symbol(self, emulator):
|
|
mkt = emulator.market("DOGE/USDT:USDT")
|
|
assert mkt["id"] == "DOGEUSDT"
|
|
assert mkt["limits"]["amount"]["min"] == 1.0
|
|
|
|
def test_unknown_symbol_fallback(self, emulator):
|
|
mkt = emulator.market("UNKNOWN/USDT:USDT")
|
|
assert "id" in mkt
|
|
assert mkt["limits"]["amount"]["min"] == 0.1
|
|
|
|
|
|
# ── Balance ──────────────────────────────────────────────────────
|
|
|
|
class TestBalance:
|
|
def test_initial_balance(self, emulator):
|
|
bal = emulator.fetch_balance()
|
|
assert bal["USDT"]["free"] == 1000.0
|
|
|
|
def test_set_leverage(self, emulator):
|
|
emulator.set_leverage(2, SYM)
|
|
assert emulator.account.get_leverage(SYM) == 2
|
|
|
|
|
|
# ── Integration: full trade cycle ────────────────────────────────
|
|
|
|
class TestFullCycle:
|
|
def test_open_trade_close_profit(self, emulator, ohlcv_data):
|
|
"""Open long, advance bars, close — verify PnL makes sense."""
|
|
_fetch_from_start(emulator, 50)
|
|
initial_balance = emulator.fetch_balance()["USDT"]["free"]
|
|
|
|
emulator.create_order(SYM, "market", "buy", 5.0)
|
|
assert len(emulator.fetch_positions([SYM])) == 1
|
|
|
|
for i in range(50, 55):
|
|
emulator.advance_to_bar(SYM, i)
|
|
|
|
emulator.create_order(
|
|
SYM, "market", "sell", 5.0, params={"reduceOnly": True}
|
|
)
|
|
assert len(emulator.fetch_positions([SYM])) == 0
|
|
|
|
final_balance = emulator.fetch_balance()["USDT"]["free"]
|
|
assert final_balance != initial_balance
|