#!/bin/bash
# OPTION 2 (SIMPLIFIED): Equity-Scaled with DD-Adaptive Throttle
# 
# Strategy: Scale lots with equity BUT reduce lot multiplier if previous
# month's DD exceeded target. This simulates a trader who:
# 1. Scales up when things are going well (low DD)
# 2. Pulls back when DD spikes (risk management)
#
# DD target: 10%. If prev DD > 10%, scale factor drops by 50%.
# If prev DD > 20%, scale factor drops by 75%.
# If prev DD < 5%, scale factor increases by 25% (up to 1.5x max).

cd /var/www/html/crpytotradingbot

MONTHS="202508 202509 202510 202511 202512 202601 202602"
BALANCE=20000.0
ORIGINAL_BALANCE=$BALANCE
SCALE=1.0  # Dynamic scale multiplier

RESULTS_FILE="results/adaptive_v2_$(date +%Y%m%d_%H%M%S).txt"
mkdir -p results

echo "╔══════════════════════════════════════════════════════════╗" | tee "$RESULTS_FILE"
echo "║  OPTION 2: DD-ADAPTIVE EQUITY SCALING                   ║" | tee -a "$RESULTS_FILE"
echo "║  Scale up when DD low, pull back when DD high            ║" | tee -a "$RESULTS_FILE"
echo "╚══════════════════════════════════════════════════════════╝" | tee -a "$RESULTS_FILE"
echo "" | tee -a "$RESULTS_FILE"

TOTAL_TRADES=0
TOTAL_GROSS_PROFIT=0
TOTAL_GROSS_LOSS=0
TOTAL_COMMISSION=0
OVERALL_MAX_DD_PCT=0
PREV_DD=0

for MONTH in $MONTHS; do
    # Adjust scale based on previous month's DD
    SCALE=$(python3 -c "
prev_dd = $PREV_DD
scale = $SCALE
if prev_dd > 20:
    scale = max(0.25, scale * 0.25)  # Aggressive pullback
elif prev_dd > 10:
    scale = max(0.25, scale * 0.5)   # Moderate pullback
elif prev_dd > 5:
    scale = scale  # Hold steady
elif prev_dd > 0:
    scale = min(1.5, scale * 1.25)   # Doing well, scale up slightly
print(round(scale, 3))
")

    # Calculate lot and target with scale
    NEW_LOT=$(python3 -c "
base_lot = $BALANCE * 0.0000015 * $SCALE
lot = round(max(0.001, min(base_lot, 15.0)), 3)
print(lot)
")
    NEW_TARGET=$(python3 -c "
base_target = $BALANCE * 0.00075 * $SCALE
target = round(max(1.0, base_target), 2)
print(target)
")

    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" | tee -a "$RESULTS_FILE"
    echo "SEGMENT: $MONTH | Balance: \$$(printf '%.2f' $BALANCE) | Scale: ${SCALE}x | Lot: ${NEW_LOT} | Target: \$${NEW_TARGET}" | tee -a "$RESULTS_FILE"
    if [ "$PREV_DD" != "0" ]; then
        echo "  (prev DD: ${PREV_DD}% → scale adjusted to ${SCALE}x)" | tee -a "$RESULTS_FILE"
    fi
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" | tee -a "$RESULTS_FILE"
    
    sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = ${BALANCE}/" settings.py
    sed -i "s/^LOT_SIZE = .*/LOT_SIZE = ${NEW_LOT}/" settings.py
    sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = ${NEW_TARGET}/" settings.py
    
    OUTPUT=$(nice -n 15 python3 bot_runner.py --csv="$MONTH" --max-rows=0 --timeout=480 --throttle=2 2>&1)
    EXIT_CODE=$?
    
    echo "$OUTPUT" | tee -a "$RESULTS_FILE"
    
    if [ $EXIT_CODE -ne 0 ]; then
        echo "ERROR: Segment $MONTH failed" | tee -a "$RESULTS_FILE"
        sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = 20000.0/" settings.py
        sed -i "s/^LOT_SIZE = .*/LOT_SIZE = 0.03/" settings.py
        sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = 15.0/" settings.py
        exit 1
    fi
    
    RESULT_JSON=$(ls -t results/result_*.json | head -1)
    if [ -f "$RESULT_JSON" ]; then
        NEW_BALANCE=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(round($BALANCE + d.get('net_profit', 0), 2))")
        TRADES=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('total_trades', 0))")
        GP=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('gross_profit', 0))")
        GL=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('gross_loss', 0))")
        COMM=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('commission', 0))")
        DD=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('max_dd_pct', 0))")
        RET=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('return_pct', 0))")
        
        TOTAL_TRADES=$((TOTAL_TRADES + TRADES))
        TOTAL_GROSS_PROFIT=$(python3 -c "print($TOTAL_GROSS_PROFIT + $GP)")
        TOTAL_GROSS_LOSS=$(python3 -c "print($TOTAL_GROSS_LOSS + $GL)")
        TOTAL_COMMISSION=$(python3 -c "print($TOTAL_COMMISSION + $COMM)")
        
        IS_WORSE=$(python3 -c "print(1 if $DD > $OVERALL_MAX_DD_PCT else 0)")
        if [ "$IS_WORSE" -eq 1 ]; then
            OVERALL_MAX_DD_PCT=$DD
        fi
        
        PREV_DD=$DD
        
        echo "" | tee -a "$RESULTS_FILE"
        echo "→ $MONTH: \$$(printf '%.2f' $BALANCE) → \$$(printf '%.2f' $NEW_BALANCE) | Scale: ${SCALE}x | Return: ${RET}% | DD: ${DD}%" | tee -a "$RESULTS_FILE"
        echo "" | tee -a "$RESULTS_FILE"
        BALANCE=$NEW_BALANCE
    fi
