Files
scalp-bot/cli.py
T
anorandClaude Opus 4.6 650ab61168 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>
2026-03-13 18:46:28 +10:00

160 lines
4.6 KiB
Python

"""CLI interface — scalp-bot command."""
from __future__ import annotations
import logging
import signal
import sys
import click
from config import load_config
from state import get_db, get_equity, get_open_positions, get_trade_history, init_db
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
datefmt="%H:%M:%S",
)
@click.group()
def main():
"""scalp-bot — ORB+FVG+Engulfing futures scalper."""
pass
@main.command()
def run():
"""Run one trading cycle."""
cfg = load_config()
conn = get_db()
init_db(conn)
from executor import run_cycle
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
click.echo(f"Running cycle ({cfg.mode} mode, {symbols})...")
logs = run_cycle(conn, cfg)
for msg in logs:
click.echo(f" {msg}")
conn.close()
click.echo("Done.")
@main.command()
def status():
"""Show current equity and positions."""
cfg = load_config()
conn = get_db()
init_db(conn)
equity = get_equity(conn)
if equity <= 0:
click.echo("Not initialized. Run: python cli.py run")
return
from state import get_state_val
peak = get_state_val(conn, "peak_equity")
trades = int(get_state_val(conn, "trades_count"))
wins = int(get_state_val(conn, "wins"))
total_pnl = get_state_val(conn, "total_pnl")
wr = wins / trades * 100 if trades > 0 else 0
click.echo()
click.echo(f"{'=' * 50}")
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
click.echo(f" SCALP-BOT — {cfg.mode.upper()} | {symbols}")
click.echo(f"{'=' * 50}")
click.echo(f" Equity: ${equity:,.2f} (peak ${peak:,.2f})")
click.echo(f" PnL: ${total_pnl:+,.2f}")
click.echo(f" Trades: {trades} | Wins: {wins} | WR: {wr:.0f}%")
positions = get_open_positions(conn)
if positions:
click.echo(f"\n Open Positions:")
for p in positions:
tag = (p.get('symbol') or '').split("/")[0] or "?"
click.echo(f" {tag} {p['direction'].upper()} @ ${p['entry_price']:,.2f} "
f"SL=${p['stop_price']:,.2f} TP=${p['tp_price']:,.2f} "
f"size={p['pos_size']:.4f}")
else:
click.echo(f"\n No open positions")
click.echo(f"{'=' * 50}")
conn.close()
@main.command()
@click.option("--limit", "-n", default=20, help="Number of trades to show")
def history(limit):
"""Show trade history."""
conn = get_db()
init_db(conn)
trades = get_trade_history(conn, limit=limit)
if not trades:
click.echo("No trades yet.")
return
click.echo()
click.echo(f" {'Date':<12s} {'Sym':>4s} {'Dir':>6s} {'Entry':>10s} {'Exit':>10s} "
f"{'PnL':>10s} {'Reason':>6s}")
click.echo(f" {'─' * 62}")
for t in reversed(trades):
pnl = t["pnl_net"] or 0
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"${pnl:>+9,.2f} {(t['exit_reason'] or ''):>6s}")
conn.close()
@main.command()
def daemon():
"""Run as daemon — auto-cycle every 5 minutes during NYSE hours."""
from apscheduler.schedulers.blocking import BlockingScheduler
from executor import run_cycle
cfg = load_config()
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {symbols})")
for sym, sc in cfg.symbols.items():
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")
def scheduled_cycle():
conn = get_db()
init_db(conn)
logs = run_cycle(conn, cfg)
conn.close()
for msg in logs:
click.echo(f" {msg}")
scheduler = BlockingScheduler()
scheduler.add_job(
scheduled_cycle, "interval", minutes=5,
next_run_time=__import__("datetime").datetime.now(),
)
def shutdown(signum, frame):
click.echo("\nShutting down...")
scheduler.shutdown(wait=False)
sys.exit(0)
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)
click.echo("Scheduler started (every 5 min). Ctrl+C to stop.")
scheduler.start()
if __name__ == "__main__":
main()