Files
2026-10-22 20:19:52 +03:00

138 lines
6.6 KiB
Python
Raw Permalink 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.
"""Offline tests for the DEX → CEX lead-lag recorder and analysis on synthetic prices."""
from __future__ import annotations
import sys
import tempfile
import threading
import unittest
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import leadlag as ll # noqa: E402
import meme_matcher as mm # noqa: E402
T0 = 1_800_000_000
def target(symbol="WIF", cex="Binance", cex_symbol="WIFUSDT", multiplier=1.0):
return ll.Target(symbol, "dogwifcoin", cex, cex_symbol, multiplier, "solana", "solana", "POOL", "TOKEN",
"raydium", 600)
def walk(seconds=1500, step=0.004, seed=1):
rng = np.random.default_rng(seed)
return 1.0 * np.exp(np.cumsum(rng.choice([-step, 0.0, step], size=seconds, p=[0.3, 0.4, 0.3])))
def trades(path, delay_s, offset=0.3):
"""One trade per second at the path's price, `delay_s` seconds late."""
return [(T0 + i + delay_s + offset, float(p)) for i, p in enumerate(path)]
def dex_rows(path, delay_s=0, publish_delay=45):
return [(T0 + i + delay_s + 0.5, float(p), 100.0, "buy", T0 + i + delay_s + publish_delay)
for i, p in enumerate(path)]
class AnalysisTests(unittest.TestCase):
def test_dex_leading_by_three_seconds_is_found(self):
path = walk()
r = ll.analyze_coin(target(), trades(path, 3), dex_rows(path, 0))
self.assertEqual(r.verdict, "DEX опережает ≥1 с", r)
self.assertEqual(r.best_lag, 3)
self.assertGreater(r.follow[5], 0)
self.assertGreater(r.hit[5], 0.7) # later random steps add noise on top of the copied move
self.assertAlmostEqual(r.dex_delay_s, 45, delta=1)
def test_futures_leading_is_not_called_a_dex_lead(self):
path = walk(seed=2)
r = ll.analyze_coin(target(), trades(path, 0), dex_rows(path, 3))
self.assertEqual(r.verdict, "фьючерс опережает")
self.assertEqual(r.best_lag, -3)
def test_simultaneous_moves_are_no_lead(self):
path = walk(seed=3)
r = ll.analyze_coin(target(), trades(path, 0, offset=0.6), dex_rows(path, 0))
self.assertEqual(r.verdict, "одновременно / нет опережения")
self.assertIn(r.best_lag, (0, 1)) # a sub-second reaction may land in the next second
def test_too_little_data(self):
r = ll.analyze_coin(target(), [(T0, 1.0)], [])
self.assertEqual(r.verdict, "мало данных")
def test_results_csv(self):
path = walk(seed=4)
res = ll.analyze([target()], {"WIF": trades(path, 2)}, {"WIF": dex_rows(path)})
with tempfile.TemporaryDirectory() as folder:
out = Path(folder) / "r.csv"
ll.save_results(res, out)
self.assertIn("WIF;DEX опережает", out.read_text(encoding="utf-8-sig"))
class DataTests(unittest.TestCase):
def test_gecko_trades_take_our_token_price(self):
data = {"data": [
{"id": "a", "attributes": {"block_timestamp": "2026-10-16T16:53:05Z", "from_token_address": "TOKEN",
"to_token_address": "SOL", "price_from_in_usd": "0.15",
"price_to_in_usd": "104", "volume_in_usd": "10", "kind": "sell"}},
{"id": "b", "attributes": {"block_timestamp": "2026-10-16T16:53:06Z", "from_token_address": "SOL",
"to_token_address": "token", "price_from_in_usd": "104",
"price_to_in_usd": "0.16", "volume_in_usd": "20", "kind": "buy"}},
{"id": "c", "attributes": {"block_timestamp": "2026-10-16T16:53:07Z", "from_token_address": "X",
"to_token_address": "Y", "price_from_in_usd": "1", "price_to_in_usd": "1"}}]}
rows = ll.parse_gecko_trades(data, "TOKEN")
self.assertEqual([(r[0], r[2], r[4]) for r in rows], [("a", 0.15, "sell"), ("b", 0.16, "buy")])
def test_exchange_messages_are_parsed_per_coin(self):
stop = threading.Event()
for exchange, symbol, msg in (
("Binance", "1000PEPEUSDT", {"data": {"e": "aggTrade", "s": "1000PEPEUSDT", "T": 1000, "p": "0.004"}}),
("Bybit", "1000PEPEUSDT", {"topic": "publicTrade.1000PEPEUSDT",
"data": [{"s": "1000PEPEUSDT", "T": 1000, "p": "0.004"}]}),
("Gate", "PEPE_USDT", {"channel": "futures.trades", "event": "update",
"result": [{"contract": "PEPE_USDT", "create_time_ms": 1000,
"price": "0.000004"}]}),
("MEXC", "PEPE_USDT", {"channel": "push.deal", "symbol": "PEPE_USDT",
"data": [{"p": 0.000004, "t": 1000}]})):
mult = 1000.0 if symbol.startswith("1000") else 1.0
t = target("PEPE", exchange, symbol, mult)
rec = ll.Recorder([t])
ll.CexFeed(exchange, [t], rec, stop).handle(msg)
self.assertEqual(len(rec.cex["PEPE"]), 1, exchange)
ts, price = rec.cex["PEPE"][0]
self.assertEqual(ts, 1.0)
self.assertAlmostEqual(price, 0.000004)
def test_dedupe_save_and_load(self):
t = target()
rec = ll.Recorder([t])
self.assertTrue(rec.add_dex("WIF", "id1", T0, 1.0, 5.0, "buy"))
self.assertFalse(rec.add_dex("WIF", "id1", T0, 1.0, 5.0, "buy"))
rec.add_cex("WIF", T0 + 0.1, 1.01)
with tempfile.TemporaryDirectory() as folder:
path = rec.save(Path(folder) / "r.jsonl.gz")
targets, cex, dex, meta = ll.load(path)
self.assertEqual(targets[0].symbol, "WIF")
self.assertEqual(len(cex["WIF"]), 1)
self.assertEqual(dex["WIF"][0][1], 1.0)
def test_pick_targets_needs_fast_chain_activity_and_supported_cex(self):
def match(symbol, chain, txns, exchange="Binance", status="совпадает"):
pool = mm.DexPair("DexScreener", chain, "raydium", f"{symbol}/SOL", 1.0, 1e6, 1e6, "TOKEN", "",
"POOL", txns)
listing = mm.Listing(exchange, f"{symbol}USDT", symbol, 1, 1.0, 1e6)
return mm.Match(symbol, symbol, symbol.lower(), 1e6, [listing], 1.0, 1e6, pool, 1, 0.0, status, [pool])
picked = ll.pick_targets([match("A", "solana", 500), match("B", "ethereum", 900), match("C", "solana", 50),
match("D", "bsc", 300, exchange="BingX"), match("E", "base", 800),
match("F", "solana", 900, status="проверить")])
self.assertEqual([t.symbol for t in picked], ["E", "A"])
if __name__ == "__main__":
unittest.main()