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>
This commit is contained in:
anor
2026-03-13 16:56:45 +10:00
co-authored by Claude Opus 4.6
parent af9c763923
commit 4c90345585
9 changed files with 1134 additions and 0 deletions
+1
View File
@@ -1,3 +1,4 @@
cache/
data/
__pycache__/
.venv/
+152
View File
@@ -0,0 +1,152 @@
"""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()
+106
View File
@@ -0,0 +1,106 @@
"""Configuration loader — single source of truth for scalp-bot."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
import yaml
from strategy import Params
CONFIG_PATH = Path(__file__).parent / "config.yaml"
@dataclass
class StrategyConfig:
rr_ratio: float = 2.5
max_trades: int = 2
fvg_expiry: int = 12
or_minutes: int = 15
session_end_h: int = 11
session_end_m: int = 0
min_range_pct: float = 0.0
min_fvg_pct: float = 0.0
min_risk_pct: float = 0.0
first_fvg_only: bool = False
def to_params(self) -> Params:
"""Convert to strategy.Params (excludes or_minutes)."""
return Params(
rr_ratio=self.rr_ratio,
max_trades=self.max_trades,
fvg_expiry=self.fvg_expiry,
session_end_h=self.session_end_h,
session_end_m=self.session_end_m,
min_range_pct=self.min_range_pct,
min_fvg_pct=self.min_fvg_pct,
min_risk_pct=self.min_risk_pct,
first_fvg_only=self.first_fvg_only,
)
@dataclass
class RiskConfig:
per_trade: float = 0.02
leverage: int = 10
taker_fee: float = 0.00055
@dataclass
class ExchangeConfig:
api_key: str = ""
api_secret: str = ""
@dataclass
class TelegramConfig:
enabled: bool = False
bot_token: str = ""
chat_id: str = ""
@dataclass
class Config:
mode: str = "paper"
capital: float = 1000.0
symbol: str = "BTC/USDT:USDT"
timeframe: str = "5m"
strategy: StrategyConfig = field(default_factory=StrategyConfig)
risk: RiskConfig = field(default_factory=RiskConfig)
exchange: ExchangeConfig = field(default_factory=ExchangeConfig)
telegram: TelegramConfig = field(default_factory=TelegramConfig)
def load_config(path: Path | None = None) -> Config:
"""Load configuration from YAML + env var overrides."""
path = path or CONFIG_PATH
if not path.exists():
return Config()
with open(path) as f:
raw = yaml.safe_load(f) or {}
strat_raw = raw.get("strategy", {})
risk_raw = raw.get("risk", {})
exchange_raw = raw.get("exchange", {})
tg_raw = raw.get("telegram", {})
exchange = ExchangeConfig(**exchange_raw)
exchange.api_key = os.environ.get("SCALP_API_KEY", exchange.api_key)
exchange.api_secret = os.environ.get("SCALP_API_SECRET", exchange.api_secret)
telegram = TelegramConfig(**tg_raw)
telegram.bot_token = os.environ.get("SCALP_TG_TOKEN", telegram.bot_token)
return Config(
mode=raw.get("mode", "paper"),
capital=raw.get("capital", 1000.0),
symbol=raw.get("symbol", "BTC/USDT:USDT"),
timeframe=raw.get("timeframe", "5m"),
strategy=StrategyConfig(**strat_raw),
risk=RiskConfig(**risk_raw),
exchange=exchange,
telegram=telegram,
)
+25
View File
@@ -0,0 +1,25 @@
mode: paper # paper | live
capital: 1000.0
symbol: "BTC/USDT:USDT"
timeframe: "5m"
strategy:
rr_ratio: 2.5
max_trades: 2
fvg_expiry: 12
or_minutes: 15
session_end_h: 11
risk:
per_trade: 0.02
leverage: 10
taker_fee: 0.00055
exchange:
api_key: "" # env: SCALP_API_KEY
api_secret: "" # env: SCALP_API_SECRET
telegram:
enabled: false
bot_token: "" # env: SCALP_TG_TOKEN
chat_id: ""
+252
View File
@@ -0,0 +1,252 @@
"""Bybit linear futures executor via ccxt.
Safety-first: balance checks, min order validation, dry-run mode,
no retries on failure.
"""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from config import ExchangeConfig
log = logging.getLogger(__name__)
class FuturesExecutor:
"""Execute linear futures trades on Bybit."""
def __init__(self, exchange_cfg: ExchangeConfig, leverage: int = 10):
import ccxt
self.exchange = ccxt.bybit({
"apiKey": exchange_cfg.api_key,
"secret": exchange_cfg.api_secret,
"enableRateLimit": True,
"options": {
"defaultType": "linear",
"recvWindow": 30000,
},
})
self.dry_run = not exchange_cfg.api_key
self.leverage = leverage
self._markets_loaded = False
self._leverage_set = False
if self.dry_run:
log.info("FuturesExecutor: DRY RUN mode (no API key)")
else:
log.info(f"FuturesExecutor: LIVE mode (leverage={leverage}x)")
def _ensure_markets(self):
if not self._markets_loaded:
self.exchange.load_markets()
self._markets_loaded = True
def setup(self, symbol: str) -> None:
"""Set leverage and position mode (call once per symbol)."""
if self._leverage_set or self.dry_run:
return
self._ensure_markets()
try:
self.exchange.set_leverage(self.leverage, symbol)
log.info(f"Leverage set to {self.leverage}x for {symbol}")
except Exception as e:
log.warning(f"Set leverage failed (may already be set): {e}")
self._leverage_set = True
def get_balance(self) -> float:
"""Get free USDT balance."""
try:
b = self.exchange.fetch_balance()
return float(b.get("USDT", {}).get("free", 0) or 0)
except Exception as e:
log.error(f"Balance fetch failed: {e}")
return 0.0
def get_price(self, symbol: str) -> float | None:
"""Get current market price."""
try:
ticker = self.exchange.fetch_ticker(symbol)
return float(ticker["last"])
except Exception as e:
log.error(f"Price fetch {symbol} failed: {e}")
return None
def get_position(self, symbol: str) -> dict | None:
"""Get current exchange position for reconciliation."""
if self.dry_run:
return None
try:
positions = self.exchange.fetch_positions([symbol])
for p in positions:
qty = float(p.get("contracts") or 0)
if qty > 0:
return {
"side": p["side"],
"qty": qty,
"entry_price": float(p.get("entryPrice") or 0),
"unrealized_pnl": float(p.get("unrealizedPnl") or 0),
}
return None
except Exception as e:
log.error(f"Position fetch {symbol} failed: {e}")
return None
def open_long(self, symbol: str, usdt_amount: float) -> dict | None:
"""Market long (buy). Returns order dict or None."""
return self._open(symbol, usdt_amount, "buy")
def open_short(self, symbol: str, usdt_amount: float) -> dict | None:
"""Market short (sell). Returns order dict or None."""
return self._open(symbol, usdt_amount, "sell")
def _open(self, symbol: str, usdt_amount: float, side: str) -> dict | None:
self._ensure_markets()
self.setup(symbol)
price = self.get_price(symbol)
if price is None:
return None
market = self.exchange.market(symbol)
amount = usdt_amount / price
amount = float(self.exchange.amount_to_precision(symbol, amount))
min_amount = float(market["limits"]["amount"]["min"] or 0)
if amount < min_amount:
log.error(f"{side.upper()} {symbol}: amount {amount} < min {min_amount}")
return None
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
log.info(f"[DRY RUN] {side.upper()} {amount} {symbol} @ ~${price:,.2f} "
f"(${usdt_amount:.2f}) at {ts}")
return {"dry_run": True, "side": side, "symbol": symbol,
"amount": amount, "price": price, "cost": usdt_amount}
try:
order = self.exchange.create_order(symbol, "market", side, amount)
order = self._fetch_order_details(order, symbol)
filled = float(order.get("filled") or amount)
avg_price = float(order.get("average") or price)
log.info(f"{side.upper()} OK: {filled} {symbol} @ ${avg_price:,.2f} "
f"order={order.get('id')}")
return order
except Exception as e:
log.error(f"{side.upper()} {symbol} FAILED: {e}")
return None
def close_position(self, symbol: str, side: str, qty: float) -> dict | None:
"""Close position with reduceOnly order."""
close_side = "sell" if side == "buy" else "buy"
if self.dry_run:
price = self.get_price(symbol) or 0
log.info(f"[DRY RUN] CLOSE {close_side} {qty} {symbol} @ ~${price:,.2f}")
return {"dry_run": True, "side": close_side, "symbol": symbol,
"amount": qty, "price": price, "cost": qty * price}
try:
order = self.exchange.create_order(
symbol, "market", close_side, qty,
params={"reduceOnly": True},
)
order = self._fetch_order_details(order, symbol)
log.info(f"CLOSE OK: {close_side} {qty} {symbol} order={order.get('id')}")
return order
except Exception as e:
log.error(f"CLOSE {symbol} FAILED: {e}")
return None
def place_sl_tp(self, symbol: str, side: str, qty: float,
sl_price: float, tp_price: float) -> tuple[dict | None, dict | None]:
"""Place SL and TP conditional orders. Returns (sl_order, tp_order)."""
close_side = "sell" if side == "buy" else "buy"
sl_price = float(self.exchange.price_to_precision(symbol, sl_price))
tp_price = float(self.exchange.price_to_precision(symbol, tp_price))
if self.dry_run:
log.info(f"[DRY RUN] SL {close_side} {qty} {symbol} @ ${sl_price:,.2f}")
log.info(f"[DRY RUN] TP {close_side} {qty} {symbol} @ ${tp_price:,.2f}")
sl = {"dry_run": True, "id": "sl_dry", "stopPrice": sl_price}
tp = {"dry_run": True, "id": "tp_dry", "stopPrice": tp_price}
return sl, tp
sl_order = tp_order = None
try:
sl_order = self.exchange.create_order(
symbol, "market", close_side, qty,
params={
"triggerPrice": str(sl_price),
"reduceOnly": True,
"triggerDirection": 2 if side == "buy" else 1,
},
)
log.info(f"SL placed: {symbol} @ ${sl_price:,.2f} id={sl_order.get('id')}")
except Exception as e:
log.error(f"SL {symbol} FAILED: {e}")
try:
tp_order = self.exchange.create_order(
symbol, "market", close_side, qty,
params={
"triggerPrice": str(tp_price),
"reduceOnly": True,
"triggerDirection": 1 if side == "buy" else 2,
},
)
log.info(f"TP placed: {symbol} @ ${tp_price:,.2f} id={tp_order.get('id')}")
except Exception as e:
log.error(f"TP {symbol} FAILED: {e}")
return sl_order, tp_order
def cancel_orders(self, symbol: str, *order_ids: str) -> None:
"""Cancel conditional orders (SL/TP on position close)."""
for oid in order_ids:
if not oid:
continue
if self.dry_run:
log.info(f"[DRY RUN] CANCEL order {oid} on {symbol}")
continue
try:
self.exchange.cancel_order(oid, symbol, params={"stop": True})
log.info(f"CANCEL OK: {oid} on {symbol}")
except Exception as e:
log.warning(f"CANCEL {oid} failed: {e}")
def fetch_candles(self, symbol: str, timeframe: str,
since_ms: int) -> list[list]:
"""Fetch OHLCV candles from exchange."""
self._ensure_markets()
all_candles = []
bar_ms = {"1m": 60_000, "5m": 300_000, "15m": 900_000}.get(timeframe, 300_000)
while True:
batch = self.exchange.fetch_ohlcv(
symbol, timeframe, since=since_ms, limit=1000,
)
if not batch:
break
all_candles.extend(batch)
since_ms = batch[-1][0] + bar_ms
if len(batch) < 1000:
break
return all_candles
def _fetch_order_details(self, order: dict, symbol: str) -> dict:
"""Fetch full order details (Bybit v5 may return None fields)."""
import time
order_id = order.get("id")
if order_id is None:
return order
try:
time.sleep(1)
return self.exchange.fetch_closed_order(order_id, symbol)
except Exception:
try:
return self.exchange.fetch_order(order_id, symbol)
except Exception:
return order
+308
View File
@@ -0,0 +1,308 @@
"""Trade executor — replay approach for ORB+FVG+Engulfing strategy.
Every 5 minutes during NYSE session:
1. Fetch all 5m candles from 9:30 to now
2. Call run_day() — same function as backtest
3. Reconcile with DB positions
4. New trades → open on exchange + SL/TP orders
5. EOD → close remaining positions
"""
from __future__ import annotations
import logging
import sqlite3
from dataclasses import dataclass, field
from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo
import pandas as pd
from config import Config
from exchange import FuturesExecutor
from notify import notify_entry, notify_exit, notify_or
from state import (
close_position, get_equity, get_open_positions, get_session,
get_today_trade_count, log_order, open_position, save_session,
set_state_val, update_equity,
)
from strategy import Params, Trade, run_day
log = logging.getLogger(__name__)
NY = ZoneInfo("America/New_York")
# Singleton executor (created once)
_futures: FuturesExecutor | None = None
def _get_futures(cfg: Config) -> FuturesExecutor:
global _futures
if _futures is None:
_futures = FuturesExecutor(cfg.exchange, leverage=cfg.risk.leverage)
return _futures
@dataclass
class SessionState:
"""In-memory state for current trading session."""
date: date | None = None
or_high: float = 0.0
or_low: float = 0.0
or_computed: bool = False
last_trade_ids: set[str] = field(default_factory=set)
_session = SessionState()
def _is_nyse_hours(now_ny: datetime) -> bool:
"""Check if within NYSE trading window (9:25-16:05 NY, weekdays)."""
if now_ny.weekday() >= 5: # Sat, Sun
return False
t = now_ny.hour * 60 + now_ny.minute
return 9 * 60 + 25 <= t <= 16 * 60 + 5
def _is_eod(now_ny: datetime) -> bool:
"""Check if at/past end of day (16:00 NY)."""
return now_ny.hour >= 16
def _trade_key(t: Trade) -> str:
"""Unique key for a strategy trade (for reconciliation)."""
return f"{t.direction}_{t.entry:.2f}_{t.stop:.2f}"
def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Run one trading cycle. Returns list of log messages."""
global _session
logs: list[str] = []
now_utc = datetime.now(timezone.utc)
now_ny = now_utc.astimezone(NY)
today = now_ny.date()
# Check NYSE hours
if not _is_nyse_hours(now_ny):
logs.append(f"Outside NYSE hours ({now_ny.strftime('%H:%M')} NY)")
return logs
# Init equity from config on first run
equity = get_equity(conn)
if equity <= 0:
update_equity(conn, cfg.capital)
set_state_val(conn, "peak_equity", cfg.capital)
equity = cfg.capital
logs.append(f"Equity initialized: ${equity:,.2f}")
# New day → reset session
if _session.date != today:
_session = SessionState(date=today)
# Try restore OR from DB
saved = get_session(conn, today)
if saved:
_session.or_high = saved["or_high"]
_session.or_low = saved["or_low"]
_session.or_computed = True
logs.append(f"Session restored: OR {_session.or_high:.2f}/{_session.or_low:.2f}")
# Fetch 5m candles from 9:30 NY to now
futures = _get_futures(cfg)
nyse_open = now_ny.replace(hour=9, minute=30, second=0, microsecond=0)
since_ms = int(nyse_open.astimezone(timezone.utc).timestamp() * 1000)
raw_candles = futures.fetch_candles(cfg.symbol, cfg.timeframe, since_ms)
if not raw_candles:
logs.append("No candles fetched")
return logs
df = pd.DataFrame(raw_candles, columns=["timestamp", "open", "high", "low", "close", "volume"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
df.drop_duplicates(subset="timestamp", inplace=True)
df.sort_values("timestamp", inplace=True)
df.reset_index(drop=True, inplace=True)
logs.append(f"Candles: {len(df)} ({df.iloc[0]['timestamp'].strftime('%H:%M')}"
f"-{df.iloc[-1]['timestamp'].strftime('%H:%M')} UTC)")
# Run strategy (replay)
params = cfg.strategy.to_params()
strategy_trades = run_day(df, params, cfg.strategy.or_minutes)
# Track OR computation
if not _session.or_computed and len(df) >= cfg.strategy.or_minutes:
from strategy import get_opening_range
rng = get_opening_range(df, cfg.strategy.or_minutes)
if rng:
_session.or_high, _session.or_low = rng
_session.or_computed = True
save_session(conn, today, _session.or_high, _session.or_low)
logs.append(f"OR computed: {_session.or_high:.2f}/{_session.or_low:.2f}")
notify_or(cfg.telegram, str(today), _session.or_high, _session.or_low)
# Build set of strategy trade keys
strat_keys = {_trade_key(t) for t in strategy_trades}
logs.append(f"Strategy signals: {len(strategy_trades)} trades")
# Get DB open positions
db_positions = get_open_positions(conn)
# Reconcile: check if DB positions are still valid
for pos in db_positions:
key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}"
# Find matching strategy trade
matched_trade = None
for t in strategy_trades:
if _trade_key(t) == key and t.exit_price > 0:
matched_trade = t
break
if matched_trade:
# Strategy says this trade is closed
_execute_exit(conn, cfg, pos, matched_trade.exit_price,
matched_trade.result, logs)
elif _is_eod(now_ny):
# EOD: close all remaining
price = futures.get_price(cfg.symbol) or pos["entry_price"]
_execute_exit(conn, cfg, pos, price, "eod", logs)
# Reconcile: new trades from strategy not yet in DB
db_keys = {f"{p['direction']}_{p['entry_price']:.2f}_{p['stop_price']:.2f}"
for p in db_positions}
for t in strategy_trades:
key = _trade_key(t)
if key in db_keys or key in _session.last_trade_ids:
continue
if t.exit_price > 0:
# Already closed in strategy — skip (historical trade)
continue
# New active trade → execute entry
_execute_entry(conn, cfg, t, equity, logs)
_session.last_trade_ids.add(key)
return logs
def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
equity: float, logs: list[str]) -> None:
"""Open a new position on exchange and in DB."""
futures = _get_futures(cfg)
symbol = cfg.symbol
# Position sizing
risk_dollar = equity * cfg.risk.per_trade
risk_dist = abs(trade.entry - trade.stop)
if risk_dist <= 0:
logs.append(f"SKIP entry: zero risk distance")
return
pos_size = risk_dollar / risk_dist
pos_value = pos_size * trade.entry
# Leverage cap
max_pos = equity * cfg.risk.leverage
if pos_value > max_pos:
pos_size = max_pos / trade.entry
pos_value = max_pos
# Exchange order
side = "buy" if trade.direction == "long" else "sell"
if trade.direction == "long":
order = futures.open_long(symbol, pos_value)
else:
order = futures.open_short(symbol, pos_value)
if order is None:
logs.append(f"ENTRY FAILED: {trade.direction} @ {trade.entry:.2f}")
return
# Actual fill
filled_price = float(order.get("average") or order.get("price") or trade.entry)
filled_qty = float(order.get("filled") or order.get("amount") or pos_size)
# Place SL/TP on exchange
sl_order, tp_order = futures.place_sl_tp(
symbol, side, filled_qty, trade.stop, trade.tp,
)
# DB
pos_id = open_position(
conn,
date=str(datetime.now(timezone.utc).astimezone(NY).date()),
direction=trade.direction,
entry_price=filled_price,
stop_price=trade.stop,
tp_price=trade.tp,
pos_size=filled_qty,
pos_value=filled_qty * filled_price,
entry_time=datetime.now(timezone.utc).isoformat(),
sl_order_id=sl_order.get("id") if sl_order else None,
tp_order_id=tp_order.get("id") if tp_order else None,
)
log_order(conn, pos_id, side, symbol, trade.entry, order)
logs.append(f"ENTRY {trade.direction.upper()} @ ${filled_price:,.2f} "
f"SL=${trade.stop:,.2f} TP=${trade.tp:,.2f} "
f"size={filled_qty:.4f} (${pos_value:,.2f})")
notify_entry(cfg.telegram, symbol, trade.direction,
filled_price, trade.stop, trade.tp)
def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict,
exit_price: float, reason: str, logs: list[str]) -> None:
"""Close a position on exchange and in DB."""
futures = _get_futures(cfg)
symbol = cfg.symbol
side = "buy" if pos["direction"] == "long" else "sell"
# Cancel SL/TP orders
futures.cancel_orders(symbol,
pos.get("sl_order_id", ""),
pos.get("tp_order_id", ""))
# Close on exchange
order = futures.close_position(symbol, side, pos["pos_size"])
# PnL
if pos["direction"] == "long":
gross = pos["pos_size"] * (exit_price - pos["entry_price"])
else:
gross = pos["pos_size"] * (pos["entry_price"] - exit_price)
commission = pos["pos_value"] * cfg.risk.taker_fee * 2
pnl_net = gross - commission
# Update equity
equity = get_equity(conn)
new_equity = equity + pnl_net
update_equity(conn, new_equity)
# Update stats
from state import get_state_val, set_state_val
trades_count = get_state_val(conn, "trades_count") + 1
set_state_val(conn, "trades_count", trades_count)
if pnl_net > 0:
wins = get_state_val(conn, "wins") + 1
set_state_val(conn, "wins", wins)
total_pnl = get_state_val(conn, "total_pnl") + pnl_net
set_state_val(conn, "total_pnl", total_pnl)
# DB
close_position(conn, pos["id"],
exit_price=exit_price,
exit_reason=reason,
pnl_net=round(pnl_net, 4),
exit_time=datetime.now(timezone.utc).isoformat())
if order:
close_side = "sell" if side == "buy" else "buy"
log_order(conn, pos["id"], close_side, symbol, exit_price, order)
result = "WIN" if pnl_net > 0 else "LOSS"
logs.append(f"EXIT {pos['direction'].upper()} @ ${exit_price:,.2f} "
f"({reason}) PnL ${pnl_net:+,.2f} [{result}]")
notify_exit(cfg.telegram, symbol, pnl_net, reason)
+63
View File
@@ -0,0 +1,63 @@
"""Telegram notifications for scalp-bot."""
from __future__ import annotations
import logging
import httpx
from config import TelegramConfig
log = logging.getLogger(__name__)
def send_telegram(cfg: TelegramConfig, message: str) -> bool:
"""Send message via Telegram bot API. Returns True on success."""
if not cfg.enabled or not cfg.bot_token or not cfg.chat_id:
return False
url = f"https://api.telegram.org/bot{cfg.bot_token}/sendMessage"
try:
resp = httpx.post(url, json={
"chat_id": cfg.chat_id,
"text": message,
"parse_mode": "HTML",
}, timeout=10)
if resp.status_code != 200:
log.warning("Telegram API error: %s", resp.text)
return False
return True
except httpx.HTTPError as e:
log.warning("Telegram send failed: %s", e)
return False
def notify_entry(cfg: TelegramConfig, symbol: str, side: str,
entry: float, stop: float, tp: float) -> None:
tag = symbol.split("/")[0]
icon = "\U0001f7e2" if side == "long" else "\U0001f534"
msg = (
f"{icon} <b>{tag} {side.upper()}</b>\n"
f"Entry: ${entry:,.2f}\n"
f"Stop: ${stop:,.2f}\n"
f"TP: ${tp:,.2f}"
)
send_telegram(cfg, msg)
def notify_exit(cfg: TelegramConfig, symbol: str, pnl: float,
reason: str) -> None:
tag = symbol.split("/")[0]
icon = "\u2705" if pnl >= 0 else "\u274c"
msg = f"{icon} <b>{tag} CLOSED</b> ({reason}) PnL ${pnl:+,.2f}"
send_telegram(cfg, msg)
def notify_or(cfg: TelegramConfig, dt_str: str,
or_high: float, or_low: float) -> None:
msg = (
f"\U0001f4ca <b>Opening Range</b> {dt_str}\n"
f"High: ${or_high:,.2f} | Low: ${or_low:,.2f}\n"
f"Range: ${or_high - or_low:,.2f}"
)
send_telegram(cfg, msg)
+4
View File
@@ -1,2 +1,6 @@
ccxt>=4.0
pandas>=2.0
pyyaml>=6.0
click>=8.1
apscheduler>=3.10,<4
httpx>=0.27
+223
View File
@@ -0,0 +1,223 @@
"""SQLite state management — positions, sessions, equity, orders."""
from __future__ import annotations
import sqlite3
from datetime import date
from pathlib import Path
DB_PATH = Path(__file__).parent / "data" / "scalp.db"
def get_db(path: Path | None = None) -> sqlite3.Connection:
"""Get database connection with row factory."""
path = path or DB_PATH
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(path))
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
return conn
def init_db(conn: sqlite3.Connection) -> None:
"""Create tables if they don't exist."""
conn.executescript("""
CREATE TABLE IF NOT EXISTS state (
key TEXT PRIMARY KEY,
value REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
date TEXT PRIMARY KEY,
or_high REAL NOT NULL,
or_low REAL NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS positions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
direction TEXT NOT NULL, -- long | short
entry_price REAL NOT NULL,
exit_price REAL,
stop_price REAL NOT NULL,
tp_price REAL NOT NULL,
pos_size REAL NOT NULL, -- qty in base currency
pos_value REAL NOT NULL, -- notional in USDT
pnl_net REAL,
status TEXT DEFAULT 'open', -- open | closed
exit_reason TEXT, -- sl | tp | eod | manual
sl_order_id TEXT,
tp_order_id TEXT,
entry_time TEXT,
exit_time TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
pos_id INTEGER NOT NULL,
exchange_order_id TEXT,
side TEXT NOT NULL, -- buy | sell
symbol TEXT NOT NULL,
qty REAL,
requested_price REAL,
filled_price REAL,
slippage_pct REAL,
fee REAL,
fee_currency TEXT,
cost REAL,
status TEXT, -- filled | failed | dry_run
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (pos_id) REFERENCES positions(id)
);
CREATE INDEX IF NOT EXISTS idx_positions_status ON positions(status);
CREATE INDEX IF NOT EXISTS idx_positions_date ON positions(date);
CREATE INDEX IF NOT EXISTS idx_orders_pos ON orders(pos_id);
""")
# Seed state defaults
for key, default in [("equity", 0), ("peak_equity", 0),
("trades_count", 0), ("wins", 0), ("total_pnl", 0)]:
conn.execute(
"INSERT OR IGNORE INTO state (key, value) VALUES (?, ?)",
(key, default),
)
conn.commit()
# -- State KV --
def get_state_val(conn: sqlite3.Connection, key: str) -> float:
row = conn.execute("SELECT value FROM state WHERE key=?", (key,)).fetchone()
return row["value"] if row else 0.0
def set_state_val(conn: sqlite3.Connection, key: str, value: float) -> None:
conn.execute(
"INSERT INTO state (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value=?",
(key, value, value),
)
conn.commit()
def get_equity(conn: sqlite3.Connection) -> float:
return get_state_val(conn, "equity")
def update_equity(conn: sqlite3.Connection, equity: float) -> None:
set_state_val(conn, "equity", equity)
peak = get_state_val(conn, "peak_equity")
if equity > peak:
set_state_val(conn, "peak_equity", equity)
# -- Sessions --
def save_session(conn: sqlite3.Connection, dt: date,
or_high: float, or_low: float) -> None:
conn.execute(
"INSERT INTO sessions (date, or_high, or_low) VALUES (?, ?, ?) "
"ON CONFLICT(date) DO UPDATE SET or_high=?, or_low=?",
(str(dt), or_high, or_low, or_high, or_low),
)
conn.commit()
def get_session(conn: sqlite3.Connection, dt: date) -> dict | None:
row = conn.execute(
"SELECT * FROM sessions WHERE date=?", (str(dt),)
).fetchone()
return dict(row) if row else None
# -- Positions --
def open_position(conn: sqlite3.Connection, **kwargs) -> int:
cols = ", ".join(kwargs.keys())
placeholders = ", ".join("?" for _ in kwargs)
cur = conn.execute(
f"INSERT INTO positions ({cols}) VALUES ({placeholders})",
list(kwargs.values()),
)
conn.commit()
return cur.lastrowid
def close_position(conn: sqlite3.Connection, pos_id: int, **kwargs) -> None:
kwargs["status"] = "closed"
sets = ", ".join(f"{k}=?" for k in kwargs)
vals = list(kwargs.values()) + [pos_id]
conn.execute(f"UPDATE positions SET {sets} WHERE id=?", vals)
conn.commit()
def get_open_positions(conn: sqlite3.Connection) -> list[dict]:
rows = conn.execute(
"SELECT * FROM positions WHERE status='open' ORDER BY id"
).fetchall()
return [dict(r) for r in rows]
def get_today_trade_count(conn: sqlite3.Connection, dt: date) -> int:
row = conn.execute(
"SELECT COUNT(*) as cnt FROM positions WHERE date=?", (str(dt),)
).fetchone()
return row["cnt"] if row else 0
def get_trade_history(conn: sqlite3.Connection, limit: int = 50) -> list[dict]:
rows = conn.execute(
"SELECT * FROM positions WHERE status='closed' ORDER BY id DESC LIMIT ?",
(limit,),
).fetchall()
return [dict(r) for r in rows]
# -- Orders --
def log_order(conn: sqlite3.Connection, pos_id: int, side: str, symbol: str,
requested_price: float, order: dict | None,
failed: bool = False) -> None:
"""Log exchange order execution details."""
if order is None or failed:
conn.execute(
"INSERT INTO orders (pos_id, side, symbol, requested_price, status) "
"VALUES (?,?,?,?,?)",
(pos_id, side, symbol, requested_price, "failed"),
)
conn.commit()
return
if order.get("dry_run"):
conn.execute(
"INSERT INTO orders (pos_id, side, symbol, requested_price, "
"filled_price, qty, cost, status) VALUES (?,?,?,?,?,?,?,?)",
(pos_id, side, symbol, requested_price,
order.get("price"), order.get("amount"), order.get("cost"), "dry_run"),
)
conn.commit()
return
filled_price = float(order.get("average") or order.get("price") or requested_price)
qty = float(order.get("filled") or order.get("amount") or 0)
cost = float(order.get("cost") or 0)
fee_info = order.get("fee") or {}
fee_cost = float(fee_info.get("cost") or 0)
fee_cur = fee_info.get("currency", "")
exchange_id = order.get("id", "")
slippage = ((filled_price - requested_price) / requested_price * 100
if requested_price > 0 else 0)
conn.execute(
"INSERT INTO orders (pos_id, exchange_order_id, side, symbol, qty, "
"requested_price, filled_price, slippage_pct, fee, fee_currency, cost, status) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
(pos_id, exchange_id, side, symbol, qty,
requested_price, filled_price, round(slippage, 4),
fee_cost, fee_cur, cost, "filled"),
)
conn.commit()