done

# Restore
sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = 20000.0/" settings.py
sed -i "s/^LOT_SIZE = .*/LOT_SIZE = 0.03/" settings.py
sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = 15.0/" settings.py

NET_PROFIT=$(python3 -c "print(round($BALANCE - $ORIGINAL_BALANCE, 2))")
TOTAL_RETURN=$(python3 -c "print(round(($BALANCE - $ORIGINAL_BALANCE) / $ORIGINAL_BALANCE * 100, 2))")
PF=$(python3 -c "gl=abs($TOTAL_GROSS_LOSS); print(round($TOTAL_GROSS_PROFIT / gl, 2) if gl > 0 else 'inf')")

echo "" | tee -a "$RESULTS_FILE"
echo "╔══════════════════════════════════════════════════════════════╗" | tee -a "$RESULTS_FILE"
echo "║  DD-ADAPTIVE 6-MONTH RESULTS (Aug 2025 - Feb 2026)          ║" | tee -a "$RESULTS_FILE"
echo "╠══════════════════════════════════════════════════════════════╣" | tee -a "$RESULTS_FILE"
printf "║  Starting Balance:  \$%14.2f                              ║\n" $ORIGINAL_BALANCE | tee -a "$RESULTS_FILE"
printf "║  Final Balance:     \$%14.2f                              ║\n" $BALANCE | tee -a "$RESULTS_FILE"
printf "║  Net Profit:        \$%14.2f                              ║\n" $NET_PROFIT | tee -a "$RESULTS_FILE"
printf "║  Total Return:      %10s%%                                ║\n" $TOTAL_RETURN | tee -a "$RESULTS_FILE"
printf "║  Worst Segment DD:  %10s%%                                ║\n" $OVERALL_MAX_DD_PCT | tee -a "$RESULTS_FILE"
printf "║  Total Trades:      %10s                                  ║\n" $TOTAL_TRADES | tee -a "$RESULTS_FILE"
printf "║  Profit Factor:     %10s                                  ║\n" $PF | tee -a "$RESULTS_FILE"
printf "║  Total Commission:  \$%14.2f                              ║\n" $TOTAL_COMMISSION | tee -a "$RESULTS_FILE"
echo "╚══════════════════════════════════════════════════════════════╝" | tee -a "$RESULTS_FILE"
