Files
scalp-bot/test_live.py
T

215 lines
8.2 KiB
Python

"""Integration test: simulate run_cycle with cached data and mock time.
Verifies OR computation, strategy signal detection, reconciliation,
position sizing, and DB state updates.
"""
from __future__ import annotations
import sqlite3
from datetime import date, datetime, timezone
from pathlib import Path
from unittest.mock import patch
from zoneinfo import ZoneInfo
import pandas as pd
from config import Config, ExchangeConfig, RiskConfig, StrategyConfig, TelegramConfig, load_config
from state import get_db, get_equity, get_open_positions, get_session, get_state_val, init_db
from strategy import Params, get_opening_range, run_day
NY = ZoneInfo("America/New_York")
# Use in-memory DB for test isolation
TEST_DB = Path("/tmp/scalp_test.db")
def test_or_computation():
"""Test that OR is computed correctly from cached 5m candles."""
df = pd.read_csv("cache/BTC_USDT_USDT_60d_5m.csv", parse_dates=["timestamp"])
df["timestamp"] = (df["timestamp"].dt.tz_localize("UTC")
if df["timestamp"].dt.tz is None else df["timestamp"])
# Pick a day with trades: 2026-01-29 (Wednesday, 2 trades)
ny = df["timestamp"].dt.tz_convert(NY)
test_date = date(2026, 1, 29)
day_df = df[ny.dt.date == test_date].reset_index(drop=True)
# Get 9:30-9:45 candles (OR=15min = 3 candles on 5m)
ny_day = day_df["timestamp"].dt.tz_convert(NY)
or_mask = (ny_day.dt.hour == 9) & (ny_day.dt.minute >= 30) & (ny_day.dt.minute < 45)
or_candles = day_df[or_mask]
print(f"\nOR candles ({len(or_candles)}):")
for _, c in or_candles.iterrows():
t = c["timestamp"].astimezone(NY)
print(f" {t.strftime('%H:%M')} O={c['open']:.2f} H={c['high']:.2f} "
f"L={c['low']:.2f} C={c['close']:.2f}")
# Compute OR
rng = get_opening_range(day_df, or_minutes=15)
assert rng is not None, "OR should not be None"
or_high, or_low = rng
print(f"\nOR: high={or_high:.2f} low={or_low:.2f} range={or_high - or_low:.2f}")
# Verify manually
assert or_high == float(or_candles["high"].max())
assert or_low == float(or_candles["low"].min())
print("✓ OR computation correct")
return day_df, or_high, or_low
def test_strategy_signals(day_df, or_high, or_low):
"""Test that run_day produces trades from cached data."""
cfg = load_config()
strat_cfg = list(cfg.symbols.values())[0] # BTC params from config.yaml
params = strat_cfg.to_params()
trades = run_day(day_df, params, or_minutes=strat_cfg.or_minutes)
print(f"\nStrategy trades ({len(trades)}):")
for t in trades:
entry_ny = t.entry_time.astimezone(NY) if t.entry_time else "?"
exit_ny = t.exit_time.astimezone(NY) if t.exit_time else "?"
risk = abs(t.entry - t.stop)
print(f" {t.direction} entry={t.entry:.2f} stop={t.stop:.2f} tp={t.tp:.2f} "
f"risk={risk:.2f} result={t.result} pnl_r={t.pnl_r:.1f}")
print(f" {entry_ny} → {exit_ny}")
print(f"✓ Strategy produced {len(trades)} trades")
return trades
def test_run_cycle_simulation():
"""Simulate run_cycle by feeding cached candles as if live."""
from executor import SessionState, _execute_entry, _execute_exit, _is_nyse_hours
cfg = load_config()
# Use test DB
if TEST_DB.exists():
TEST_DB.unlink()
conn = get_db(TEST_DB)
init_db(conn)
# Load cached day
df = pd.read_csv("cache/BTC_USDT_USDT_60d_5m.csv", parse_dates=["timestamp"])
df["timestamp"] = (df["timestamp"].dt.tz_localize("UTC")
if df["timestamp"].dt.tz is None else df["timestamp"])
ny = df["timestamp"].dt.tz_convert(NY)
test_date = date(2026, 1, 29)
day_df = df[ny.dt.date == test_date].reset_index(drop=True)
# Simulate incremental candle feed (as daemon would do every 5 min)
# Use first symbol's strategy config for test
test_symbol = list(cfg.symbols.keys())[0]
strat_cfg = cfg.symbols[test_symbol]
params = strat_cfg.to_params()
from state import save_session, update_equity, set_state_val
# Init equity (capital=0 means auto-fetch, use 1000 for test)
capital = cfg.capital if cfg.capital > 0 else 1000.0
update_equity(conn, capital)
set_state_val(conn, "peak_equity", capital)
ny_times = day_df["timestamp"].dt.tz_convert(NY)
# Filter from 9:30 to 16:00 — matches real executor (fetches from 9:30)
nyse_mask = (
((ny_times.dt.hour == 9) & (ny_times.dt.minute >= 30)) |
((ny_times.dt.hour >= 10) & (ny_times.dt.hour < 16))
)
nyse_df = day_df[nyse_mask].reset_index(drop=True)
print(f"\n{'='*60}")
print(f"Simulating run_cycle incrementally ({len(nyse_df)} NYSE candles)")
print(f"{'='*60}")
or_computed = False
opened_keys = set() # currently active
seen_keys = set() # all ever seen (matches _session.last_trade_ids)
cycle_count = 0
# Simulate every 5 min (every candle)
for i in range(1, len(nyse_df) + 1):
partial = nyse_df.iloc[:i].reset_index(drop=True)
now_ny = partial.iloc[-1]["timestamp"].astimezone(NY)
# Skip pre-market
if now_ny.hour == 9 and now_ny.minute < 30:
continue
cycle_count += 1
# Run strategy on partial data
trades = run_day(partial, params, strat_cfg.or_minutes)
# Check OR
tf_minutes = 5
or_candles_needed = max(1, strat_cfg.or_minutes // tf_minutes)
if not or_computed and i >= or_candles_needed:
rng = get_opening_range(partial, strat_cfg.or_minutes)
if rng:
or_h, or_l = rng
or_computed = True
save_session(conn, test_date, or_h, or_l, test_symbol)
print(f" [{now_ny.strftime('%H:%M')}] OR computed: "
f"high={or_h:.2f} low={or_l:.2f}")
# Check for new/closed trades (matches executor reconciliation)
for t in trades:
key = f"{t.direction}_{t.entry:.2f}_{t.stop:.2f}"
if key in opened_keys:
# Already known — check if now closed
if t.exit_price > 0:
print(f" [{now_ny.strftime('%H:%M')}] EXIT {t.direction.upper()} "
f"@ ${t.exit_price:,.2f} ({t.result})")
opened_keys.discard(key)
continue
if key in seen_keys:
continue # Already processed (flash trade or closed)
# New trade
risk = abs(t.entry - t.stop)
if risk <= 0:
continue
equity = get_equity(conn)
risk_dollar = equity * cfg.risk.per_trade
pos_size = risk_dollar / risk
pos_value = pos_size * t.entry
max_pos = equity * cfg.risk.leverage
if pos_value > max_pos:
pos_size = max_pos / t.entry
pos_value = max_pos
print(f" [{now_ny.strftime('%H:%M')}] ENTRY {t.direction.upper()} "
f"@ ${t.entry:,.2f} SL=${t.stop:,.2f} TP=${t.tp:,.2f} "
f"size={pos_size:.6f} (${pos_value:,.2f})")
opened_keys.add(key)
seen_keys.add(key)
# Flash trade: entered and exited in same cycle
if t.exit_price > 0:
if t.direction == "long":
gross = pos_size * (t.exit_price - t.entry)
else:
gross = pos_size * (t.entry - t.exit_price)
commission = pos_value * (cfg.risk.maker_fee + cfg.risk.taker_fee)
pnl = gross - commission
print(f" [{now_ny.strftime('%H:%M')}] EXIT {t.direction.upper()} "
f"@ ${t.exit_price:,.2f} ({t.result}) PnL ${pnl:+,.2f} [flash]")
opened_keys.discard(key)
# Verify session was saved
saved = get_session(conn, test_date, test_symbol)
assert saved is not None, "Session should be saved"
print(f"\nDB session: OR {saved['or_high']:.2f}/{saved['or_low']:.2f}")
print(f"Cycles simulated: {cycle_count}")
print(f"✓ Simulation complete")
conn.close()
TEST_DB.unlink(missing_ok=True)
if __name__ == "__main__":
day_df, or_high, or_low = test_or_computation()
trades = test_strategy_signals(day_df, or_high, or_low)
test_run_cycle_simulation()