#!/usr/bin/env bash

# Usage: run_hyperopt_batch.sh <PAIR_LIST_FILE>
# <PAIR_LIST_FILE> contains one pair per line, e.g., BTC-USDT\nETH-USDT
#
# This script will read each pair, detect regimes (using detect_regime.py),
# and run freqtrade hyperopt for each detected regime, saving user_data/strategies/params in user_data/strategies/params/PAIR/REGIME/

# Lanement par docker exec -i freqtrade user_data/strategies/tools/run_hyperopt_batch.sh user_data/strategies/pairs.txt
# user_data/strategies/tools/run_hyperopt_batch.sh user_data/strategies/pairs.txt

STRATEGIE="Zeus_8_3_2_B_4_2"

if [ $# -ne 1 ]; then
    echo "Usage: $0 <PAIR_LIST_FILE>" >&2
    exit 1
fi

PAIR_LIST_FILE="$1"

if [ ! -f "$PAIR_LIST_FILE" ]; then
    echo "File not found: $PAIR_LIST_FILE" >&2
    exit 1
fi
echo "ici $PAIR_LIST_FILE"

while read -r PAIR; do
    echo $PAIR
    [ -z "$PAIR" ] && continue
    echo "\nProcessing pair: $PAIR"

    DATA_FEATHER="user_data/data/binance/$(echo $PAIR | tr '[:upper:]' '[:upper:]')-1d.feather"
    if [ ! -f "$DATA_FEATHER" ]; then
        echo "Data file not found for $PAIR: $DATA_FEATHER" >&2
        continue
    fi
    echo "Work with data file $PAIR: $DATA_FEATHER" >&2

    # Detect regimes using Python script
    REGIMES=$(python3 user_data/strategies/tools/detect_regime.py "$PAIR" "$DATA_FEATHER") # | awk '{print tolower($1) " " $2 " " $4}')

    while read -r REGIME START st END et; do
        echo "Work with dates $REGIME : $START - $END" >&2

        if [ -z "$START" ] || [ -z "$END" ]; then
            echo "Skipping $PAIR $REGIME : cannot determine timerange" >&2
            continue
        fi

#        if [[ "$START" < "2024-09-01" ]]; then
#            echo "TOO OLD $START"
#            continue
#        fi

        TIMERANGE="${START//-/}-${END//-/}"
        echo "Running hyperopt for $PAIR $REGIME with timerange $TIMERANGE"

        OUTPUT_JSON="user_data/strategies/params/$PAIR/$REGIME/$START-$END-hyperopt_result.json"
        OUTPUT_TXT="user_data/strategies/params/$PAIR/$REGIME/$START-$END-hyperopt_result.txt"
        mkdir -p "user_data/strategies/params/$PAIR/$REGIME"

        converted="${PAIR/_//}"

#        COLUMNS=200 LINES=40 script -q -c "

        freqtrade hyperopt --strategy $STRATEGIE --config user_data/config.json --hyperopt-loss OnlyProfitHyperOptLoss --timerange $TIMERANGE --timeframe 5m --spaces sell buy --pair $converted -e 80 -j7 --print-all

        echo "Saved hyperopt output to $OUTPUT_JSON"

        cp user_data/strategies/$STRATEGIE.json $OUTPUT_JSON

        # COLUMNS=120 LINES=40 script -q -c "
#        docker exec -i freqtrade
        freqtrade hyperopt-list  --profitable --no-details > $OUTPUT_TXT

        sleep 1

    done <<< "$REGIMES"

done < "$PAIR_LIST_FILE"