"""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 CONNECTIONS_FILE = SIM_DIR / "lead_connections.json" HISTORY_CSV = ROOT / "autoscan_history.csv" LOG_FILE = ROOT / "autoscan.log" LOCK_FILE = ROOT / "autoscan.lock" LEAD_VERDICT = "DEX опережает ≥1 с" SIM_EXCHANGES = ["Binance", "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((SIM_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: """One autoscan at a time (they would share GeckoTerminal's rate limit).""" 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: 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 = ROOT / "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) def stop_background() -> None: pid = running_pid() if pid: import subprocess subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) 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()