"""
Optimisation fine autour de la config gagnante
"""
import pandas as pd
import numpy as np
from apollo_client import ApolloDegenClient

client = ApolloDegenClient()
df = client.get_klines('BTCUSDT', '1m', limit=1500)
df['ma'] = df['close'].rolling(20).mean()

print('\n🔬 OPTIMISATION FINE AUTOUR DE LA CONFIG GAGNANTE')
print('='*90)
print('{:<8} | {:<8} | {:<8} | {:<6} | {:<10} | {:<7} | {:<8}'.format('SL%', 'TP%', 'Ratio', 'Lev', 'Return%', 'WR%', 'Trades'))
print('-'*90)

# Test fine variations
configs = []
for sl in [0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008]:  # 0.03% - 0.08%
    for tp_ratio in [1.5, 2, 2.5, 3, 4, 5]:
        for lev in [200, 225, 250]:
            configs.append({'sl': sl, 'tp_ratio': tp_ratio, 'lev': lev})

results = []

for cfg in configs:
    capital = 1000
    trades = []

    for i in range(50, len(df)-10, 5):
        if pd.isna(df.iloc[i]['ma']):
            continue

        close = df.iloc[i]['close']
        ma = df.iloc[i]['ma']
        side = 'LONG' if close > ma else 'SHORT'

        if side == 'LONG':
            sl = close * (1 - cfg['sl'])
            tp = close * (1 + cfg['sl'] * cfg['tp_ratio'])
        else:
            sl = close * (1 + cfg['sl'])
            tp = close * (1 - cfg['sl'] * cfg['tp_ratio'])

        for j in range(i+1, min(i+15, len(df))):
            candle = df.iloc[j]
            exit_price = None

            if side == 'LONG':
                if candle['low'] <= sl:
                    exit_price = sl
                elif candle['high'] >= tp:
                    exit_price = tp
            else:
                if candle['high'] >= sl:
                    exit_price = sl
                elif candle['low'] <= tp:
                    exit_price = tp

            if exit_price:
                pnl_pct = ((exit_price - close) / close) if side == 'LONG' else ((close - exit_price) / close)
                pnl_usd = capital * 0.05 * cfg['lev'] * pnl_pct
                capital += pnl_usd
                trades.append(pnl_usd)
                break

    if len(trades) >= 50:
        total_return = ((capital - 1000) / 1000) * 100
        wins = len([t for t in trades if t > 0])
        wr = wins / len(trades) * 100

        results.append({
            'sl': cfg['sl'],
            'tp': cfg['sl'] * cfg['tp_ratio'],
            'tp_ratio': cfg['tp_ratio'],
            'lev': cfg['lev'],
            'return': total_return,
            'wr': wr,
            'trades': len(trades),
            'capital': capital
        })

# Top 20
results.sort(key=lambda x: x['return'], reverse=True)
for i, r in enumerate(results[:20], 1):
    print('{:<8.3f} | {:<8.3f} | {:<8.1f} | {:<6} | {:<10.2f} | {:<7.1f} | {:<8}'.format(
        r['sl']*100, r['tp']*100, r['tp_ratio'], r['lev'], r['return'], r['wr'], r['trades']
    ))

if results:
    best = results[0]
    print('\n' + '='*90)
    print('🥇 MEILLEURE CONFIGURATION')
    print('='*90)
    print('SL:        {:.3f}%'.format(best['sl']*100))
    print('TP:        {:.3f}% (ratio {:.1f}:1)'.format(best['tp']*100, best['tp_ratio']))
    print('Leverage:  {}x'.format(best['lev']))
    print('')
    print('Return:    {:+.2f}%'.format(best['return']))
    print('Win Rate:  {:.1f}%'.format(best['wr']))
    print('Trades:    {}'.format(best['trades']))
    print('Capital:   ${:.2f}'.format(best['capital']))
    print('='*90)
