linux
This commit is contained in:
1 parent
f6f1ae20c2
commit
efd4e1dcf4
43 files changed
+25641
No files matched your search
@@ -0,0 +1,105 @@
|
||||
# Meme Matcher
|
||||
|
||||
Finds the same memecoins on **CEX perpetual futures** and on **DEX spot**, and compares their prices.
|
||||
|
||||
```
|
||||
py -3 meme_matcher.py # window
|
||||
py -3 meme_matcher.py --once # console table + meme_matches.csv
|
||||
```
|
||||
|
||||
Python 3.10+ standard library only; all APIs are public (no keys).
|
||||
|
||||
## Sources
|
||||
|
||||
| What | Where |
|
||||
|---|---|
|
||||
| USDT perpetuals: price, 24h volume, funding | Bybit, Binance, OKX, Gate, MEXC, Bitget, BingX |
|
||||
| Which coins are memecoins, market cap, contract addresses | CoinGecko, category `meme-token` (top 1000 by default, 4 pages × 250) |
|
||||
| DEX pools: price, liquidity, 24h volume | DexScreener (Solana, Ethereum, BSC, Base, Arbitrum, TON, …) |
|
||||
| DEX spot order book | HyperLiquid spot (USDC pairs) |
|
||||
|
||||
The CoinGecko contract list (~4 MB) is cached in `cache/` for 24 h.
|
||||
|
||||
## How a coin is identified
|
||||
|
||||
A ticker alone is not enough: CoinGecko lists 21 different "PEPE" tokens, and one exchange can list `CAT` and
|
||||
`1000CAT` as two different coins. So:
|
||||
|
||||
1. Contract size prefixes and suffixes are removed and the price is converted to one coin (`1000PEPE`, `1MBABYDOGE`,
|
||||
`SHIB1000`).
|
||||
2. Each CEX contract is tied to the CoinGecko meme token with the same symbol **whose price agrees** with it (within
|
||||
±50%); contracts that agree with no meme token are skipped (not a memecoin, or an unknown one).
|
||||
3. For that token's contract addresses every DexScreener pool is fetched; the token must be the pool's base asset.
|
||||
The chosen pool is the deepest one whose price is within ±25% of the CEX price; HyperLiquid spot is added by
|
||||
token name with the same price check.
|
||||
4. Status by the DEX − CEX price gap: **совпадает** ≤ 5%, **проверить** ≤ 25%, **разные монеты?** above that (only
|
||||
pools at a very different price exist — usually a copycat token on another chain), **нет на DEX**.
|
||||
|
||||
## Window
|
||||
|
||||
Exchange checkboxes, minimum DEX liquidity and CEX volume, number of CoinGecko pages, "only on DEX" and
|
||||
"only matching" filters. Columns sort on click; a double click opens the pool on DexScreener / HyperLiquid;
|
||||
"Сохранить CSV" saves what is shown. `(+N)` after the DEX means the coin also trades on N more chains at the same
|
||||
price. Funding is the largest absolute funding rate over the listed exchanges.
|
||||
|
||||
## Lead-lag: does the DEX move before the futures?
|
||||
|
||||
```
|
||||
py -3 leadlag.py --minutes 30 --coins 12 # scan, record, analyse
|
||||
py -3 leadlag.py --analyze recordings\leadlag_….jsonl.gz
|
||||
```
|
||||
|
||||
Also the «Опережение DEX…» button in the window. Coins: status «совпадает», a pool on **Solana, BSC or Base**
|
||||
(blocks ≤ 2 s; a 12 s Ethereum block cannot show a 1 s lead) with at least 120 swaps an hour (the most active pool
|
||||
is used), and a perpetual on Binance, Bybit, Gate or MEXC (in that order of preference).
|
||||
|
||||
Recorded at the same time:
|
||||
* futures trades over WebSockets with exchange timestamps in ms (Binance `fstream…/market/stream` aggTrade, Bybit
|
||||
publicTrade, Gate futures.trades, MEXC push.deal);
|
||||
* DEX swaps from GeckoTerminal (`/pools/{pool}/trades`, last 300 swaps, polled every 30 s, ≤ 26 requests a minute)
|
||||
with **on-chain block timestamps** — so the lead is measured on chain time, not on when the API showed the swap.
|
||||
|
||||
Recordings go to `recordings/`, verdicts to `leadlag_results.csv`.
|
||||
|
||||
Analysis on a 1-second grid (DEX: volume-weighted price of the block second; futures: last trade of the second):
|
||||
* correlation of 1-s returns at lags −10…+10 s (+ = futures after the DEX);
|
||||
* events — seconds where the DEX moved ≥ 0.15%: the futures move in the same direction in that second, and **from
|
||||
t+1 to t+3/5/10** — i.e. after the DEX second and the next one, so a sub-second reaction that merely lands in the
|
||||
next second does not count as a lead. Block times are whole seconds, so a lead under ~1 s cannot be told apart
|
||||
from "simultaneous".
|
||||
* verdicts: **DEX опережает ≥1 с** (t+1→t+5 move the DEX way, t ≥ 2, hit rate ≥ 60%, ≥ 10 events), **фьючерс
|
||||
опережает** (best correlation at a negative lag), **после DEX фьючерс откатывает**, **одновременно / нет
|
||||
опережения**, **мало движений DEX / мало данных**.
|
||||
|
||||
**Live use:** GeckoTerminal publishes swaps 1–2 minutes late (column «Задержка данных DEX»). The tool can find
|
||||
which coins lead; acting on a lead needs a direct chain feed (Solana RPC WebSocket on the pool), not this API.
|
||||
|
||||
## Autonomous search (autoscan)
|
||||
|
||||
```
|
||||
py -3 autoscan.py --minutes 15 --coins 12 # or autoscan.bat, or «Автопоиск…» → «Запустить» in the window
|
||||
```
|
||||
|
||||
Runs on its own in a loop: scan → up to 12 coins (earlier leaders are re-checked first, the rest rotate through all
|
||||
candidates) → 15 min recording → lead analysis → next cycle (one cycle ≈ 20 min). Every result is appended to
|
||||
`autoscan_history.csv`, the log to `autoscan.log`. A coin with «DEX опережает ≥1 с» whose pool is on Solana and of a
|
||||
type the simulator reads live (Raydium AMM v4 / CPMM, PumpSwap, Meteora DLMM — checked through the pool account's
|
||||
owner program) and whose futures are on Binance, Bybit or MEXC is added to the simulator's `../lead_connections.json`
|
||||
(never removed; the simulator's active connection is not changed; the simulator picks the new entry up within 30 s).
|
||||
Only one autoscan runs at a time (`autoscan.lock`); the manual «Опережение DEX…» recording shares GeckoTerminal's
|
||||
rate limit with it. «Автопоиск…» in the window shows the history (leaders highlighted, what was added) and starts or
|
||||
stops the background process, which keeps running when the windows are closed.
|
||||
|
||||
## Limits
|
||||
|
||||
* The meme universe is CoinGecko's `meme-token` category: memecoins that CoinGecko has not tagged, or that are
|
||||
outside the scanned pages, are not found.
|
||||
* The CoinGecko free API allows a few requests per minute; the scanner waits between pages and retries on HTTP 429.
|
||||
* Prices come from different moments (each API is polled once); small gaps are timing, not arbitrage. DEX prices
|
||||
do not include swap fees, slippage or gas.
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
py -3 -m unittest discover -s tests
|
||||
```
|
||||
@@ -0,0 +1,420 @@
|
||||
"""Autonomous DEX → futures lead search: scan, record, analyse, repeat — and hand the leaders to the simulator.
|
||||
|
||||
Each cycle:
|
||||
1. Meme Matcher scan (CEX perpetuals ↔ DEX pools, same coin, prices agree);
|
||||
2. up to N coins: coins that led before are re-checked first, the rest rotate through every candidate (most active
|
||||
pools first), so all of them get measured over a few cycles;
|
||||
3. record M minutes (CEX trades + on-chain DEX swaps) and analyse the lead (leadlag.analyze);
|
||||
4. every result goes to autoscan_history.csv; a coin where the DEX leads ≥ 1 s, on a Solana pool the simulator can
|
||||
read live (Raydium AMM v4 / CPMM / CLMM, PumpSwap, Meteora DLMM, Orca Whirlpool, PancakeSwap CLMM) and a futures exchange it can trade (Binance, Bybit,
|
||||
MEXC), is added to the simulator's connection list (../lead_connections.json) — never removed, the active
|
||||
connection is not changed;
|
||||
5. start again.
|
||||
|
||||
Run: py -3 autoscan.py --minutes 15 --coins 12 (or autoscan.bat; stop with Ctrl+C or by closing the window)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import leadlag as ll
|
||||
import meme_matcher as mm
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
SIM_DIR = ROOT.parent
|
||||
DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", SIM_DIR / "web_sim_data")).resolve()
|
||||
CONNECTIONS_FILE = DATA_DIR / "lead_connections.json"
|
||||
HISTORY_CSV = DATA_DIR / "autoscan_history.csv"
|
||||
LOG_FILE = DATA_DIR / "autoscan.log"
|
||||
LOCK_FILE = DATA_DIR / "autoscan.lock"
|
||||
LEAD_VERDICT = "DEX опережает ≥1 с"
|
||||
SIM_EXCHANGES = ["Bybit", "MEXC"] # futures the simulator can paper-trade on
|
||||
SUPPORTED_OWNERS = {
|
||||
"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8": "Raydium AMM v4",
|
||||
"CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C": "Raydium CPMM",
|
||||
"pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA": "PumpSwap",
|
||||
"LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo": "Meteora DLMM",
|
||||
"whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc": "Orca Whirlpool",
|
||||
"CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK": "Raydium CLMM",
|
||||
"HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq": "PancakeSwap CLMM",
|
||||
}
|
||||
HISTORY_COLUMNS = ["time", "cycle", "symbol", "verdict", "futures", "futures_symbol", "dex_pool", "pool_address",
|
||||
"dex_moves", "best_lag_s", "follow_t1_t5_pct", "hit_t5", "t_stat", "added_to_simulator"]
|
||||
|
||||
|
||||
def log(text: str) -> None:
|
||||
line = f"{datetime.now():%Y-%m-%d %H:%M:%S} {text}"
|
||||
print(line, flush=True)
|
||||
try:
|
||||
with LOG_FILE.open("a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def pool_owner(pool: str) -> str:
|
||||
"""Program that owns a Solana pool account (public RPC)."""
|
||||
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "getAccountInfo",
|
||||
"params": [pool, {"encoding": "base64", "dataSlice": {"offset": 0, "length": 0}}]}).encode()
|
||||
req = urllib.request.Request("https://api.mainnet-beta.solana.com", data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
value = json.loads(resp.read())["result"]["value"]
|
||||
return value["owner"] if value else ""
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return ""
|
||||
|
||||
|
||||
def simulator_connection(t: ll.Target) -> dict | None:
|
||||
"""The simulator's connection for a target, or None when the simulator cannot trade / read it live."""
|
||||
if t.chain != "solana" or t.cex not in SIM_EXCHANGES:
|
||||
return None
|
||||
exchange = t.cex.lower()
|
||||
return {"lead_market": "raydium", "lead_ticker": f"{t.symbol}USDTM", "lead_pool": t.pool,
|
||||
"follow_exchange": exchange, "follow_ticker": t.cex_symbol}
|
||||
|
||||
|
||||
def same_connection(a: dict, b: dict) -> bool:
|
||||
keys = ["lead_market", "follow_exchange", "follow_ticker"]
|
||||
keys.append("lead_pool" if a.get("lead_market") == "raydium" else "lead_ticker")
|
||||
return all(a.get(k) == b.get(k) for k in keys)
|
||||
|
||||
|
||||
def lw_removed(conn: dict) -> bool:
|
||||
"""The user deleted this pair from the simulator (lead_connections_removed.json)."""
|
||||
try:
|
||||
removed = json.loads((DATA_DIR / "lead_connections_removed.json").read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
return any(isinstance(r, dict) and same_connection(r, conn) for r in removed)
|
||||
|
||||
|
||||
def add_connection(conn: dict, path: Path = CONNECTIONS_FILE) -> bool:
|
||||
"""Append a connection to the simulator's list (re-read first, so nothing written meanwhile is lost)."""
|
||||
try:
|
||||
existing = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(existing, list):
|
||||
existing = []
|
||||
except (OSError, ValueError):
|
||||
existing = []
|
||||
if any(isinstance(c, dict) and same_connection(c, conn) for c in existing):
|
||||
return False
|
||||
existing.append(conn)
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(existing, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
os.replace(tmp, path)
|
||||
return True
|
||||
|
||||
|
||||
def choose_targets(candidates: list[ll.Target], leaders: list[str], offset: int, n: int) -> tuple[list, int]:
|
||||
"""Earlier leaders first (re-check), then the next coins of the rotation."""
|
||||
by_symbol = {t.symbol: t for t in candidates}
|
||||
chosen = [by_symbol[s] for s in leaders if s in by_symbol][:n]
|
||||
rest = [t for t in candidates if t.symbol not in {c.symbol for c in chosen}]
|
||||
if rest:
|
||||
start = offset % len(rest)
|
||||
rotated = rest[start:] + rest[:start]
|
||||
take = rotated[:max(0, n - len(chosen))]
|
||||
chosen += take
|
||||
offset = (start + len(take)) % len(rest)
|
||||
return chosen, offset
|
||||
|
||||
|
||||
def append_history(cycle: int, results: list[ll.LeadResult], targets: dict, added: dict,
|
||||
path: Path = HISTORY_CSV) -> None:
|
||||
new = not path.exists()
|
||||
with path.open("a", newline="", encoding="utf-8-sig") as f:
|
||||
w = csv.writer(f, delimiter=";")
|
||||
if new:
|
||||
w.writerow(HISTORY_COLUMNS)
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
for r in results:
|
||||
t = targets.get(r.symbol)
|
||||
w.writerow([now, cycle, r.symbol, r.verdict, r.cex, t.cex_symbol if t else "", r.pool, t.pool if t else "",
|
||||
r.events, r.best_lag, f"{r.follow.get(5, 0):+.3f}", f"{r.hit.get(5, 0):.2f}",
|
||||
f"{r.t_stat:+.2f}", added.get(r.symbol, "")])
|
||||
|
||||
|
||||
def read_leaders(path: Path = HISTORY_CSV, last_cycles: int = 3) -> list[str]:
|
||||
"""Coins that led in any of the last few cycles (to re-check first)."""
|
||||
try:
|
||||
rows = list(csv.DictReader(path.open(encoding="utf-8-sig"), delimiter=";"))
|
||||
except OSError:
|
||||
return []
|
||||
if not rows:
|
||||
return []
|
||||
top = max(int(r["cycle"]) for r in rows)
|
||||
return list(dict.fromkeys(r["symbol"] for r in rows
|
||||
if r["verdict"] == LEAD_VERDICT and int(r["cycle"]) > top - last_cycles))
|
||||
|
||||
|
||||
def last_cycle(path: Path = HISTORY_CSV) -> int:
|
||||
try:
|
||||
rows = list(csv.DictReader(path.open(encoding="utf-8-sig"), delimiter=";"))
|
||||
return max(int(r["cycle"]) for r in rows) if rows else 0
|
||||
except (OSError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def take_lock() -> bool:
|
||||
"""Allow one autoscan per application account."""
|
||||
try:
|
||||
pid = int(LOCK_FILE.read_text())
|
||||
if pid != os.getpid() and _alive(pid):
|
||||
return False
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
LOCK_FILE.write_text(str(os.getpid()))
|
||||
return True
|
||||
|
||||
|
||||
def _alive(pid: int) -> bool:
|
||||
if os.name != "nt":
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
import ctypes
|
||||
handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
||||
if not handle:
|
||||
return False
|
||||
code = ctypes.c_ulong()
|
||||
ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
return code.value == 259 # STILL_ACTIVE
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
CONFIG_FILE = DATA_DIR / "autoscan_config.json"
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
"""auto_add: add DEX leaders to the simulator by themselves (off: the web page's «Добавить» button does it)."""
|
||||
try:
|
||||
cfg = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
cfg = {}
|
||||
return {"auto_add": bool(cfg.get("auto_add", False))}
|
||||
|
||||
|
||||
def save_config(cfg: dict) -> None:
|
||||
CONFIG_FILE.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def run(minutes: float, coins: int, min_txns: int, threshold: float, stop: threading.Event | None = None) -> None:
|
||||
import traceback
|
||||
stop = stop or threading.Event()
|
||||
ll.CEX_PRIORITY = SIM_EXCHANGES + [e for e in ll.CEX_PRIORITY if e not in SIM_EXCHANGES]
|
||||
state = {"cycle": last_cycle(), "offset": 0}
|
||||
while not stop.is_set():
|
||||
try:
|
||||
_cycle(state, minutes, coins, min_txns, threshold, stop)
|
||||
except Exception:
|
||||
log("ошибка цикла, продолжаю через минуту:\n" + traceback.format_exc())
|
||||
stop.wait(60)
|
||||
|
||||
|
||||
def _cycle(st: dict, minutes: float, coins: int, min_txns: int, threshold: float, stop: threading.Event) -> None:
|
||||
st["cycle"] += 1
|
||||
cycle = st["cycle"]
|
||||
log(f"=== цикл {cycle}: сканирую биржи и DEX")
|
||||
try:
|
||||
matches = mm.scan(log=lambda s: None)
|
||||
except Exception as exc:
|
||||
log(f"скан не удался: {exc}; повтор через минуту")
|
||||
stop.wait(60)
|
||||
return
|
||||
candidates = ll.pick_targets(matches, max_coins=1000, min_txns_h1=min_txns)
|
||||
leaders = read_leaders()
|
||||
targets, st["offset"] = choose_targets(candidates, leaders, st["offset"], coins)
|
||||
if not targets:
|
||||
log("подходящих монет нет; повтор через 5 минут")
|
||||
stop.wait(300)
|
||||
return
|
||||
log(f"кандидатов {len(candidates)}, в этом цикле: " + ", ".join(
|
||||
f"{t.symbol}{'*' if t.symbol in leaders else ''} ({t.cex}, {t.chain}/{t.dex})" for t in targets)
|
||||
+ " (* — перепроверка лидера)")
|
||||
# record() sets its stop event when it is done (to stop its threads), so it gets its own one: sharing the
|
||||
# loop's event used to end the whole autoscan after the first cycle
|
||||
rec = ll.record(targets, minutes, log=lambda s: None, stop=threading.Event())
|
||||
if stop.is_set():
|
||||
return
|
||||
path = rec.save()
|
||||
results = ll.analyze(targets, rec.cex, rec.dex, rec.gaps, threshold)
|
||||
by_symbol = {t.symbol: t for t in targets}
|
||||
auto_add = load_config()["auto_add"]
|
||||
added = {}
|
||||
for r in results:
|
||||
if r.verdict != LEAD_VERDICT:
|
||||
continue
|
||||
t = by_symbol[r.symbol]
|
||||
conn = simulator_connection(t)
|
||||
if conn is None:
|
||||
added[r.symbol] = f"нет: {t.chain}/{t.cex} не поддерживается симулятором"
|
||||
continue
|
||||
owner = pool_owner(t.pool)
|
||||
if owner not in SUPPORTED_OWNERS:
|
||||
added[r.symbol] = "нет: тип пула не читается симулятором вживую"
|
||||
continue
|
||||
if auto_add and lw_removed(conn):
|
||||
added[r.symbol] = f"можно добавить ({SUPPORTED_OWNERS[owner]}; удалена вручную — сама не добавляется)"
|
||||
elif auto_add:
|
||||
added[r.symbol] = ("да" if add_connection(conn) else "уже был") + f" ({SUPPORTED_OWNERS[owner]})"
|
||||
else:
|
||||
added[r.symbol] = f"можно добавить ({SUPPORTED_OWNERS[owner]})"
|
||||
append_history(cycle, results, by_symbol, added)
|
||||
ll.save_results(results)
|
||||
found = [f"{r.symbol} ({added.get(r.symbol, '')})" for r in results if r.verdict == LEAD_VERDICT]
|
||||
log(f"цикл {cycle} готов, запись {path.name}; DEX опережает: {', '.join(found) if found else 'не найдено'}")
|
||||
|
||||
|
||||
def running_pid() -> int | None:
|
||||
try:
|
||||
pid = int(LOCK_FILE.read_text())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return pid if _alive(pid) else None
|
||||
|
||||
|
||||
def start_background(minutes: float = 15, coins: int = 12) -> None:
|
||||
"""Start autoscan as its own hidden process, so it keeps running when the windows are closed."""
|
||||
import subprocess
|
||||
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0)
|
||||
subprocess.Popen([sys.executable, str(ROOT / "autoscan.py"), "--minutes", str(minutes), "--coins", str(coins)],
|
||||
cwd=ROOT, creationflags=flags, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=os.name != "nt")
|
||||
|
||||
|
||||
def stop_background() -> None:
|
||||
pid = running_pid()
|
||||
if pid:
|
||||
import subprocess
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True)
|
||||
else:
|
||||
try:
|
||||
os.kill(pid, 15)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
LOCK_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
log("остановлено из окна")
|
||||
|
||||
|
||||
def open_window(parent) -> None:
|
||||
"""History of the autonomous search + start/stop, refreshed every 15 s."""
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
win = tk.Toplevel(parent)
|
||||
win.title("Автопоиск: DEX опережает фьючерсы")
|
||||
win.geometry("1250x620")
|
||||
top = ttk.Frame(win, padding=6)
|
||||
top.pack(fill="x")
|
||||
minutes, coins = tk.StringVar(value="15"), tk.StringVar(value="12")
|
||||
ttk.Label(top, text="Минут на цикл").pack(side="left")
|
||||
ttk.Entry(top, textvariable=minutes, width=5).pack(side="left", padx=(4, 10))
|
||||
ttk.Label(top, text="Монет за цикл (до 13)").pack(side="left")
|
||||
ttk.Entry(top, textvariable=coins, width=5).pack(side="left", padx=(4, 10))
|
||||
start_btn = ttk.Button(top, text="▶ Запустить автопоиск")
|
||||
start_btn.pack(side="left", padx=4)
|
||||
stop_btn = ttk.Button(top, text="■ Остановить")
|
||||
stop_btn.pack(side="left")
|
||||
state_var = tk.StringVar()
|
||||
ttk.Label(top, textvariable=state_var, padding=(10, 0)).pack(side="left")
|
||||
only_leaders = tk.BooleanVar(value=False)
|
||||
ttk.Checkbutton(top, text="Только «DEX опережает»", variable=only_leaders, command=lambda: fill()).pack(side="left")
|
||||
cols = {"time": ("Время", 110), "cycle": ("Цикл", 45), "symbol": ("Монета", 80), "verdict": ("Вывод", 200),
|
||||
"futures": ("Фьючерс", 70), "dex_pool": ("Пул DEX", 130), "dex_moves": ("Движений", 70),
|
||||
"best_lag_s": ("Лаг, с", 50), "follow_t1_t5_pct": ("t+1→t+5", 70), "hit_t5": ("Попад.", 55),
|
||||
"t_stat": ("t", 50), "added_to_simulator": ("В симулятор", 230)}
|
||||
tree = ttk.Treeview(win, columns=list(cols), show="headings", height=18)
|
||||
for key, (title, width) in cols.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)
|
||||
log_var = tk.StringVar()
|
||||
ttk.Label(win, textvariable=log_var, padding=6, wraplength=1200, justify="left", foreground="#444").pack(fill="x")
|
||||
|
||||
def fill() -> None:
|
||||
tree.delete(*tree.get_children())
|
||||
try:
|
||||
rows = list(csv.DictReader(HISTORY_CSV.open(encoding="utf-8-sig"), delimiter=";"))
|
||||
except OSError:
|
||||
rows = []
|
||||
for r in reversed(rows[-500:]):
|
||||
if only_leaders.get() and r["verdict"] != LEAD_VERDICT:
|
||||
continue
|
||||
tree.insert("", "end", values=[r.get(k, "") for k in cols],
|
||||
tags=("lead",) if r["verdict"] == LEAD_VERDICT else ())
|
||||
|
||||
def refresh() -> None:
|
||||
pid = running_pid()
|
||||
state_var.set(f"автопоиск работает (процесс {pid})" if pid else "автопоиск остановлен")
|
||||
start_btn.configure(state="disabled" if pid else "normal")
|
||||
stop_btn.configure(state="normal" if pid else "disabled")
|
||||
fill()
|
||||
try:
|
||||
lines = LOG_FILE.read_text(encoding="utf-8").splitlines()[-4:]
|
||||
except OSError:
|
||||
lines = []
|
||||
log_var.set("\n".join(lines))
|
||||
if win.winfo_exists():
|
||||
win.after(15000, refresh)
|
||||
|
||||
def start() -> None:
|
||||
try:
|
||||
m, n = float(minutes.get()), max(1, min(13, int(coins.get())))
|
||||
except ValueError:
|
||||
state_var.set("проверьте числа")
|
||||
return
|
||||
start_background(m, n)
|
||||
win.after(1500, refresh)
|
||||
|
||||
start_btn.configure(command=start)
|
||||
stop_btn.configure(command=lambda: (stop_background(), win.after(500, refresh)))
|
||||
refresh()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description="autonomous DEX → futures lead search")
|
||||
parser.add_argument("--minutes", type=float, default=15, help="recording per cycle")
|
||||
parser.add_argument("--coins", type=int, default=12, help="coins per cycle (GeckoTerminal allows ~13)")
|
||||
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, %%")
|
||||
args = parser.parse_args()
|
||||
if not take_lock():
|
||||
print("Автопоиск уже запущен (autoscan.lock) — второй экземпляр не нужен")
|
||||
return
|
||||
try:
|
||||
run(args.minutes, min(13, args.coins), args.min_txns, args.threshold)
|
||||
except KeyboardInterrupt:
|
||||
log("остановлено")
|
||||
finally:
|
||||
try:
|
||||
LOCK_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,591 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,714 @@
|
||||
"""Meme Matcher: the same memecoins on CEX perpetual futures and on DEX spot.
|
||||
|
||||
Sources (public APIs, no keys):
|
||||
* CEX USDT perpetuals: Bybit, Binance, OKX, Gate, MEXC, Bitget, BingX - symbol, price, 24h volume, funding.
|
||||
* CoinGecko category "meme-token" - which coins are memecoins, their market cap and contract addresses.
|
||||
* DexScreener - the most liquid DEX pair of each contract (Solana, Ethereum, BSC, Base, Arbitrum, ...).
|
||||
* HyperLiquid spot - matched by token name and price.
|
||||
|
||||
A ticker alone does not identify a coin (CoinGecko has 21 different "PEPE" tokens), so a CEX symbol is tied to
|
||||
the meme token with the same symbol whose price agrees with the CEX price, and the DEX pair is looked up by that
|
||||
token's contract address. The DEX price is compared with the CEX price again: a large gap means a different coin.
|
||||
|
||||
Run: py -3 meme_matcher.py (window)
|
||||
py -3 meme_matcher.py --once (console table + meme_matches.csv)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import webbrowser
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
CACHE_DIR = ROOT / "cache"
|
||||
OUT_CSV = ROOT / "meme_matches.csv"
|
||||
USER_AGENT = "Mozilla/5.0 (meme-matcher)"
|
||||
|
||||
MATCH_PCT = 5.0 # DEX vs CEX price within this -> "совпадает"
|
||||
CHECK_PCT = 25.0 # up to this -> "проверить"; beyond -> probably a different coin
|
||||
SYMBOL_PRICE_TOL = 0.5 # CoinGecko vs CEX price: |log ratio| below ln(1.5) still counts as the same coin
|
||||
|
||||
# CoinGecko platform id -> DexScreener chain id
|
||||
CHAINS = {
|
||||
"solana": "solana", "ethereum": "ethereum", "binance-smart-chain": "bsc", "base": "base",
|
||||
"arbitrum-one": "arbitrum", "polygon-pos": "polygon", "avalanche": "avalanche", "optimistic-ethereum": "optimism",
|
||||
"the-open-network": "ton", "sui": "sui", "tron": "tron", "hyperevm": "hyperevm", "blast": "blast",
|
||||
"fantom": "fantom", "sonic": "sonic", "mantle": "mantle", "cronos": "cronos", "linea": "linea",
|
||||
"zksync": "zksync", "abstract": "abstract", "berachain": "berachain", "aptos": "aptos", "near-protocol": "near",
|
||||
"pulsechain": "pulsechain", "unichain": "unichain", "monad": "monad", "plasma": "plasma",
|
||||
}
|
||||
EVM_CHAINS = {"ethereum", "bsc", "base", "arbitrum", "polygon", "avalanche", "optimism", "hyperevm", "blast",
|
||||
"fantom", "sonic", "mantle", "cronos", "linea", "zksync", "abstract", "berachain", "pulsechain",
|
||||
"unichain", "monad", "plasma"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# HTTP
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
def http_json(url: str, body: dict | None = None, retries: int = 3, timeout: float = 30):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
for attempt in range(retries):
|
||||
req = urllib.request.Request(url, data=data, headers={"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return json.loads(resp.read())
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 429 and attempt < retries - 1: # rate limit (CoinGecko free tier)
|
||||
time.sleep(20 * (attempt + 1))
|
||||
continue
|
||||
raise
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
if attempt < retries - 1:
|
||||
time.sleep(2)
|
||||
continue
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# CEX perpetual futures
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class Listing:
|
||||
exchange: str
|
||||
symbol: str # as the exchange names it
|
||||
base: str # coin ticker without the size prefix, upper case
|
||||
multiplier: float # 1000PEPE -> 1000 (one contract unit = 1000 coins)
|
||||
price: float # price of ONE coin
|
||||
volume_usd: float
|
||||
funding: float | None = None
|
||||
|
||||
|
||||
_PREFIX = re.compile(r"^(1000000|100000|10000|1000|100|1M)(?=[A-Z])")
|
||||
_SUFFIX = re.compile(r"^([A-Z][A-Z0-9]*?)(1000000|10000|1000)$")
|
||||
|
||||
|
||||
def split_base(raw: str) -> tuple[str, float]:
|
||||
"""'1000PEPE' -> ('PEPE', 1000); '1MBABYDOGE' -> ('BABYDOGE', 1e6); 'SHIB1000' -> ('SHIB', 1000); '1INCH' stays."""
|
||||
raw = raw.upper()
|
||||
m = _PREFIX.match(raw)
|
||||
if m:
|
||||
mult = 1_000_000.0 if m.group(1) == "1M" else float(m.group(1))
|
||||
return raw[m.end():], mult
|
||||
m = _SUFFIX.match(raw)
|
||||
if m and len(m.group(1)) >= 2:
|
||||
return m.group(1), float(m.group(2))
|
||||
return raw, 1.0
|
||||
|
||||
|
||||
def _f(value, default=0.0) -> float:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _listing(exchange: str, symbol: str, raw_base: str, price, volume_usd, funding=None) -> Listing | None:
|
||||
base, mult = split_base(raw_base)
|
||||
price = _f(price)
|
||||
if not base or price <= 0:
|
||||
return None
|
||||
return Listing(exchange, symbol, base, mult, price / mult, _f(volume_usd),
|
||||
None if funding in (None, "") else _f(funding))
|
||||
|
||||
|
||||
def parse_bybit(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data["result"]["list"]:
|
||||
s = t["symbol"]
|
||||
if s.endswith("USDT"):
|
||||
out.append(_listing("Bybit", s, s[:-4], t.get("lastPrice"), t.get("turnover24h"), t.get("fundingRate")))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
def parse_binance(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data:
|
||||
s = t["symbol"]
|
||||
if s.endswith("USDT") and "_" not in s:
|
||||
out.append(_listing("Binance", s, s[:-4], t.get("lastPrice"), t.get("quoteVolume")))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
def parse_okx(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data["data"]:
|
||||
s = t["instId"]
|
||||
if s.endswith("-USDT-SWAP"):
|
||||
last = _f(t.get("last"))
|
||||
out.append(_listing("OKX", s, s[:-10], last, _f(t.get("volCcy24h")) * last))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
def parse_gate(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data:
|
||||
s = t["contract"]
|
||||
if s.endswith("_USDT"):
|
||||
out.append(_listing("Gate", s, s[:-5], t.get("last"), t.get("volume_24h_quote"), t.get("funding_rate")))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
def parse_mexc(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data["data"]:
|
||||
s = t["symbol"]
|
||||
if s.endswith("_USDT"):
|
||||
out.append(_listing("MEXC", s, s[:-5], t.get("lastPrice"), t.get("amount24"), t.get("fundingRate")))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
def parse_bitget(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data["data"]:
|
||||
s = t["symbol"]
|
||||
if s.endswith("USDT"):
|
||||
out.append(_listing("Bitget", s, s[:-4], t.get("lastPr"), t.get("usdtVolume"), t.get("fundingRate")))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
def parse_bingx(data) -> list[Listing]:
|
||||
out = []
|
||||
for t in data["data"]:
|
||||
s = t["symbol"]
|
||||
if s.endswith("-USDT"):
|
||||
out.append(_listing("BingX", s, s[:-5], t.get("lastPrice"), t.get("quoteVolume")))
|
||||
return [x for x in out if x]
|
||||
|
||||
|
||||
CEX_SOURCES = {
|
||||
"Bybit": ("https://api.bybit.com/v5/market/tickers?category=linear", parse_bybit),
|
||||
"Gate": ("https://api.gateio.ws/api/v4/futures/usdt/tickers", parse_gate),
|
||||
"MEXC": ("https://contract.mexc.com/api/v1/contract/ticker", parse_mexc),
|
||||
}
|
||||
|
||||
|
||||
def fetch_cex(exchanges: list[str], log=print) -> list[Listing]:
|
||||
def one(name):
|
||||
url, parser = CEX_SOURCES[name]
|
||||
try:
|
||||
items = parser(http_json(url))
|
||||
log(f"{name}: {len(items)} фьючерсов")
|
||||
return items
|
||||
except Exception as exc: # one exchange down must not stop the rest
|
||||
log(f"{name}: ошибка {exc}")
|
||||
return []
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(exchanges) or 1) as pool:
|
||||
return [x for chunk in pool.map(one, exchanges) for x in chunk]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# CoinGecko: which coins are memes, and their contracts
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class MemeCoin:
|
||||
cg_id: str
|
||||
symbol: str # upper case
|
||||
name: str
|
||||
price: float
|
||||
market_cap: float
|
||||
platforms: dict[str, str] = field(default_factory=dict) # CoinGecko platform -> contract
|
||||
|
||||
|
||||
def fetch_memes(pages: int, log=print) -> list[dict]:
|
||||
rows = []
|
||||
for page in range(1, pages + 1):
|
||||
chunk = http_json("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token"
|
||||
f"&order=market_cap_desc&per_page=250&page={page}") or []
|
||||
rows += chunk
|
||||
log(f"CoinGecko: мемкойнов {len(rows)}")
|
||||
if len(chunk) < 250:
|
||||
break
|
||||
time.sleep(2.5) # free tier: a few requests per minute
|
||||
return rows
|
||||
|
||||
|
||||
def fetch_platforms(max_age_hours: float = 24, log=print) -> dict[str, dict[str, str]]:
|
||||
"""CoinGecko id -> {platform: contract}; the 4 MB list is cached for a day."""
|
||||
CACHE_DIR.mkdir(exist_ok=True)
|
||||
path = CACHE_DIR / "coingecko_platforms.json"
|
||||
if path.exists() and time.time() - path.stat().st_mtime < max_age_hours * 3600:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
data = http_json("https://api.coingecko.com/api/v3/coins/list?include_platform=true") or []
|
||||
platforms = {c["id"]: {k: v for k, v in (c.get("platforms") or {}).items() if k and v} for c in data}
|
||||
path.write_text(json.dumps(platforms), encoding="utf-8")
|
||||
log(f"CoinGecko: адреса контрактов {len(platforms)} монет")
|
||||
return platforms
|
||||
|
||||
|
||||
def build_memes(markets: list[dict], platforms: dict[str, dict[str, str]]) -> list[MemeCoin]:
|
||||
out = []
|
||||
for m in markets:
|
||||
price = _f(m.get("current_price"))
|
||||
if not m.get("symbol") or price <= 0:
|
||||
continue
|
||||
out.append(MemeCoin(m["id"], m["symbol"].upper(), m.get("name") or m["id"], price, _f(m.get("market_cap")),
|
||||
platforms.get(m["id"], {})))
|
||||
return out
|
||||
|
||||
|
||||
def pick_coin(base: str, cex_price: float, memes_by_symbol: dict[str, list[MemeCoin]]) -> MemeCoin | None:
|
||||
"""The meme token behind a CEX ticker: same symbol, price closest to the CEX price (and not wildly off)."""
|
||||
best, best_gap = None, None
|
||||
for coin in memes_by_symbol.get(base.upper(), []):
|
||||
gap = abs(math.log(coin.price / cex_price))
|
||||
if best_gap is None or gap < best_gap:
|
||||
best, best_gap = coin, gap
|
||||
if best is None or best_gap > math.log(1 + SYMBOL_PRICE_TOL) + 1e-12:
|
||||
return None
|
||||
return best
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# DEX
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class DexPair:
|
||||
source: str # DexScreener / HyperLiquid
|
||||
chain: str
|
||||
dex: str
|
||||
pair: str # e.g. PEPE/WETH
|
||||
price: float
|
||||
liquidity_usd: float
|
||||
volume_usd: float
|
||||
contract: str
|
||||
url: str
|
||||
pair_address: str = ""
|
||||
txns_h1: int = 0 # swaps in the last hour (DexScreener)
|
||||
|
||||
|
||||
def best_pairs(pairs: list[dict]) -> dict[tuple[str, str], DexPair]:
|
||||
"""(chain, lower-case token address) -> its most liquid pair where the token is the BASE asset."""
|
||||
out: dict[tuple[str, str], DexPair] = {}
|
||||
for p in pairs:
|
||||
base = p.get("baseToken") or {}
|
||||
price = _f(p.get("priceUsd"))
|
||||
if not base.get("address") or price <= 0:
|
||||
continue
|
||||
key = (p.get("chainId", ""), base["address"].lower())
|
||||
liq = _f((p.get("liquidity") or {}).get("usd"))
|
||||
if key in out and out[key].liquidity_usd >= liq:
|
||||
continue
|
||||
h1 = (p.get("txns") or {}).get("h1") or {}
|
||||
out[key] = DexPair("DexScreener", p.get("chainId", ""), p.get("dexId", ""),
|
||||
f"{base.get('symbol', '')}/{(p.get('quoteToken') or {}).get('symbol', '')}", price, liq,
|
||||
_f((p.get("volume") or {}).get("h24")), base["address"], p.get("url", ""),
|
||||
p.get("pairAddress", ""), int(_f(h1.get("buys")) + _f(h1.get("sells"))))
|
||||
return out
|
||||
|
||||
|
||||
def fetch_dexscreener(contracts: dict[str, set[str]], log=print) -> dict[tuple[str, str], list[DexPair]]:
|
||||
"""contracts: DexScreener chain -> addresses. One request per contract returns all its pools (DexScreener
|
||||
allows ~300 requests a minute); the batch endpoint returns only one pool per token, often not the deepest."""
|
||||
jobs = [(chain, address) for chain, addresses in contracts.items() for address in sorted(addresses)]
|
||||
|
||||
def one(job):
|
||||
chain, address = job
|
||||
try:
|
||||
return http_json(f"https://api.dexscreener.com/token-pairs/v1/{chain}/{address}") or []
|
||||
except Exception as exc:
|
||||
log(f"DexScreener {chain} {address[:10]}…: ошибка {exc}")
|
||||
return []
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
pairs = [p for chunk in pool.map(one, jobs) for p in chunk]
|
||||
log(f"DexScreener: {len(pairs)} пар по {len(jobs)} контрактам")
|
||||
return all_pairs(pairs)
|
||||
|
||||
|
||||
def all_pairs(pairs: list[dict]) -> dict[tuple[str, str], list[DexPair]]:
|
||||
"""(chain, lower-case token address) -> every pool where the token is the BASE asset, deepest first."""
|
||||
out: dict[tuple[str, str], list[DexPair]] = {}
|
||||
seen = set()
|
||||
for p in pairs:
|
||||
if p.get("pairAddress") in seen:
|
||||
continue
|
||||
seen.add(p.get("pairAddress"))
|
||||
best = best_pairs([p])
|
||||
for key, pair in best.items():
|
||||
out.setdefault(key, []).append(pair)
|
||||
for items in out.values():
|
||||
items.sort(key=lambda d: (-d.liquidity_usd, -d.volume_usd))
|
||||
return out
|
||||
|
||||
|
||||
def parse_hyperliquid_spot(data) -> dict[str, DexPair]:
|
||||
"""Upper-case token name -> its USDC spot pair on HyperLiquid."""
|
||||
meta, ctxs = data
|
||||
tokens = {t["index"]: t for t in meta["tokens"]}
|
||||
out = {}
|
||||
for market in meta["universe"]:
|
||||
base_i, quote_i = market["tokens"]
|
||||
if tokens.get(quote_i, {}).get("name") != "USDC" or market["index"] >= len(ctxs):
|
||||
continue
|
||||
ctx = ctxs[market["index"]]
|
||||
price = _f(ctx.get("midPx")) or _f(ctx.get("markPx"))
|
||||
name = tokens.get(base_i, {}).get("name", "").upper()
|
||||
if not name or price <= 0:
|
||||
continue
|
||||
pair = DexPair("HyperLiquid", "hyperliquid", "hyperliquid", f"{name}/USDC", price, 0.0,
|
||||
_f(ctx.get("dayNtlVlm")), tokens[base_i].get("tokenId", ""),
|
||||
f"https://app.hyperliquid.xyz/trade/{market['name']}")
|
||||
if name not in out or pair.volume_usd > out[name].volume_usd:
|
||||
out[name] = pair
|
||||
return out
|
||||
|
||||
|
||||
def fetch_hyperliquid(log=print) -> dict[str, DexPair]:
|
||||
try:
|
||||
out = parse_hyperliquid_spot(http_json("https://api.hyperliquid.xyz/info", {"type": "spotMetaAndAssetCtxs"}))
|
||||
log(f"HyperLiquid: спот-пар {len(out)}")
|
||||
return out
|
||||
except Exception as exc:
|
||||
log(f"HyperLiquid: ошибка {exc}")
|
||||
return {}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Matching
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class Match:
|
||||
symbol: str
|
||||
name: str
|
||||
cg_id: str
|
||||
market_cap: float
|
||||
cex: list[Listing]
|
||||
cex_price: float # median price of one coin over the CEX listings
|
||||
cex_volume_usd: float
|
||||
dex: DexPair | None
|
||||
dex_count: int # how many chains the token has a DEX pair on
|
||||
diff_pct: float | None # (DEX - CEX) / CEX
|
||||
status: str
|
||||
pools: list[DexPair] = field(default_factory=list) # every DEX pool whose price agrees with the CEX
|
||||
|
||||
@property
|
||||
def exchanges(self) -> str:
|
||||
return ", ".join(sorted(f"{l.exchange}" + (f"×{l.multiplier:g}" if l.multiplier != 1 else "")
|
||||
for l in self.cex))
|
||||
|
||||
@property
|
||||
def funding(self) -> float | None:
|
||||
values = [l.funding for l in self.cex if l.funding is not None]
|
||||
return max(values, key=abs) if values else None
|
||||
|
||||
|
||||
def status_of(diff_pct: float | None) -> str:
|
||||
if diff_pct is None:
|
||||
return "нет на DEX"
|
||||
if abs(diff_pct) <= MATCH_PCT:
|
||||
return "совпадает"
|
||||
if abs(diff_pct) <= CHECK_PCT:
|
||||
return "проверить"
|
||||
return "разные монеты?"
|
||||
|
||||
|
||||
def contracts_for(coins: list[MemeCoin]) -> dict[str, set[str]]:
|
||||
out: dict[str, set[str]] = {}
|
||||
for coin in coins:
|
||||
for platform, address in coin.platforms.items():
|
||||
chain = CHAINS.get(platform)
|
||||
if chain:
|
||||
out.setdefault(chain, set()).add(address.lower() if chain in EVM_CHAINS else address)
|
||||
return out
|
||||
|
||||
|
||||
def _agrees(price: float, ref: float, pct: float = CHECK_PCT) -> bool:
|
||||
return price > 0 and ref > 0 and abs(math.log(price / ref)) <= math.log(1 + pct / 100)
|
||||
|
||||
|
||||
def match(listings: list[Listing], memes: list[MemeCoin], dex_pairs: dict[tuple[str, str], list[DexPair]],
|
||||
hl_pairs: dict[str, DexPair]) -> list[Match]:
|
||||
by_symbol: dict[str, list[MemeCoin]] = {}
|
||||
for coin in memes:
|
||||
by_symbol.setdefault(coin.symbol, []).append(coin)
|
||||
# Each CEX contract is tied to a coin by its own price: CAT and 1000CAT on one exchange can be two coins.
|
||||
groups: dict[str, tuple[MemeCoin, list[Listing]]] = {}
|
||||
for l in listings:
|
||||
coin = pick_coin(l.base, l.price, by_symbol)
|
||||
if coin is not None:
|
||||
groups.setdefault(coin.cg_id, (coin, []))[1].append(l)
|
||||
out = []
|
||||
for coin, items in groups.values():
|
||||
cex_price = statistics.median(l.price for l in items)
|
||||
pools = []
|
||||
for platform, address in coin.platforms.items():
|
||||
chain = CHAINS.get(platform)
|
||||
if chain:
|
||||
pools += dex_pairs.get((chain, address.lower()), [])
|
||||
hl = hl_pairs.get(coin.symbol)
|
||||
if hl and _agrees(hl.price, cex_price):
|
||||
pools.append(hl)
|
||||
# The deepest pool whose price agrees with the CEX; a lone disagreeing pool is still shown, flagged.
|
||||
agreeing = [p for p in pools if _agrees(p.price, cex_price)]
|
||||
candidates = agreeing or pools
|
||||
dex = max(candidates, key=lambda p: (p.liquidity_usd, p.volume_usd)) if candidates else None
|
||||
diff = (dex.price / cex_price - 1) * 100 if dex else None
|
||||
chains = len({p.chain for p in agreeing})
|
||||
out.append(Match(coin.symbol, coin.name, coin.cg_id, coin.market_cap, items, cex_price,
|
||||
sum(l.volume_usd for l in items), dex, chains, diff, status_of(diff), agreeing))
|
||||
out.sort(key=lambda m: -m.cex_volume_usd)
|
||||
return out
|
||||
|
||||
|
||||
def scan(exchanges: list[str] | None = None, meme_pages: int = 4, log=print) -> list[Match]:
|
||||
exchanges = exchanges or list(CEX_SOURCES)
|
||||
listings = fetch_cex(exchanges, log)
|
||||
memes = build_memes(fetch_memes(meme_pages, log), fetch_platforms(log=log))
|
||||
bases = {l.base for l in listings}
|
||||
wanted = [c for c in memes if c.symbol in bases]
|
||||
log(f"Мемкойнов с фьючерсами на CEX (по тикеру): {len(wanted)}")
|
||||
dex_pairs = fetch_dexscreener(contracts_for(wanted), log)
|
||||
hl_pairs = fetch_hyperliquid(log)
|
||||
result = match(listings, wanted, dex_pairs, hl_pairs)
|
||||
log(f"Готово: совпадений {len(result)}, из них на DEX {sum(m.dex is not None for m in result)}")
|
||||
return result
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Output
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
CSV_COLUMNS = ["symbol", "name", "coingecko_id", "market_cap_usd", "cex_exchanges", "cex_price", "cex_volume_24h_usd",
|
||||
"max_funding", "dex_source", "dex_chain", "dex", "dex_pair", "dex_price", "dex_liquidity_usd",
|
||||
"dex_volume_24h_usd", "dex_chains", "diff_pct", "status", "contract", "url"]
|
||||
|
||||
|
||||
def to_row(m: Match) -> list:
|
||||
d = m.dex
|
||||
return [m.symbol, m.name, m.cg_id, f"{m.market_cap:.0f}", m.exchanges, f"{m.cex_price:.10g}",
|
||||
f"{m.cex_volume_usd:.0f}", "" if m.funding is None else f"{m.funding:.6f}",
|
||||
d.source if d else "", d.chain if d else "", d.dex if d else "", d.pair if d else "",
|
||||
f"{d.price:.10g}" if d else "", f"{d.liquidity_usd:.0f}" if d else "", f"{d.volume_usd:.0f}" if d else "",
|
||||
m.dex_count, "" if m.diff_pct is None else f"{m.diff_pct:+.2f}", m.status, d.contract if d else "",
|
||||
d.url if d else ""]
|
||||
|
||||
|
||||
def save_csv(matches: list[Match], path: Path = OUT_CSV) -> None:
|
||||
with path.open("w", newline="", encoding="utf-8-sig") as f:
|
||||
writer = csv.writer(f, delimiter=";")
|
||||
writer.writerow(CSV_COLUMNS)
|
||||
writer.writerows(to_row(m) for m in matches)
|
||||
|
||||
|
||||
def human(value: float) -> str:
|
||||
for unit, size in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
|
||||
if abs(value) >= size:
|
||||
return f"{value / size:.1f}{unit}"
|
||||
return f"{value:.0f}"
|
||||
|
||||
|
||||
def print_table(matches: list[Match]) -> None:
|
||||
print(f"{'Монета':12s} {'CEX фьючерсы':38s} {'Объём CEX':>9s} {'DEX':24s} {'Ликв.':>7s} {'Разница':>8s} Статус")
|
||||
for m in matches:
|
||||
d = m.dex
|
||||
dex = f"{d.chain}/{d.dex}" if d else "—"
|
||||
print(f"{m.symbol:12s} {m.exchanges[:38]:38s} {human(m.cex_volume_usd):>9s} {dex[:24]:24s} "
|
||||
f"{human(d.liquidity_usd) if d else '':>7s} {'' if m.diff_pct is None else f'{m.diff_pct:+.2f}%':>8s} "
|
||||
f"{m.status}")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
# Window
|
||||
# --------------------------------------------------------------------------------------------
|
||||
|
||||
def run_window() -> None:
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
root = tk.Tk()
|
||||
root.title("Meme Matcher — мемкойны: фьючерсы CEX ↔ спот DEX")
|
||||
root.geometry("1280x720")
|
||||
state: dict = {"matches": [], "sort": ("cex_volume", True)}
|
||||
|
||||
top = ttk.Frame(root, padding=6)
|
||||
top.pack(fill="x")
|
||||
ex_vars = {name: tk.BooleanVar(value=True) for name in CEX_SOURCES}
|
||||
ttk.Label(top, text="Биржи:").pack(side="left")
|
||||
for name, var in ex_vars.items():
|
||||
ttk.Checkbutton(top, text=name, variable=var).pack(side="left")
|
||||
filters = ttk.Frame(root, padding=(6, 0))
|
||||
filters.pack(fill="x")
|
||||
min_liq = tk.StringVar(value="10000")
|
||||
min_vol = tk.StringVar(value="0")
|
||||
pages = tk.StringVar(value="4")
|
||||
only_dex = tk.BooleanVar(value=True)
|
||||
only_match = tk.BooleanVar(value=False)
|
||||
for label, var, width in (("Мин. ликвидность DEX, $", min_liq, 10), ("Мин. объём CEX за 24 ч, $", min_vol, 12),
|
||||
("Страниц мемов CoinGecko (×250)", pages, 4)):
|
||||
ttk.Label(filters, text=label).pack(side="left", padx=(0, 4))
|
||||
ttk.Entry(filters, textvariable=var, width=width).pack(side="left", padx=(0, 12))
|
||||
ttk.Checkbutton(filters, text="Только есть на DEX", variable=only_dex, command=lambda: fill()).pack(side="left")
|
||||
ttk.Checkbutton(filters, text="Только «совпадает»", variable=only_match, command=lambda: fill()).pack(side="left")
|
||||
scan_btn = ttk.Button(filters, text="Обновить", command=lambda: start())
|
||||
scan_btn.pack(side="left", padx=8)
|
||||
ttk.Button(filters, text="Сохранить CSV", command=lambda: export()).pack(side="left")
|
||||
ttk.Button(filters, text="Опережение DEX…", command=lambda: open_leadlag()).pack(side="left", padx=8)
|
||||
ttk.Button(filters, text="Автопоиск…", command=lambda: __import__("autoscan").open_window(root)).pack(side="left")
|
||||
|
||||
def open_leadlag():
|
||||
import leadlag
|
||||
leadlag.open_window(root, lambda: state["matches"])
|
||||
|
||||
columns = {"symbol": ("Монета", 90), "name": ("Название", 140), "cex": ("Фьючерсы CEX", 250),
|
||||
"cex_volume": ("Объём CEX 24 ч", 100), "funding": ("Funding", 70), "dex": ("DEX", 150),
|
||||
"pair": ("Пара", 110), "liquidity": ("Ликвидность", 90), "dex_volume": ("Объём DEX", 90),
|
||||
"diff": ("Разница", 70), "status": ("Статус", 110), "mcap": ("Капитализация", 100)}
|
||||
frame = ttk.Frame(root, padding=6)
|
||||
frame.pack(fill="both", expand=True)
|
||||
tree = ttk.Treeview(frame, columns=list(columns), show="headings")
|
||||
for key, (title, width) in columns.items():
|
||||
tree.heading(key, text=title, command=lambda k=key: sort_by(k))
|
||||
tree.column(key, width=width, anchor="w")
|
||||
tree.tag_configure("совпадает", background="#e8f7e8")
|
||||
tree.tag_configure("проверить", background="#fff6d8")
|
||||
tree.tag_configure("разные монеты?", background="#fde3e3")
|
||||
scroll = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
|
||||
tree.configure(yscrollcommand=scroll.set)
|
||||
tree.pack(side="left", fill="both", expand=True)
|
||||
scroll.pack(side="right", fill="y")
|
||||
status = tk.StringVar(value="Нажмите «Обновить». Двойной щелчок по строке открывает пару на DEX.")
|
||||
ttk.Label(root, textvariable=status, padding=6).pack(fill="x")
|
||||
|
||||
def keyf(m: Match, key: str):
|
||||
d = m.dex
|
||||
return {"symbol": m.symbol, "name": m.name, "cex": m.exchanges, "cex_volume": m.cex_volume_usd,
|
||||
"funding": abs(m.funding or 0), "dex": f"{d.chain}/{d.dex}" if d else "", "pair": d.pair if d else "",
|
||||
"liquidity": d.liquidity_usd if d else -1, "dex_volume": d.volume_usd if d else -1,
|
||||
"diff": abs(m.diff_pct) if m.diff_pct is not None else 1e9, "status": m.status,
|
||||
"mcap": m.market_cap}[key]
|
||||
|
||||
def sort_by(key):
|
||||
prev, desc = state["sort"]
|
||||
state["sort"] = (key, not desc if prev == key else key in ("cex_volume", "liquidity", "dex_volume", "mcap"))
|
||||
fill()
|
||||
|
||||
def visible() -> list[Match]:
|
||||
try:
|
||||
liq, vol = float(min_liq.get() or 0), float(min_vol.get() or 0)
|
||||
except ValueError:
|
||||
liq = vol = 0.0
|
||||
out = []
|
||||
for m in state["matches"]:
|
||||
if only_dex.get() and m.dex is None:
|
||||
continue
|
||||
if only_match.get() and m.status != "совпадает":
|
||||
continue
|
||||
if m.dex is not None and m.dex.source == "DexScreener" and m.dex.liquidity_usd < liq:
|
||||
continue
|
||||
if m.cex_volume_usd < vol:
|
||||
continue
|
||||
out.append(m)
|
||||
key, desc = state["sort"]
|
||||
return sorted(out, key=lambda m: keyf(m, key), reverse=desc)
|
||||
|
||||
def fill():
|
||||
tree.delete(*tree.get_children())
|
||||
rows = visible()
|
||||
for i, m in enumerate(rows):
|
||||
d = m.dex
|
||||
tree.insert("", "end", iid=str(i), tags=(m.status,), values=(
|
||||
m.symbol, m.name, m.exchanges, human(m.cex_volume_usd),
|
||||
"" if m.funding is None else f"{m.funding * 100:+.3f}%",
|
||||
f"{d.chain}/{d.dex}" + (f" (+{m.dex_count - 1})" if m.dex_count > 1 else "") if d else "—",
|
||||
d.pair if d else "", human(d.liquidity_usd) if d and d.liquidity_usd else ("" if not d else "—"),
|
||||
human(d.volume_usd) if d else "", "" if m.diff_pct is None else f"{m.diff_pct:+.2f}%", m.status,
|
||||
human(m.market_cap)))
|
||||
state["rows"] = rows
|
||||
total = len(state["matches"])
|
||||
on_dex = sum(m.dex is not None for m in state["matches"])
|
||||
same = sum(m.status == "совпадает" for m in state["matches"])
|
||||
if total:
|
||||
status.set(f"Мемкойнов с фьючерсами: {total} · есть на DEX: {on_dex} · цена совпадает: {same} · "
|
||||
f"показано: {len(rows)}")
|
||||
|
||||
def open_row(_event=None):
|
||||
sel = tree.selection()
|
||||
if sel:
|
||||
m = state["rows"][int(sel[0])]
|
||||
if m.dex and m.dex.url:
|
||||
webbrowser.open(m.dex.url)
|
||||
|
||||
tree.bind("<Double-1>", open_row)
|
||||
|
||||
def log(text):
|
||||
root.after(0, status.set, text)
|
||||
|
||||
def start():
|
||||
chosen = [n for n, v in ex_vars.items() if v.get()]
|
||||
if not chosen:
|
||||
messagebox.showwarning("Meme Matcher", "Выберите хотя бы одну биржу", parent=root)
|
||||
return
|
||||
try:
|
||||
n_pages = max(1, min(20, int(pages.get())))
|
||||
except ValueError:
|
||||
n_pages = 4
|
||||
scan_btn.configure(state="disabled")
|
||||
|
||||
def work():
|
||||
try:
|
||||
result = scan(chosen, n_pages, log)
|
||||
save_csv(result)
|
||||
root.after(0, done, result, "")
|
||||
except Exception as exc:
|
||||
root.after(0, done, None, str(exc))
|
||||
|
||||
threading.Thread(target=work, daemon=True).start()
|
||||
|
||||
def done(result, error):
|
||||
scan_btn.configure(state="normal")
|
||||
if error:
|
||||
status.set(f"Ошибка: {error}")
|
||||
return
|
||||
state["matches"] = result
|
||||
fill()
|
||||
|
||||
def export():
|
||||
save_csv(visible())
|
||||
status.set(f"Сохранено: {OUT_CSV}")
|
||||
|
||||
root.after(200, start)
|
||||
root.mainloop()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import sys
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--once", action="store_true", help="print the table and save meme_matches.csv")
|
||||
parser.add_argument("--pages", type=int, default=4, help="CoinGecko meme pages of 250 coins")
|
||||
parser.add_argument("--exchanges", default=",".join(CEX_SOURCES), help="comma-separated CEX list")
|
||||
args = parser.parse_args()
|
||||
if args.once:
|
||||
matches = scan([e for e in args.exchanges.split(",") if e in CEX_SOURCES], args.pages)
|
||||
save_csv(matches)
|
||||
print_table([m for m in matches if m.dex is not None])
|
||||
print(f"\nCSV: {OUT_CSV}")
|
||||
else:
|
||||
run_window()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user