#!/bin/bash # One-shot scheduled task: close legacy positions, then start the new trading bot. # Removes its own cron entry after running. BOT_DIR="$(cd "$(dirname "$0")" && pwd)" LOG="$BOT_DIR/close_legacy_positions.log" BOT_LOG="$BOT_DIR/trading_bot.log" if pgrep -f "python.*main\.py" > /dev/null; then echo "$(date) ABORT: trading bot is already running; skipping cleanup" >> "$LOG" else echo "=== $(date) legacy cleanup start ===" >> "$LOG" "$BOT_DIR/.venv/bin/python" "$BOT_DIR/close_legacy_positions.py" >> "$LOG" 2>&1 RC=$? echo "=== $(date) legacy cleanup done (exit=$RC) ===" >> "$LOG" if [ "$RC" -eq 0 ]; then echo "=== $(date) cleanup OK, starting new trading bot ===" >> "$LOG" setsid nohup "$BOT_DIR/.venv/bin/python" "$BOT_DIR/main.py" >> "$BOT_LOG" 2>&1 < /dev/null & BOT_PID=$! sleep 8 if kill -0 "$BOT_PID" 2>/dev/null; then echo "=== bot started successfully (PID: $BOT_PID) ===" >> "$LOG" else echo "=== bot FAILED to start, check $BOT_LOG ===" >> "$LOG" fi else echo "=== $(date) cleanup FAILED (exit=$RC) - bot NOT started." >> "$LOG" echo "=== Fix manually (run: .venv/bin/python close_legacy_positions.py), then ./restart_bot.sh ===" >> "$LOG" fi fi # self-remove from crontab (one-shot task) crontab -l 2>/dev/null | grep -v "close_legacy_positions" | crontab -