File size: 9,091 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""
Engine unit tests on synthetic fixtures (spec Β§14). No network, no geo dependency
β€” fully verifiable anywhere. Run: python tests/test_engine.py
"""
import os, sys
os.environ.setdefault("DB_PATH", "./_test.db")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from engine import layers, scoring, lifecycle, risk
from engine.scoring import LayerScores

PASS = 0
FAIL = 0


def check(name, cond):
    global PASS, FAIL
    if cond:
        PASS += 1
        print(f"  PASS  {name}")
    else:
        FAIL += 1
        print(f"  FAIL  {name}")


# ── L1 liquidation ────────────────────────────────────────────────────────────
print("L1 liquidation flush")
check("baselineΓ—1 => 0", layers.score_liquidation(100, 100) == 0.0)
check("baselineΓ—5 => 1 (cap)", layers.score_liquidation(500, 100) == 1.0)
check("baselineΓ—3 => 0.5", abs(layers.score_liquidation(300, 100) - 0.5) < 1e-9)
check("zero baseline => 0", layers.score_liquidation(500, 0) == 0.0)

# ── L2 funding/OI ──────────────────────────────────────────────────────────────
print("L2 funding/OI divergence")
# long reversal: crowd very long (funding_z +2) + OI dropping 5% => ~1.0
check("long: extreme +funding & OI drop => high",
      layers.score_funding_oi(2.0, -5.0, "long") > 0.95)
check("long: negative funding => low", layers.score_funding_oi(-2.0, -5.0, "long") < 0.45)
check("short mirror of long", abs(
    layers.score_funding_oi(-2.0, -5.0, "short") - layers.score_funding_oi(2.0, -5.0, "long")) < 1e-9)
check("OI rising kills OI sub", layers.score_funding_oi(2.0, +10.0, "long") < 0.65)

# ── L3 order-flow ──────────────────────────────────────────────────────────────
print("L3 order-flow exhaustion")
check("long: heavy selling (delta -2) => 1", layers.score_orderflow(-2.0, "long") == 1.0)
check("long: buying delta => 0", layers.score_orderflow(+2.0, "long") == 0.0)
check("short: heavy buying => 1", layers.score_orderflow(+2.0, "short") == 1.0)

# ── L4 structure (synthetic candles) ───────────────────────────────────────────
print("L4 structure")
def candle(o, h, l, c):
    return {"ts": 0, "open": o, "high": h, "low": l, "close": c, "volume": 1, "taker_buy_volume": 0}

# downtrend into a swing low then a bullish FVG + BoS up (long reversal setup)
kl = [candle(110, 111, 109, 110), candle(109, 110, 107, 108), candle(108, 109, 104, 105),
      candle(105, 106, 100, 101),  # swing low ~100
      candle(101, 103, 100, 102), candle(104, 108, 104, 107),  # gap: low(108?) ... build FVG
      candle(107, 112, 106, 111)]  # close breaks above => BoS
a = layers.atr(kl)
check("ATR positive", a > 0)
s4, det = layers.score_structure(kl, "long", price=100.5)
check("structure score in 0..1", 0.0 <= s4 <= 1.0)
check("detects at least one structural element", (det["fvg"] or det["swing"] or det["bos"]))

# ── confluence + tiers ──────────────────────────────────────────────────────────
print("Confluence & tiers")
strong = LayerScores(1.0, 1.0, 1.0, 1.0)
check("all layers max => 100 confluence", scoring.confluence_score(strong) == 100.0)
check("100 => sniper", scoring.tier_of(100.0) == "sniper")
check("60 => setup", scoring.tier_of(60.0) == "setup")
check("40 => watch", scoring.tier_of(40.0) == "watch")
check("20 => none", scoring.tier_of(20.0) == "none")
weak = LayerScores(0.2, 0.2, 0.2, 0.2)
check("weak layers => 20 confluence", scoring.confluence_score(weak) == 20.0)

# ── conviction & ranking ────────────────────────────────────────────────────────
print("Conviction & ranking (no active cap)")
big = scoring.build_setup("BTC-USDT-SWAP", "long", LayerScores(0.9, 0.8, 0.9, 0.8))
small = scoring.build_setup("XYZ-USDT-SWAP", "long", LayerScores(0.9, 0.8, 0.9, 0.8))
scoring.conviction(big, turnover_usd=2.0e9, baseline_days=7)        # deep + mature
scoring.conviction(small, turnover_usd=2.5e7, baseline_days=1)      # thin + cold
check("same confluence, deeper coin ranks higher", big.conviction > small.conviction)
check("elite tag on top setup", big.conviction_tag in ("elite", "strong"))
check("size mult follows tag", big.size_mult == scoring.T["size_by_tag"][big.conviction_tag])
# many setups -> all ranked, none dropped
setups = [big, small,
          scoring.build_setup("A-USDT-SWAP", "short", LayerScores(0.6, 0.6, 0.6, 0.6))]
for s in setups[2:]:
    scoring.conviction(s, turnover_usd=5.0e8, baseline_days=5)
ranked = scoring.rank(setups)
check("ranking keeps ALL setups (no cap)", len(ranked) == 3)
check("ranked descending by conviction",
      all(ranked[i].conviction >= ranked[i + 1].conviction for i in range(len(ranked) - 1)))

# trend safety: counter-trend into strong BTC move lowers conviction
ct = scoring.build_setup("Z-USDT-SWAP", "long", LayerScores(0.9, 0.8, 0.9, 0.8))
safe = scoring.build_setup("Z-USDT-SWAP", "long", LayerScores(0.9, 0.8, 0.9, 0.8))
scoring.conviction(ct, 2.0e9, 7, btc_trend_atr=2.0, btc_dir="down")   # long vs BTC dumping
scoring.conviction(safe, 2.0e9, 7, btc_trend_atr=0.0, btc_dir="flat")
check("counter-trend penalised vs calm", ct.conviction < safe.conviction)

# ── levels ──────────────────────────────────────────────────────────────────────
print("Levels (ATR-based)")
setup = scoring.build_setup("BTC-USDT-SWAP", "long", strong)
scoring.compute_levels(setup, flush_extreme=100.0, atr_val=2.0)
check("long entry above flush low", setup.entry > 100.0)
check("long stop below flush low", setup.stop < 100.0)
check("targets ordered (t2>t1>entry)", setup.target2 > setup.target1 > setup.entry)
ssetup = scoring.build_setup("BTC-USDT-SWAP", "short", strong)
scoring.compute_levels(ssetup, flush_extreme=100.0, atr_val=2.0)
check("short targets ordered (t2<t1<entry)", ssetup.target2 < ssetup.target1 < ssetup.entry)

# ── lifecycle ────────────────────────────────────────────────────────────────────
print("Lifecycle state machine")
st, _ = lifecycle.advance(lifecycle.PENDING, "long", price=99.5, entry=100.0, stop=97.0,
                          target1=104.0, target2=108.0, age_sec=10)
check("price in zone => ACTIVE", st == lifecycle.ACTIVE)
st, _ = lifecycle.advance(lifecycle.PENDING, "long", 101.0, 100.0, 97.0, 104.0, 108.0, age_sec=99999)
check("no entry + 24h => EXPIRED", st == lifecycle.EXPIRED)
st, _ = lifecycle.advance(lifecycle.ACTIVE, "long", 96.0, 100.0, 97.0, 104.0, 108.0, age_sec=10)
check("stop breach => HIT_STOP", st == lifecycle.HIT_STOP)
st, _ = lifecycle.advance(lifecycle.ACTIVE, "long", 104.5, 100.0, 97.0, 104.0, 108.0, age_sec=10)
check("t1 from ACTIVE => HIT_TARGET1", st == lifecycle.HIT_TARGET1)
st, _ = lifecycle.advance(lifecycle.HIT_TARGET1, "long", 108.5, 100.0, 97.0, 104.0, 108.0, age_sec=10)
check("t2 from T1 => HIT_TARGET2", st == lifecycle.HIT_TARGET2)
check("realized R at +1R", lifecycle.realized_r("long", 100.0, 97.0, 103.0) == 1.0)

# ── risk: cooldown only, no cap ───────────────────────────────────────────────────
print("Risk gates (cooldown only, no active cap)")
active = [{"symbol": "BTC-USDT-SWAP", "state": lifecycle.ACTIVE, "created_ts": 1000}]
check("same coin within window blocked",
      risk.cooldown_ok("BTC-USDT-SWAP", now_ts=1000 + 3600, active_signals=active) is False)
check("same coin after window ok",
      risk.cooldown_ok("BTC-USDT-SWAP", now_ts=1000 + 5 * 3600, active_signals=active) is True)
check("different coin never blocked",
      risk.cooldown_ok("ETH-USDT-SWAP", now_ts=1000 + 60, active_signals=active) is True)
check("terminal signal doesn't block",
      risk.cooldown_ok("BTC-USDT-SWAP", 1000 + 60,
                       [{"symbol": "BTC-USDT-SWAP", "state": lifecycle.HIT_STOP, "created_ts": 1000}]) is True)
adm, _ = risk.admit(big, now_ts=1000 + 5 * 3600, active_signals=active)
check("strong setup admitted", adm is True)
none_setup = scoring.build_setup("Q-USDT-SWAP", "long", LayerScores(0.05, 0.05, 0.05, 0.05))
adm2, _ = risk.admit(none_setup, now_ts=99999, active_signals=[])
check("below-watch setup rejected", adm2 is False)

print(f"\n==== {PASS} passed, {FAIL} failed ====")
sys.exit(1 if FAIL else 0)