Files
scalp-bot/cli.py
T
anorandClaude Opus 4.6 4c90345585 feat: live execution — replay approach для ORB+FVG+Engulfing
config.yaml + config.py: конфигурация с YAML + env var overrides
state.py: SQLite state (equity, sessions, positions, orders)
exchange.py: Bybit linear futures executor (dry-run + live)
executor.py: торговый цикл — fetch candles → run_day() → reconcile
cli.py: Click CLI (run, status, history, daemon с APScheduler 5m)
notify.py: Telegram alerts (entry, exit, OR)

Существующие backtest-скрипты не затронуты.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 16:56:45 +10:00

153 lines
4.1 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
click.echo(f"Running cycle ({cfg.mode} mode, {cfg.symbol})...")
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}")
click.echo(f" SCALP-BOT — {cfg.mode.upper()} | {cfg.symbol}")
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:
click.echo(f" {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} {'Dir':>6s} {'Entry':>10s} {'Exit':>10s} "
f"{'PnL':>10s} {'Reason':>6s}")
click.echo(f" {'─' * 58}")
for t in reversed(trades):
pnl = t["pnl_net"] or 0
click.echo(f" {t['date']:<12s} {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()
click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {cfg.symbol})")
click.echo(f"Strategy: RR={cfg.strategy.rr_ratio} OR={cfg.strategy.or_minutes}m "
f"max_trades={cfg.strategy.max_trades}")
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()