marketedgeAI / core /patterns.py
SKaush's picture
Upload 32 files
176e688 verified
Raw History Blame Contribute Delete
37.8 kB
"""MarketEdge AI — Pattern Detection
All chart patterns, RSI cycles, divergence, setups.
"""
import numpy as np
import pandas as pd
from datetime import datetime, timezone
from config.constants import RSI_OB, RSI_OS, ADX_MIN, EMA_FAST, EMA_SLOW
from core.indicators import pip
def detect_head_and_shoulders(df, bias):
"""
Head & Shoulders (bearish reversal) / Inverse H&S (bullish reversal).
Logic:
Find 3 swing highs (or lows for inverse):
Left shoulder → Head (highest) → Right shoulder
Left & right shoulders roughly equal height (within 30% of head)
Neckline = line connecting the two troughs between shoulders
Confirmation = price breaks neckline
Returns: (detected: bool, note: str, neckline: float or None)
"""
df = detect_swings(df)
recent = df.iloc[-60:] # look back 60 bars
if bias == -1: # Head & Shoulders (bearish)
peaks = recent["swing_high"].dropna()
if len(peaks) < 3:
return False, "H&S: insufficient peaks", None
p = peaks.values[-3:] # last 3 swing highs
left, head, right = p[0], p[1], p[2]
head_is_highest = head > left and head > right
shoulders_equal = abs(left - right) / head < 0.30 # within 30% of head
if not (head_is_highest and shoulders_equal):
return False, "H&S: peak shape not valid", None
# Neckline from the two troughs between shoulders
troughs = recent["swing_low"].dropna()
trough_vals = troughs.values
if len(trough_vals) < 2:
return False, "H&S: no neckline troughs", None
neckline = np.mean(trough_vals[-2:])
price_now = df.iloc[-1]["close"]
broken = price_now < neckline # price broke below neckline
note = (f"H&S: L:{left:.5f} H:{head:.5f} R:{right:.5f} "
f"Neckline:{neckline:.5f} Break:{'✅' if broken else '⏳ forming'}")
return broken, note, neckline
else: # Inverse H&S (bullish)
troughs = recent["swing_low"].dropna()
if len(troughs) < 3:
return False, "Inv H&S: insufficient troughs", None
t = troughs.values[-3:]
left, head, right = t[0], t[1], t[2]
head_is_lowest = head < left and head < right
shoulders_equal = abs(left - right) / abs(head) < 0.30
if not (head_is_lowest and shoulders_equal):
return False, "Inv H&S: trough shape not valid", None
peaks = recent["swing_high"].dropna()
if len(peaks) < 2:
return False, "Inv H&S: no neckline peaks", None
neckline = np.mean(peaks.values[-2:])
price_now = df.iloc[-1]["close"]
broken = price_now > neckline
note = (f"Inv H&S: L:{left:.5f} H:{head:.5f} R:{right:.5f} "
f"Neckline:{neckline:.5f} Break:{'✅' if broken else '⏳ forming'}")
return broken, note, neckline
def detect_double_top_bottom(df, bias):
"""
Double Top (bearish) / Double Bottom (bullish).
Logic:
Two swing highs/lows at roughly the same price level (within 0.3%)
Valley/peak between them at least 1% away
Price has since broken through the valley/peak (confirmation)
Returns: (detected: bool, note: str)
"""
df = detect_swings(df)
recent = df.iloc[-50:]
if bias == -1: # Double Top
peaks = recent["swing_high"].dropna()
if len(peaks) < 2:
return False, "Dbl Top: insufficient peaks"
p1, p2 = peaks.values[-2], peaks.values[-1]
similar = abs(p1 - p2) / max(p1, p2) < 0.003 # within 0.3%
if not similar:
return False, f"Dbl Top: peaks too different ({p1:.5f} vs {p2:.5f})"
troughs = recent["swing_low"].dropna()
if troughs.empty:
return False, "Dbl Top: no trough between peaks"
valley = troughs.values[-1]
deep_enough = (min(p1, p2) - valley) / min(p1, p2) > 0.01
price_now = df.iloc[-1]["close"]
confirmed = price_now < valley
note = (f"Dbl Top: {p1:.5f} & {p2:.5f} Valley:{valley:.5f} "
f"Break:{'✅' if confirmed else '⏳'}")
return confirmed and deep_enough, note
else: # Double Bottom
troughs = recent["swing_low"].dropna()
if len(troughs) < 2:
return False, "Dbl Bot: insufficient troughs"
t1, t2 = troughs.values[-2], troughs.values[-1]
similar = abs(t1 - t2) / max(abs(t1), abs(t2)) < 0.003
if not similar:
return False, f"Dbl Bot: troughs too different ({t1:.5f} vs {t2:.5f})"
peaks = recent["swing_high"].dropna()
if peaks.empty:
return False, "Dbl Bot: no peak between troughs"
peak = peaks.values[-1]
deep_enough = (peak - max(t1, t2)) / peak > 0.01
price_now = df.iloc[-1]["close"]
confirmed = price_now > peak
note = (f"Dbl Bot: {t1:.5f} & {t2:.5f} Peak:{peak:.5f} "
f"Break:{'✅' if confirmed else '⏳'}")
return confirmed and deep_enough, note
def detect_flag(df, bias):
"""
Bull Flag (bullish continuation) / Bear Flag (bearish continuation).
Logic:
Strong impulse move (flagpole) in bias direction over last 10-15 bars
→ Price moved > 0.5% in one direction
Followed by tight consolidation (flag) retracing 30-60% of the move
EMA20 still pointing in bias direction during consolidation
Current bar breaking out of flag in bias direction
Returns: (detected: bool, note: str)
"""
recent = df.iloc[-20:].copy()
pole = df.iloc[-20:-8] # flagpole period
flag = df.iloc[-8:] # flag/consolidation period
if pole.empty or flag.empty:
return False, "Flag: insufficient data"
pole_move = pole["close"].iloc[-1] - pole["close"].iloc[0]
pole_pct = abs(pole_move) / pole["close"].iloc[0] * 100
flag_range = flag["high"].max() - flag["low"].min()
flag_retrace = flag_range / abs(pole_move) if abs(pole_move) > 0 else 1
if pole_pct < 0.5:
return False, f"Flag: pole too small ({pole_pct:.2f}%)"
if flag_retrace > 0.65:
return False, f"Flag: too deep ({flag_retrace:.0%} retrace)"
price_now = df.iloc[-1]["close"]
flag_high = flag["high"].max()
flag_low = flag["low"].min()
ema_ok = df.iloc[-1]["ma_fast"] > df.iloc[-2]["ma_fast"] if bias == 1 else df.iloc[-1]["ma_fast"] < df.iloc[-2]["ma_fast"]
if bias == 1: # Bull flag
pole_up = pole_move > 0
breakout = price_now > flag_high
ok = pole_up and breakout and ema_ok
note = (f"Bull Flag: pole +{pole_pct:.2f}% retrace:{flag_retrace:.0%} "
f"Breakout:{'✅' if breakout else '⏳'}")
else: # Bear flag
pole_down = pole_move < 0
breakout = price_now < flag_low
ok = pole_down and breakout and ema_ok
note = (f"Bear Flag: pole -{pole_pct:.2f}% retrace:{flag_retrace:.0%} "
f"Breakout:{'✅' if breakout else '⏳'}")
return ok, note
def detect_triangle(df, bias):
"""
Ascending Triangle (bullish) / Descending Triangle (bearish).
Logic:
Ascending: flat resistance (highs roughly equal) + rising lows → bullish breakout
Descending: flat support (lows roughly equal) + falling highs → bearish breakout
Uses linear regression on highs and lows over last 30 bars
Ascending → slope of lows > 0, slope of highs ≈ 0
Descending → slope of highs < 0, slope of lows ≈ 0
Breakout confirmed when price crosses the flat side
Returns: (detected: bool, note: str)
"""
recent = df.iloc[-30:].copy()
if len(recent) < 15:
return False, "Triangle: insufficient data"
x = np.arange(len(recent))
# Linear regression slopes
high_slope = np.polyfit(x, recent["high"].values, 1)[0]
low_slope = np.polyfit(x, recent["low"].values, 1)[0]
price_now = df.iloc[-1]["close"]
resistance = recent["high"].max()
support = recent["low"].min()
if bias == 1: # Ascending triangle
rising_lows = low_slope > 0.00001
flat_highs = abs(high_slope) < abs(low_slope) * 0.3
breakout = price_now > resistance * 0.999
ok = rising_lows and flat_highs and breakout
note = (f"Asc Triangle: low slope:{low_slope:.6f} high slope:{high_slope:.6f} "
f"Breakout:{'✅' if breakout else '⏳ ' + str(round(resistance,5))}")
else: # Descending triangle
falling_highs = high_slope < -0.00001
flat_lows = abs(low_slope) < abs(high_slope) * 0.3
breakout = price_now < support * 1.001
ok = falling_highs and flat_lows and breakout
note = (f"Desc Triangle: high slope:{high_slope:.6f} low slope:{low_slope:.6f} "
f"Breakout:{'✅' if breakout else '⏳ ' + str(round(support,5))}")
return ok, note
def detect_engulfing(df, bias):
"""
Bullish / Bearish Engulfing candle — strongest single-bar reversal signal.
Logic:
Previous candle moves against bias (small pullback candle)
Current candle completely engulfs previous candle body in bias direction
Current candle body is at least 1.5x size of previous candle body
Occurs near a key EMA or S&R level (adds confluence)
Returns: (detected: bool, note: str)
"""
if len(df) < 3:
return False, "Engulfing: insufficient data"
curr = df.iloc[-1]
prev = df.iloc[-2]
curr_body = abs(curr["close"] - curr["open"])
prev_body = abs(prev["close"] - prev["open"])
if prev_body == 0:
return False, "Engulfing: zero body candle"
size_ratio = curr_body / prev_body
if bias == 1: # Bullish engulfing
prev_bearish = prev["close"] < prev["open"]
curr_bullish = curr["close"] > curr["open"]
engulfs = curr["open"] <= prev["close"] and curr["close"] >= prev["open"]
strong_enough = size_ratio >= 1.5
ok = prev_bearish and curr_bullish and engulfs and strong_enough
note = (f"Bullish Engulf: ratio:{size_ratio:.1f}x "
f"{'✅' if ok else '❌ not confirmed'}")
else: # Bearish engulfing
prev_bullish = prev["close"] > prev["open"]
curr_bearish = curr["close"] < curr["open"]
engulfs = curr["open"] >= prev["close"] and curr["close"] <= prev["open"]
strong_enough = size_ratio >= 1.5
ok = prev_bullish and curr_bearish and engulfs and strong_enough
note = (f"Bearish Engulf: ratio:{size_ratio:.1f}x "
f"{'✅' if ok else '❌ not confirmed'}")
return ok, note
def run_all_patterns(df_mtf, df_ltf, bias):
"""
Run all 5 pattern detections.
MTF (4H) patterns: H&S, Double Top/Bottom, Triangle (structural patterns)
LTF (1H) patterns: Flag, Engulfing (entry timing patterns)
Returns a dict of pattern results and an overall pattern score.
"""
results = {}
# ── 4H structural patterns ────────────────────────
ok, note, neckline = detect_head_and_shoulders(df_mtf, bias)
results["hs"] = {"ok": ok, "note": note, "neckline": neckline, "tf": "4H"}
ok, note = detect_double_top_bottom(df_mtf, bias)
results["double"] = {"ok": ok, "note": note, "tf": "4H"}
ok, note = detect_triangle(df_mtf, bias)
results["triangle"] = {"ok": ok, "note": note, "tf": "4H"}
# ── 1H entry patterns ─────────────────────────────
ok, note = detect_flag(df_ltf, bias)
results["flag"] = {"ok": ok, "note": note, "tf": "1H"}
ok, note = detect_engulfing(df_ltf, bias)
results["engulfing"] = {"ok": ok, "note": note, "tf": "1H"}
# Pattern score: how many detected
pattern_score = sum(1 for v in results.values() if v["ok"])
any_pattern = pattern_score > 0
# Best pattern for SL/TP override
best = None
if results["hs"]["ok"] and results["hs"].get("neckline"):
best = {"type": "H&S", "neckline": results["hs"]["neckline"]}
elif results["double"]["ok"]:
best = {"type": "Double Top/Bottom"}
return {
"patterns": results,
"pattern_score": pattern_score,
"any_pattern": any_pattern,
"best": best,
}
# ══════════════════════════════════════════════════════
# ADDITIONAL SETUPS
# ══════════════════════════════════════════════════════
# ── Setup 1: RSI Divergence ───────────────────────────
def detect_rsi_divergence(df, bias, lookback=20):
"""
RSI Divergence — price and RSI moving in opposite directions.
Bullish divergence (bias=1):
Price makes a lower low BUT RSI makes a higher low
→ Selling momentum weakening, reversal likely up
Bearish divergence (bias=-1):
Price makes a higher high BUT RSI makes a lower high
→ Buying momentum weakening, reversal likely down
Uses last `lookback` bars to find swing points.
Returns (detected, note, strength)
"""
if len(df) < lookback + 5:
return False, "Insufficient data", 0
recent = df.iloc[-lookback:]
price = recent["close"]
rsi = recent["rsi"]
if bias == 1: # Bullish divergence
# Find two recent price lows
price_lows = []
rsi_lows = []
for i in range(2, len(recent)-2):
if price.iloc[i] < price.iloc[i-1] and price.iloc[i] < price.iloc[i+1]:
price_lows.append((i, price.iloc[i], rsi.iloc[i]))
if len(price_lows) < 2:
return False, "Not enough price lows for divergence", 0
# Get last two swing lows
p1_idx, p1_price, p1_rsi = price_lows[-2]
p2_idx, p2_price, p2_rsi = price_lows[-1]
# Bullish divergence: price lower low, RSI higher low
price_lower = p2_price < p1_price
rsi_higher = p2_rsi > p1_rsi
diverging = price_lower and rsi_higher
if diverging:
strength = round((p2_rsi - p1_rsi) / max(abs(p1_price - p2_price) / pip("EUR_USD"), 1), 2)
note = (f"Bullish divergence: Price {p1_price:.5f}→{p2_price:.5f} (↓) "
f"RSI {p1_rsi:.1f}→{p2_rsi:.1f} (↑)")
return True, note, min(strength, 3.0)
return False, f"No bullish divergence (Price:{'↓' if price_lower else '↑'} RSI:{'↑' if rsi_higher else '↓'})", 0
else: # Bearish divergence
price_highs = []
for i in range(2, len(recent)-2):
if price.iloc[i] > price.iloc[i-1] and price.iloc[i] > price.iloc[i+1]:
price_highs.append((i, price.iloc[i], rsi.iloc[i]))
if len(price_highs) < 2:
return False, "Not enough price highs for divergence", 0
p1_idx, p1_price, p1_rsi = price_highs[-2]
p2_idx, p2_price, p2_rsi = price_highs[-1]
price_higher = p2_price > p1_price
rsi_lower = p2_rsi < p1_rsi
diverging = price_higher and rsi_lower
if diverging:
strength = round((p1_rsi - p2_rsi) / max(abs(p2_price - p1_price) / pip("EUR_USD"), 1), 2)
note = (f"Bearish divergence: Price {p1_price:.5f}→{p2_price:.5f} (↑) "
f"RSI {p1_rsi:.1f}→{p2_rsi:.1f} (↓)")
return True, note, min(strength, 3.0)
return False, f"No bearish divergence", 0
# ── Setup 2: EMA50 Pullback ───────────────────────────
def detect_ema50_pullback(df, bias):
"""
EMA50 Pullback — price pulls back to touch EMA50 in a trend
without a crossover, then bounces. Higher conviction than a
crossover because the trend structure is intact.
Bull: Price was above EMA50, dipped to within 5 pips, now recovering
Bear: Price was below EMA50, rallied to within 5 pips, now falling
Returns (detected, note)
"""
if len(df) < 10: return False, "Insufficient data"
row = df.iloc[-1]
prev = df.iloc[-2]
p = pip("EUR_USD") # approximate pip for distance calc
zone = 5 * p # within 5 pips = "touching"
if bias == 1:
# Price should be above EMA20 (trend intact)
trend_ok = row["ma_fast"] > row["ma_slow"] # EMA20 > EMA50
# Price recently touched EMA50
touched_ema = any(
abs(df["close"].iloc[i] - df["ma_slow"].iloc[i]) < zone * 3
for i in range(-6, -1)
)
# Now recovering — close above EMA50 and rising
recovering = row["close"] > row["ma_slow"] and row["close"] > prev["close"]
# RSI not overbought
rsi_ok = row["rsi"] < RSI_OB
ok = trend_ok and touched_ema and recovering and rsi_ok
note = (f"EMA50 pullback bull: touch={'✅' if touched_ema else '❌'} "
f"recover={'✅' if recovering else '❌'} RSI:{row['rsi']:.1f}")
return ok, note
else:
trend_ok = row["ma_fast"] < row["ma_slow"]
touched_ema = any(
abs(df["close"].iloc[i] - df["ma_slow"].iloc[i]) < zone * 3
for i in range(-6, -1)
)
recovering = row["close"] < row["ma_slow"] and row["close"] < prev["close"]
rsi_ok = row["rsi"] > RSI_OS
ok = trend_ok and touched_ema and recovering and rsi_ok
note = (f"EMA50 pullback bear: touch={'✅' if touched_ema else '❌'} "
f"recover={'✅' if recovering else '❌'} RSI:{row['rsi']:.1f}")
return ok, note
# ── Setup 3: Failed Breakout Reversal ─────────────────
def detect_failed_breakout(df, bias, instrument):
"""
Failed Breakout — price breaks a key S&R level but fails to hold,
then reverses back through the level. High probability setup.
Bull failed breakout → SELL:
Price broke above resistance, came back below → short opportunity
Bear failed breakout → BUY:
Price broke below support, came back above → long opportunity
We check:
- There was a S&R level nearby
- Recent candles broke beyond it
- Current price has returned back through it (failed)
- Volume was low on the break (weak breakout)
"""
if len(df) < 20: return False, "Insufficient data"
levels = find_sr(df, instrument)
if not levels: return False, "No S&R levels"
row = df.iloc[-1]
prev5 = df.iloc[-6:-1]
p = pip(instrument)
zone = 10 * p
if bias == -1: # Looking for failed bull breakout → SELL
# Find resistance levels above recent price
resistance = [l for l in levels if l > df["close"].iloc[-10:].min()]
if not resistance: return False, "No resistance levels"
nearest = min(resistance, key=lambda l: abs(row["close"]-l))
# Check if price previously broke above this level
broke_above = any(prev5["high"] > nearest + zone)
# Now back below
back_below = row["close"] < nearest
# Low volume on break (weak breakout signal)
break_vol = prev5["vol_ratio"].max()
weak_break = break_vol < 1.5
ok = broke_above and back_below
note = (f"Failed bull breakout: broke {nearest:.5f}, back below {'✅' if back_below else '❌'} "
f"vol_ratio:{break_vol:.1f}")
return ok, note
else: # Looking for failed bear breakout → BUY
support = [l for l in levels if l < df["close"].iloc[-10:].max()]
if not support: return False, "No support levels"
nearest = min(support, key=lambda l: abs(row["close"]-l))
broke_below = any(prev5["low"] < nearest - zone)
back_above = row["close"] > nearest
break_vol = prev5["vol_ratio"].max()
ok = broke_below and back_above
note = (f"Failed bear breakout: broke {nearest:.5f}, back above {'✅' if back_above else '❌'} "
f"vol_ratio:{break_vol:.1f}")
return ok, note
# ── Setup 4: Session Open Breakout ────────────────────
def detect_session_breakout(df_ltf, bias):
"""
Session Open Breakout — strong directional move in the first
60 minutes of London (07:00 UTC) or NY (12:00 UTC) open.
Logic:
Find the high/low of the pre-session range (last 2 hours before open)
If current price breaks above/below that range → breakout confirmed
Volume should be above average on the break bar
Returns (detected, note)
"""
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
hour = now.hour
# Only valid in first 60 min of London or NY open
is_london_open = 7 <= hour <= 8
is_ny_open = 12 <= hour <= 13
if not (is_london_open or is_ny_open):
return False, "Not session open time"
if len(df_ltf) < 10: return False, "Insufficient data"
# Pre-session range: bars from 2 hours before open
pre_session = df_ltf.iloc[-4:-1] # last 3 bars before current
if pre_session.empty: return False, "No pre-session data"
range_high = pre_session["high"].max()
range_low = pre_session["low"].min()
range_size = (range_high - range_low) / pip("EUR_USD")
# Range must be meaningful (not too tight, not too wide)
if range_size < 5 or range_size > 80:
return False, f"Range size {range_size:.0f} pips — not suitable"
row = df_ltf.iloc[-1]
vol_ok = row["vol_ratio"] > 1.2 # above average volume
session = "London" if is_london_open else "New York"
if bias == 1:
broke_out = row["close"] > range_high
ok = broke_out and vol_ok
note = (f"{session} open breakout ↑: range {range_low:.5f}–{range_high:.5f} "
f"({range_size:.0f}pips) break={'✅' if broke_out else '❌'} vol={'✅' if vol_ok else '❌'}")
else:
broke_out = row["close"] < range_low
ok = broke_out and vol_ok
note = (f"{session} open breakout ↓: range {range_low:.5f}–{range_high:.5f} "
f"({range_size:.0f}pips) break={'✅' if broke_out else '❌'} vol={'✅' if vol_ok else '❌'}")
return ok, note
# ── Setup 5: SMA200 Rejection ─────────────────────────
def detect_rsi_cycle_completion(df, bias, lookback=15):
"""
RSI Cycle Completion — detects when a relief bounce/pullback
is COMPLETE and the trend is resuming.
This is the pattern you identified on NZD/USD:
Phase 1: Impulse move → RSI drops to 30-35 (bear) or rises to 65-70 (bull)
Phase 2: Relief bounce → RSI recovers to 45-55 (bear) or dips to 45-55 (bull)
Phase 3: Continuation → RSI peaks and turns back down (bear) or troughs and up (bull)
We detect the START of Phase 3 — the moment the bounce is over.
BEARISH cycle completion (bias=-1):
- RSI fell to oversold area (< 40) in last 20 bars → Phase 1 confirmed
- RSI bounced back up (rose for 3+ bars) → Phase 2 confirmed
- RSI has now peaked and is turning down again → Phase 3 starting
- Price closed BELOW a key level (not just a wick) → Breakdown confirmed
- RSI peak during bounce < previous peak (lower high) → Hidden bearish weakness
BULLISH cycle completion (bias=1):
- RSI rose to overbought area (> 60) in last 20 bars → Phase 1 confirmed
- RSI pulled back down (fell for 3+ bars) → Phase 2 confirmed
- RSI has now troughed and is turning up again → Phase 3 starting
Returns: (detected, note, phase_info)
"""
if len(df) < lookback + 5:
return False, "Insufficient data for cycle detection", {}
rsi = df["rsi"]
close = df["close"]
recent = df.iloc[-lookback:]
row = df.iloc[-1]
prev = df.iloc[-2]
if bias == -1: # BEARISH — look for bounce completion
# Phase 1: RSI reached oversold territory (< 42) recently
phase1_ok = (recent["rsi"] < 42).any()
# Phase 2: RSI bounced — find the local peak in recent bars
rsi_recent = rsi.iloc[-12:].values
rsi_peak = max(rsi_recent)
peak_idx = list(rsi_recent).index(rsi_peak)
phase2_ok = rsi_peak > 40 and peak_idx < len(rsi_recent) - 1
# Phase 3: RSI has turned down from peak
bars_after_peak = len(rsi_recent) - 1 - peak_idx
phase3_ok = (bars_after_peak >= 1 and
row["rsi"] < rsi_peak and
row["rsi"] < prev["rsi"])
# Lower high: RSI peak during bounce < previous cycle peak
prev_window = df.iloc[-30:-12]
prev_peak = prev_window["rsi"].max() if len(prev_window) > 0 else rsi_peak
lower_high = rsi_peak < prev_peak
# ── KEY LEVEL CLOSE CHECK ─────────────────────────
# This is the most important confirmation:
# The candle must CLOSE below a key S&R level — not just wick through.
# A close below the level confirms sellers have control.
# e.g. NZD/USD: "wait for 4H to close below 0.5700"
#
# Method: find the nearest S&R level ABOVE current price
# (resistance that price bounced to during Phase 2).
# Current close must be below that level.
# Also check close is below recent swing low (structure break).
# Find nearest resistance above current close (from swing highs)
df_sw = detect_swings(df, n=2)
swing_highs = df_sw["swing_high"].dropna()
swing_lows = df_sw["swing_low"].dropna()
price_now = row["close"]
# Resistance: nearest swing high above current price
res_above = swing_highs[swing_highs > price_now].sort_values()
# Support: nearest swing low below current price
sup_below = swing_lows[swing_lows < price_now].sort_values(ascending=False)
# Closed below resistance (Phase 2 bounce peak acted as resistance)
# Find the bounce peak price (not RSI peak)
bounce_window = df.iloc[-12:]
bounce_high = bounce_window["high"].max()
closed_below_bounce = price_now < bounce_high # below the bounce high
# Closed below a key swing level (structure confirmed)
if not sup_below.empty:
nearest_sup = sup_below.iloc[0]
# Check if close breaks below the most recent swing low
prev_swing_low = swing_lows.iloc[-2] if len(swing_lows) >= 2 else nearest_sup
struct_break = price_now < prev_swing_low
else:
struct_break = False
prev_swing_low = None
# Level close: at minimum, current candle closed below previous candle's low
# (this confirms the candle is a genuine bearish close, not just a pullback)
candle_close_ok = row["close"] < prev["low"]
# Combined level close check:
# Either candle closed below prev candle low (bearish close)
# OR price broke below a swing low (structure break)
level_close_ok = candle_close_ok or struct_break
# Overall detection — ALL phases + level close
price_ok = row["close"] < prev["close"]
detected = phase1_ok and phase2_ok and phase3_ok and price_ok and level_close_ok
# Build informative note
level_note = (f"ClosedBelowSwing:{prev_swing_low:.5f}✅" if struct_break
else f"BearishClose(below prev low)✅" if candle_close_ok
else f"LevelClose:❌(close:{price_now:.5f} prev_low:{prev['low']:.5f})")
note = (f"RSI cycle {'✅' if detected else '❌'}: "
f"P1(oversold<42):{'✅' if phase1_ok else '❌'} "
f"P2(bounce peak:{rsi_peak:.1f}):{'✅' if phase2_ok else '❌'} "
f"P3(turning↓ {bars_after_peak}bars):{'✅' if phase3_ok else '❌'} "
f"LowerHigh:{'✅' if lower_high else '—'} "
f"{level_note}")
return detected, note, {
"phase1": phase1_ok,
"phase2": phase2_ok,
"phase3": phase3_ok,
"rsi_peak": round(rsi_peak, 1),
"lower_high": lower_high,
"bars_after_peak": bars_after_peak,
"level_close": level_close_ok,
"candle_close_ok": candle_close_ok,
"struct_break": struct_break,
"prev_swing_low": round(prev_swing_low, 5) if prev_swing_low else None,
}
else: # BULLISH — look for pullback completion
# Phase 1: RSI reached overbought territory (> 58) recently
phase1_ok = (recent["rsi"] > 58).any()
# Phase 2: RSI pulled back — find the local trough
rsi_recent = rsi.iloc[-12:].values
rsi_trough = min(rsi_recent)
trough_idx = list(rsi_recent).index(rsi_trough)
phase2_ok = rsi_trough < 60 and trough_idx < len(rsi_recent) - 1
# Phase 3: RSI turned up from trough
bars_after_trough = len(rsi_recent) - 1 - trough_idx
phase3_ok = (bars_after_trough >= 1 and
row["rsi"] > rsi_trough and
row["rsi"] > prev["rsi"])
prev_window = df.iloc[-30:-12]
prev_trough = prev_window["rsi"].min() if len(prev_window) > 0 else rsi_trough
higher_low = rsi_trough > prev_trough
price_ok = row["close"] > prev["close"]
# ── KEY LEVEL CLOSE CHECK (BULLISH) ──────────────
# Candle must CLOSE above a key level — not just wick through
# Bullish: close above previous candle's high = genuine bullish close
df_sw = detect_swings(df, n=2)
swing_lows = df_sw["swing_low"].dropna()
price_now = row["close"]
# Closed above previous candle high (bullish close confirmation)
candle_close_ok = row["close"] > prev["high"]
# Structure break: closed above a swing high
swing_highs_df = df_sw["swing_high"].dropna()
sup_above = swing_highs_df[swing_highs_df < price_now].sort_values(ascending=False)
prev_swing_high = swing_highs_df.iloc[-2] if len(swing_highs_df) >= 2 else None
struct_break = (prev_swing_high is not None and price_now > prev_swing_high)
level_close_ok = candle_close_ok or struct_break
price_ok = row["close"] > prev["close"]
detected = phase1_ok and phase2_ok and phase3_ok and price_ok and level_close_ok
level_note = (f"ClosedAboveSwing:{prev_swing_high:.5f}✅" if struct_break
else f"BullishClose(above prev high)✅" if candle_close_ok
else f"LevelClose:❌(close:{price_now:.5f} prev_high:{prev['high']:.5f})")
note = (f"RSI cycle {'✅' if detected else '❌'}: "
f"P1(OB>58):{'✅' if phase1_ok else '❌'} "
f"P2(pullback trough:{rsi_trough:.1f}):{'✅' if phase2_ok else '❌'} "
f"P3(turning↑ {bars_after_trough}bars):{'✅' if phase3_ok else '❌'} "
f"HigherLow:{'✅' if higher_low else '—'} "
f"{level_note}")
return detected, note, {
"phase1": phase1_ok,
"phase2": phase2_ok,
"phase3": phase3_ok,
"rsi_trough": round(rsi_trough, 1),
"higher_low": higher_low,
"bars_after_trough": bars_after_trough,
"level_close": level_close_ok,
"candle_close_ok": candle_close_ok,
"struct_break": struct_break,
"prev_swing_high": round(prev_swing_high, 5) if prev_swing_high else None,
}
def detect_rsi_ma_bounce(df, bias):
"""
RSI SMA-9 Bounce — 4H bonus confluence check.
Bullish bounce (bias=1):
RSI dipped below its SMA9 recently (last 5 bars)
RSI is now back above SMA9 and rising
→ Momentum pulled back to average and is resuming upward
Bearish bounce (bias=-1):
RSI rallied above its SMA9 recently (last 5 bars)
RSI is now back below SMA9 and falling
→ Momentum bounced to average and is resuming downward
This is a bonus +0.5 — not a required check.
Most valuable in trending markets (ADX > 20).
Returns: (detected: bool, note: str, rsi_val: float, rsi_ma_val: float)
"""
if "rsi_ma" not in df.columns or len(df) < RSI_MA_PERIOD + 3:
return False, "RSI MA not available", 0, 0
row = df.iloc[-1]
prev = df.iloc[-2]
recent = df.iloc[-6:-1] # last 5 bars before current
rsi_now = row["rsi"]
rsi_ma_now = row["rsi_ma"]
rsi_prev = prev["rsi"]
if pd.isna(rsi_ma_now): return False, "RSI MA not ready", rsi_now, 0
if bias == 1: # Bullish — RSI bouncing up off SMA9
# Recently dipped below SMA9
dipped_below = any(recent["rsi"] < recent["rsi_ma"])
# Now back above SMA9
back_above = rsi_now > rsi_ma_now
# RSI rising
rsi_rising = rsi_now > rsi_prev
# SMA9 itself is rising or flat (not falling steeply)
ma_direction = rsi_ma_now >= df["rsi_ma"].iloc[-4]
detected = dipped_below and back_above and rsi_rising
note = (f"RSI({rsi_now:.1f}) bounced off SMA9({rsi_ma_now:.1f}) ↑ "
f"{'✅' if detected else '❌'} "
f"| dip:{'✅' if dipped_below else '❌'} "
f"above:{'✅' if back_above else '❌'} "
f"rising:{'✅' if rsi_rising else '❌'}")
else: # Bearish — RSI bouncing down off SMA9
# Recently rallied above SMA9
rallied_above = any(recent["rsi"] > recent["rsi_ma"])
# Now back below SMA9
back_below = rsi_now < rsi_ma_now
# RSI falling
rsi_falling = rsi_now < rsi_prev
# SMA9 itself is falling or flat
ma_direction = rsi_ma_now <= df["rsi_ma"].iloc[-4]
detected = rallied_above and back_below and rsi_falling
note = (f"RSI({rsi_now:.1f}) rejected at SMA9({rsi_ma_now:.1f}) ↓ "
f"{'✅' if detected else '❌'} "
f"| rally:{'✅' if rallied_above else '❌'} "
f"below:{'✅' if back_below else '❌'} "
f"falling:{'✅' if rsi_falling else '❌'}")
return detected, note, round(rsi_now, 1), round(rsi_ma_now, 1)
def run_all_setups(df_htf, df_mtf, df_ltf, htf_result, bias, instrument):
"""
Run ALL pattern and setup detections.
Returns extended results dict including new setups.
"""
# Original 5 patterns
base_patterns = run_all_patterns(df_mtf, df_ltf, bias)
results = base_patterns["patterns"]
# ── New setups ────────────────────────────────────
# RSI divergence on both 4H and 1H
div_ok_4h, div_note_4h, div_str_4h = detect_rsi_divergence(df_mtf, bias, lookback=30)
div_ok_1h, div_note_1h, div_str_1h = detect_rsi_divergence(df_ltf, bias, lookback=20)
div_ok = div_ok_4h or div_ok_1h
div_note = (div_note_4h if div_ok_4h else "") + (" | " if div_ok_4h and div_ok_1h else "") + (div_note_1h if div_ok_1h else "")
results["rsi_divergence"] = {"ok": div_ok, "note": div_note or "No divergence", "tf": "4H+1H"}
# EMA50 pullback on 1H
pb_ok, pb_note = detect_ema50_pullback(df_ltf, bias)
results["ema50_pullback"] = {"ok": pb_ok, "note": pb_note, "tf": "1H"}
# Failed breakout on 4H
fb_ok, fb_note = detect_failed_breakout(df_mtf, bias, instrument)
results["failed_breakout"] = {"ok": fb_ok, "note": fb_note, "tf": "4H"}
# Session open breakout on 1H
sb_ok, sb_note = detect_session_breakout(df_ltf, bias)
results["session_breakout"] = {"ok": sb_ok, "note": sb_note, "tf": "1H"}
# RSI Cycle Completion on 4H — the key "bounce is over, trend resuming" signal
cyc_ok_4h, cyc_note_4h, cyc_info_4h = detect_rsi_cycle_completion(df_mtf, bias, lookback=20)
results["rsi_cycle_4h"] = {"ok": cyc_ok_4h, "note": cyc_note_4h, "tf": "4H",
"info": cyc_info_4h}
# RSI Cycle Completion on 1H — entry timing confirmation
cyc_ok_1h, cyc_note_1h, cyc_info_1h = detect_rsi_cycle_completion(df_ltf, bias, lookback=15)
results["rsi_cycle_1h"] = {"ok": cyc_ok_1h, "note": cyc_note_1h, "tf": "1H",
"info": cyc_info_1h}
# Recalculate pattern score including new setups
pattern_score = sum(1 for v in results.values() if v["ok"])
# Best pattern for SL/TP override
best = base_patterns["best"]
return {
"patterns": results,
"pattern_score": pattern_score,
"any_pattern": pattern_score > 0,
"best": best,
}
# ══════════════════════════════════════════════════════
# HTF / MTF / LTF
# ══════════════════════════════════════════════════════