update
This commit is contained in:
commit
5c6b0dc54a
62 files changed
+28141
No files matched your search
@@ -0,0 +1,94 @@
|
||||
"""Autonomous search: coin rotation, leaders first, simulator connections, history."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
import autoscan as au # noqa: E402
|
||||
import leadlag as ll # noqa: E402
|
||||
|
||||
|
||||
def target(symbol, cex="MEXC", chain="solana", cex_symbol=None):
|
||||
return ll.Target(symbol, symbol.lower(), cex, cex_symbol or f"{symbol}_USDT", 1.0, chain, chain, f"POOL{symbol}",
|
||||
"TOKEN", "pumpswap", 500)
|
||||
|
||||
|
||||
def result(symbol, verdict=au.LEAD_VERDICT):
|
||||
return ll.LeadResult(symbol, "MEXC", "solana/pumpswap", 900, 100, 100, 30, {0: 0.1}, 2, 0.0, {5: 0.1},
|
||||
{5: 0.6}, 2.5, 70.0, 0, verdict)
|
||||
|
||||
|
||||
class AutoscanTests(unittest.TestCase):
|
||||
def test_rotation_covers_everyone_and_leaders_come_first(self):
|
||||
cands = [target(s) for s in "ABCDEFG"]
|
||||
first, off = au.choose_targets(cands, [], 0, 3)
|
||||
second, off = au.choose_targets(cands, [], off, 3)
|
||||
third, off = au.choose_targets(cands, [], off, 3)
|
||||
seen = [t.symbol for t in first + second + third]
|
||||
self.assertEqual(set(seen), set("ABCDEFG"))
|
||||
with_leader, _ = au.choose_targets(cands, ["F"], 0, 3)
|
||||
self.assertEqual(with_leader[0].symbol, "F")
|
||||
self.assertEqual(len({t.symbol for t in with_leader}), 3)
|
||||
|
||||
def test_simulator_connection_mapping(self):
|
||||
conn = au.simulator_connection(target("CLAUDIA"))
|
||||
self.assertEqual(conn, {"lead_market": "raydium", "lead_ticker": "CLAUDIAUSDTM", "lead_pool": "POOLCLAUDIA",
|
||||
"follow_exchange": "mexc", "follow_ticker": "CLAUDIA_USDT"})
|
||||
self.assertEqual(au.simulator_connection(target("X", cex="Binance", cex_symbol="1000XUSDT"))["follow_ticker"],
|
||||
"1000XUSDT")
|
||||
self.assertIsNone(au.simulator_connection(target("X", cex="Gate")))
|
||||
self.assertIsNone(au.simulator_connection(target("X", chain="bsc")))
|
||||
|
||||
def test_add_connection_keeps_existing_and_skips_duplicates(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "lead_connections.json"
|
||||
old = {"lead_market": "futures", "lead_ticker": "MARSCOINUSDTM", "lead_pool": "", "follow_exchange": "bybit",
|
||||
"follow_ticker": "MARSCOINUSDT"}
|
||||
path.write_text(json.dumps([old]), encoding="utf-8")
|
||||
conn = au.simulator_connection(target("SI"))
|
||||
self.assertTrue(au.add_connection(conn, path))
|
||||
self.assertFalse(au.add_connection(conn, path))
|
||||
saved = json.loads(path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved, [old, conn])
|
||||
|
||||
def test_loop_survives_the_recording_and_errors(self):
|
||||
"""record() sets the stop event it is given; the loop must keep running for the next cycle."""
|
||||
import threading
|
||||
from unittest import mock
|
||||
calls = {"n": 0}
|
||||
loop_stop = threading.Event()
|
||||
|
||||
def fake_cycle(st, *args):
|
||||
calls["n"] += 1
|
||||
given = threading.Event()
|
||||
given.set() # what record() does with its own event
|
||||
if calls["n"] == 2:
|
||||
raise RuntimeError("boom") # an error in a cycle is logged, not fatal
|
||||
if calls["n"] >= 3:
|
||||
loop_stop.set()
|
||||
|
||||
with tempfile.TemporaryDirectory() as folder, \
|
||||
mock.patch.object(au, "_cycle", fake_cycle), mock.patch.object(au, "LOG_FILE", Path(folder) / "l.log"), \
|
||||
mock.patch.object(loop_stop, "wait", lambda s: None):
|
||||
au.run(1, 1, 1, 0.15, stop=loop_stop)
|
||||
self.assertEqual(calls["n"], 3)
|
||||
|
||||
def test_history_and_leaders(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "h.csv"
|
||||
targets = {s: target(s) for s in ("A", "B", "C")}
|
||||
au.append_history(1, [result("A"), result("B", "одновременно / нет опережения")], targets, {"A": "да"}, path)
|
||||
au.append_history(2, [result("C")], targets, {}, path)
|
||||
self.assertEqual(set(au.read_leaders(path)), {"A", "C"})
|
||||
self.assertEqual(au.last_cycle(path), 2)
|
||||
self.assertIn("да", path.read_text(encoding="utf-8-sig"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Offline tests: symbol parsing, coin identification by price, DEX pool choice, statuses, CSV."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
import meme_matcher as mm # noqa: E402
|
||||
|
||||
|
||||
def coin(cg_id, symbol, price, platforms=None, mcap=1e6):
|
||||
return mm.MemeCoin(cg_id, symbol, cg_id, price, mcap, platforms or {})
|
||||
|
||||
|
||||
def ds_pair(chain, address, price, liquidity, symbol="X", pair_address=None, dex="uniswap"):
|
||||
return {"chainId": chain, "dexId": dex, "pairAddress": pair_address or f"{address}-{liquidity}",
|
||||
"priceUsd": str(price), "liquidity": {"usd": liquidity}, "volume": {"h24": liquidity / 10},
|
||||
"baseToken": {"address": address, "symbol": symbol}, "quoteToken": {"symbol": "WETH"},
|
||||
"url": f"https://dexscreener.com/{chain}/{address}"}
|
||||
|
||||
|
||||
class SymbolTests(unittest.TestCase):
|
||||
def test_size_prefixes_and_suffixes(self):
|
||||
self.assertEqual(mm.split_base("1000PEPE"), ("PEPE", 1000.0))
|
||||
self.assertEqual(mm.split_base("1000000BABYDOGE"), ("BABYDOGE", 1_000_000.0))
|
||||
self.assertEqual(mm.split_base("1MBABYDOGE"), ("BABYDOGE", 1_000_000.0))
|
||||
self.assertEqual(mm.split_base("SHIB1000"), ("SHIB", 1000.0))
|
||||
self.assertEqual(mm.split_base("1INCH"), ("1INCH", 1.0))
|
||||
self.assertEqual(mm.split_base("WIF"), ("WIF", 1.0))
|
||||
|
||||
def test_exchange_parsers_give_price_per_coin(self):
|
||||
bybit = mm.parse_bybit({"result": {"list": [
|
||||
{"symbol": "1000PEPEUSDT", "lastPrice": "0.004", "turnover24h": "100", "fundingRate": "0.0001"},
|
||||
{"symbol": "BTCPERP", "lastPrice": "1", "turnover24h": "1"}]}})
|
||||
self.assertEqual(len(bybit), 1)
|
||||
self.assertAlmostEqual(bybit[0].price, 0.000004)
|
||||
self.assertEqual((bybit[0].base, bybit[0].funding), ("PEPE", 0.0001))
|
||||
okx = mm.parse_okx({"data": [{"instId": "WIF-USDT-SWAP", "last": "2", "volCcy24h": "50"}]})
|
||||
self.assertEqual((okx[0].base, okx[0].volume_usd), ("WIF", 100.0))
|
||||
gate = mm.parse_gate([{"contract": "BONK_USDT", "last": "0.00002", "volume_24h_quote": "7"}])
|
||||
self.assertEqual(gate[0].base, "BONK")
|
||||
binance = mm.parse_binance([{"symbol": "BTCUSDT_261225", "lastPrice": "1", "quoteVolume": "1"},
|
||||
{"symbol": "DOGEUSDT", "lastPrice": "0.1", "quoteVolume": "5"}])
|
||||
self.assertEqual([l.base for l in binance], ["DOGE"])
|
||||
|
||||
|
||||
class MatchTests(unittest.TestCase):
|
||||
def test_coin_is_picked_by_price_among_same_tickers(self):
|
||||
by_symbol = {"PEPE": [coin("baby-pepe", "PEPE", 0.5), coin("pepe", "PEPE", 0.000004)]}
|
||||
self.assertEqual(mm.pick_coin("PEPE", 0.0000041, by_symbol).cg_id, "pepe")
|
||||
self.assertIsNone(mm.pick_coin("PEPE", 0.01, by_symbol)) # no coin at that price
|
||||
self.assertIsNone(mm.pick_coin("DOGE", 0.1, by_symbol)) # not a meme coin
|
||||
|
||||
def test_two_contracts_with_one_ticker_are_two_coins(self):
|
||||
listings = [mm.Listing("Binance", "CATUSDT", "CAT", 1, 0.02, 10),
|
||||
mm.Listing("Binance", "1000CATUSDT", "CAT", 1000, 0.000005, 20)]
|
||||
memes = [coin("cat-a", "CAT", 0.02), coin("simons-cat", "CAT", 0.000005)]
|
||||
result = {m.cg_id: m for m in mm.match(listings, memes, {}, {})}
|
||||
self.assertEqual(set(result), {"cat-a", "simons-cat"})
|
||||
self.assertEqual(len(result["simons-cat"].cex), 1)
|
||||
|
||||
def test_deepest_agreeing_pool_wins_and_fakes_are_flagged(self):
|
||||
address = "0xAbC"
|
||||
memes = [coin("pepe", "PEPE", 0.000004, {"ethereum": address, "solana": "SoLpEpE"})]
|
||||
pools = mm.all_pairs([
|
||||
ds_pair("ethereum", address, 0.000004, 1_000_000),
|
||||
ds_pair("ethereum", address, 0.0000041, 5_000_000),
|
||||
ds_pair("solana", "SoLpEpE", 0.9, 50_000_000), # a fake: price way off, ignored
|
||||
])
|
||||
listing = mm.Listing("Bybit", "1000PEPEUSDT", "PEPE", 1000, 0.000004, 100)
|
||||
m = mm.match([listing], memes, pools, {})[0]
|
||||
self.assertEqual(m.dex.liquidity_usd, 5_000_000)
|
||||
self.assertEqual(m.status, "совпадает")
|
||||
self.assertEqual(m.dex_count, 1)
|
||||
# only a fake pool: still shown, but flagged
|
||||
fake_only = mm.all_pairs([ds_pair("solana", "SoLpEpE", 0.9, 1_000)])
|
||||
m = mm.match([listing], memes, fake_only, {})[0]
|
||||
self.assertEqual(m.status, "разные монеты?")
|
||||
|
||||
def test_pool_where_token_is_quote_is_ignored(self):
|
||||
pair = ds_pair("ethereum", "0xother", 1.0, 1e6)
|
||||
pair["quoteToken"] = {"address": "0xabc", "symbol": "PEPE"}
|
||||
self.assertNotIn(("ethereum", "0xabc"), mm.all_pairs([pair]))
|
||||
|
||||
def test_hyperliquid_spot_and_status(self):
|
||||
data = ({"tokens": [{"index": 0, "name": "USDC"}, {"index": 1, "name": "WIF", "tokenId": "0x1"}],
|
||||
"universe": [{"tokens": [1, 0], "name": "@7", "index": 0}]},
|
||||
[{"midPx": "1.01", "dayNtlVlm": "5000"}])
|
||||
hl = mm.parse_hyperliquid_spot(data)
|
||||
listing = mm.Listing("OKX", "WIF-USDT-SWAP", "WIF", 1, 1.0, 50)
|
||||
m = mm.match([listing], [coin("dogwifcoin", "WIF", 1.0)], {}, hl)[0]
|
||||
self.assertEqual((m.dex.source, m.status), ("HyperLiquid", "совпадает"))
|
||||
self.assertEqual(mm.status_of(None), "нет на DEX")
|
||||
self.assertEqual(mm.status_of(10.0), "проверить")
|
||||
self.assertEqual(mm.status_of(-40.0), "разные монеты?")
|
||||
|
||||
def test_contracts_keep_case_for_solana_only(self):
|
||||
out = mm.contracts_for([coin("x", "X", 1, {"ethereum": "0xAbC", "solana": "AbC", "unknown-chain": "q"})])
|
||||
self.assertEqual(out, {"ethereum": {"0xabc"}, "solana": {"AbC"}})
|
||||
|
||||
def test_csv(self):
|
||||
listing = mm.Listing("Bybit", "WIFUSDT", "WIF", 1, 1.0, 50, 0.0001)
|
||||
m = mm.match([listing], [coin("dogwifcoin", "WIF", 1.0)], {}, {})[0]
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "m.csv"
|
||||
mm.save_csv([m], path)
|
||||
text = path.read_text(encoding="utf-8-sig")
|
||||
self.assertIn("WIF;dogwifcoin", text)
|
||||
self.assertIn("нет на DEX", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user