"""
AUTO HEDGE-MART V4.12beta SETTINGS
====================================
Ported from Auto Hedge-Mart-V4.mq4 to Python backtesting framework.

Strategy: Hedged martingale recovery grid
- Opens initial trades based on bar patterns + Fibonacci zone filters
- When trade goes against you, opens hedged BUY+SELL pairs at grid levels
- Lot sizes scale to cover previous losses + fixed profit target
- Sub-order pairs repeat after TP hits
- Thread profit exit closes everything at net profit target

Reference: V4.12beta XAUUSD test (M15, 2021.04-2021.11)
  Profit factor 1.88, 64.19% win rate, 4544 trades
"""

# =============================================================================
# TRADING PAIR  —  switch between XAUUSD / BTCUSD / etc.
# =============================================================================
SYMBOL = "BTCUSD"

# =============================================================================
# ACCOUNT
# =============================================================================
INITIAL_BALANCE = 20000.0

# =============================================================================
# PAIR SPECIFICATIONS
# =============================================================================
CRYPTO_PAIRS = {
    "XAUUSD": {
        "pip_size": 0.1,        # Gold: 1 pip = $0.10 (matches MT4 Point*10)
        "min_lot": 0.01,
        "max_lot": 100.0,
        "lot_step": 0.01,
        "decimals": 2,
        "ref_price": 1900.0,    # Reference price for normalization
    },
    "BTCUSD": {
        "pip_size": 0.1,
        "min_lot": 0.001,
        "max_lot": 100.0,
        "lot_step": 0.001,
        "decimals": 1,
        "ref_price": 108000.0,  # Mid-2025 actual price range (~102K-115K)
    },
    "BTCUSDT": {
        "pip_size": 0.01,
        "min_lot": 0.001,
        "max_lot": 100.0,
        "lot_step": 0.001,
        "decimals": 2,
        "ref_price": 50000.0,
    },
    "ETHUSDT": {
        "pip_size": 0.01,
        "min_lot": 0.01,
        "max_lot": 1000.0,
        "lot_step": 0.01,
        "decimals": 2,
        "ref_price": 3000.0,
    },
    "BNBUSDT": {
        "pip_size": 0.01,
        "min_lot": 0.01,
        "max_lot": 10000.0,
        "lot_step": 0.01,
        "decimals": 2,
        "ref_price": 600.0,
    },
    "XRPUSDT": {
        "pip_size": 0.0001,
        "min_lot": 1.0,
        "max_lot": 1000000.0,
        "lot_step": 1.0,
        "decimals": 4,
        "ref_price": 0.50,
    },
    "SOLUSDT": {
        "pip_size": 0.01,
        "min_lot": 0.1,
        "max_lot": 100000.0,
        "lot_step": 0.1,
        "decimals": 2,
        "ref_price": 150.0,
    },
    "DOGEUSDT": {
        "pip_size": 0.00001,
        "min_lot": 1.0,
        "max_lot": 10000000.0,
        "lot_step": 1.0,
        "decimals": 5,
        "ref_price": 0.08,
    },
}

DEFAULT_PAIR_CONFIG = {
    "pip_size": 0.01,
    "min_lot": 0.001,
    "max_lot": 100.0,
    "lot_step": 0.001,
    "decimals": 2,
    "ref_price": 1900.0,
}

# =============================================================================
# V4.12beta REFERENCE PARAMETERS  (XAUUSD Gold, pip_size=0.1)
# All pip values are calibrated for Gold at ~$1900.
# For other pairs, they auto-scale via PAIR_STRATEGY_PARAMS below.
# =============================================================================
_REF_PAIR = "XAUUSD"
_REF_PRICE = 1900.0

# --- Entry (V4: Takeprofit2=200, Stoploss2=2000) ---
_REF_ENTRY_TP_PIPS = 123          # BTC $700 (70% hit rate on M5 scan)
_REF_ENTRY_SL_PIPS = 2000         # $200 (10.5% of Gold)

# --- Recovery Grid (V4: 19 levels) ---
_REF_GRID_STEPS = [
    246, 246, 246, 317, 317, 317, 387, 387, 387, 493,
    493, 493, 563, 563, 563, 633, 633, 633, 704,
]

