File size: 5,682 Bytes
c6262df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
The four signal layers (spec Β§3). Each returns a normalized 0..1 score so they
combine cleanly into the weighted confluence score. All logic is relative
(z-scores / ratios / ATR) so one threshold set generalizes across all coins.

Direction convention: 'long' = expect a bounce UP (longs were liquidated, i.e.
forced selling exhausted); 'short' = expect a drop (shorts squeezed / forced
buying exhausted). Each layer scores how strongly it CONFIRMS that direction.

Pure functions β€” no I/O β€” fully unit-testable on synthetic fixtures.
"""
from __future__ import annotations

from config import THRESHOLDS as T


def clamp(x: float, lo: float = 0.0, hi: float = 1.0) -> float:
    return lo if x < lo else hi if x > hi else x


# ── L1: Liquidation flush ────────────────────────────────────────────────────
def score_liquidation(flush_notional: float, baseline_notional: float) -> float:
    """Bigger the flush vs the coin's own rolling baseline, stronger the signal.
    baselineΓ—1 => 0 ; baselineΓ—cap_mult => 1."""
    if baseline_notional <= 0:
        return 0.0
    ratio = flush_notional / baseline_notional
    cap = T["liq_flush_cap_mult"]
    return clamp((ratio - 1.0) / (cap - 1.0))


# ── L2: Funding / OI divergence ──────────────────────────────────────────────
def score_funding_oi(funding_z: float, oi_change_pct: float, direction: str) -> float:
    """Crowd over-leveraged on the wrong side (extreme funding) AND now exiting
    (OI dropping). For a LONG reversal we want the crowd extremely LONG
    (funding_z high positive); mirror for SHORT."""
    signed = funding_z if direction == "long" else -funding_z
    funding_sub = clamp(signed / T["funding_z_ref"])
    oi_sub = clamp((-oi_change_pct) / T["oi_drop_ref_pct"])  # OI falling = good
    return clamp(funding_sub * T["funding_sub_w"] + oi_sub * T["oi_sub_w"])


# ── L3: Order-flow imbalance / exhaustion ────────────────────────────────────
def score_orderflow(taker_delta_z: float, direction: str) -> float:
    """Aggressive taker flow capitulating INTO the flush = exhaustion. For a LONG
    reversal we want heavy aggressive SELLING (delta strongly negative)."""
    signed = (-taker_delta_z) if direction == "long" else taker_delta_z
    return clamp(signed / T["taker_delta_z_ref"])


# ── L4: Structural context (FVG / swings / BoS) ──────────────────────────────
def atr(klines: list[dict], period: int | None = None) -> float:
    period = period or T["atr_period"]
    if len(klines) < 2:
        return 0.0
    trs = []
    for i in range(1, len(klines)):
        h, l, pc = klines[i]["high"], klines[i]["low"], klines[i - 1]["close"]
        trs.append(max(h - l, abs(h - pc), abs(l - pc)))
    window = trs[-period:] if len(trs) >= period else trs
    return sum(window) / len(window) if window else 0.0


def find_swings(klines: list[dict], lookback: int | None = None) -> tuple[list[int], list[int]]:
    """(swing_high_idxs, swing_low_idxs): extremes vs `lookback` bars each side."""
    lb = lookback or T["swing_lookback"]
    highs, lows = [], []
    for i in range(lb, len(klines) - lb):
        win = klines[i - lb:i + lb + 1]
        if klines[i]["high"] == max(k["high"] for k in win):
            highs.append(i)
        if klines[i]["low"] == min(k["low"] for k in win):
            lows.append(i)
    return highs, lows


def detect_fvg(klines: list[dict], direction: str) -> bool:
    """3-candle Fair Value Gap in the last few bars. Bullish (long): low[i] >
    high[i-2]. Bearish (short): high[i] < low[i-2]."""
    if len(klines) < 3:
        return False
    for i in range(len(klines) - 1, 1, -1):
        if direction == "long" and klines[i]["low"] > klines[i - 2]["high"]:
            return True
        if direction == "short" and klines[i]["high"] < klines[i - 2]["low"]:
            return True
    return False


def detect_bos(klines: list[dict], direction: str) -> bool:
    """Break of Structure confirming the reversal: last close pushes back through
    the most recent opposing swing (long: close > last swing high; short: close
    < last swing low)."""
    highs, lows = find_swings(klines)
    last = klines[-1]["close"]
    if direction == "long" and highs:
        return last > klines[highs[-1]]["high"]
    if direction == "short" and lows:
        return last < klines[lows[-1]]["low"]
    return False


def at_swing(klines: list[dict], direction: str, price: float, atr_val: float) -> bool:
    """Price sitting AT a meaningful swing (long: near a swing low; short: near a
    swing high), within ~0.5 ATR."""
    highs, lows = find_swings(klines)
    tol = 0.5 * atr_val if atr_val > 0 else 0.0
    if direction == "long" and lows:
        return abs(price - klines[lows[-1]]["low"]) <= tol
    if direction == "short" and highs:
        return abs(price - klines[highs[-1]]["high"]) <= tol
    return False


def score_structure(klines: list[dict], direction: str, price: float) -> tuple[float, dict]:
    """Combine FVG / swing / BoS into the L4 score plus a detail dict."""
    a = atr(klines)
    fvg = detect_fvg(klines, direction)
    swing = at_swing(klines, direction, price, a)
    bos = detect_bos(klines, direction)
    w = T["struct_w"]
    score = w["fvg"] * fvg + w["swing"] * swing + w["bos"] * bos
    return clamp(score), {"fvg": fvg, "swing": swing, "bos": bos, "atr": a}