Confluence_Reversal_Engine / signals_worker.py
GitHub Actions
Clean project deployment
c6262df
Raw History Blame Contribute Delete
11.2 kB
"""
Signal engine + active-signal monitor (spec §5, §8) — the live integration that
turns liquidation flushes into scored, ranked, persisted signals.
signal_engine():
Event-driven. Every cycle it scans recent liquidation buckets for the current
universe; any minute whose one-sided notional clears the flush threshold
(>= flush_mult × the coin's self-collected baseline) is a candidate. Direction
is AGAINST the liquidated side. It then gathers the layer inputs (L1 from the
flush, L2 funding_z from snapshot + self-collected OI change, L3 taker delta z,
L4 structure from klines), scores confluence + conviction, applies the cooldown
gate, persists the signal, and pushes an alert for SETUP/SNIPER.
active_monitor():
Every cycle advances each non-terminal signal through the lifecycle state machine
using the latest mark price and records outcomes (state, resolved_ts, result_r).
Heavy per-coin work happens ONLY for coins that actually flushed, so a wide
universe stays cheap (decision D5).
"""
from __future__ import annotations
import asyncio
import statistics
import time
import config
import links
from config import THRESHOLDS as T
from exchange.base import ExchangeClient
from store import db
from engine import layers, scoring, lifecycle, risk
from engine.scoring import LayerScores
from alerts import telegram
from workers import UniverseState
# flush detection knobs
FLUSH_MULT = float(T.get("liq_flush_cap_mult", 5.0)) * 0.5 # >=2.5× baseline = candidate
COLD_START_MIN_NOTIONAL = 50_000.0 # before baseline matures, require an absolute floor
_SCAN_LOOKBACK_MIN = 5 # only react to flushes in the last few minutes
async def _btc_trend(client: ExchangeClient) -> tuple[float, str]:
"""BTC 1h trend strength in ATR units + direction, for conviction trend-safety."""
try:
kl = await client.klines("BTC-USDT-SWAP", "1H", 30)
a = layers.atr(kl)
if a <= 0 or len(kl) < 6:
return 0.0, "flat"
move = kl[-1]["close"] - kl[-6]["close"] # ~5h move
atr_units = abs(move) / a
direction = "up" if move > 0 else "down" if move < 0 else "flat"
return atr_units, direction
except Exception:
return 0.0, "flat"
async def _score_symbol(client: ExchangeClient, symbol: str, direction: str,
flush_notional: float, flush_minute: int,
btc_atr: float, btc_dir: str) -> scoring.Setup | None:
baseline = await asyncio.to_thread(db.liq_baseline_notional, symbol)
cold = baseline <= 0
# L1
l1 = layers.score_liquidation(flush_notional, baseline) if not cold else \
layers.clamp(flush_notional / (COLD_START_MIN_NOTIONAL * config.THRESHOLDS["liq_flush_cap_mult"]))
# L2 inputs: funding_z from latest snapshot, OI change from our own history
snap = await asyncio.to_thread(
db.query, "SELECT funding_z FROM market_snapshots WHERE symbol=? ORDER BY ts DESC LIMIT 1", (symbol,)
)
funding_z = float(snap[0]["funding_z"]) if snap else 0.0
oi_chg = await asyncio.to_thread(db.oi_change_pct, symbol)
l2 = layers.score_funding_oi(funding_z, oi_chg, direction)
# L3: taker delta z over recent bars
try:
taker = await client.taker_volume(symbol, T["taker_period"], 48)
except Exception:
taker = []
l3 = _taker_delta_score(taker, direction)
# L4: structure from klines
try:
kl = await client.klines(symbol, "15m", T["kline_limit"])
except Exception:
kl = []
if len(kl) < 20:
return None
price = kl[-1]["close"]
l4, sdetail = layers.score_structure(kl, direction, price)
atr_val = sdetail["atr"]
flush_extreme = min(k["low"] for k in kl[-3:]) if direction == "long" else max(k["high"] for k in kl[-3:])
setup = scoring.build_setup(symbol, direction, LayerScores(l1, l2, l3, l4))
if setup.tier == "none":
return None
# conviction (turnover from latest snapshot's mark × — use mark*OI proxy via snapshot oi_usd)
turnover = await _turnover(client, symbol)
baseline_days = await asyncio.to_thread(db.liq_baseline_days, symbol)
scoring.conviction(setup, turnover_usd=turnover, baseline_days=baseline_days,
btc_trend_atr=btc_atr, btc_dir=btc_dir)
scoring.compute_levels(setup, flush_extreme=flush_extreme, atr_val=atr_val or (price * 0.01))
setup.detail.update({"cold_start": cold, "funding_z": funding_z, "oi_chg": oi_chg,
"flush_minute": flush_minute, "flush_notional": flush_notional})
return setup
def _taker_delta_score(taker: list[dict], direction: str) -> float:
if len(taker) < 6:
return 0.0
deltas = [t["buy"] - t["sell"] for t in taker]
last = deltas[-1]
mu = statistics.fmean(deltas[:-1])
sd = statistics.pstdev(deltas[:-1]) or 1.0
z = (last - mu) / sd
return layers.score_orderflow(z, direction)
async def _turnover(client: ExchangeClient, symbol: str) -> float:
try:
for t in await client.tickers_universe():
if t.symbol == symbol:
return t.turnover_usd
except Exception:
pass
return config.UNIVERSE_MIN_TURNOVER_USD
async def signal_engine(client: ExchangeClient, state: UniverseState, stop: asyncio.Event) -> None:
while not stop.is_set():
now = int(time.time())
now_min = now // 60
try:
btc_atr, btc_dir = await _btc_trend(client)
active = await asyncio.to_thread(db.active_signals)
for symbol in list(state.symbols):
buckets = await asyncio.to_thread(db.recent_liq_buckets, symbol, now_min - _SCAN_LOOKBACK_MIN)
if not buckets:
continue
baseline = await asyncio.to_thread(db.liq_baseline_notional, symbol)
thresh = max(baseline * FLUSH_MULT, COLD_START_MIN_NOTIONAL)
for b in buckets:
# longs liquidated (forced sells) -> LONG reversal; shorts -> SHORT
if b["long_notional"] >= thresh:
direction, notion = "long", b["long_notional"]
elif b["short_notional"] >= thresh:
direction, notion = "short", b["short_notional"]
else:
continue
if not risk.cooldown_ok(symbol, now, active):
continue
setup = await _score_symbol(client, symbol, direction, notion,
b["minute_ts"], btc_atr, btc_dir)
if setup is None:
continue
ok, _ = risk.admit(setup, now, active)
if not ok:
continue
sid = await asyncio.to_thread(_persist, setup, now)
if sid is None:
continue # duplicate
active.append({"symbol": symbol, "state": lifecycle.PENDING, "created_ts": now})
if risk.is_alertable(setup.tier):
await _dispatch(setup, sid)
except Exception as e:
print(f"[engine] cycle error: {type(e).__name__}: {e}", flush=True)
await _sleep_or_stop(stop, config.POLL_INTERVAL_SEC)
def _persist(setup: scoring.Setup, now: int) -> int | None:
ls = setup.layers
row = {
"created_ts": now, "symbol": setup.symbol, "direction": setup.direction,
"tier": setup.tier, "state": lifecycle.PENDING,
"score_total": int(round(setup.confluence)),
"score_funding": int(round(ls.l2 * 100)),
"score_oi": int(round(setup.detail.get("oi_chg", 0))),
"score_liq": int(round(ls.l1 * 100)),
"score_priceflow": int(round(ls.l3 * 100)),
"funding_z": setup.detail.get("funding_z", 0.0),
"oi_pctile": 0.0,
"liq_mult": setup.detail.get("flush_notional", 0.0),
"flush_candle_ts": int(setup.detail.get("flush_minute", now // 60)),
"entry": setup.entry, "stop": setup.stop,
"target1": setup.target1, "target2": setup.target2, "rr1": setup.rr1,
"cold_start": 1 if setup.detail.get("cold_start") else 0,
"config_version": config.CONFIG_VERSION,
}
return db.insert_signal(row)
async def _dispatch(setup: scoring.Setup, sid: int) -> None:
sig = {
"symbol": setup.symbol, "direction": setup.direction, "tier": setup.tier,
"conviction": setup.conviction, "conviction_tag": setup.conviction_tag,
"score_total": int(round(setup.confluence)),
"score_liq": int(round(setup.layers.l1 * 100)),
"score_funding": int(round(setup.layers.l2 * 100)),
"score_oi": int(round(setup.detail.get("oi_chg", 0))),
"score_priceflow": int(round(setup.layers.l3 * 100)),
"entry": setup.entry, "stop": setup.stop, "target1": setup.target1,
"target2": setup.target2, "rr1": setup.rr1,
"cold_start": 1 if setup.detail.get("cold_start") else 0,
}
text = telegram.format_alert(sig)
delivered = await telegram.send(text)
await asyncio.to_thread(db.log_alert, sid, setup.tier, 1 if delivered else 0)
async def active_monitor(client: ExchangeClient, stop: asyncio.Event) -> None:
while not stop.is_set():
try:
active = await asyncio.to_thread(db.active_signals)
for s in active:
try:
price = await client.mark_price(s["symbol"])
except Exception:
continue
age = int(time.time()) - int(s["created_ts"])
new_state, _ = lifecycle.advance(
s["state"], s["direction"], price, s["entry"], s["stop"],
s["target1"], s["target2"], age,
)
if new_state != s["state"]:
resolved = int(time.time()) if new_state in lifecycle.TERMINAL else None
outcome = new_state if new_state in lifecycle.TERMINAL else None
rr = None
if new_state in (lifecycle.HIT_STOP, lifecycle.HIT_TARGET2):
exitp = s["stop"] if new_state == lifecycle.HIT_STOP else s["target2"]
rr = lifecycle.realized_r(s["direction"], s["entry"], s["stop"], exitp)
await asyncio.to_thread(db.update_signal_state, s["id"], new_state, resolved, outcome, rr)
except Exception as e:
print(f"[monitor] cycle error: {type(e).__name__}: {e}", flush=True)
await _sleep_or_stop(stop, max(15, config.POLL_INTERVAL_SEC // 2))
async def _sleep_or_stop(stop: asyncio.Event, seconds: float) -> None:
try:
await asyncio.wait_for(stop.wait(), timeout=seconds)
except asyncio.TimeoutError:
pass
def start(client: ExchangeClient, state: UniverseState, stop: asyncio.Event) -> list[asyncio.Task]:
return [
asyncio.create_task(signal_engine(client, state, stop), name="signal_engine"),
asyncio.create_task(active_monitor(client, stop), name="active_monitor"),
]