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>
This commit is contained in:
@@ -0,0 +1,274 @@
|
||||
{
|
||||
"DOGE": {
|
||||
"k": 5,
|
||||
"shift": 42,
|
||||
"sm": 5.0,
|
||||
"tw_start": 0.15,
|
||||
"tw_end": 0.25,
|
||||
"longs_only": false,
|
||||
"pnl": 40.610499393088645,
|
||||
"wr": 47.43589743589743,
|
||||
"trades": 312,
|
||||
"stops": 141,
|
||||
"max_dd": 20.159773507076075,
|
||||
"pnl_phase1": 32.68254695064131,
|
||||
"pnl_phase2": 40.610499393088645,
|
||||
"pnl_longs": 19.241705759867813
|
||||
},
|
||||
"APT": {
|
||||
"k": 2,
|
||||
"shift": 48,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.25,
|
||||
"tw_end": 0.35,
|
||||
"longs_only": false,
|
||||
"pnl": 48.354210113697576,
|
||||
"wr": 54.93562231759657,
|
||||
"trades": 233,
|
||||
"stops": 67,
|
||||
"max_dd": 15.947107862209547,
|
||||
"pnl_phase1": 30.33051620378569,
|
||||
"pnl_phase2": 48.354210113697576,
|
||||
"pnl_longs": 1.6693599324768513
|
||||
},
|
||||
"FIL": {
|
||||
"k": 5,
|
||||
"shift": 48,
|
||||
"sm": 3.5,
|
||||
"tw_start": 0.5,
|
||||
"tw_end": 0.6,
|
||||
"longs_only": false,
|
||||
"pnl": 37.11353851923015,
|
||||
"wr": 47.94520547945205,
|
||||
"trades": 146,
|
||||
"stops": 93,
|
||||
"max_dd": 12.33610441046674,
|
||||
"pnl_phase1": 19.470961399132264,
|
||||
"pnl_phase2": 37.11353851923015,
|
||||
"pnl_longs": 8.169577294082188
|
||||
},
|
||||
"LINK": {
|
||||
"k": 3,
|
||||
"shift": 44,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.0,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 49.99482487790576,
|
||||
"wr": 48.92086330935252,
|
||||
"trades": 278,
|
||||
"stops": 83,
|
||||
"max_dd": 18.23785486231342,
|
||||
"pnl_phase1": 49.99482487790576,
|
||||
"pnl_phase2": 49.99482487790576,
|
||||
"pnl_longs": 28.404882358847203
|
||||
},
|
||||
"ETH": {
|
||||
"k": 5,
|
||||
"shift": 42,
|
||||
"sm": 5.0,
|
||||
"tw_start": 0.2,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 7.845767082365455,
|
||||
"wr": 44.67353951890035,
|
||||
"trades": 291,
|
||||
"stops": 116,
|
||||
"max_dd": 18.128715901211496,
|
||||
"pnl_phase1": 5.632538276011431,
|
||||
"pnl_phase2": 7.845767082365455,
|
||||
"pnl_longs": 6.393275204523391
|
||||
},
|
||||
"INJ": {
|
||||
"k": 3,
|
||||
"shift": 42,
|
||||
"sm": 4.5,
|
||||
"tw_start": 0.0,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 53.532897128858,
|
||||
"wr": 46.04810996563574,
|
||||
"trades": 291,
|
||||
"stops": 145,
|
||||
"max_dd": 25.508516660285007,
|
||||
"pnl_phase1": 53.532897128858,
|
||||
"pnl_phase2": 53.532897128858,
|
||||
"pnl_longs": 4.75080799134404
|
||||
},
|
||||
"AVAX": {
|
||||
"k": 4,
|
||||
"shift": 48,
|
||||
"sm": 4.5,
|
||||
"tw_start": 0.25,
|
||||
"tw_end": 0.35,
|
||||
"longs_only": false,
|
||||
"pnl": 37.616886737604176,
|
||||
"wr": 50.847457627118644,
|
||||
"trades": 236,
|
||||
"stops": 114,
|
||||
"max_dd": 18.36140942082604,
|
||||
"pnl_phase1": 27.76683790687578,
|
||||
"pnl_phase2": 37.616886737604176,
|
||||
"pnl_longs": 2.6118929898072096
|
||||
},
|
||||
"WIF": {
|
||||
"k": 3,
|
||||
"shift": 48,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.3,
|
||||
"tw_end": 0.4,
|
||||
"longs_only": false,
|
||||
"pnl": 174.78013175434853,
|
||||
"wr": 55.96330275229357,
|
||||
"trades": 218,
|
||||
"stops": 61,
|
||||
"max_dd": 16.27794308641819,
|
||||
"pnl_phase1": 112.94898661046568,
|
||||
"pnl_phase2": 174.78013175434853,
|
||||
"pnl_longs": 32.620692096785845
|
||||
},
|
||||
"NEAR": {
|
||||
"k": 4,
|
||||
"shift": 36,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.25,
|
||||
"tw_end": 0.35,
|
||||
"longs_only": false,
|
||||
"pnl": 45.5669585881394,
|
||||
"wr": 52.6984126984127,
|
||||
"trades": 315,
|
||||
"stops": 71,
|
||||
"max_dd": 16.737091280033837,
|
||||
"pnl_phase1": 41.07188270786767,
|
||||
"pnl_phase2": 45.5669585881394,
|
||||
"pnl_longs": 14.799190257192024
|
||||
},
|
||||
"SUI": {
|
||||
"k": 3,
|
||||
"shift": 42,
|
||||
"sm": 4.0,
|
||||
"tw_start": 0.0,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 37.57078661335677,
|
||||
"wr": 46.391752577319586,
|
||||
"trades": 291,
|
||||
"stops": 182,
|
||||
"max_dd": 25.72634219039096,
|
||||
"pnl_phase1": 37.57078661335677,
|
||||
"pnl_phase2": 37.57078661335677,
|
||||
"pnl_longs": -0.6098503404982978
|
||||
},
|
||||
"ADA": {
|
||||
"k": 4,
|
||||
"shift": 42,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.2,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 67.6994538804743,
|
||||
"wr": 50.85910652920962,
|
||||
"trades": 291,
|
||||
"stops": 78,
|
||||
"max_dd": 28.808629793785318,
|
||||
"pnl_phase1": 52.45774500516181,
|
||||
"pnl_phase2": 67.6994538804743,
|
||||
"pnl_longs": 29.01497977391854
|
||||
},
|
||||
"SOL": {
|
||||
"k": 3,
|
||||
"shift": 48,
|
||||
"sm": 3.0,
|
||||
"tw_start": 0.75,
|
||||
"tw_end": 0.85,
|
||||
"longs_only": false,
|
||||
"pnl": 4.722005711420408,
|
||||
"wr": 40.0,
|
||||
"trades": 55,
|
||||
"stops": 43,
|
||||
"max_dd": 13.838268828224487,
|
||||
"pnl_phase1": -4.473869975704012,
|
||||
"pnl_phase2": 4.722005711420408,
|
||||
"pnl_longs": 0.20145683177814533
|
||||
},
|
||||
"ARB": {
|
||||
"k": 2,
|
||||
"shift": 48,
|
||||
"sm": 5.0,
|
||||
"tw_start": 0.3,
|
||||
"tw_end": 0.4,
|
||||
"longs_only": false,
|
||||
"pnl": 63.94353257032604,
|
||||
"wr": 52.336448598130836,
|
||||
"trades": 214,
|
||||
"stops": 93,
|
||||
"max_dd": 17.41431662424587,
|
||||
"pnl_phase1": 38.79157785748234,
|
||||
"pnl_phase2": 63.94353257032604,
|
||||
"pnl_longs": 8.361784109893065
|
||||
},
|
||||
"DOT": {
|
||||
"k": 4,
|
||||
"shift": 42,
|
||||
"sm": 4.5,
|
||||
"tw_start": 0.0,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 30.798640529050445,
|
||||
"wr": 47.766323024054984,
|
||||
"trades": 291,
|
||||
"stops": 138,
|
||||
"max_dd": 23.878893136472794,
|
||||
"pnl_phase1": 30.798640529050445,
|
||||
"pnl_phase2": 30.798640529050445,
|
||||
"pnl_longs": 10.077056392580417
|
||||
},
|
||||
"OP": {
|
||||
"k": 5,
|
||||
"shift": 36,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.0,
|
||||
"tw_end": 0.3,
|
||||
"longs_only": false,
|
||||
"pnl": 34.126719810466625,
|
||||
"wr": 53.392330383480825,
|
||||
"trades": 339,
|
||||
"stops": 71,
|
||||
"max_dd": 21.29385972377485,
|
||||
"pnl_phase1": 34.126719810466625,
|
||||
"pnl_phase2": 34.126719810466625,
|
||||
"pnl_longs": 10.076135167709111
|
||||
},
|
||||
"TIA": {
|
||||
"k": 2,
|
||||
"shift": 48,
|
||||
"sm": 6.0,
|
||||
"tw_start": 0.3,
|
||||
"tw_end": 0.4,
|
||||
"longs_only": false,
|
||||
"pnl": 77.4527624171148,
|
||||
"wr": 52.093023255813954,
|
||||
"trades": 215,
|
||||
"stops": 63,
|
||||
"max_dd": 32.02587453846343,
|
||||
"pnl_phase1": 61.82709595612029,
|
||||
"pnl_phase2": 77.4527624171148,
|
||||
"pnl_longs": 4.522096128133775
|
||||
},
|
||||
"ATOM": {
|
||||
"k": 2,
|
||||
"shift": 44,
|
||||
"sm": 5.0,
|
||||
"tw_start": 0.1,
|
||||
"tw_end": 0.2,
|
||||
"longs_only": false,
|
||||
"pnl": 50.017747846546015,
|
||||
"wr": 47.284345047923324,
|
||||
"trades": 313,
|
||||
"stops": 136,
|
||||
"max_dd": 15.250649744914297,
|
||||
"pnl_phase1": 30.218469365571025,
|
||||
"pnl_phase2": 50.017747846546015,
|
||||
"pnl_longs": 12.018096982906258
|
||||
}
|
||||
}
|
||||
+36
-13
@@ -586,8 +586,9 @@ def _update_config_leverage(leverage: int):
|
||||
def optimize_windows(apply):
|
||||
"""Find optimal training window for each asset via sliding 10% test."""
|
||||
from .core import model as model_mod, signals
|
||||
from .core.risk import calculate_pnl, compute_atr, update_trailing_stop, is_stopped
|
||||
from .core.risk import calculate_pnl, update_trailing_stop, is_stopped
|
||||
from .core.risk import calculate_position
|
||||
from .emulator.runner import true_atr
|
||||
|
||||
cfg = load_config()
|
||||
commission_rates = {a.ticker: cfg.commission_for(a) for a in cfg.assets}
|
||||
@@ -652,8 +653,10 @@ def optimize_windows(apply):
|
||||
T = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, W, T, model_cfg.epochs, model_cfg.lr)
|
||||
|
||||
# Run backtest on test_data (bar-by-bar stop checks)
|
||||
# Run backtest on test_data (bar-by-bar stops, realistic costs)
|
||||
comm = commission_rates[ticker]
|
||||
SPREAD = 0.0003 # realistic bid-ask spread
|
||||
STOP_SLIP = 0.002 # slippage on stop fills
|
||||
eq = cap; pos = None; cool = 0
|
||||
for d in test_data:
|
||||
pi = d["price_idx"]; cp = float(prices[pi])
|
||||
@@ -666,7 +669,8 @@ def optimize_windows(apply):
|
||||
# Check stop FIRST with adverse price (conservative)
|
||||
adv = l if pos["dir"] == 1 else h
|
||||
if is_stopped(adv, pos["stop"], pos["dir"]):
|
||||
ep = pos["stop"] # filled at stop price
|
||||
# Fill at stop + slippage (realistic)
|
||||
ep = pos["stop"] * (1 - pos["dir"] * STOP_SLIP)
|
||||
pnl, _ = calculate_pnl(pos["entry"], ep, pos["dir"],
|
||||
pos["sz"], pos["val"], commission=comm)
|
||||
eq += pnl; pos = None
|
||||
@@ -682,7 +686,8 @@ def optimize_windows(apply):
|
||||
if pos and not stopped:
|
||||
te = (pi - pos["bar"]) >= (shift - pos["k"])
|
||||
if te:
|
||||
pnl, _ = calculate_pnl(pos["entry"], cp, pos["dir"],
|
||||
exit_p = cp * (1 - pos["dir"] * SPREAD)
|
||||
pnl, _ = calculate_pnl(pos["entry"], exit_p, pos["dir"],
|
||||
pos["sz"], pos["val"], commission=comm)
|
||||
eq += pnl; pos = None
|
||||
if pos is None and pi >= ws + K and pi >= cool:
|
||||
@@ -692,16 +697,18 @@ def optimize_windows(apply):
|
||||
ni = (w - mu) / std
|
||||
pred = model_mod.predict(mdl, ni)[-shift:]
|
||||
d2 = signals.get_direction(pred, K)
|
||||
if d2 and not (d2 == -1):
|
||||
atr = compute_atr(prices, pi)
|
||||
sd = max(atr * sm * ss, cp * 0.005)
|
||||
sp = cp - d2 * sd
|
||||
sz, val = calculate_position(eq, cp, sd, cfg.risk)
|
||||
pos = {"dir": d2, "entry": cp, "stop": sp, "sd": sd,
|
||||
"best": cp, "sz": sz, "val": val, "bar": pi, "k": K,
|
||||
"last_check": pi}
|
||||
if d2:
|
||||
# Entry with spread (realistic)
|
||||
entry_p = cp + d2 * cp * SPREAD
|
||||
atr = true_atr(highs, lows, prices, pi)
|
||||
sd = max(atr * sm * ss, entry_p * 0.005)
|
||||
sp = entry_p - d2 * sd
|
||||
sz, val = calculate_position(eq, entry_p, sd, cfg.risk)
|
||||
pos = {"dir": d2, "entry": entry_p, "stop": sp, "sd": sd,
|
||||
"best": entry_p, "sz": sz, "val": val, "bar": pi,
|
||||
"k": K, "last_check": pi}
|
||||
if pos:
|
||||
lp = float(prices[-1])
|
||||
lp = float(prices[-1]) * (1 - pos["dir"] * SPREAD)
|
||||
pnl, _ = calculate_pnl(pos["entry"], lp, pos["dir"],
|
||||
pos["sz"], pos["val"], commission=comm)
|
||||
eq += pnl
|
||||
@@ -819,3 +826,19 @@ def config(key, value):
|
||||
"""Show or update config value (e.g., risk.per_trade 0.05)."""
|
||||
click.echo(f"Config: {key} = {value}")
|
||||
click.echo("(Config update via CLI not yet implemented — edit config.yaml directly)")
|
||||
|
||||
|
||||
@main.command()
|
||||
@click.option("--model", "-m", default="realistic",
|
||||
type=click.Choice(["ideal", "realistic", "pessimistic"]),
|
||||
help="Fill model: ideal (no costs), realistic, pessimistic")
|
||||
@click.option("--compare", is_flag=True, help="Run all 3 models and compare")
|
||||
@click.option("--cache-dir", default="/tmp/ohlcv_cache", help="OHLCV cache dir")
|
||||
@click.option("--cap", default=59.0, help="Capital per coin")
|
||||
def emulate(model, compare, cache_dir, cap):
|
||||
"""Run portfolio backtest through exchange emulator."""
|
||||
from .emulator.portfolio import run_portfolio, compare_models
|
||||
if compare:
|
||||
compare_models(cache_dir, cap)
|
||||
else:
|
||||
run_portfolio(cache_dir, cap, model)
|
||||
|
||||
@@ -21,17 +21,22 @@ log = logging.getLogger(__name__)
|
||||
class FuturesExecutor:
|
||||
"""Execute linear perpetual futures trades on Bybit."""
|
||||
|
||||
def __init__(self, exchange_cfg: ExchangeConfig, leverage: int = 1):
|
||||
import ccxt
|
||||
self.exchange = ccxt.bybit({
|
||||
"apiKey": exchange_cfg.api_key,
|
||||
"secret": exchange_cfg.api_secret,
|
||||
"enableRateLimit": True,
|
||||
"options": {
|
||||
"recvWindow": 30000,
|
||||
"defaultType": "linear",
|
||||
},
|
||||
})
|
||||
def __init__(self, exchange_cfg: ExchangeConfig, leverage: int = 1,
|
||||
exchange: object | None = None):
|
||||
if exchange is not None:
|
||||
# External exchange instance (e.g. BybitEmulator)
|
||||
self.exchange = exchange
|
||||
else:
|
||||
import ccxt
|
||||
self.exchange = ccxt.bybit({
|
||||
"apiKey": exchange_cfg.api_key,
|
||||
"secret": exchange_cfg.api_secret,
|
||||
"enableRateLimit": True,
|
||||
"options": {
|
||||
"recvWindow": 30000,
|
||||
"defaultType": "linear",
|
||||
},
|
||||
})
|
||||
self.dry_run = exchange_cfg.testnet
|
||||
self.leverage = leverage
|
||||
self._markets_loaded = False
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Bybit exchange emulator — drop-in ccxt.bybit replacement for backtesting."""
|
||||
|
||||
from .exchange import BybitEmulator
|
||||
from .account import AccountState
|
||||
from .matching import FillModel
|
||||
from .runner import run_single_coin
|
||||
|
||||
__all__ = ["BybitEmulator", "AccountState", "FillModel", "run_single_coin"]
|
||||
@@ -0,0 +1,181 @@
|
||||
"""In-memory account state: balances, positions, orders, PnL."""
|
||||
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
import uuid
|
||||
|
||||
|
||||
@dataclass
|
||||
class Position:
|
||||
symbol: str
|
||||
side: str # "long" or "short"
|
||||
size: float # always positive
|
||||
entry_price: float
|
||||
stop_loss: float | None = None
|
||||
unrealized_pnl: float = 0.0
|
||||
|
||||
@property
|
||||
def direction(self) -> int:
|
||||
return 1 if self.side == "long" else -1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Order:
|
||||
id: str
|
||||
symbol: str
|
||||
type: str # "market", "stop"
|
||||
side: str # "buy", "sell"
|
||||
amount: float
|
||||
price: float | None = None # trigger price for stops
|
||||
filled: float = 0.0
|
||||
average: float = 0.0
|
||||
cost: float = 0.0
|
||||
fee_cost: float = 0.0
|
||||
fee_currency: str = "USDT"
|
||||
status: str = "open" # "open", "closed", "canceled"
|
||||
reduce_only: bool = False
|
||||
params: dict = field(default_factory=dict)
|
||||
|
||||
def to_ccxt(self) -> dict:
|
||||
"""Return ccxt-compatible order dict."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"symbol": self.symbol,
|
||||
"type": self.type,
|
||||
"side": self.side,
|
||||
"amount": self.amount,
|
||||
"price": self.price,
|
||||
"filled": self.filled,
|
||||
"average": self.average,
|
||||
"cost": self.cost,
|
||||
"remaining": self.amount - self.filled,
|
||||
"status": self.status,
|
||||
"fee": {"cost": self.fee_cost, "currency": self.fee_currency},
|
||||
"info": {},
|
||||
}
|
||||
|
||||
|
||||
class AccountState:
|
||||
"""Manages balances, positions, orders in-memory."""
|
||||
|
||||
def __init__(self, initial_usdt: float = 100.0):
|
||||
self.balances: dict[str, dict[str, float]] = {
|
||||
"USDT": {"free": initial_usdt, "used": 0.0, "total": initial_usdt},
|
||||
}
|
||||
self.positions: dict[str, Position] = {} # symbol -> Position
|
||||
self.orders: dict[str, Order] = {} # order_id -> Order
|
||||
self.closed_pnl: list[dict] = [] # history of closed positions
|
||||
self._leverage: dict[str, int] = {}
|
||||
|
||||
def get_balance(self, coin: str = "USDT") -> dict:
|
||||
"""Return balance for a coin in ccxt format."""
|
||||
return self.balances.get(coin, {"free": 0.0, "used": 0.0, "total": 0.0})
|
||||
|
||||
def get_full_balance(self) -> dict:
|
||||
"""Return full balance dict in ccxt format."""
|
||||
return dict(self.balances)
|
||||
|
||||
def set_leverage(self, leverage: int, symbol: str):
|
||||
self._leverage[symbol] = leverage
|
||||
|
||||
def get_leverage(self, symbol: str) -> int:
|
||||
return self._leverage.get(symbol, 1)
|
||||
|
||||
def open_position(self, symbol: str, side: str, size: float,
|
||||
entry_price: float, cost: float, fee: float):
|
||||
"""Open or add to position. Deduct margin from balance."""
|
||||
self.balances["USDT"]["free"] -= cost + fee
|
||||
self.balances["USDT"]["used"] += cost
|
||||
self.balances["USDT"]["total"] -= fee # fee is consumed
|
||||
self.positions[symbol] = Position(
|
||||
symbol=symbol, side=side, size=size, entry_price=entry_price,
|
||||
)
|
||||
|
||||
def close_position(self, symbol: str, exit_price: float,
|
||||
fee: float) -> float:
|
||||
"""Close position, return realized PnL (after fees)."""
|
||||
pos = self.positions.pop(symbol, None)
|
||||
if not pos:
|
||||
return 0.0
|
||||
pnl_gross = pos.direction * (exit_price - pos.entry_price) * pos.size
|
||||
pnl_net = pnl_gross - fee
|
||||
margin = pos.size * pos.entry_price
|
||||
self.balances["USDT"]["free"] += margin + pnl_net
|
||||
self.balances["USDT"]["used"] -= margin
|
||||
self.balances["USDT"]["total"] = (
|
||||
self.balances["USDT"]["free"] + self.balances["USDT"]["used"]
|
||||
)
|
||||
# Bybit symbol: "DOGE/USDT:USDT" -> "DOGEUSDT"
|
||||
bybit_sym = symbol.split("/")[0] + symbol.split("/")[1].split(":")[0]
|
||||
self.closed_pnl.append({
|
||||
"symbol": bybit_sym,
|
||||
"side": "Buy" if pos.side == "long" else "Sell",
|
||||
"qty": str(pos.size),
|
||||
"avgEntryPrice": str(pos.entry_price),
|
||||
"avgExitPrice": str(exit_price),
|
||||
"closedPnl": str(pnl_net),
|
||||
})
|
||||
return pnl_net
|
||||
|
||||
def update_unrealized_pnl(self, symbol: str, current_price: float):
|
||||
"""Update unrealized PnL for a position."""
|
||||
pos = self.positions.get(symbol)
|
||||
if pos:
|
||||
pos.unrealized_pnl = pos.direction * (
|
||||
current_price - pos.entry_price
|
||||
) * pos.size
|
||||
|
||||
def charge_funding(self, symbol: str, rate: float):
|
||||
"""Charge funding rate on open position."""
|
||||
pos = self.positions.get(symbol)
|
||||
if not pos:
|
||||
return
|
||||
cost = pos.size * pos.entry_price * rate
|
||||
self.balances["USDT"]["free"] -= cost
|
||||
self.balances["USDT"]["total"] -= cost
|
||||
|
||||
def create_order(self, symbol: str, type_: str, side: str,
|
||||
amount: float, price: float | None = None,
|
||||
params: dict | None = None) -> Order:
|
||||
"""Create order in-memory, return Order object."""
|
||||
order = Order(
|
||||
id=uuid.uuid4().hex[:12],
|
||||
symbol=symbol,
|
||||
type=type_,
|
||||
side=side,
|
||||
amount=amount,
|
||||
price=price,
|
||||
params=params or {},
|
||||
reduce_only=bool((params or {}).get("reduceOnly")),
|
||||
)
|
||||
self.orders[order.id] = order
|
||||
return order
|
||||
|
||||
def cancel_order(self, order_id: str):
|
||||
"""Cancel pending order."""
|
||||
order = self.orders.get(order_id)
|
||||
if order and order.status == "open":
|
||||
order.status = "canceled"
|
||||
|
||||
def fill_order(self, order: Order, fill_price: float, commission: float):
|
||||
"""Fill order at given price with commission."""
|
||||
order.filled = order.amount
|
||||
order.average = fill_price
|
||||
order.cost = order.amount * fill_price
|
||||
order.fee_cost = order.cost * commission
|
||||
order.fee_currency = "USDT"
|
||||
order.status = "closed"
|
||||
|
||||
def get_position_ccxt(self, symbol: str) -> dict | None:
|
||||
"""Return position in ccxt fetch_positions format."""
|
||||
pos = self.positions.get(symbol)
|
||||
if not pos:
|
||||
return None
|
||||
return {
|
||||
"symbol": symbol,
|
||||
"contracts": pos.size,
|
||||
"side": pos.side,
|
||||
"entryPrice": pos.entry_price,
|
||||
"unrealizedPnl": pos.unrealized_pnl,
|
||||
"info": {},
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
"""BybitEmulator — drop-in ccxt.bybit replacement for backtesting.
|
||||
|
||||
Usage:
|
||||
from remizov_trader.emulator import BybitEmulator, FillModel
|
||||
emu = BybitEmulator(ohlcv_dict, initial_usdt=59.0)
|
||||
# Use exactly like ccxt.bybit:
|
||||
ohlcv = emu.fetch_ohlcv("DOGE/USDT:USDT", "4h", limit=1000)
|
||||
emu.create_order("DOGE/USDT:USDT", "market", "buy", 100)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import math
|
||||
import numpy as np
|
||||
from .account import AccountState
|
||||
from .matching import MatchingEngine, FillModel
|
||||
|
||||
# Default market metadata for common futures pairs
|
||||
_DEFAULT_MARKETS = {
|
||||
"DOGE/USDT:USDT": {"id": "DOGEUSDT", "base": "DOGE", "min_amt": 1.0, "min_cost": 5.0, "amt_prec": 0, "px_prec": 5},
|
||||
"APT/USDT:USDT": {"id": "APTUSDT", "base": "APT", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"FIL/USDT:USDT": {"id": "FILUSDT", "base": "FIL", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"LINK/USDT:USDT": {"id": "LINKUSDT", "base": "LINK", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"ETH/USDT:USDT": {"id": "ETHUSDT", "base": "ETH", "min_amt": 0.001, "min_cost": 5.0, "amt_prec": 3, "px_prec": 2},
|
||||
"INJ/USDT:USDT": {"id": "INJUSDT", "base": "INJ", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"AVAX/USDT:USDT": {"id": "AVAXUSDT", "base": "AVAX", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"WIF/USDT:USDT": {"id": "WIFUSDT", "base": "WIF", "min_amt": 1.0, "min_cost": 5.0, "amt_prec": 0, "px_prec": 4},
|
||||
"UNI/USDT:USDT": {"id": "UNIUSDT", "base": "UNI", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"NEAR/USDT:USDT": {"id": "NEARUSDT", "base": "NEAR", "min_amt": 0.1, "min_cost": 5.0, "amt_prec": 1, "px_prec": 4},
|
||||
"SOL/USDT:USDT": {"id": "SOLUSDT", "base": "SOL", "min_amt": 0.01, "min_cost": 5.0, "amt_prec": 2, "px_prec": 3},
|
||||
"BTC/USDT:USDT": {"id": "BTCUSDT", "base": "BTC", "min_amt": 0.001, "min_cost": 5.0, "amt_prec": 3, "px_prec": 1},
|
||||
}
|
||||
|
||||
|
||||
class BybitEmulator:
|
||||
"""CCXT-compatible Bybit emulator driven by OHLCV data.
|
||||
|
||||
Args:
|
||||
ohlcv_data: {symbol: np.array of [ts, open, high, low, close, volume]}
|
||||
initial_usdt: Starting USDT balance per account.
|
||||
fill_model: Cost model (spread, slippage, funding, commission).
|
||||
markets: Optional custom market metadata.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ohlcv_data: dict[str, np.ndarray],
|
||||
initial_usdt: float = 100.0,
|
||||
fill_model: FillModel | None = None,
|
||||
markets: dict | None = None,
|
||||
):
|
||||
self._ohlcv = ohlcv_data # {symbol: array shape (N, 6)}
|
||||
self._current_bar: dict[str, int] = {} # symbol -> bar index
|
||||
self._custom_markets = markets or {}
|
||||
self.account = AccountState(initial_usdt)
|
||||
self.engine = MatchingEngine(self.account, fill_model)
|
||||
self.markets_loaded = False
|
||||
|
||||
# ── Market Data ──────────────────────────────────────────────
|
||||
|
||||
def load_markets(self):
|
||||
self.markets_loaded = True
|
||||
return {}
|
||||
|
||||
def fetch_ohlcv(self, symbol: str, timeframe: str = "4h",
|
||||
since: int | None = None, limit: int = 1000,
|
||||
params: dict | None = None) -> list[list]:
|
||||
"""Return OHLCV bars up to current time. No look-ahead."""
|
||||
data = self._ohlcv.get(symbol)
|
||||
if data is None:
|
||||
raise Exception(f"No OHLCV data for {symbol}")
|
||||
|
||||
if since is not None:
|
||||
# Find first bar >= since
|
||||
timestamps = data[:, 0]
|
||||
start = int(np.searchsorted(timestamps, since))
|
||||
else:
|
||||
start = max(0, len(data) - limit)
|
||||
|
||||
end = min(start + limit, len(data))
|
||||
# Advance current bar pointer
|
||||
if end > 0:
|
||||
self._current_bar[symbol] = end - 1
|
||||
|
||||
return [
|
||||
[int(row[0]), float(row[1]), float(row[2]),
|
||||
float(row[3]), float(row[4]), float(row[5])]
|
||||
for row in data[start:end]
|
||||
]
|
||||
|
||||
def fetch_ticker(self, symbol: str) -> dict:
|
||||
"""Return current price (close of last seen bar)."""
|
||||
price = self._get_current_price(symbol)
|
||||
return {"last": price, "bid": price, "ask": price}
|
||||
|
||||
def market(self, symbol: str) -> dict:
|
||||
"""Return market metadata in ccxt format."""
|
||||
m = self._custom_markets.get(symbol) or _DEFAULT_MARKETS.get(symbol)
|
||||
if not m:
|
||||
# Fallback: generic market
|
||||
base = symbol.split("/")[0]
|
||||
m = {"id": base + "USDT", "base": base, "min_amt": 0.1,
|
||||
"min_cost": 5.0, "amt_prec": 2, "px_prec": 4}
|
||||
return {
|
||||
"id": m["id"],
|
||||
"symbol": symbol,
|
||||
"base": m["base"],
|
||||
"quote": "USDT",
|
||||
"active": True,
|
||||
"type": "linear",
|
||||
"limits": {
|
||||
"amount": {"min": m["min_amt"], "max": None},
|
||||
"cost": {"min": m["min_cost"], "max": None},
|
||||
"price": {"min": None, "max": None},
|
||||
},
|
||||
"precision": {"amount": m["amt_prec"], "price": m["px_prec"]},
|
||||
"info": {},
|
||||
}
|
||||
|
||||
# ── Account & Positions ──────────────────────────────────────
|
||||
|
||||
def fetch_balance(self, params: dict | None = None) -> dict:
|
||||
return self.account.get_full_balance()
|
||||
|
||||
def fetch_positions(self, symbols: list[str] | None = None,
|
||||
params: dict | None = None) -> list[dict]:
|
||||
"""Return open positions in ccxt format."""
|
||||
result = []
|
||||
check = symbols or list(self.account.positions.keys())
|
||||
for sym in check:
|
||||
pos = self.account.get_position_ccxt(sym)
|
||||
if pos:
|
||||
result.append(pos)
|
||||
return result
|
||||
|
||||
def set_leverage(self, leverage: int, symbol: str = None,
|
||||
params: dict | None = None):
|
||||
if symbol:
|
||||
self.account.set_leverage(leverage, symbol)
|
||||
|
||||
def set_position_mode(self, hedged: bool, symbol: str = None,
|
||||
params: dict | None = None):
|
||||
pass # Always one-way mode
|
||||
|
||||
# ── Orders ───────────────────────────────────────────────────
|
||||
|
||||
def create_order(self, symbol: str, type_: str, side: str,
|
||||
amount: float, price: float | None = None,
|
||||
params: dict | None = None) -> dict:
|
||||
"""Create and optionally fill order."""
|
||||
params = params or {}
|
||||
order = self.account.create_order(
|
||||
symbol, type_, side, amount, price, params
|
||||
)
|
||||
|
||||
if type_ == "market":
|
||||
current_price = self._get_current_price(symbol)
|
||||
ts = self._get_current_timestamp(symbol)
|
||||
self.engine.fill_market_order(order, current_price, ts)
|
||||
# Stop/conditional orders stay pending until triggered by on_bar
|
||||
|
||||
return order.to_ccxt()
|
||||
|
||||
def fetch_order(self, order_id: str, symbol: str = None,
|
||||
params: dict | None = None) -> dict:
|
||||
order = self.account.orders.get(order_id)
|
||||
if not order:
|
||||
raise Exception(f"Order {order_id} not found")
|
||||
return order.to_ccxt()
|
||||
|
||||
def fetch_closed_order(self, order_id: str, symbol: str = None,
|
||||
params: dict | None = None) -> dict:
|
||||
return self.fetch_order(order_id, symbol)
|
||||
|
||||
def cancel_order(self, order_id: str, symbol: str = None,
|
||||
params: dict | None = None):
|
||||
self.account.cancel_order(order_id)
|
||||
|
||||
# ── Bybit-specific ───────────────────────────────────────────
|
||||
|
||||
def privatePostV5PositionTradingStop(self, params: dict) -> dict:
|
||||
"""Set position-level stop loss."""
|
||||
bybit_symbol = params.get("symbol", "")
|
||||
stop_loss = float(params.get("stopLoss", 0))
|
||||
# Find position by bybit symbol
|
||||
for sym, pos in self.account.positions.items():
|
||||
mkt = self.market(sym)
|
||||
if mkt["id"] == bybit_symbol:
|
||||
pos.stop_loss = stop_loss
|
||||
return {"retCode": 0, "retMsg": "OK"}
|
||||
return {"retCode": 0, "retMsg": "OK"}
|
||||
|
||||
def privateGetV5PositionClosedPnl(self, params: dict) -> dict:
|
||||
"""Return closed PnL history."""
|
||||
bybit_symbol = params.get("symbol", "")
|
||||
matching = [
|
||||
p for p in reversed(self.account.closed_pnl)
|
||||
if p["symbol"] == bybit_symbol
|
||||
]
|
||||
limit = int(params.get("limit", 5))
|
||||
return {"result": {"list": matching[:limit]}}
|
||||
|
||||
# ── Precision helpers ────────────────────────────────────────
|
||||
|
||||
def amount_to_precision(self, symbol: str, amount: float) -> str:
|
||||
mkt = self.market(symbol)
|
||||
prec = mkt["precision"]["amount"]
|
||||
truncated = math.floor(amount * 10**prec) / 10**prec
|
||||
return f"{truncated:.{prec}f}"
|
||||
|
||||
def price_to_precision(self, symbol: str, price: float) -> str:
|
||||
mkt = self.market(symbol)
|
||||
prec = mkt["precision"]["price"]
|
||||
return f"{round(price, prec):.{prec}f}"
|
||||
|
||||
# ── Emulator control (not in ccxt) ───────────────────────────
|
||||
|
||||
def advance_to_bar(self, symbol: str, bar_index: int):
|
||||
"""Advance time to specific bar, processing stops and funding."""
|
||||
data = self._ohlcv.get(symbol)
|
||||
if data is None:
|
||||
return
|
||||
prev = self._current_bar.get(symbol, -1)
|
||||
for i in range(prev + 1, bar_index + 1):
|
||||
row = data[i]
|
||||
self.engine.on_bar(
|
||||
symbol, int(row[0]),
|
||||
float(row[1]), float(row[2]), float(row[3]), float(row[4]),
|
||||
)
|
||||
self._current_bar[symbol] = bar_index
|
||||
|
||||
# ── Internal ─────────────────────────────────────────────────
|
||||
|
||||
def _get_current_price(self, symbol: str) -> float:
|
||||
data = self._ohlcv.get(symbol)
|
||||
if data is None:
|
||||
raise Exception(f"No data for {symbol}")
|
||||
idx = self._current_bar.get(symbol, len(data) - 1)
|
||||
return float(data[idx][4]) # close price
|
||||
|
||||
def _get_current_timestamp(self, symbol: str) -> int:
|
||||
data = self._ohlcv.get(symbol)
|
||||
if data is None:
|
||||
return 0
|
||||
idx = self._current_bar.get(symbol, len(data) - 1)
|
||||
return int(data[idx][0])
|
||||
@@ -0,0 +1,261 @@
|
||||
"""Integration runner: drive real run_cycle() through BybitEmulator.
|
||||
|
||||
Bar-by-bar execution of the real bot code against historical data.
|
||||
Patches signals.fetch_prices and executor singletons to use emulator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..config import (
|
||||
AssetConfig, Config, ExchangeConfig, ModelConfig,
|
||||
RiskConfig, CircuitBreakerConfig,
|
||||
)
|
||||
from ..state import init_db, upsert_asset
|
||||
from ..core import model as model_mod, signals
|
||||
from ..core.futures import FuturesExecutor
|
||||
from .exchange import BybitEmulator
|
||||
from .matching import FillModel
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
WS = 64
|
||||
SHIFT = 14
|
||||
EPOCHS = 300
|
||||
LR = 0.005
|
||||
|
||||
|
||||
def _make_config(symbol: str, ticker: str, equity: float,
|
||||
leverage: int = 1) -> Config:
|
||||
"""Create Config suitable for emulator integration."""
|
||||
return Config(
|
||||
mode="live",
|
||||
initial_capital=equity,
|
||||
total_capital=equity,
|
||||
timeframe="4h",
|
||||
assets=[AssetConfig(
|
||||
ticker=ticker,
|
||||
symbol=symbol,
|
||||
K=2,
|
||||
corr_thresh=0.5,
|
||||
trailing_stop=True,
|
||||
timeframe="4h",
|
||||
market_type="futures",
|
||||
weight=0.0, # use risk-based sizing
|
||||
shape_confirm=True,
|
||||
retrain_enabled=False,
|
||||
cooldown_bars=3,
|
||||
stop_mult=4.0,
|
||||
)],
|
||||
model=ModelConfig(
|
||||
window_size=WS, n_steps=20, total_time=0.5,
|
||||
shift=SHIFT, epochs=EPOCHS, lr=LR,
|
||||
),
|
||||
risk=RiskConfig(
|
||||
per_trade=0.05, max_position_pct=0.40,
|
||||
max_open_positions=3, leverage=leverage,
|
||||
safety_stop_pct=0.10, time_exit=True,
|
||||
),
|
||||
circuit_breaker=CircuitBreakerConfig(
|
||||
atr_ratio_on=99.0, atr_ratio_off=99.0, # disable CB
|
||||
max_drawdown=0.99, dd_reset=0.01,
|
||||
),
|
||||
exchange=ExchangeConfig(
|
||||
api_key="emu", api_secret="emu", testnet=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _init_db(ticker: str, equity: float) -> sqlite3.Connection:
|
||||
"""Create in-memory DB with asset initialized."""
|
||||
conn = sqlite3.connect(":memory:")
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
init_db(conn)
|
||||
upsert_asset(conn, ticker, equity)
|
||||
return conn
|
||||
|
||||
|
||||
def _normalize_ohlcv(ohlcv: np.ndarray, dates: list | None = None) -> np.ndarray:
|
||||
"""Convert (N,4) [O,H,L,C] to (N,6) [ts,O,H,L,C,vol] format.
|
||||
|
||||
If already (N,6), return as-is.
|
||||
"""
|
||||
if ohlcv.shape[1] >= 6:
|
||||
return ohlcv
|
||||
|
||||
n = len(ohlcv)
|
||||
# Generate synthetic timestamps (4h bars from 2023-01-01)
|
||||
if dates:
|
||||
from datetime import timezone as tz
|
||||
timestamps = np.array([
|
||||
int(datetime.combine(d, datetime.min.time(),
|
||||
tzinfo=tz.utc).timestamp() * 1000)
|
||||
for d in dates
|
||||
], dtype=np.float64)
|
||||
else:
|
||||
base_ts = 1672531200000 # 2023-01-01 00:00 UTC
|
||||
timestamps = np.array([base_ts + i * 4 * 3600 * 1000 for i in range(n)],
|
||||
dtype=np.float64)
|
||||
|
||||
volumes = np.ones(n) * 1000.0 # placeholder
|
||||
result = np.column_stack([timestamps, ohlcv, volumes])
|
||||
return result
|
||||
|
||||
|
||||
def run_integrated(
|
||||
symbol: str,
|
||||
ohlcv: np.ndarray,
|
||||
cap: float = 59.0,
|
||||
fill_model: FillModel | None = None,
|
||||
leverage: int = 1,
|
||||
dates: list | None = None,
|
||||
) -> dict:
|
||||
"""Run real run_cycle() bar-by-bar through BybitEmulator.
|
||||
|
||||
Args:
|
||||
symbol: ccxt symbol, e.g. "UNI/USDT:USDT"
|
||||
ohlcv: numpy array shape (N, 4) or (N, 6)
|
||||
cap: starting capital
|
||||
fill_model: cost model (None = realistic defaults)
|
||||
leverage: position leverage
|
||||
dates: optional list of date objects (for 4-col OHLCV)
|
||||
|
||||
Returns:
|
||||
dict with: pnl, trades, wins, equity_curve, logs
|
||||
"""
|
||||
ticker = symbol.split("/")[0] + "-USD"
|
||||
fm = fill_model or FillModel()
|
||||
|
||||
# Normalize to 6-column format
|
||||
ohlcv = _normalize_ohlcv(ohlcv, dates)
|
||||
|
||||
# Train model on first 30% of data
|
||||
prices = ohlcv[:, 4] # close prices
|
||||
data = signals.prepare_windows(prices, WS, SHIFT)
|
||||
n_train = max(int(len(data) * 0.30), 20)
|
||||
|
||||
import torch
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(ModelConfig(
|
||||
window_size=WS, n_steps=20, total_time=0.5,
|
||||
shift=SHIFT, epochs=EPOCHS, lr=LR,
|
||||
))
|
||||
W = np.array([d["norm_input"] for d in data[:n_train]])
|
||||
T = np.array([d["norm_target"] for d in data[:n_train]])
|
||||
model_mod.train(mdl, W, T, EPOCHS, LR)
|
||||
|
||||
# Setup — emulator balance MUST match DB equity to avoid deposit detection
|
||||
ohlcv_dict = {symbol: ohlcv}
|
||||
emu = BybitEmulator(ohlcv_dict, initial_usdt=cap, fill_model=fm)
|
||||
cfg = _make_config(symbol, ticker, cap, leverage)
|
||||
conn = _init_db(ticker, cap)
|
||||
|
||||
executor = FuturesExecutor(cfg.exchange, leverage=leverage, exchange=emu)
|
||||
|
||||
# Determine test bars (after training data)
|
||||
test_start_idx = data[n_train]["price_idx"] if n_train < len(data) else WS + SHIFT
|
||||
total_bars = len(ohlcv)
|
||||
|
||||
all_logs = []
|
||||
equity_curve = [cap]
|
||||
|
||||
# Bar-by-bar execution
|
||||
for bar_idx in range(test_start_idx, total_bars):
|
||||
# Advance emulator to this bar
|
||||
first_ts = int(ohlcv[0][0])
|
||||
emu.fetch_ohlcv(symbol, "4h", since=first_ts, limit=bar_idx + 1)
|
||||
|
||||
# Process intermediate bars (stops, funding)
|
||||
emu.advance_to_bar(symbol, bar_idx)
|
||||
|
||||
# Emulated "now" from bar timestamp
|
||||
bar_ts_ms = int(ohlcv[bar_idx][0])
|
||||
emu_now = datetime.fromtimestamp(bar_ts_ms / 1000, tz=timezone.utc)
|
||||
emu_now_iso = emu_now.isoformat()
|
||||
emu_date = str(emu_now.date())
|
||||
|
||||
# Prices up to current bar (what the bot would see)
|
||||
current_prices = prices[:bar_idx + 1].copy()
|
||||
current_dates = [
|
||||
datetime.fromtimestamp(int(ohlcv[i][0]) / 1000, tz=timezone.utc).date()
|
||||
for i in range(bar_idx + 1)
|
||||
]
|
||||
|
||||
# Patch dependencies and run cycle
|
||||
def mock_fetch_prices(sym, interval, period, exchange_cfg=None, source="exchange"):
|
||||
return current_prices, current_dates
|
||||
|
||||
def mock_get_futures(c):
|
||||
return executor
|
||||
|
||||
def mock_get_exchange_balance(c):
|
||||
return emu.fetch_balance().get("USDT", {}).get("free", cap)
|
||||
|
||||
def mock_load_model(t, mcfg):
|
||||
return mdl
|
||||
|
||||
with (
|
||||
patch("remizov_trader.core.executor.signals.fetch_prices", mock_fetch_prices),
|
||||
patch("remizov_trader.core.executor._get_futures", mock_get_futures),
|
||||
patch("remizov_trader.core.executor._get_executor", lambda c, a: executor),
|
||||
patch("remizov_trader.notify._get_exchange_balance", mock_get_exchange_balance),
|
||||
patch("remizov_trader.core.executor.model_mod.load_model", mock_load_model),
|
||||
patch("remizov_trader.core.executor.detect_deposit", lambda *a, **kw: None),
|
||||
):
|
||||
from ..core.executor import run_cycle
|
||||
try:
|
||||
logs = run_cycle(conn, cfg)
|
||||
all_logs.extend(logs)
|
||||
except Exception as e:
|
||||
log.error(f"Bar {bar_idx}: run_cycle error: {e}")
|
||||
all_logs.append(f"ERROR bar {bar_idx}: {e}")
|
||||
|
||||
# Fix DB timestamps to match emulated time.
|
||||
# run_cycle uses datetime.now() which is wall-clock, but we need
|
||||
# emulated time for correct bars_held and cooldown calculations.
|
||||
conn.execute(
|
||||
"UPDATE positions SET created_at = ? "
|
||||
"WHERE status = 'open' AND created_at > ?",
|
||||
(emu_now_iso, emu_now_iso))
|
||||
conn.execute(
|
||||
"UPDATE assets SET last_stop_date = ? "
|
||||
"WHERE last_stop_date IS NOT NULL AND last_stop_date > ?",
|
||||
(emu_now_iso, emu_now_iso))
|
||||
conn.commit()
|
||||
|
||||
# Track equity
|
||||
from ..state import get_asset
|
||||
asset = get_asset(conn, ticker)
|
||||
if asset:
|
||||
equity_curve.append(asset["equity"])
|
||||
|
||||
# Final results
|
||||
from ..state import get_asset, get_trade_history
|
||||
asset = get_asset(conn, ticker)
|
||||
trades = get_trade_history(conn, ticker=ticker, limit=9999)
|
||||
conn.close()
|
||||
|
||||
total_pnl = asset["equity"] - cap if asset else 0
|
||||
wins = asset["wins"] if asset else 0
|
||||
losses = asset["losses"] if asset else 0
|
||||
n_trades = asset["trades_count"] if asset else 0
|
||||
wr = wins / n_trades * 100 if n_trades > 0 else 0
|
||||
|
||||
return {
|
||||
"pnl": total_pnl,
|
||||
"trades": n_trades,
|
||||
"wins": wins,
|
||||
"losses": losses,
|
||||
"wr": wr,
|
||||
"equity_curve": equity_curve,
|
||||
"logs": all_logs,
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Order matching engine: fills by OHLCV bars with realistic costs."""
|
||||
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from .account import AccountState, Order
|
||||
|
||||
|
||||
@dataclass
|
||||
class FillModel:
|
||||
"""Realistic cost parameters (from grid_realistic.py)."""
|
||||
spread: float = 0.0003 # 0.03% half-spread on entry/exit
|
||||
stop_slippage: float = 0.002 # 0.2% worse fill on stop triggers
|
||||
market_slippage: float = 0.0 # additional market order slippage
|
||||
funding_rate: float = 0.0001 # 0.01% per 8h
|
||||
funding_interval_h: int = 8 # funding every 8 hours
|
||||
commission: float = 0.00055 # taker fee (entry + exit combined)
|
||||
|
||||
|
||||
class MatchingEngine:
|
||||
"""Matches orders against OHLCV bars. Bar-by-bar, adverse price first."""
|
||||
|
||||
def __init__(self, account: AccountState, fill_model: FillModel | None = None):
|
||||
self.account = account
|
||||
self.fm = fill_model or FillModel()
|
||||
self._last_funding_ts: dict[str, int] = {} # symbol -> last funding timestamp
|
||||
|
||||
def fill_market_order(self, order: Order, price: float,
|
||||
timestamp_ms: int = 0):
|
||||
"""Fill market order immediately at price + spread + slippage."""
|
||||
# Determine direction: buy = worse price is higher
|
||||
sign = 1 if order.side == "buy" else -1
|
||||
fill_price = price * (1 + sign * (self.fm.spread + self.fm.market_slippage))
|
||||
|
||||
self.account.fill_order(order, fill_price, self.fm.commission)
|
||||
|
||||
if order.reduce_only:
|
||||
# Closing position
|
||||
self.account.close_position(
|
||||
order.symbol, fill_price, order.fee_cost
|
||||
)
|
||||
self.reset_funding_tracker(order.symbol)
|
||||
else:
|
||||
# Opening position
|
||||
side = "long" if order.side == "buy" else "short"
|
||||
self.account.open_position(
|
||||
order.symbol, side, order.amount,
|
||||
fill_price, order.cost, order.fee_cost,
|
||||
)
|
||||
# Initialize funding tracker at order time
|
||||
if timestamp_ms:
|
||||
self._last_funding_ts[order.symbol] = timestamp_ms
|
||||
|
||||
def check_stop_orders(self, symbol: str, high: float, low: float,
|
||||
close: float) -> list[Order]:
|
||||
"""Check and fill triggered stop orders. Returns filled orders."""
|
||||
filled = []
|
||||
for order in list(self.account.orders.values()):
|
||||
if order.symbol != symbol or order.status != "open":
|
||||
continue
|
||||
if order.type != "stop" or order.price is None:
|
||||
continue
|
||||
|
||||
triggered = False
|
||||
if order.side == "sell" and low <= order.price:
|
||||
# Stop sell (long protection): triggered when price drops to stop
|
||||
triggered = True
|
||||
elif order.side == "buy" and high >= order.price:
|
||||
# Stop buy (short protection): triggered when price rises to stop
|
||||
triggered = True
|
||||
|
||||
if triggered:
|
||||
# Fill at stop price + slippage (worse)
|
||||
sign = 1 if order.side == "buy" else -1
|
||||
fill_price = order.price * (1 + sign * self.fm.stop_slippage)
|
||||
self.account.fill_order(order, fill_price, self.fm.commission)
|
||||
if order.reduce_only:
|
||||
self.account.close_position(symbol, fill_price, order.fee_cost)
|
||||
filled.append(order)
|
||||
return filled
|
||||
|
||||
def check_position_sl(self, symbol: str, high: float, low: float) -> bool:
|
||||
"""Check position-level stop loss (set via tradingStop). Returns True if triggered."""
|
||||
pos = self.account.positions.get(symbol)
|
||||
if not pos or not pos.stop_loss:
|
||||
return False
|
||||
|
||||
triggered = False
|
||||
if pos.side == "long" and low <= pos.stop_loss:
|
||||
triggered = True
|
||||
elif pos.side == "short" and high >= pos.stop_loss:
|
||||
triggered = True
|
||||
|
||||
if triggered:
|
||||
sign = -pos.direction
|
||||
fill_price = pos.stop_loss * (1 + sign * self.fm.stop_slippage)
|
||||
fee = pos.size * fill_price * self.fm.commission
|
||||
self.account.close_position(symbol, fill_price, fee)
|
||||
# Cancel related stop orders
|
||||
for order in list(self.account.orders.values()):
|
||||
if order.symbol == symbol and order.status == "open":
|
||||
order.status = "canceled"
|
||||
return True
|
||||
return False
|
||||
|
||||
def process_funding(self, symbol: str, bar_timestamp_ms: int):
|
||||
"""Charge funding if interval elapsed since last charge."""
|
||||
pos = self.account.positions.get(symbol)
|
||||
if not pos:
|
||||
return
|
||||
|
||||
interval_ms = self.fm.funding_interval_h * 3600 * 1000
|
||||
last = self._last_funding_ts.get(symbol, 0)
|
||||
|
||||
if last == 0:
|
||||
self._last_funding_ts[symbol] = bar_timestamp_ms
|
||||
return
|
||||
|
||||
if bar_timestamp_ms - last >= interval_ms:
|
||||
self.account.charge_funding(symbol, self.fm.funding_rate)
|
||||
self._last_funding_ts[symbol] = bar_timestamp_ms
|
||||
|
||||
def on_bar(self, symbol: str, timestamp_ms: int,
|
||||
open_: float, high: float, low: float, close: float):
|
||||
"""Process one OHLCV bar: funding, stop checks, unrealized PnL."""
|
||||
self.process_funding(symbol, timestamp_ms)
|
||||
self.check_position_sl(symbol, high, low)
|
||||
self.check_stop_orders(symbol, high, low, close)
|
||||
self.account.update_unrealized_pnl(symbol, close)
|
||||
|
||||
def reset_funding_tracker(self, symbol: str):
|
||||
"""Reset funding tracker when position is closed."""
|
||||
self._last_funding_ts.pop(symbol, None)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Portfolio backtest: run all coins through emulator, print summary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from .runner import run_single_coin, load_cached_ohlcv
|
||||
from .matching import FillModel
|
||||
|
||||
CONFIGS = [
|
||||
("DOGE/USDT:USDT", "DOGE", 1, 20),
|
||||
("APT/USDT:USDT", "APT", 1, 12),
|
||||
("FIL/USDT:USDT", "FIL", 1, 14),
|
||||
("LINK/USDT:USDT", "LINK", 1, 20),
|
||||
("ETH/USDT:USDT", "ETH", 1, 20),
|
||||
("INJ/USDT:USDT", "INJ", 1, 20),
|
||||
("AVAX/USDT:USDT", "AVAX", 2, 14),
|
||||
("WIF/USDT:USDT", "WIF", 0, 20),
|
||||
]
|
||||
|
||||
FILL_MODELS = {
|
||||
"ideal": FillModel(spread=0, stop_slippage=0, market_slippage=0,
|
||||
funding_rate=0, commission=0.00055),
|
||||
"realistic": FillModel(), # defaults from grid_realistic.py
|
||||
"pessimistic": FillModel(spread=0.0005, stop_slippage=0.003,
|
||||
funding_rate=0.00015, commission=0.00055),
|
||||
}
|
||||
|
||||
|
||||
def run_portfolio(
|
||||
cache_dir: str = "/tmp/ohlcv_cache",
|
||||
cap: float = 59.0,
|
||||
model_name: str = "realistic",
|
||||
coins: list[tuple] | None = None,
|
||||
) -> dict:
|
||||
"""Run full portfolio backtest. Returns summary dict."""
|
||||
configs = coins or CONFIGS
|
||||
fm = FILL_MODELS.get(model_name, FILL_MODELS["realistic"])
|
||||
|
||||
results = []
|
||||
total_pnl = 0.0
|
||||
total_funding = 0.0
|
||||
|
||||
print(f"\n{'='*90}")
|
||||
print(f" EMULATOR PORTFOLIO BACKTEST — {model_name} fill model")
|
||||
print(f" spread={fm.spread:.4f} slip={fm.stop_slippage:.4f} "
|
||||
f"fund={fm.funding_rate:.5f} comm={fm.commission:.5f}")
|
||||
print(f"{'='*90}")
|
||||
print(f"\n{'Coin':<6} {'PnL':>10} {'Trades':>7} {'WR':>6} "
|
||||
f"{'Stops':>6} {'MaxDD':>7} {'Fund':>7}")
|
||||
print("-" * 55)
|
||||
|
||||
for sym, coin, delay, hold in configs:
|
||||
t0 = time.time()
|
||||
try:
|
||||
ohlcv, _ = load_cached_ohlcv(cache_dir, sym)
|
||||
except FileNotFoundError:
|
||||
print(f"{coin:<6} SKIP (no cache)")
|
||||
continue
|
||||
|
||||
r = run_single_coin(sym, ohlcv, delay, hold, cap, fm)
|
||||
elapsed = time.time() - t0
|
||||
|
||||
total_pnl += r["pnl"]
|
||||
total_funding += r["funding"]
|
||||
results.append({"coin": coin, "symbol": sym, **r})
|
||||
|
||||
print(f"{coin:<6} ${r['pnl']:>+9.2f} {r['trades']:>7} "
|
||||
f"{r['wr']:>5.1f}% {r['stops']:>6} "
|
||||
f"{r['max_dd']:>6.1f}% ${r['funding']:>6.2f} "
|
||||
f"({elapsed:.0f}s)")
|
||||
|
||||
print("-" * 55)
|
||||
n_coins = len(results)
|
||||
total_cap = n_coins * cap
|
||||
months = 24 # approx test period
|
||||
print(f"{'TOTAL':<6} ${total_pnl:>+9.2f} "
|
||||
f"{'':>7} {'':>6} {'':>6} {'':>7} "
|
||||
f"${total_funding:>6.2f}")
|
||||
print(f"\n Capital: {n_coins} x ${cap:.0f} = ${total_cap:.0f}")
|
||||
print(f" Return: {total_pnl/total_cap*100:+.1f}%")
|
||||
print(f" $/month: ${total_pnl/months:+.2f}")
|
||||
print(f" Funding: ${total_funding:.2f} "
|
||||
f"({total_funding/total_pnl*100:.1f}% of PnL)" if total_pnl else "")
|
||||
|
||||
return {
|
||||
"results": results,
|
||||
"total_pnl": total_pnl,
|
||||
"total_funding": total_funding,
|
||||
"capital": total_cap,
|
||||
"fill_model": model_name,
|
||||
}
|
||||
|
||||
|
||||
def compare_models(cache_dir: str = "/tmp/ohlcv_cache", cap: float = 59.0):
|
||||
"""Run portfolio with all fill models and compare."""
|
||||
summaries = {}
|
||||
for name in ["ideal", "realistic", "pessimistic"]:
|
||||
s = run_portfolio(cache_dir, cap, name)
|
||||
summaries[name] = s
|
||||
|
||||
print(f"\n\n{'='*60}")
|
||||
print(f" COMPARISON: ideal vs realistic vs pessimistic")
|
||||
print(f"{'='*60}")
|
||||
print(f" {'Model':<14} {'PnL':>10} {'$/mo':>8} {'Return':>8}")
|
||||
print(f" {'-'*44}")
|
||||
for name, s in summaries.items():
|
||||
months = 24
|
||||
print(f" {name:<14} ${s['total_pnl']:>+9.2f} "
|
||||
f"${s['total_pnl']/months:>+7.2f} "
|
||||
f"{s['total_pnl']/s['capital']*100:>+7.1f}%")
|
||||
|
||||
ideal = summaries["ideal"]["total_pnl"]
|
||||
real = summaries["realistic"]["total_pnl"]
|
||||
if ideal:
|
||||
print(f"\n Realistic multiplier: {real/ideal:.2f}x")
|
||||
|
||||
return summaries
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Realistic backtest runner.
|
||||
|
||||
Stop mechanics:
|
||||
- ATR: True ATR (high-low-close) — financial standard
|
||||
- Stop check: by high/low (exchange checks ticks continuously)
|
||||
- Trailing update: by high/low (bar extremes)
|
||||
|
||||
Note: prod bot uses close-only ATR (risk.compute_atr) — a known
|
||||
limitation giving ~2.5x tighter stops. Fix planned for prod.
|
||||
FillModel controls spread/slippage/funding parameters.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pickle
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from ..core import model as model_mod, signals, risk
|
||||
from ..config import ModelConfig, RiskConfig
|
||||
from .matching import FillModel
|
||||
|
||||
WS = 64
|
||||
K = 2
|
||||
SHIFT = 14
|
||||
EPOCHS = 300
|
||||
LR = 0.005
|
||||
SM = 4.0
|
||||
|
||||
|
||||
def load_cached_ohlcv(cache_dir: str, symbol: str,
|
||||
timeframe: str = "4h") -> tuple[np.ndarray, list]:
|
||||
"""Load OHLCV from pickle cache."""
|
||||
safe = symbol.replace("/", "_").replace(":", "_")
|
||||
with open(f"{cache_dir}/{safe}_{timeframe}.pkl", "rb") as f:
|
||||
return pickle.load(f)
|
||||
|
||||
|
||||
def _train_model(data_slice: list[dict], shift: int = SHIFT) -> object:
|
||||
"""Train ScoreNet model on data slice."""
|
||||
mcfg = ModelConfig(
|
||||
window_size=WS, n_steps=20, total_time=0.5, shift=shift,
|
||||
epochs=EPOCHS, finetune_epochs=50, lr=LR,
|
||||
)
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(mcfg)
|
||||
W = np.array([d["norm_input"] for d in data_slice])
|
||||
T = np.array([d["norm_target"] for d in data_slice])
|
||||
model_mod.train(mdl, W, T, EPOCHS, LR)
|
||||
return mdl
|
||||
|
||||
|
||||
def true_atr(highs, lows, prices, idx, period=14):
|
||||
"""True ATR: max(high-low, |high-prev_close|, |low-prev_close|)."""
|
||||
if idx < period + 1:
|
||||
return float(prices[idx]) * 0.02
|
||||
trs = []
|
||||
for i in range(idx - period, idx):
|
||||
hl = float(highs[i]) - float(lows[i])
|
||||
hc = abs(float(highs[i]) - float(prices[i - 1]))
|
||||
lc = abs(float(lows[i]) - float(prices[i - 1]))
|
||||
trs.append(max(hl, hc, lc))
|
||||
return float(np.mean(trs))
|
||||
|
||||
|
||||
def run_single_coin(
|
||||
symbol: str,
|
||||
ohlcv: np.ndarray,
|
||||
delay: int,
|
||||
hold: int,
|
||||
cap: float = 59.0,
|
||||
fill_model: FillModel | None = None,
|
||||
k: int = K,
|
||||
shift: int = SHIFT,
|
||||
sm: float = SM,
|
||||
train_start_pct: float = 0.0,
|
||||
train_end_pct: float = 0.30,
|
||||
longs_only: bool = False,
|
||||
) -> dict:
|
||||
"""Run realistic backtest matching prod optimizer behavior.
|
||||
|
||||
ATR: close-only (prod risk.compute_atr).
|
||||
Stop check: by high/low (exchange checks ticks continuously).
|
||||
Trailing update: by high/low (matches optimize-windows CLI).
|
||||
"""
|
||||
prices = ohlcv[:, 3]
|
||||
highs = ohlcv[:, 1]
|
||||
lows = ohlcv[:, 2]
|
||||
|
||||
data = signals.prepare_windows(prices, WS, shift)
|
||||
n = len(data)
|
||||
n_start = max(int(n * train_start_pct), 0)
|
||||
n_end = max(int(n * train_end_pct), n_start + 20)
|
||||
train_data = data[n_start:n_end]
|
||||
test_data = data[n_end:]
|
||||
if not test_data or len(train_data) < 10:
|
||||
return {"pnl": 0, "trades": 0, "wr": 0, "stops": 0,
|
||||
"max_dd": 0, "funding": 0}
|
||||
|
||||
mdl = _train_model(train_data, shift)
|
||||
rcfg = RiskConfig(
|
||||
per_trade=0.05, max_position_pct=0.40,
|
||||
max_open_positions=3, leverage=1,
|
||||
)
|
||||
fm = fill_model or FillModel()
|
||||
|
||||
eq = cap
|
||||
pos = None # {d, e, s, sd, b, sz, v, bar, lc}
|
||||
pending = None
|
||||
cool = 0
|
||||
pnls = []
|
||||
trades = 0
|
||||
wins = 0
|
||||
stops = 0
|
||||
ah = hold if hold > 0 else (shift - k)
|
||||
funding_total = 0.0
|
||||
FUND_INTERVAL = 2 # every 2 bars (8h on 4h timeframe)
|
||||
|
||||
def _open_pos(direction, entry_price, bar_idx):
|
||||
"""Open position with trailing stop."""
|
||||
atr_val = true_atr(highs, lows, prices, bar_idx)
|
||||
ep = entry_price + direction * entry_price * fm.spread
|
||||
sd = max(atr_val * sm, ep * 0.005)
|
||||
sp = ep - direction * sd
|
||||
sz, val = risk.calculate_position(eq, ep, sd, rcfg)
|
||||
return {"d": direction, "e": ep, "s": sp, "sd": sd,
|
||||
"b": ep, "sz": sz, "v": val, "bar": bar_idx,
|
||||
"lc": bar_idx}
|
||||
|
||||
for d_item in test_data:
|
||||
pi = d_item["price_idx"]
|
||||
cp = float(prices[pi])
|
||||
|
||||
# Handle pending delayed entry
|
||||
if pending and pi >= pending["ea"]:
|
||||
pos = _open_pos(pending["d"], float(prices[pending["ea"]]),
|
||||
pending["ea"])
|
||||
pending = None
|
||||
|
||||
# Bar-by-bar position management
|
||||
if pos:
|
||||
sf = pos.get("lc", pos["bar"]) + 1
|
||||
for bi in range(sf, pi + 1):
|
||||
h = float(highs[bi])
|
||||
l = float(lows[bi])
|
||||
c = float(prices[bi])
|
||||
|
||||
# Funding rate
|
||||
bars_in = bi - pos["bar"]
|
||||
if bars_in > 0 and bars_in % FUND_INTERVAL == 0:
|
||||
fund_cost = pos["v"] * fm.funding_rate
|
||||
eq -= fund_cost
|
||||
funding_total += fund_cost
|
||||
|
||||
# Stop check by high/low (exchange checks ticks)
|
||||
adv = l if pos["d"] == 1 else h
|
||||
if risk.is_stopped(adv, pos["s"], pos["d"]):
|
||||
exit_p = pos["s"] * (1 - pos["d"] * fm.stop_slippage)
|
||||
pnl, _ = risk.calculate_pnl(
|
||||
pos["e"], exit_p, pos["d"],
|
||||
pos["sz"], pos["v"], commission=fm.commission,
|
||||
)
|
||||
eq += pnl
|
||||
pnls.append(pnl)
|
||||
trades += 1
|
||||
stops += 1
|
||||
if pnl > 0:
|
||||
wins += 1
|
||||
pos = None
|
||||
cool = bi + 3
|
||||
break
|
||||
|
||||
# Trailing update by high/low (matches optimizer)
|
||||
fav = h if pos["d"] == 1 else l
|
||||
pos["b"], pos["s"] = risk.update_trailing_stop(
|
||||
fav, pos["b"], pos["s"], pos["sd"], pos["d"],
|
||||
)
|
||||
|
||||
# Time exit
|
||||
if bi - pos["bar"] >= ah:
|
||||
exit_p = c * (1 - pos["d"] * fm.spread)
|
||||
pnl, _ = risk.calculate_pnl(
|
||||
pos["e"], exit_p, pos["d"],
|
||||
pos["sz"], pos["v"], commission=fm.commission,
|
||||
)
|
||||
eq += pnl
|
||||
pnls.append(pnl)
|
||||
trades += 1
|
||||
if pnl > 0:
|
||||
wins += 1
|
||||
pos = None
|
||||
break
|
||||
|
||||
if pos:
|
||||
pos["lc"] = pi
|
||||
|
||||
# Look for new signal
|
||||
if pos is None and pending is None and pi >= WS + k and pi >= cool:
|
||||
w = prices[pi - WS - k:pi - k].copy()
|
||||
mu, std = w.mean(), w.std()
|
||||
if std < 1e-10:
|
||||
continue
|
||||
pred = model_mod.predict(mdl, (w - mu) / std)[-shift:]
|
||||
d2 = signals.get_direction(pred, k)
|
||||
if d2:
|
||||
if longs_only and d2 == -1:
|
||||
continue
|
||||
if delay == 0:
|
||||
pos = _open_pos(d2, cp, pi)
|
||||
else:
|
||||
pending = {
|
||||
"d": d2,
|
||||
"ea": min(pi + delay, len(prices) - 1),
|
||||
}
|
||||
|
||||
# Close open position at end
|
||||
if pos:
|
||||
lp = float(prices[-1]) * (1 - pos["d"] * fm.spread)
|
||||
pnl, _ = risk.calculate_pnl(
|
||||
pos["e"], lp, pos["d"],
|
||||
pos["sz"], pos["v"], commission=fm.commission,
|
||||
)
|
||||
eq += pnl
|
||||
pnls.append(pnl)
|
||||
trades += 1
|
||||
if pnl > 0:
|
||||
wins += 1
|
||||
|
||||
# Calculate max drawdown
|
||||
total_pnl = eq - cap
|
||||
wr = wins / trades * 100 if trades else 0
|
||||
mx = cap
|
||||
mdd = 0
|
||||
run = cap
|
||||
for p in pnls:
|
||||
run += p
|
||||
if run > mx:
|
||||
mx = run
|
||||
dd = (mx - run) / mx if mx > 0 else 0
|
||||
if dd > mdd:
|
||||
mdd = dd
|
||||
|
||||
return {
|
||||
"pnl": total_pnl,
|
||||
"trades": trades,
|
||||
"wr": wr,
|
||||
"stops": stops,
|
||||
"max_dd": mdd * 100,
|
||||
"funding": funding_total,
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
"""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
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Verification: emulator runner PnL vs grid_realistic.py PnL.
|
||||
|
||||
Run with: python -m pytest tests/test_emulator_vs_realistic.py -v -s
|
||||
Requires: /tmp/ohlcv_cache/ with cached OHLCV data.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import pickle
|
||||
import pytest
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
from remizov_trader.emulator.runner import run_single_coin, load_cached_ohlcv
|
||||
from remizov_trader.emulator.matching import FillModel
|
||||
from remizov_trader.core import model as model_mod, signals, risk
|
||||
from remizov_trader.config import ModelConfig, RiskConfig
|
||||
|
||||
CACHE_DIR = "/tmp/ohlcv_cache"
|
||||
CAP = 59.0
|
||||
WS = 64; K = 2; SHIFT = 14; EPOCHS = 300; LR = 0.005; SM = 4.0
|
||||
COMM = 0.00055
|
||||
|
||||
CONFIGS = [
|
||||
("DOGE/USDT:USDT", "DOGE", 1, 20),
|
||||
("APT/USDT:USDT", "APT", 1, 12),
|
||||
("LINK/USDT:USDT", "LINK", 1, 20),
|
||||
]
|
||||
|
||||
|
||||
def _has_cache():
|
||||
if not os.path.isdir(CACHE_DIR):
|
||||
return False
|
||||
for sym, _, _, _ in CONFIGS:
|
||||
safe = sym.replace("/", "_").replace(":", "_")
|
||||
if not os.path.exists(f"{CACHE_DIR}/{safe}_4h.pkl"):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# ── Reference: grid_realistic.py logic (copied for comparison) ──
|
||||
|
||||
def _true_atr(highs, lows, prices, idx, period=14):
|
||||
if idx < period + 1:
|
||||
return float(prices[idx]) * 0.02
|
||||
trs = []
|
||||
for i in range(idx - period, idx):
|
||||
hl = float(highs[i]) - float(lows[i])
|
||||
hc = abs(float(highs[i]) - float(prices[i - 1]))
|
||||
lc = abs(float(lows[i]) - float(prices[i - 1]))
|
||||
trs.append(max(hl, hc, lc))
|
||||
return float(np.mean(trs))
|
||||
|
||||
|
||||
def _run_reference(prices, highs, lows, mdl, delay, hold, cap):
|
||||
"""Realistic backtest from grid_realistic.py — the reference implementation."""
|
||||
SPREAD = 0.0003
|
||||
STOP_SLIP = 0.002
|
||||
FUND_RATE = 0.0001
|
||||
FUND_INTERVAL = 2
|
||||
RCFG = RiskConfig(per_trade=0.05, max_position_pct=0.40,
|
||||
max_open_positions=3, leverage=1)
|
||||
|
||||
data = signals.prepare_windows(prices, WS, SHIFT)
|
||||
n = len(data); n_train = max(int(n * 0.30), 20)
|
||||
test_data = data[n_train:]
|
||||
if not test_data:
|
||||
return None
|
||||
|
||||
eq = cap; pos = None; cool = 0; pending = None
|
||||
pnls = []; trades = 0; wins = 0; stops = 0
|
||||
ah = hold if hold > 0 else (SHIFT - K)
|
||||
|
||||
for d in test_data:
|
||||
pi = d["price_idx"]; cp = float(prices[pi])
|
||||
if pending and pi >= pending["ea"]:
|
||||
ei = pending["ea"]; ep = float(prices[ei])
|
||||
atr_val = _true_atr(highs, lows, prices, ei)
|
||||
ep += pending["d"] * ep * SPREAD
|
||||
sd = max(atr_val * SM, ep * 0.005); sp = ep - pending["d"] * sd
|
||||
sz, val = risk.calculate_position(eq, ep, sd, RCFG)
|
||||
pos = {"d": pending["d"], "e": ep, "s": sp, "sd": sd,
|
||||
"b": ep, "sz": sz, "v": val, "bar": ei, "lc": ei}
|
||||
pending = None
|
||||
if pos:
|
||||
sf = pos.get("lc", pos["bar"]) + 1
|
||||
for bi in range(sf, pi + 1):
|
||||
h, l = float(highs[bi]), float(lows[bi]); c = float(prices[bi])
|
||||
if (bi - pos["bar"]) > 0 and (bi - pos["bar"]) % FUND_INTERVAL == 0:
|
||||
eq -= pos["v"] * FUND_RATE
|
||||
adv = l if pos["d"] == 1 else h
|
||||
if risk.is_stopped(adv, pos["s"], pos["d"]):
|
||||
exit_p = pos["s"] * (1 - pos["d"] * STOP_SLIP)
|
||||
pnl, _ = risk.calculate_pnl(pos["e"], exit_p, pos["d"],
|
||||
pos["sz"], pos["v"], commission=COMM)
|
||||
eq += pnl; pnls.append(pnl); trades += 1; stops += 1
|
||||
if pnl > 0: wins += 1
|
||||
pos = None; cool = bi + 3; break
|
||||
fav = h if pos["d"] == 1 else l
|
||||
pos["b"], pos["s"] = risk.update_trailing_stop(
|
||||
fav, pos["b"], pos["s"], pos["sd"], pos["d"])
|
||||
if bi - pos["bar"] >= ah:
|
||||
exit_p = c * (1 - pos["d"] * SPREAD)
|
||||
pnl, _ = risk.calculate_pnl(pos["e"], exit_p, pos["d"],
|
||||
pos["sz"], pos["v"], commission=COMM)
|
||||
eq += pnl; pnls.append(pnl); trades += 1
|
||||
if pnl > 0: wins += 1
|
||||
pos = None; break
|
||||
if pos: pos["lc"] = pi
|
||||
if pos is None and pending is None and pi >= WS + K and pi >= cool:
|
||||
w = prices[pi-WS-K:pi-K].copy(); mu, std = w.mean(), w.std()
|
||||
if std < 1e-10: continue
|
||||
pred = model_mod.predict(mdl, (w - mu) / std)[-SHIFT:]
|
||||
d2 = signals.get_direction(pred, K)
|
||||
if d2:
|
||||
if delay == 0:
|
||||
atr_val = _true_atr(highs, lows, prices, pi)
|
||||
ep = cp + d2 * cp * SPREAD
|
||||
sd = max(atr_val * SM, ep * 0.005)
|
||||
sp = ep - d2 * sd; sz, val = risk.calculate_position(eq, ep, sd, RCFG)
|
||||
pos = {"d": d2, "e": ep, "s": sp, "sd": sd,
|
||||
"b": ep, "sz": sz, "v": val, "bar": pi, "lc": pi}
|
||||
else:
|
||||
pending = {"d": d2, "ea": min(pi + delay, len(prices) - 1)}
|
||||
if pos:
|
||||
lp = float(prices[-1]) * (1 - pos["d"] * SPREAD)
|
||||
pnl, _ = risk.calculate_pnl(pos["e"], lp, pos["d"], pos["sz"], pos["v"], commission=COMM)
|
||||
eq += pnl; pnls.append(pnl); trades += 1
|
||||
if pnl > 0: wins += 1
|
||||
return {"pnl": eq - cap, "trades": trades, "wr": wins / trades * 100 if trades else 0,
|
||||
"stops": stops}
|
||||
|
||||
|
||||
# ── Tests ──
|
||||
|
||||
@pytest.mark.skipif(not _has_cache(), reason="No OHLCV cache at /tmp/ohlcv_cache")
|
||||
class TestEmulatorVsRealistic:
|
||||
"""Compare emulator runner PnL with reference grid_realistic.py implementation."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _setup(self):
|
||||
"""Train models once for all tests."""
|
||||
self.models = {}
|
||||
for sym, coin, delay, hold in CONFIGS:
|
||||
ohlcv, _ = load_cached_ohlcv(CACHE_DIR, sym)
|
||||
prices = ohlcv[:, 3]
|
||||
data = signals.prepare_windows(prices, WS, SHIFT)
|
||||
n_train = max(int(len(data) * 0.30), 20)
|
||||
mcfg = ModelConfig(window_size=WS, n_steps=20, total_time=0.5,
|
||||
shift=SHIFT, epochs=EPOCHS, finetune_epochs=50, lr=LR)
|
||||
torch.manual_seed(42); np.random.seed(42)
|
||||
mdl = model_mod.create_model(mcfg)
|
||||
W = np.array([d["norm_input"] for d in data[:n_train]])
|
||||
T = np.array([d["norm_target"] for d in data[:n_train]])
|
||||
model_mod.train(mdl, W, T, EPOCHS, LR)
|
||||
self.models[sym] = mdl
|
||||
|
||||
@pytest.mark.parametrize("sym,coin,delay,hold", CONFIGS)
|
||||
def test_emulator_pnl_direction(self, sym, coin, delay, hold):
|
||||
"""Emulator PnL should have the same sign as reference."""
|
||||
ohlcv, _ = load_cached_ohlcv(CACHE_DIR, sym)
|
||||
prices = ohlcv[:, 3]; highs = ohlcv[:, 1]; lows = ohlcv[:, 2]
|
||||
|
||||
ref = _run_reference(prices, highs, lows, self.models[sym],
|
||||
delay, hold, CAP)
|
||||
fm = FillModel(spread=0.0003, stop_slippage=0.002,
|
||||
commission=COMM, funding_rate=0.0001)
|
||||
emu = run_single_coin(sym, ohlcv, delay, hold, CAP, fm)
|
||||
|
||||
print(f"\n{coin}: ref=${ref['pnl']:+.2f} ({ref['trades']}tr) "
|
||||
f"emu=${emu['pnl']:+.2f} ({emu['trades']}tr)")
|
||||
|
||||
# Same sign (both profitable or both losing)
|
||||
if abs(ref["pnl"]) > 1.0: # skip near-zero
|
||||
assert (ref["pnl"] > 0) == (emu["pnl"] > 0), \
|
||||
f"PnL sign mismatch: ref={ref['pnl']:.2f} emu={emu['pnl']:.2f}"
|
||||
|
||||
@pytest.mark.parametrize("sym,coin,delay,hold", CONFIGS)
|
||||
def test_trade_count_similar(self, sym, coin, delay, hold):
|
||||
"""Emulator should produce similar number of trades."""
|
||||
ohlcv, _ = load_cached_ohlcv(CACHE_DIR, sym)
|
||||
prices = ohlcv[:, 3]; highs = ohlcv[:, 1]; lows = ohlcv[:, 2]
|
||||
|
||||
ref = _run_reference(prices, highs, lows, self.models[sym],
|
||||
delay, hold, CAP)
|
||||
fm = FillModel(spread=0.0003, stop_slippage=0.002,
|
||||
commission=COMM, funding_rate=0.0001)
|
||||
emu = run_single_coin(sym, ohlcv, delay, hold, CAP, fm)
|
||||
|
||||
if ref["trades"] > 0:
|
||||
ratio = emu["trades"] / ref["trades"]
|
||||
print(f"\n{coin}: ref={ref['trades']} trades, emu={emu['trades']} "
|
||||
f"(ratio={ratio:.2f})")
|
||||
# Should be within 50% (emulator may differ due to
|
||||
# different ATR calculation and equity path)
|
||||
assert 0.5 <= ratio <= 2.0, \
|
||||
f"Trade count too different: ref={ref['trades']} emu={emu['trades']}"
|
||||
@@ -0,0 +1,199 @@
|
||||
"""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
|
||||
@@ -0,0 +1,74 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user