# --- Recovery TPs (V4: decreasing, TP4=0 disables sub-pair 4) ---
_REF_RECOVERY_TPS = [123, 62, 31, 0]

# --- Dollar targets (don't scale with pip — absolute $) ---
_REF_RECOVERY_PROFIT_TARGET = 30.0
_REF_THREAD_PROFIT_TARGET = 15.0

# =============================================================================
# AUTO-NORMALIZE: Scale pip values for the active SYMBOL
# =============================================================================
def _normalize_for_pair(symbol: str) -> dict:
    """Scale reference (Gold) pip values to the target pair.

    Normalization logic:
      scale = (target_ref_price / gold_ref_price) / (target_pip_size / gold_pip_size)

    This keeps the PERCENTAGE distance from entry identical across pairs.
    E.g., Grid L1 = ~3.16% of price for any pair.
    """
    pair_cfg = CRYPTO_PAIRS.get(symbol, DEFAULT_PAIR_CONFIG)
    ref_cfg = CRYPTO_PAIRS.get(_REF_PAIR, DEFAULT_PAIR_CONFIG)

    target_price = pair_cfg["ref_price"]
    target_pip = pair_cfg["pip_size"]
    ref_price = ref_cfg["ref_price"]
    ref_pip = ref_cfg["pip_size"]

    # scale converts Gold pips → target pips keeping same % of price
    scale = (target_price / ref_price) / (target_pip / ref_pip)

    return {
        "entry_tp_pips": round(scale * _REF_ENTRY_TP_PIPS),
        "entry_sl_pips": round(scale * _REF_ENTRY_SL_PIPS),
        "grid_steps": [round(scale * s) for s in _REF_GRID_STEPS],
        "recovery_tps": [round(scale * t) if t > 0 else 0 for t in _REF_RECOVERY_TPS],
    }

# Build normalized params for active pair
_NORM = _normalize_for_pair(SYMBOL)

# =============================================================================
# INITIAL ENTRY PARAMETERS  (auto-scaled from Gold reference)
# =============================================================================
LOT_SIZE = 0.03
ENTRY_TP_PIPS = _NORM["entry_tp_pips"]
ENTRY_SL_PIPS = 0                     # V3 BTC: Stoploss2=0 (disabled)
MAX_INITIAL_ORDERS = 10       # V3 BTC used 30; 10 for conservative multi-thread

# =============================================================================
# ENTRY TYPE ENABLES
# =============================================================================
# V4: BUY_ZONE_MIN=0, BUY_ZONE_MAX=1 → always enter (no zone filter)
ENABLE_REVERSAL_ENTRIES = False
ENABLE_CONTINUATION_ENTRIES = True

# =============================================================================
# FIBONACCI ZONE FILTERS
# =============================================================================
FIBO_BARS_BACK = 13                 # V3 BTC=13, shorter lookback for M5
FIBO_BUY_ZONE = (0.0, 1.0)         # V4: (0,1) → always allow buys
FIBO_SELL_ZONE = (0.0, 1.0)         # V4: (0,1) → always allow sells
FIBO_RANGE_ZONE = (0.0, 1.0)        # Always pass
RECOVERY_FIBO_ZONE = (0.0, 1.0)     # Recovery grid Fibo gate: (min, max), default always-pass

# =============================================================================
# ADAPTIVE GRID (auto-scale grid/TP to current volatility)
# =============================================================================
ADAPTIVE_GRID = True                 # Enable volatility-adaptive grid sizing
ADAPTIVE_ATR_BARS = 13               # Rolling ATR lookback (same as Fibo)
REFERENCE_ATR = 132.1                # Baseline ATR from M5 scan ($132.1/bar avg)
ADAPTIVE_MIN_SCALE = 0.5             # Floor: never shrink below 50% of base grid
ADAPTIVE_MAX_SCALE = 2.5             # Ceiling: never expand beyond 250% of base grid

# =============================================================================
# RECOVERY GRID  (auto-scaled)
# =============================================================================
RECOVERY_GRID_STEPS = _NORM["grid_steps"]

