"""Lead-lag: does the DEX spot price move BEFORE the CEX perpetual (by at least a second)? For memecoins found by meme_matcher (same coin, price agrees, a pool on a fast chain) it records at the same time * CEX perpetual trades from a WebSocket (Binance, Bybit, Gate or MEXC) with exchange timestamps in milliseconds; * DEX swaps of the most active pool from GeckoTerminal with ON-CHAIN block timestamps (1 s resolution). Then, on a 1-second grid, it checks whether a DEX move in second t is followed by the futures moving the same way AFTER second t+1 - i.e. later than any same-second reaction could explain. That is the part one could trade. Note: GeckoTerminal publishes swaps ~40-60 s after the block (it caches for 30 s), so this tool MEASURES the lead on chain time; using a lead live needs a direct chain feed (e.g. a Solana RPC WebSocket). The DEX data delay is reported per coin. Run: py -3 leadlag.py --minutes 20 --coins 10 (scan, record, analyse) py -3 leadlag.py --analyze recordings\\leadlag_....jsonl.gz """ from __future__ import annotations import argparse import csv import gzip import json import math import threading import time from collections import deque from dataclasses import asdict, dataclass, field from datetime import datetime from pathlib import Path import numpy as np import meme_matcher as mm ROOT = Path(__file__).resolve().parent REC_DIR = ROOT / "recordings" RESULTS_CSV = ROOT / "leadlag_results.csv" # DexScreener chain -> GeckoTerminal network. Only chains with blocks of ~2 s or faster: a 12 s Ethereum block # cannot show a 1 s lead. FAST_CHAINS = {"solana": "solana", "bsc": "bsc", "base": "base"} CEX_PRIORITY = ["Binance", "Bybit", "Gate", "MEXC"] GECKO_CALLS_PER_MIN = 26 # free tier: 30 a minute MIN_POLL_S = 30 # GeckoTerminal caches responses for 30 s TAIL_S = 180 # extra DEX polling after the CEX recording ends (swaps are published late) @dataclass class Target: symbol: str cg_id: str cex: str cex_symbol: str multiplier: float chain: str network: str pool: str token: str dex: str txns_h1: int def pick_targets(matches: list[mm.Match], max_coins: int = 10, min_txns_h1: int = 120) -> list[Target]: out = [] for m in matches: if m.status != "совпадает": continue pools = [p for p in m.pools if p.source == "DexScreener" and p.chain in FAST_CHAINS and p.pair_address] if not pools: continue pool = max(pools, key=lambda p: p.txns_h1) if pool.txns_h1 < min_txns_h1: continue by_exchange = {l.exchange: l for l in m.cex} listing = next((by_exchange[e] for e in CEX_PRIORITY if e in by_exchange), None) if listing is None: continue out.append(Target(m.symbol, m.cg_id, listing.exchange, listing.symbol, listing.multiplier, pool.chain, FAST_CHAINS[pool.chain], pool.pair_address, pool.contract, pool.dex, pool.txns_h1)) out.sort(key=lambda t: -t.txns_h1) return out[:max_coins] # -------------------------------------------------------------------------------------------- # Recording # -------------------------------------------------------------------------------------------- class Recorder: def __init__(self, targets: list[Target]) -> None: self.targets = targets self.lock = threading.Lock() self.cex: dict[str, list[tuple[float, float]]] = {t.symbol: [] for t in targets} self.dex: dict[str, list[tuple[float, float, float, str, float]]] = {t.symbol: [] for t in targets} self.seen: set[str] = set() self.gaps: dict[str, int] = {t.symbol: 0 for t in targets} self.errors: deque[str] = deque(maxlen=20) self.started = time.time() def add_cex(self, symbol: str, ts: float, price: float) -> None: with self.lock: self.cex[symbol].append((ts, price)) def add_dex(self, symbol: str, trade_id: str, ts: float, price: float, volume: float, kind: str) -> bool: with self.lock: if trade_id in self.seen: return False self.seen.add(trade_id) self.dex[symbol].append((ts, price, volume, kind, time.time())) return True def counts(self) -> dict[str, tuple[int, int]]: with self.lock: return {s: (len(self.cex[s]), len(self.dex[s])) for s in self.cex} def save(self, path: Path | None = None) -> Path: REC_DIR.mkdir(exist_ok=True) path = path or REC_DIR / f"leadlag_{datetime.now():%Y%m%d_%H%M%S}.jsonl.gz" with self.lock, gzip.open(path, "wt", encoding="utf-8") as f: f.write(json.dumps({"meta": {"started": self.started, "saved": time.time(), "gaps": self.gaps, "targets": [asdict(t) for t in self.targets]}}) + "\n") for s, rows in self.cex.items(): for ts, price in rows: f.write(json.dumps(["C", s, ts, price]) + "\n") for s, rows in self.dex.items(): for row in rows: f.write(json.dumps(["D", s, *row]) + "\n") return path def load(path: Path) -> tuple[list[Target], dict, dict, dict]: cex: dict[str, list] = {} dex: dict[str, list] = {} meta = {} with gzip.open(path, "rt", encoding="utf-8") as f: for line in f: row = json.loads(line) if isinstance(row, dict): meta = row["meta"] elif row[0] == "C": cex.setdefault(row[1], []).append((row[2], row[3])) else: dex.setdefault(row[1], []).append(tuple(row[2:])) targets = [Target(**t) for t in meta.get("targets", [])] return targets, cex, dex, meta class CexFeed(threading.Thread): """Trades of one exchange's perpetuals over a WebSocket; reconnects on errors.""" def __init__(self, exchange: str, targets: list[Target], rec: Recorder, stop: threading.Event) -> None: super().__init__(daemon=True) self.exchange, self.rec, self.stop_event = exchange, rec, stop self.by_symbol = {t.cex_symbol: t for t in targets} def _url(self) -> str: if self.exchange == "Binance": streams = "/".join(f"{s.lower()}@aggTrade" for s in self.by_symbol) return f"wss://fstream.binance.com/market/stream?streams={streams}" return {"Bybit": "wss://stream.bybit.com/v5/public/linear", "Gate": "wss://fx-ws.gateio.ws/v4/ws/usdt", "MEXC": "wss://contract.mexc.com/edge"}[self.exchange] def _subscribe(self, ws) -> None: symbols = list(self.by_symbol) if self.exchange == "Bybit": for i in range(0, len(symbols), 10): ws.send(json.dumps({"op": "subscribe", "args": [f"publicTrade.{s}" for s in symbols[i:i + 10]]})) elif self.exchange == "Gate": ws.send(json.dumps({"time": int(time.time()), "channel": "futures.trades", "event": "subscribe", "payload": symbols})) elif self.exchange == "MEXC": for s in symbols: ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": s}})) def _ping(self, ws) -> None: if self.exchange == "Bybit": ws.send(json.dumps({"op": "ping"})) elif self.exchange == "Gate": ws.send(json.dumps({"time": int(time.time()), "channel": "futures.ping"})) elif self.exchange == "MEXC": ws.send(json.dumps({"method": "ping"})) def _emit(self, symbol: str, ts_ms, price) -> None: target = self.by_symbol.get(symbol) if target is not None: self.rec.add_cex(target.symbol, float(ts_ms) / 1000, float(price) / target.multiplier) def handle(self, msg: dict) -> None: if self.exchange == "Binance": d = msg.get("data") or {} if d.get("e") == "aggTrade": self._emit(d["s"], d["T"], d["p"]) elif self.exchange == "Bybit": if str(msg.get("topic", "")).startswith("publicTrade."): for d in msg.get("data", []): self._emit(d["s"], d["T"], d["p"]) elif self.exchange == "Gate": if msg.get("channel") == "futures.trades" and msg.get("event") == "update": for d in msg.get("result", []): self._emit(d["contract"], d["create_time_ms"], d["price"]) elif self.exchange == "MEXC": if msg.get("channel") == "push.deal": data = msg.get("data") for d in data if isinstance(data, list) else [data]: self._emit(msg.get("symbol", ""), d["t"], d["p"]) def run(self) -> None: import websocket while not self.stop_event.is_set(): try: ws = websocket.create_connection(self._url(), timeout=5) self._subscribe(ws) last_ping = time.time() while not self.stop_event.is_set(): if time.time() - last_ping > 15: self._ping(ws) last_ping = time.time() try: raw = ws.recv() except websocket.WebSocketTimeoutException: continue if raw: self.handle(json.loads(raw)) ws.close() except Exception as exc: self.rec.errors.append(f"{self.exchange}: {exc}") self.stop_event.wait(3) def parse_gecko_trades(data: dict, token: str) -> list[tuple[str, float, float, float, str]]: """GeckoTerminal /trades -> (id, block time, price of OUR token in USD, volume USD, buy/sell).""" token = token.lower() out = [] for item in data.get("data") or []: a = item.get("attributes") or {} try: ts = datetime.fromisoformat(a["block_timestamp"].replace("Z", "+00:00")).timestamp() except (KeyError, ValueError): continue if str(a.get("from_token_address", "")).lower() == token: price = mm._f(a.get("price_from_in_usd")) elif str(a.get("to_token_address", "")).lower() == token: price = mm._f(a.get("price_to_in_usd")) else: continue if price > 0: out.append((item.get("id") or a.get("tx_hash", ""), ts, price, mm._f(a.get("volume_in_usd")), a.get("kind", ""))) return out class DexPoller(threading.Thread): def __init__(self, targets: list[Target], rec: Recorder, stop: threading.Event) -> None: super().__init__(daemon=True) self.targets, self.rec, self.stop_event = targets, rec, stop def run(self) -> None: gap = 60.0 / GECKO_CALLS_PER_MIN first = {t.symbol: True for t in self.targets} while not self.stop_event.is_set(): cycle_start = time.time() for t in self.targets: if self.stop_event.is_set(): return try: data = mm.http_json(f"https://api.geckoterminal.com/api/v2/networks/{t.network}/pools/{t.pool}" "/trades", retries=2) trades = parse_gecko_trades(data or {}, t.token) new = sum(self.rec.add_dex(t.symbol, *tr) for tr in trades) if not first[t.symbol] and trades and new == len(trades) and len(trades) >= 300: self.rec.gaps[t.symbol] += 1 # all 300 were new: some swaps were missed first[t.symbol] = False except Exception as exc: self.rec.errors.append(f"GeckoTerminal {t.symbol}: {exc}") self.stop_event.wait(gap) rest = MIN_POLL_S - (time.time() - cycle_start) if rest > 0: self.stop_event.wait(rest) def record(targets: list[Target], minutes: float, log=print, stop: threading.Event | None = None) -> Recorder: rec = Recorder(targets) stop = stop or threading.Event() threads = [DexPoller(targets, rec, stop)] for exchange in CEX_PRIORITY: mine = [t for t in targets if t.cex == exchange] if mine: threads.append(CexFeed(exchange, mine, rec, stop)) for th in threads: th.start() end = time.time() + minutes * 60 while time.time() < end and not stop.is_set(): stop.wait(10) counts = rec.counts() left = max(0, end - time.time()) / 60 log(f"Запись: осталось {left:.1f} мин · " + ", ".join(f"{s} {c}/{d}" for s, (c, d) in counts.items()) + " (сделок фьючерс/DEX)") # GeckoTerminal shows swaps 1-2 min late: keep polling the DEX so the last minutes of CEX data are covered if not stop.is_set(): log(f"Дозаписываю последние сделки DEX (они появляются с задержкой 1–2 мин), {TAIL_S // 60} мин…") stop.wait(TAIL_S) stop.set() for th in threads: th.join(timeout=10) return rec # -------------------------------------------------------------------------------------------- # Analysis # -------------------------------------------------------------------------------------------- @dataclass class LeadResult: symbol: str cex: str pool: str seconds: int cex_trades: int dex_trades: int events: int # seconds with a DEX move of at least the threshold corr: dict[int, float] # lag (s, + = futures after DEX) -> correlation of 1-s returns best_lag: int same_second: float # mean futures move in the DEX move's direction, same second, % follow: dict[int, float] # mean futures move from t+1 to t+k in the DEX direction, % hit: dict[int, float] # share of events where that move went the DEX way (of those that moved) t_stat: float # of the follow move t+1 -> t+5 dex_delay_s: float # how late GeckoTerminal published the swaps (median) gaps: int verdict: str notes: list[str] = field(default_factory=list) def second_series(trades: list[tuple], t0: int, t1: int, vwap: bool) -> np.ndarray: """Price per second on [t0, t1], forward-filled. DEX: volume-weighted within the block second.""" n = t1 - t0 + 1 px = np.full(n, np.nan) if vwap: num, den = np.zeros(n), np.zeros(n) for ts, price, vol, *_ in trades: i = int(ts) - t0 if 0 <= i < n: w = max(vol, 1e-9) num[i] += price * w den[i] += w mask = den > 0 px[mask] = num[mask] / den[mask] else: for ts, price in sorted(trades): i = int(math.floor(ts)) - t0 if 0 <= i < n: px[i] = price # last trade of the second # forward fill last = np.nan for i in range(n): if np.isnan(px[i]): px[i] = last else: last = px[i] return px def analyze_coin(target: Target, cex: list, dex: list, gaps: int = 0, threshold_pct: float = 0.15, max_lag: int = 10) -> LeadResult: notes = [] empty = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", 0, len(cex), len(dex), 0, {}, 0, 0.0, {}, {}, 0.0, 0.0, gaps, "мало данных", notes) if len(cex) < 20 or len(dex) < 20: return empty t0 = int(max(min(t for t, _ in cex), min(r[0] for r in dex))) t1 = int(min(max(t for t, _ in cex), max(r[0] for r in dex))) if t1 - t0 < 120: return empty c = second_series(cex, t0, t1, vwap=False) d = second_series(dex, t0, t1, vwap=True) ok = ~(np.isnan(c) | np.isnan(d)) start = int(np.argmax(ok)) c, d = np.log(c[start:]), np.log(d[start:]) rc, rd = np.diff(c), np.diff(d) n = len(rc) corr = {} for k in range(-max_lag, max_lag + 1): a = rd[max(0, -k): n - max(0, k)] b = rc[max(0, k): n - max(0, -k)] corr[k] = float(np.corrcoef(a, b)[0, 1]) if len(a) > 30 and a.std() > 0 and b.std() > 0 else 0.0 best_lag = max(corr, key=lambda k: corr[k]) # events: DEX moved at least the threshold within one second (rd[i] = second i+1 vs i) thr = threshold_pct / 100 horizons = (2, 3, 5, 10) same, follow, hit = [], {k: [] for k in horizons}, {k: [] for k in horizons} for i in np.nonzero(np.abs(rd) >= thr)[0]: t = i + 1 # index of the second where the DEX move landed if t + max(horizons) >= len(c) or t < 1: continue sign = 1.0 if rd[i] > 0 else -1.0 same.append(sign * (c[t] - c[t - 1])) for k in horizons: move = sign * (c[t + k] - c[t + 1]) # strictly after the DEX second and the next one follow[k].append(move) if abs(move) > 1e-12: hit[k].append(move > 0) events = len(same) f5 = np.array(follow[5]) if follow[5] else np.array([0.0]) t_stat = float(f5.mean() / (f5.std(ddof=1) / math.sqrt(len(f5)))) if len(f5) > 2 and f5.std() > 0 else 0.0 # publication delay only for swaps made during the recording (the first poll returns old history) first_cex = min(t for t, _ in cex) delays = [r[4] - r[0] for r in dex if len(r) > 4 and r[0] >= first_cex] res = LeadResult(target.symbol, target.cex, f"{target.chain}/{target.dex}", n, len(cex), len(dex), events, corr, best_lag, float(np.mean(same) * 100) if same else 0.0, {k: float(np.mean(v) * 100) if v else 0.0 for k, v in follow.items()}, {k: float(np.mean(v)) if v else 0.0 for k, v in hit.items()}, t_stat, float(np.median(delays)) if delays else 0.0, gaps, "", notes) if gaps: notes.append(f"пропуски DEX: {gaps} раз пришло 300 новых сделок подряд") if events < 10: res.verdict = "мало движений DEX" elif t_stat >= 2 and res.hit[5] >= 0.6 and res.follow[5] > 0: res.verdict = "DEX опережает ≥1 с" elif best_lag < 0 and corr[best_lag] > corr.get(0, 0) and corr[best_lag] > 3 / math.sqrt(n): res.verdict = "фьючерс опережает" elif t_stat <= -2: res.verdict = "после DEX фьючерс откатывает" else: res.verdict = "одновременно / нет опережения" return res def analyze(targets: list[Target], cex: dict, dex: dict, gaps: dict | None = None, threshold_pct: float = 0.15) -> list[LeadResult]: out = [analyze_coin(t, cex.get(t.symbol, []), dex.get(t.symbol, []), (gaps or {}).get(t.symbol, 0), threshold_pct) for t in targets] order = {"DEX опережает ≥1 с": 0, "одновременно / нет опережения": 1, "фьючерс опережает": 2, "после DEX фьючерс откатывает": 3, "мало движений DEX": 4, "мало данных": 5} out.sort(key=lambda r: (order.get(r.verdict, 9), -r.t_stat)) return out RESULT_COLUMNS = ["symbol", "verdict", "cex", "dex_pool", "minutes", "cex_trades", "dex_trades", "dex_moves", "best_lag_s", "corr_lag0", "corr_lag1", "corr_lag2", "corr_lag-1", "same_second_pct", "follow_t1_t3_pct", "follow_t1_t5_pct", "follow_t1_t10_pct", "hit_t5", "t_stat", "dex_publish_delay_s", "notes"] def result_row(r: LeadResult) -> list: return [r.symbol, r.verdict, r.cex, r.pool, f"{r.seconds / 60:.1f}", r.cex_trades, r.dex_trades, r.events, r.best_lag, f"{r.corr.get(0, 0):.3f}", f"{r.corr.get(1, 0):.3f}", f"{r.corr.get(2, 0):.3f}", f"{r.corr.get(-1, 0):.3f}", f"{r.same_second:+.3f}", f"{r.follow.get(3, 0):+.3f}", f"{r.follow.get(5, 0):+.3f}", f"{r.follow.get(10, 0):+.3f}", f"{r.hit.get(5, 0):.2f}", f"{r.t_stat:+.2f}", f"{r.dex_delay_s:.0f}", "; ".join(r.notes)] def save_results(results: list[LeadResult], path: Path = RESULTS_CSV) -> None: with path.open("w", newline="", encoding="utf-8-sig") as f: w = csv.writer(f, delimiter=";") w.writerow(RESULT_COLUMNS) w.writerows(result_row(r) for r in results) def print_results(results: list[LeadResult]) -> None: print(f"\n{'Монета':10s} {'Вывод':30s} {'Фьючерс':8s} {'DEX':18s} {'Движ.':>5s} {'Лаг':>4s} " f"{'Та же с':>8s} {'t+1→t+5':>8s} {'Попад.':>6s} {'t':>6s} {'Задержка':>8s}") for r in results: print(f"{r.symbol:10s} {r.verdict:30s} {r.cex:8s} {r.pool[:18]:18s} {r.events:5d} {r.best_lag:+4d} " f"{r.same_second:+7.3f}% {r.follow.get(5, 0):+7.3f}% {r.hit.get(5, 0) * 100:5.0f}% {r.t_stat:+6.2f} " f"{r.dex_delay_s:7.0f}с") def open_window(parent, get_matches) -> None: """'Опережение DEX' dialog for the Meme Matcher window: pick coins, record N minutes, show the verdicts.""" import tkinter as tk from tkinter import ttk win = tk.Toplevel(parent) win.title("Опережение DEX → фьючерсы") win.geometry("1200x560") form = ttk.Frame(win, padding=6) form.pack(fill="x") minutes, coins, min_txns, thr = (tk.StringVar(value=v) for v in ("20", "10", "120", "0.15")) for label, var in (("Минут записи", minutes), ("Монет (до 13)", coins), ("Мин. сделок в пуле за час", min_txns), ("Движение DEX за 1 с, %", thr)): ttk.Label(form, text=label).pack(side="left", padx=(0, 4)) ttk.Entry(form, textvariable=var, width=7).pack(side="left", padx=(0, 10)) start_btn = ttk.Button(form, text="Записать и проверить") start_btn.pack(side="left", padx=4) stop_btn = ttk.Button(form, text="Остановить", state="disabled") stop_btn.pack(side="left") columns = {"symbol": ("Монета", 80), "verdict": ("Вывод", 210), "cex": ("Фьючерс", 70), "pool": ("Пул DEX", 140), "events": ("Движений DEX", 90), "lag": ("Лучший лаг, с", 85), "same": ("Та же секунда", 90), "follow": ("После t+1 → t+5", 105), "hit": ("Попадание", 75), "t": ("t-стат.", 60), "delay": ("Задержка данных DEX", 125)} tree = ttk.Treeview(win, columns=list(columns), show="headings", height=14) for key, (title, width) in columns.items(): tree.heading(key, text=title) tree.column(key, width=width, anchor="w") tree.tag_configure("lead", background="#e8f7e8") tree.pack(fill="both", expand=True, padx=6) status = tk.StringVar(value="Берутся монеты со статусом «совпадает», пулом на Solana/BSC/Base и фьючерсом на " "Binance/Bybit/Gate/MEXC. «После t+1 → t+5» — движение фьючерса в сторону DEX, " "начиная со следующей секунды после движения на DEX.") ttk.Label(win, textvariable=status, padding=6, wraplength=1150).pack(fill="x") stop_event = threading.Event() def show(results): tree.delete(*tree.get_children()) for r in results: tree.insert("", "end", tags=("lead",) if r.verdict.startswith("DEX опережает") else (), values=( r.symbol, r.verdict, r.cex, r.pool, r.events, f"{r.best_lag:+d}", f"{r.same_second:+.3f}%", f"{r.follow.get(5, 0):+.3f}%", f"{r.hit.get(5, 0) * 100:.0f}%", f"{r.t_stat:+.2f}", f"{r.dex_delay_s:.0f} с")) def log(text): win.after(0, status.set, text) def start(): matches = get_matches() if not matches: status.set("Сначала дождитесь сканирования в главном окне") return try: n_min, n_coins = float(minutes.get()), max(1, min(13, int(coins.get()))) n_txns, threshold = int(min_txns.get()), float(thr.get()) except ValueError: status.set("Проверьте числа в полях") return targets = pick_targets(matches, n_coins, n_txns) if not targets: status.set("Нет подходящих монет — уменьшите «Мин. сделок в пуле за час»") return stop_event.clear() start_btn.configure(state="disabled") stop_btn.configure(state="normal") def work(): rec = record(targets, n_min, log, stop_event) path = rec.save() results = analyze(targets, rec.cex, rec.dex, rec.gaps, threshold) save_results(results) win.after(0, finish, results, path) threading.Thread(target=work, daemon=True).start() def finish(results, path): start_btn.configure(state="normal") stop_btn.configure(state="disabled") show(results) leaders = [r.symbol for r in results if r.verdict.startswith("DEX опережает")] status.set(f"Запись: {path.name} · результаты: {RESULTS_CSV.name} · DEX опережает: " f"{', '.join(leaders) if leaders else 'не найдено'}") start_btn.configure(command=start) stop_btn.configure(command=lambda: (stop_event.set(), status.set("Останавливаю и считаю…"))) def main() -> None: import sys if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8") parser = argparse.ArgumentParser(description="DEX → CEX futures lead-lag for memecoins") parser.add_argument("--minutes", type=float, default=20) parser.add_argument("--coins", type=int, default=10) parser.add_argument("--min-txns", type=int, default=120, help="min swaps per hour in the DEX pool") parser.add_argument("--threshold", type=float, default=0.15, help="DEX move in one second, %%") parser.add_argument("--analyze", type=Path, help="analyse an existing recording instead of recording") args = parser.parse_args() if args.analyze: targets, cex, dex, meta = load(args.analyze) results = analyze(targets, cex, dex, meta.get("gaps"), args.threshold) else: matches = mm.scan() targets = pick_targets(matches, args.coins, args.min_txns) if not targets: print("Нет подходящих монет (совпадение цены, пул на Solana/BSC/Base, достаточно сделок в час)") return print("Монеты для записи:") for t in targets: print(f" {t.symbol:10s} {t.cex:8s} {t.cex_symbol:16s} {t.chain}/{t.dex} пул {t.pool[:10]}… " f"сделок в час {t.txns_h1}") rec = record(targets, args.minutes) path = rec.save() print(f"Запись: {path}") for e in rec.errors: print(" ошибка:", e) results = analyze(targets, rec.cex, rec.dex, rec.gaps, args.threshold) save_results(results) print_results(results) print(f"\nCSV: {RESULTS_CSV}") if __name__ == "__main__": main()