fix: max_trades=99, leverage per symbol, crash recovery, test_live.py
- max_trades=99 в config/backtest — стратегия находит ВСЕ входы, лимит позиций контролирует executor (Phase 2) - leverage setup per symbol (set[str] вместо bool) - crash recovery: get_today_trade_keys() восстанавливает last_trade_ids - flash trade exit по new_positions[-1] (slippage-safe) - last_trade_ids.add() только в Phase 2 для исполненных трейдов - test_live.py: cfg.strategy → per-symbol strat_cfg - backtest_wf: risk 5%, max_trades=[99] - cli daemon: per-symbol params display Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+2
-2
@@ -23,7 +23,7 @@ NY = ZoneInfo("America/New_York")
|
|||||||
|
|
||||||
# ── Config ───────────────────────────────────────────────────────────
|
# ── Config ───────────────────────────────────────────────────────────
|
||||||
INITIAL_CAPITAL = 1_000.0
|
INITIAL_CAPITAL = 1_000.0
|
||||||
RISK_PCT = 0.02 # 2% risk per trade
|
RISK_PCT = 0.05 # 5% risk per trade
|
||||||
TAKER_FEE = 0.00055 # Bybit linear futures taker fee (0.055%)
|
TAKER_FEE = 0.00055 # Bybit linear futures taker fee (0.055%)
|
||||||
LEVERAGE = 10 # max leverage (caps position value)
|
LEVERAGE = 10 # max leverage (caps position value)
|
||||||
TRAIN_RATIO = 0.5 # first 50% days = in-sample
|
TRAIN_RATIO = 0.5 # first 50% days = in-sample
|
||||||
@@ -32,7 +32,7 @@ OR_MINUTES = 15 # opening range duration (3 x 5m candles)
|
|||||||
|
|
||||||
GRID = {
|
GRID = {
|
||||||
"rr_ratio": [2.0, 2.5, 3.0],
|
"rr_ratio": [2.0, 2.5, 3.0],
|
||||||
"max_trades": [1, 2, 3],
|
"max_trades": [99],
|
||||||
"min_range_pct": [0.0, 0.1, 0.2],
|
"min_range_pct": [0.0, 0.1, 0.2],
|
||||||
"min_fvg_pct": [0.0, 0.02, 0.05],
|
"min_fvg_pct": [0.0, 0.02, 0.05],
|
||||||
"first_fvg_only": [False, True],
|
"first_fvg_only": [False, True],
|
||||||
|
|||||||
@@ -98,13 +98,14 @@ def history(limit):
|
|||||||
return
|
return
|
||||||
|
|
||||||
click.echo()
|
click.echo()
|
||||||
click.echo(f" {'Date':<12s} {'Dir':>6s} {'Entry':>10s} {'Exit':>10s} "
|
click.echo(f" {'Date':<12s} {'Sym':>4s} {'Dir':>6s} {'Entry':>10s} {'Exit':>10s} "
|
||||||
f"{'PnL':>10s} {'Reason':>6s}")
|
f"{'PnL':>10s} {'Reason':>6s}")
|
||||||
click.echo(f" {'─' * 58}")
|
click.echo(f" {'─' * 62}")
|
||||||
|
|
||||||
for t in reversed(trades):
|
for t in reversed(trades):
|
||||||
pnl = t["pnl_net"] or 0
|
pnl = t["pnl_net"] or 0
|
||||||
click.echo(f" {t['date']:<12s} {t['direction'].upper():>6s} "
|
tag = (t.get("symbol") or "").split("/")[0] or "?"
|
||||||
|
click.echo(f" {t['date']:<12s} {tag:>4s} {t['direction'].upper():>6s} "
|
||||||
f"${t['entry_price']:>9,.2f} ${(t['exit_price'] or 0):>9,.2f} "
|
f"${t['entry_price']:>9,.2f} ${(t['exit_price'] or 0):>9,.2f} "
|
||||||
f"${pnl:>+9,.2f} {(t['exit_reason'] or ''):>6s}")
|
f"${pnl:>+9,.2f} {(t['exit_reason'] or ''):>6s}")
|
||||||
|
|
||||||
@@ -122,8 +123,10 @@ def daemon():
|
|||||||
|
|
||||||
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
|
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
|
||||||
click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {symbols})")
|
click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {symbols})")
|
||||||
click.echo(f"Strategy: RR={cfg.strategy.rr_ratio} OR={cfg.strategy.or_minutes}m "
|
for sym, sc in cfg.symbols.items():
|
||||||
f"max_trades={cfg.strategy.max_trades}")
|
tag = sym.split("/")[0]
|
||||||
|
click.echo(f" {tag}: RR={sc.rr_ratio} OR={sc.or_minutes}m max={sc.max_trades} "
|
||||||
|
f"fvg_exp={sc.fvg_expiry} fvg_only={sc.first_fvg_only}")
|
||||||
click.echo(f"Risk: {cfg.risk.per_trade*100:.0f}% per trade, {cfg.risk.leverage}x leverage")
|
click.echo(f"Risk: {cfg.risk.per_trade*100:.0f}% per trade, {cfg.risk.leverage}x leverage")
|
||||||
|
|
||||||
def scheduled_cycle():
|
def scheduled_cycle():
|
||||||
|
|||||||
+4
-4
@@ -6,14 +6,14 @@ timeframe: "5m"
|
|||||||
symbols:
|
symbols:
|
||||||
BTC/USDT:USDT:
|
BTC/USDT:USDT:
|
||||||
rr_ratio: 3.0
|
rr_ratio: 3.0
|
||||||
max_trades: 1
|
max_trades: 99
|
||||||
fvg_expiry: 6
|
fvg_expiry: 6
|
||||||
or_minutes: 15
|
or_minutes: 15
|
||||||
session_end_h: 11
|
session_end_h: 11
|
||||||
|
|
||||||
ETH/USDT:USDT:
|
ETH/USDT:USDT:
|
||||||
rr_ratio: 3.0
|
rr_ratio: 3.0
|
||||||
max_trades: 1
|
max_trades: 99
|
||||||
fvg_expiry: 6
|
fvg_expiry: 6
|
||||||
or_minutes: 15
|
or_minutes: 15
|
||||||
session_end_h: 11
|
session_end_h: 11
|
||||||
@@ -21,7 +21,7 @@ symbols:
|
|||||||
|
|
||||||
SOL/USDT:USDT:
|
SOL/USDT:USDT:
|
||||||
rr_ratio: 3.0
|
rr_ratio: 3.0
|
||||||
max_trades: 1
|
max_trades: 99
|
||||||
fvg_expiry: 12
|
fvg_expiry: 12
|
||||||
or_minutes: 15
|
or_minutes: 15
|
||||||
session_end_h: 11
|
session_end_h: 11
|
||||||
@@ -30,7 +30,7 @@ symbols:
|
|||||||
first_fvg_only: true
|
first_fvg_only: true
|
||||||
|
|
||||||
risk:
|
risk:
|
||||||
per_trade: 0.02
|
per_trade: 0.05
|
||||||
leverage: 10
|
leverage: 10
|
||||||
taker_fee: 0.00055
|
taker_fee: 0.00055
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -31,7 +31,7 @@ class FuturesExecutor:
|
|||||||
self.dry_run = not exchange_cfg.api_key
|
self.dry_run = not exchange_cfg.api_key
|
||||||
self.leverage = leverage
|
self.leverage = leverage
|
||||||
self._markets_loaded = False
|
self._markets_loaded = False
|
||||||
self._leverage_set = False
|
self._leverage_set: set[str] = set()
|
||||||
|
|
||||||
if self.dry_run:
|
if self.dry_run:
|
||||||
log.info("FuturesExecutor: DRY RUN mode (no API key)")
|
log.info("FuturesExecutor: DRY RUN mode (no API key)")
|
||||||
@@ -45,7 +45,7 @@ class FuturesExecutor:
|
|||||||
|
|
||||||
def setup(self, symbol: str) -> None:
|
def setup(self, symbol: str) -> None:
|
||||||
"""Set leverage and position mode (call once per symbol)."""
|
"""Set leverage and position mode (call once per symbol)."""
|
||||||
if self._leverage_set or self.dry_run:
|
if symbol in self._leverage_set or self.dry_run:
|
||||||
return
|
return
|
||||||
self._ensure_markets()
|
self._ensure_markets()
|
||||||
try:
|
try:
|
||||||
@@ -53,7 +53,7 @@ class FuturesExecutor:
|
|||||||
log.info(f"Leverage set to {self.leverage}x for {symbol}")
|
log.info(f"Leverage set to {self.leverage}x for {symbol}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning(f"Set leverage failed (may already be set): {e}")
|
log.warning(f"Set leverage failed (may already be set): {e}")
|
||||||
self._leverage_set = True
|
self._leverage_set.add(symbol)
|
||||||
|
|
||||||
def get_balance(self) -> float:
|
def get_balance(self) -> float:
|
||||||
"""Get free USDT balance."""
|
"""Get free USDT balance."""
|
||||||
|
|||||||
+10
-10
@@ -23,8 +23,8 @@ from exchange import FuturesExecutor
|
|||||||
from notify import notify_entry, notify_exit, notify_or
|
from notify import notify_entry, notify_exit, notify_or
|
||||||
from state import (
|
from state import (
|
||||||
close_position, get_equity, get_open_positions, get_session,
|
close_position, get_equity, get_open_positions, get_session,
|
||||||
get_state_val, log_order, open_position, save_session,
|
get_state_val, get_today_trade_keys, log_order, open_position,
|
||||||
set_state_val, update_equity,
|
save_session, set_state_val, update_equity,
|
||||||
)
|
)
|
||||||
from strategy import Trade, run_day
|
from strategy import Trade, run_day
|
||||||
|
|
||||||
@@ -150,17 +150,15 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
|||||||
key = _trade_key(best_trade)
|
key = _trade_key(best_trade)
|
||||||
|
|
||||||
if best_trade.exit_price > 0:
|
if best_trade.exit_price > 0:
|
||||||
# Flash trade
|
# Flash trade — entry + exit in same cycle
|
||||||
_execute_entry(conn, cfg, best_trade, best_symbol,
|
_execute_entry(conn, cfg, best_trade, best_symbol,
|
||||||
get_equity(conn), logs)
|
get_equity(conn), logs)
|
||||||
sess.last_trade_ids.add(key)
|
sess.last_trade_ids.add(key)
|
||||||
|
# Find the just-opened position (last open for this symbol)
|
||||||
new_positions = get_open_positions(conn, best_symbol)
|
new_positions = get_open_positions(conn, best_symbol)
|
||||||
for pos in new_positions:
|
if new_positions:
|
||||||
pos_key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}"
|
_execute_exit(conn, cfg, new_positions[-1], best_symbol,
|
||||||
if pos_key == key:
|
best_trade.exit_price, best_trade.result, logs)
|
||||||
_execute_exit(conn, cfg, pos, best_symbol,
|
|
||||||
best_trade.exit_price, best_trade.result, logs)
|
|
||||||
break
|
|
||||||
else:
|
else:
|
||||||
_execute_entry(conn, cfg, best_trade, best_symbol,
|
_execute_entry(conn, cfg, best_trade, best_symbol,
|
||||||
get_equity(conn), logs)
|
get_equity(conn), logs)
|
||||||
@@ -182,7 +180,7 @@ def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str,
|
|||||||
candidates: list[tuple[str, Trade]] = []
|
candidates: list[tuple[str, Trade]] = []
|
||||||
sess = _get_session(symbol)
|
sess = _get_session(symbol)
|
||||||
|
|
||||||
# Try restore OR from DB on first cycle
|
# Try restore state from DB on first cycle (crash recovery)
|
||||||
if not sess.or_computed:
|
if not sess.or_computed:
|
||||||
saved = get_session(conn, today, symbol)
|
saved = get_session(conn, today, symbol)
|
||||||
if saved:
|
if saved:
|
||||||
@@ -190,6 +188,8 @@ def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str,
|
|||||||
sess.or_low = saved["or_low"]
|
sess.or_low = saved["or_low"]
|
||||||
sess.or_computed = True
|
sess.or_computed = True
|
||||||
logs.append(f"Session restored: OR {sess.or_high:.2f}/{sess.or_low:.2f}")
|
logs.append(f"Session restored: OR {sess.or_high:.2f}/{sess.or_low:.2f}")
|
||||||
|
# Restore trade keys to prevent duplicates after restart
|
||||||
|
sess.last_trade_ids = get_today_trade_keys(conn, today, symbol)
|
||||||
|
|
||||||
# Fetch 5m candles from 9:30 NY to now
|
# Fetch 5m candles from 9:30 NY to now
|
||||||
futures = _get_futures(cfg)
|
futures = _get_futures(cfg)
|
||||||
|
|||||||
@@ -179,6 +179,17 @@ def get_today_trade_count(conn: sqlite3.Connection, dt: date) -> int:
|
|||||||
return row["cnt"] if row else 0
|
return row["cnt"] if row else 0
|
||||||
|
|
||||||
|
|
||||||
|
def get_today_trade_keys(conn: sqlite3.Connection, dt: date,
|
||||||
|
symbol: str) -> set[str]:
|
||||||
|
"""Get trade keys for today's positions (for crash recovery)."""
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT direction, entry_price, stop_price FROM positions "
|
||||||
|
"WHERE date=? AND symbol=?", (str(dt), symbol)
|
||||||
|
).fetchall()
|
||||||
|
return {f"{r['direction']}_{r['entry_price']:.2f}_{r['stop_price']:.2f}"
|
||||||
|
for r in rows}
|
||||||
|
|
||||||
|
|
||||||
def get_trade_history(conn: sqlite3.Connection, limit: int = 50) -> list[dict]:
|
def get_trade_history(conn: sqlite3.Connection, limit: int = 50) -> list[dict]:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"SELECT * FROM positions WHERE status='closed' ORDER BY id DESC LIMIT ?",
|
"SELECT * FROM positions WHERE status='closed' ORDER BY id DESC LIMIT ?",
|
||||||
|
|||||||
+18
-12
@@ -60,8 +60,10 @@ def test_or_computation():
|
|||||||
|
|
||||||
def test_strategy_signals(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."""
|
"""Test that run_day produces trades from cached data."""
|
||||||
params = Params(rr_ratio=2.5, max_trades=2, fvg_expiry=12, session_end_h=11)
|
cfg = load_config()
|
||||||
trades = run_day(day_df, params, or_minutes=15)
|
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)}):")
|
print(f"\nStrategy trades ({len(trades)}):")
|
||||||
for t in trades:
|
for t in trades:
|
||||||
@@ -78,7 +80,7 @@ def test_strategy_signals(day_df, or_high, or_low):
|
|||||||
|
|
||||||
def test_run_cycle_simulation():
|
def test_run_cycle_simulation():
|
||||||
"""Simulate run_cycle by feeding cached candles as if live."""
|
"""Simulate run_cycle by feeding cached candles as if live."""
|
||||||
from executor import SessionState, _execute_entry, _execute_exit, _is_nyse_hours, _session
|
from executor import SessionState, _execute_entry, _execute_exit, _is_nyse_hours
|
||||||
|
|
||||||
cfg = load_config()
|
cfg = load_config()
|
||||||
|
|
||||||
@@ -97,12 +99,16 @@ def test_run_cycle_simulation():
|
|||||||
day_df = df[ny.dt.date == test_date].reset_index(drop=True)
|
day_df = df[ny.dt.date == test_date].reset_index(drop=True)
|
||||||
|
|
||||||
# Simulate incremental candle feed (as daemon would do every 5 min)
|
# Simulate incremental candle feed (as daemon would do every 5 min)
|
||||||
params = cfg.strategy.to_params()
|
# 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
|
from state import save_session, update_equity, set_state_val
|
||||||
|
|
||||||
# Init equity
|
# Init equity (capital=0 means auto-fetch, use 1000 for test)
|
||||||
update_equity(conn, cfg.capital)
|
capital = cfg.capital if cfg.capital > 0 else 1000.0
|
||||||
set_state_val(conn, "peak_equity", cfg.capital)
|
update_equity(conn, capital)
|
||||||
|
set_state_val(conn, "peak_equity", capital)
|
||||||
|
|
||||||
ny_times = day_df["timestamp"].dt.tz_convert(NY)
|
ny_times = day_df["timestamp"].dt.tz_convert(NY)
|
||||||
# Filter from 9:30 to 16:00 — matches real executor (fetches from 9:30)
|
# Filter from 9:30 to 16:00 — matches real executor (fetches from 9:30)
|
||||||
@@ -133,17 +139,17 @@ def test_run_cycle_simulation():
|
|||||||
cycle_count += 1
|
cycle_count += 1
|
||||||
|
|
||||||
# Run strategy on partial data
|
# Run strategy on partial data
|
||||||
trades = run_day(partial, params, cfg.strategy.or_minutes)
|
trades = run_day(partial, params, strat_cfg.or_minutes)
|
||||||
|
|
||||||
# Check OR
|
# Check OR
|
||||||
tf_minutes = 5
|
tf_minutes = 5
|
||||||
or_candles_needed = max(1, cfg.strategy.or_minutes // tf_minutes)
|
or_candles_needed = max(1, strat_cfg.or_minutes // tf_minutes)
|
||||||
if not or_computed and i >= or_candles_needed:
|
if not or_computed and i >= or_candles_needed:
|
||||||
rng = get_opening_range(partial, cfg.strategy.or_minutes)
|
rng = get_opening_range(partial, strat_cfg.or_minutes)
|
||||||
if rng:
|
if rng:
|
||||||
or_h, or_l = rng
|
or_h, or_l = rng
|
||||||
or_computed = True
|
or_computed = True
|
||||||
save_session(conn, test_date, or_h, or_l)
|
save_session(conn, test_date, or_h, or_l, test_symbol)
|
||||||
print(f" [{now_ny.strftime('%H:%M')}] OR computed: "
|
print(f" [{now_ny.strftime('%H:%M')}] OR computed: "
|
||||||
f"high={or_h:.2f} low={or_l:.2f}")
|
f"high={or_h:.2f} low={or_l:.2f}")
|
||||||
|
|
||||||
@@ -192,7 +198,7 @@ def test_run_cycle_simulation():
|
|||||||
opened_keys.discard(key)
|
opened_keys.discard(key)
|
||||||
|
|
||||||
# Verify session was saved
|
# Verify session was saved
|
||||||
saved = get_session(conn, test_date)
|
saved = get_session(conn, test_date, test_symbol)
|
||||||
assert saved is not None, "Session should be saved"
|
assert saved is not None, "Session should be saved"
|
||||||
print(f"\nDB session: OR {saved['or_high']:.2f}/{saved['or_low']:.2f}")
|
print(f"\nDB session: OR {saved['or_high']:.2f}/{saved['or_low']:.2f}")
|
||||||
print(f"Cycles simulated: {cycle_count}")
|
print(f"Cycles simulated: {cycle_count}")
|
||||||
|
|||||||
Reference in New Issue
Block a user