# =============================================================================
# RECOVERY TAKE PROFITS  (auto-scaled)
# =============================================================================
RECOVERY_TPS = _NORM["recovery_tps"]

# TP multiplier: V4: recoveryTPmultiple=1 (disabled — no cumulative TP scaling)
TP_MULTIPLIER = 1.0
TP_MULT_START_LEVEL = 5
TP_MULT_STOP_LEVEL = 8

# =============================================================================
# LOT SIZING MODE
# =============================================================================
# V4: autocalculatelots=false (loss-recovery mode)
AUTO_CALCULATE_LOTS = False
RECOVERY_PROFIT_TARGET = 30.0         # V4: $30 profit target per recovery pair
RECOVERY_LOT_MULTIPLIER = 1.1

# V4: OutsideLotMultiplier1=1.5, InsideLotMultiplier1=2.5
OUTSIDE_LOT_MULTIPLIER = 1.5
INSIDE_LOT_MULTIPLIER = 2.5

# V4: OutsideLotStart1=2, OutsideLotStop1=20, InsideLotStart1=1, InsideLotStop1=20
OUTSIDE_LOT_START = 2
OUTSIDE_LOT_STOP = 20
INSIDE_LOT_START = 1
INSIDE_LOT_STOP = 20

# =============================================================================
# REPEAT / RE-ENTRY
# =============================================================================
# V4: RepeatBothSides=false, RepeatSingleSides=true
REPEAT_BOTH_SIDES = False
REPEAT_SINGLE_SIDES = True

# =============================================================================
# BAR REVERSAL MODE
# =============================================================================
# V4: BarReversal=false
BAR_REVERSAL_MODE = False
FIRST_HEDGE_PROFIT_MIN = -9999.0    # V4: fhedgeprofit=-9999 (effectively disabled)
FIRST_HEDGE_BAR_COUNT = 1           # V4: fhedgebar=1

# =============================================================================
# THREAD PROFIT EXIT
# =============================================================================
# V4: ThreadProfit=true, threadprofit=1
THREAD_PROFIT_ENABLED = True
THREAD_PROFIT_TARGET = 15

# =============================================================================
# LOT SIZE CONSTRAINTS
# =============================================================================
MIN_LOT_SIZE = 0.001
MAX_LOT_SIZE = 15.0
LOT_STEP = 0.001

# =============================================================================
# EXECUTION COSTS
# =============================================================================
COMMISSION_PERCENT = 0.04
SLIPPAGE_PIPS = 1

# =============================================================================
# BACKTESTING DATA
# =============================================================================
SAMPLE_DATA_CANDLES = 5000
SAMPLE_START_PRICE = CRYPTO_PAIRS.get(SYMBOL, DEFAULT_PAIR_CONFIG)["ref_price"]
SAMPLE_VOLATILITY = 0.008          # ~0.8% per candle (tuned for Gold M15)

DATA_FILE_CSV = ""
DATA_FILE_JSON = ""

CSV_TIMESTAMP_COL = "timestamp"
CSV_OPEN_COL = "open"
CSV_HIGH_COL = "high"
CSV_LOW_COL = "low"
CSV_CLOSE_COL = "close"
CSV_VOLUME_COL = "volume"

# =============================================================================
# TICK DATA SETTINGS
# =============================================================================
TICK_DATA_FILE = ""
TICK_MAX_ROWS = None
TICK_SKIP_ROWS = 0
TICK_REPORT_INTERVAL = 10000

# =============================================================================
# BACKTEST OPTIONS
# =============================================================================
USE_TICK_DATA = False
TICKS_PER_CANDLE = 4

# =============================================================================
# LIVE TRADING
# =============================================================================
EXCHANGE = "simulated"
TESTNET = True
POLL_INTERVAL = 1.0

# =============================================================================
# LOGGING
# =============================================================================
LOG_LEVEL = "INFO"
LOG_FILE = "trading_bot.log"
LOG_TO_CONSOLE = True
LOG_TO_FILE = True
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

# =============================================================================
# MAGIC NUMBER
# =============================================================================
BASE_MAGIC = 100000
