feat: deploy-конфиг + trailing stops + reconcile positions

- deploy/scalp-bot.service — systemd unit для пользователя scalp
- deploy/update.sh — скрипт обновления на сервере
- cli.py: stop-update cycle каждые 15 мин (trailing stops + safety orders)
- executor.py: reconcile_positions (синхронизация с биржей), update_stops

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-13 21:43:21 +10:00
co-authored by Claude Opus 4.6
parent 87a4dd7645
commit af6885c3e7
4 changed files with 217 additions and 1 deletions
+29
View File
@@ -0,0 +1,29 @@
[Unit]
Description=scalp-bot ETH futures scalper (Bybit)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=scalp
Group=scalp
WorkingDirectory=/home/scalp/app
EnvironmentFile=/home/scalp/app/.env
ExecStart=/home/scalp/app/.venv/bin/python cli.py daemon
Restart=on-failure
RestartSec=30
StartLimitIntervalSec=300
StartLimitBurst=5
KillSignal=SIGTERM
TimeoutStopSec=30
NoNewPrivileges=yes
PrivateTmp=yes
StandardOutput=journal
StandardError=journal
SyslogIdentifier=scalp-bot
[Install]
WantedBy=multi-user.target
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
cd /home/scalp/app
git pull --ff-only
source .venv/bin/activate
pip install -r requirements.txt --quiet
echo "Updated. Restart: sudo systemctl restart scalp-bot"
+18 -1
View File
@@ -193,7 +193,7 @@ def daemon():
"""Run as daemon — auto-cycle on schedule + web dashboard."""
from apscheduler.schedulers.background import BackgroundScheduler
from .core.executor import run_cycle
from .core.executor import run_cycle, update_stops
from .notify import (format_cycle_report, format_morning_report_with_ai,
format_startup_details,
format_status_report, send_status, send_telegram)
@@ -263,6 +263,23 @@ def daemon():
scheduler.add_job(morning_report, "cron", hour=0, minute=0)
click.echo("Morning report scheduled: daily at 00:00 UTC (10:00 AEST)")
# Stop-update cycle: update trailing stops + re-place safety orders
# Runs every 15 min so stops track price between 4h main cycles
if cfg.mode == "live":
def stop_update_cycle():
c = get_db()
init_db(c)
stop_logs = update_stops(c, cfg)
c.close()
for msg in stop_logs:
click.echo(f" [stops] {msg}")
if cfg.telegram.enabled and any("trailing stop" in m for m in stop_logs):
send_telegram(cfg.telegram,
"🔄 " + "\n".join(m for m in stop_logs if "trailing" in m or "safety" in m))
scheduler.add_job(stop_update_cycle, "interval", minutes=15)
click.echo("Stop updates scheduled: every 15 min")
scheduler.start()
click.echo("Daemon started. Web dashboard + scheduler running.")
+163
View File
@@ -33,6 +33,80 @@ def _get_spot(cfg: Config):
return _spot_executor
def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Sync DB positions with actual exchange state.
Detects positions closed externally (by user on exchange UI) and
updates DB accordingly. Call at start of every cycle.
Returns list of log messages.
"""
logs = []
if cfg.mode != "live":
return logs
spot = _get_spot(cfg)
for asset_cfg in cfg.assets:
ticker = asset_cfg.ticker
pos = get_open_position(conn, ticker)
if pos is None:
continue
# Check actual coin balance on exchange
coin = asset_cfg.symbol.split("/")[0]
coin_balance = spot.get_balance(coin)
min_threshold = pos["pos_size"] * 0.1 # <10% of position = closed
if coin_balance < min_threshold:
# Position was closed externally (user sold on exchange)
current_price = spot.get_price(asset_cfg.symbol)
if current_price is None:
current_price = pos["entry_price"] # fallback
pnl_net, pnl_pct = risk.calculate_pnl(
pos["entry_price"], current_price, pos["direction"],
pos["pos_size"], pos["pos_value"],
)
close_position(conn, pos["id"],
exit_price=current_price,
exit_date=str(date.today()),
exit_reason="external",
pnl_net=pnl_net, pnl_pct=pnl_pct)
asset = _get_or_skip(conn, ticker)
if asset:
new_equity = asset["equity"] + pnl_net
new_peak = max(asset["peak_equity"], new_equity)
win = pnl_net > 0
update_asset(conn, ticker,
equity=new_equity, peak_equity=new_peak,
trades_count=asset["trades_count"] + 1,
wins=asset["wins"] + (1 if win else 0),
losses=asset["losses"] + (0 if win else 1),
total_pnl=asset["total_pnl"] + pnl_net)
# Cancel orphaned safety stop
safety_id = pos.get("safety_stop_order_id")
if safety_id and safety_id != "dry_run":
spot.cancel_order(asset_cfg.symbol, safety_id)
dir_str = "LONG" if pos["direction"] == 1 else "SHORT"
logs.append(f"{ticker}: RECONCILE — {dir_str} closed externally "
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
else:
# Position exists — update DB with actual size if different
if abs(coin_balance - pos["pos_size"]) > pos["pos_size"] * 0.02:
current_price = spot.get_price(asset_cfg.symbol) or pos["entry_price"]
update_position(conn, pos["id"],
pos_size=coin_balance,
pos_value=coin_balance * current_price)
logs.append(f"{ticker}: RECONCILE — size adjusted "
f"{pos['pos_size']:.4f} → {coin_balance:.4f}")
return logs
def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Run one trading cycle: check stops, generate signals.
@@ -45,6 +119,12 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
logs = []
today = str(date.today())
# Reconcile DB with exchange reality first
if cfg.mode == "live":
recon_logs = reconcile_positions(conn, cfg)
logs.extend(recon_logs)
if cfg.mode == "live" and len(cfg.assets) > 1:
log.warning(f"Live mode with {len(cfg.assets)} assets — "
f"exchange balance is shared, not per-asset")
@@ -175,6 +255,20 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
logs.append(f"DEPOSIT: {action} ${abs(deposit):,.2f} "
f"(${prev_bal:,.2f} → ${exchange_bal:,.2f})")
# Sync DB equity: distribute deposit/withdrawal proportionally
all_a = get_all_assets(conn)
total_db = sum(a["equity"] for a in all_a)
if total_db > 0:
for a in all_a:
share = a["equity"] / total_db
adj = deposit * share
new_eq = max(a["equity"] + adj, 0.0)
new_peak = max(a["peak_equity"], new_eq)
update_asset(conn, a["ticker"],
equity=new_eq, peak_equity=new_peak)
logs.append(f"SYNC: DB equity adjusted by ${deposit:+,.2f} "
f"across {len(all_a)} assets")
log_balance_snapshot(conn, today, exchange_bal, db_total)
return logs
@@ -608,3 +702,72 @@ def _retrain(conn, ticker, prices, cfg):
consecutive_losses=0,
last_atr_regime=current_regime,
last_train_date=str(date.today()))
def update_stops(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Lightweight stop-update cycle: fetch prices, update trailing stops,
re-place safety stop orders on exchange.
Runs every 15 min between main 4h cycles. No model/signal logic.
"""
logs = []
if cfg.mode != "live":
return logs
# Reconcile first — detect externally closed positions
recon_logs = reconcile_positions(conn, cfg)
logs.extend(recon_logs)
spot = _get_spot(cfg)
for asset_cfg in cfg.assets:
ticker = asset_cfg.ticker
pos = get_open_position(conn, ticker)
if pos is None:
continue
# Fetch current price from exchange
current_price = spot.get_price(asset_cfg.symbol)
if current_price is None:
logs.append(f"{ticker}: price fetch failed — skip stop update")
continue
direction = pos["direction"]
stop_price = pos["stop_price"]
stop_dist = pos["stop_dist"]
best_price = pos["best_price"]
# Check if stopped right now
stopped = risk.is_stopped(current_price, stop_price, direction)
if stopped:
# Don't close here — let main cycle handle closing with proper PnL
# But log the alert
logs.append(f"{ticker}: STOP HIT @ ${current_price:,.3f} "
f"(stop ${stop_price:,.3f}) — will close on next cycle")
continue
# Update trailing stop
if asset_cfg.trailing_stop:
new_best, new_stop = risk.update_trailing_stop(
current_price, best_price, stop_price, stop_dist, direction,
)
if new_stop != stop_price:
update_position(conn, pos["id"],
best_price=new_best, stop_price=new_stop)
logs.append(f"{ticker}: trailing stop ${stop_price:,.3f} → "
f"${new_stop:,.3f} (price ${current_price:,.3f})")
# Re-place safety stop on exchange at trailing level
safety_id = pos.get("safety_stop_order_id")
if safety_id and safety_id != "dry_run":
spot.cancel_order(asset_cfg.symbol, safety_id)
new_safety = spot.place_safety_stop(
asset_cfg.symbol, pos["pos_size"], new_stop)
if new_safety:
new_safety_id = new_safety.get("id") or "dry_run"
update_position(conn, pos["id"],
safety_stop_order_id=new_safety_id)
logs.append(f"{ticker}: safety stop moved to ${new_stop:,.3f}")
return logs