"""analysis/levels.py — SL/TP calculation, Fibonacci, weekly S&R, round numbers, multi-TF confluence.""" import numpy as np import pandas as pd from config import (SR_LOOKBACK, SR_ZONE_PIPS, STRUCT_LOOKBACK, SL_BUFFER_PIPS, MIN_SL_PIPS, MIN_RR, FALLBACK_SL_PIPS, FALLBACK_TP_PIPS) from analysis.structure import detect_swings, find_sr from data.oanda import pip, digs def calc_fibonacci(df, instrument, bias, lookback=100): """ Fibonacci retracement levels from the last major swing. For SELL: finds recent swing HIGH to swing LOW — retracements are resistance For BUY: finds recent swing LOW to swing HIGH — retracements are support Key levels: 23.6%, 38.2%, 50.0%, 61.8%, 78.6% The 50% and 61.8% are the strongest — institutional accumulation zones. """ df_sw = detect_swings(df.iloc[-lookback:], n=3) d = digs(instrument) p = pip(instrument) price = df.iloc[-1]["close"] highs = df_sw["swing_high"].dropna() lows = df_sw["swing_low"].dropna() if highs.empty or lows.empty: return {"levels": {}, "nearest": None, "note": "Insufficient swings"} if bias == -1: # SELL — measure from recent high down to low swing_high = highs.iloc[-1] # Find the most recent low AFTER the high recent_lows = lows[lows.index > highs.index[-1]] swing_low = recent_lows.iloc[-1] if not recent_lows.empty else lows.iloc[-1] rng = swing_high - swing_low levels = { "23.6%": round(swing_high - 0.236 * rng, d), "38.2%": round(swing_high - 0.382 * rng, d), "50.0%": round(swing_high - 0.500 * rng, d), "61.8%": round(swing_high - 0.618 * rng, d), "78.6%": round(swing_high - 0.786 * rng, d), } swing_from, swing_to = swing_high, swing_low else: # BUY — measure from recent low up to high swing_low = lows.iloc[-1] recent_highs = highs[highs.index > lows.index[-1]] swing_high = recent_highs.iloc[-1] if not recent_highs.empty else highs.iloc[-1] rng = swing_high - swing_low levels = { "23.6%": round(swing_low + 0.236 * rng, d), "38.2%": round(swing_low + 0.382 * rng, d), "50.0%": round(swing_low + 0.500 * rng, d), "61.8%": round(swing_low + 0.618 * rng, d), "78.6%": round(swing_low + 0.786 * rng, d), } swing_from, swing_to = swing_low, swing_high # Find nearest fib level to current price nearest_key = min(levels, key=lambda k: abs(levels[k] - price)) nearest_val = levels[nearest_key] nearest_dist = abs(price - nearest_val) / p # Is price near a fib level? (within 15 pips) near_fib = nearest_dist <= 15 return { "levels": levels, "nearest": nearest_key, "nearest_val": nearest_val, "nearest_dist": round(nearest_dist, 1), "near_fib": near_fib, "swing_from": round(swing_from, d), "swing_to": round(swing_to, d), "range_pips": round(rng / p, 0), "note": f"Fib from {swing_from:.{d}f} to {swing_to:.{d}f} ({rng/p:.0f} pips)", } def calc_levels(df_ltf, df_mtf, instrument, direction, entry): """ Level-based SL/TP with: - ATR comparison: uses tighter of swing-based SL vs 1.5×ATR - Multiple TP targets: TP1 (1:1), TP2 (next S&R), TP3 (extended S&R) - Fibonacci confluence: checks if TP levels align with fib retracements """ p = pip(instrument) d = digs(instrument) buf = SL_BUFFER_PIPS * p # ATR for volatility-adaptive SL atr = df_ltf.iloc[-1].get("atr", 0) if "atr" in df_ltf.columns else 0 atr_sl = atr * 1.5 # 1.5× ATR is standard institutional SL buffer # Swing-based SL ltf_sw = detect_swings(df_ltf) recent = ltf_sw.iloc[-STRUCT_LOOKBACK:] if direction == "buy": lows = recent["swing_low"].dropna() valid = lows[lows < entry].sort_index() if not valid.empty: sw_sl = round(valid.iloc[-1] - buf, d) sl_src = f"Swing low @ {valid.iloc[-1]:.{d}f} −{SL_BUFFER_PIPS}pip" else: sw_sl = round(entry - FALLBACK_SL_PIPS * p, d) sl_src = f"Fallback {FALLBACK_SL_PIPS} pips" # ATR-based SL atr_sl_price = round(entry - atr_sl, d) if atr_sl > 0 else sw_sl # Use whichever gives tighter (less risk) but still above minimum sl = max(sw_sl, atr_sl_price) if atr_sl > 0 else sw_sl # max = closer to entry for buys if atr_sl > 0 and sl != sw_sl: sl_src += f" | ATR(1.5×)={atr/p:.1f}pip → using ATR SL" if (entry - sl) < MIN_SL_PIPS * p: sl = round(entry - MIN_SL_PIPS * p, d) sl_src += " [floored]" else: highs = recent["swing_high"].dropna() valid = highs[highs > entry].sort_index() if not valid.empty: sw_sl = round(valid.iloc[-1] + buf, d) sl_src = f"Swing high @ {valid.iloc[-1]:.{d}f} +{SL_BUFFER_PIPS}pip" else: sw_sl = round(entry + FALLBACK_SL_PIPS * p, d) sl_src = f"Fallback {FALLBACK_SL_PIPS} pips" atr_sl_price = round(entry + atr_sl, d) if atr_sl > 0 else sw_sl sl = min(sw_sl, atr_sl_price) if atr_sl > 0 else sw_sl # min = closer to entry for sells if atr_sl > 0 and sl != sw_sl: sl_src += f" | ATR(1.5×)={atr/p:.1f}pip → using ATR SL" if (sl - entry) < MIN_SL_PIPS * p: sl = round(entry + MIN_SL_PIPS * p, d) sl_src += " [floored]" sl_pips = abs(entry - sl) / p # Multiple TP targets from S&R levels sr_levels = find_sr(df_mtf, instrument) # TP must be at least MIN_RR × SL distance away (enforces 2.0 R:R minimum) min_tp_dist = sl_pips * MIN_RR * p if direction == "buy": tgts = sorted([l for l in sr_levels if l > entry + min_tp_dist]) tp1 = round(entry + sl_pips * p, d) # 1:1 RR tp2 = round(tgts[0], d) if len(tgts) > 0 else round(entry + sl_pips * MIN_RR * p, d) tp3 = round(tgts[1], d) if len(tgts) > 1 else round(tp2 + (tp2 - entry) * 0.5, d) tp = tp2 # primary TP tp_src = f"4H resistance @ {tp2:.{d}f}" if tgts else f"Min {MIN_RR}R:R target" else: tgts = sorted([l for l in sr_levels if l < entry - min_tp_dist], reverse=True) tp1 = round(entry - sl_pips * p, d) # 1:1 RR tp2 = round(tgts[0], d) if len(tgts) > 0 else round(entry - sl_pips * MIN_RR * p, d) tp3 = round(tgts[1], d) if len(tgts) > 1 else round(tp2 - (entry - tp2) * 0.5, d) tp = tp2 tp_src = f"4H support @ {tp2:.{d}f}" if tgts else f"Min {MIN_RR}R:R target" tp_pips = abs(tp - entry) / p tp1_pips = abs(tp1 - entry) / p tp2_pips = abs(tp2 - entry) / p tp3_pips = abs(tp3 - entry) / p rr = round(tp_pips / sl_pips, 2) if sl_pips > 0 else 0 rr2 = round(tp2_pips / sl_pips, 2) if sl_pips > 0 else 0 rr3 = round(tp3_pips / sl_pips, 2) if sl_pips > 0 else 0 # Breakeven level (move SL here after TP1) be_level = round(entry + buf if direction == "buy" else entry - buf, d) return { "entry": round(entry, d), "sl": sl, "tp": tp, "tp1": tp1, # 1:1 close 40% "tp2": tp2, # main target close 40% "tp3": tp3, # extended target close 20% "be": be_level, # breakeven level "sl_pips": round(sl_pips, 1), "tp_pips": round(tp_pips, 1), "tp1_pips": round(tp1_pips, 1), "tp2_pips": round(tp2_pips, 1), "tp3_pips": round(tp3_pips, 1), "rr_ratio": rr, "rr2": rr2, "rr3": rr3, "good_rr": rr >= MIN_RR, "sl_source": sl_src, "tp_source": tp_src, "digits": d, "atr_pips": round(atr / p, 1) if atr > 0 else None, } # ══════════════════════════════════════════════════════