Files
Crypto_Scam/meme_matcher/meme_matcher.py
T
2026-10-22 20:19:52 +03:00

719 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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),
"Binance": ("https://fapi.binance.com/fapi/v1/ticker/24hr", parse_binance),
"OKX": ("https://www.okx.com/api/v5/market/tickers?instType=SWAP", parse_okx),
"Gate": ("https://api.gateio.ws/api/v4/futures/usdt/tickers", parse_gate),
"MEXC": ("https://contract.mexc.com/api/v1/contract/ticker", parse_mexc),
"Bitget": ("https://api.bitget.com/api/v2/mix/market/tickers?productType=USDT-FUTURES", parse_bitget),
"BingX": ("https://open-api.bingx.com/openApi/swap/v2/quote/ticker", parse_bingx),
}
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()