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

134 lines
6.1 KiB
Python

"""Tests for the MetaScalp scalping hint (order book, signal, plan and journal)."""
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 scalp_hint as sh # noqa: E402
TICK = 0.00001
def book_from(asks: dict[float, float], bids: dict[float, float]) -> sh.OrderBook:
book = sh.OrderBook()
book.apply_snapshot({"asks": [{"price": p, "size": s, "type": "Ask"} for p, s in asks.items()],
"bids": [{"price": p, "size": s, "type": "Bid"} for p, s in bids.items()]})
return book
def tape_from(trades: list[tuple[float, float, str]], now: float) -> sh.Tape:
tape = sh.Tape()
for i, (price, size, side) in enumerate(trades):
tape.add(sh.Trade(now - len(trades) + i, price, size, side))
return tape
def levels(start: float, count: int, step: float, size: float) -> dict[float, float]:
return {round(start + i * step, 5): size for i in range(count)}
class OrderBookTests(unittest.TestCase):
def test_updates_are_absolute_and_zero_removes(self):
book = book_from({0.04905: 10.0}, {0.049: 5.0})
book.apply_updates([{"price": 0.04905, "size": 0.0, "type": "Ask"},
{"price": 0.04906, "size": 7.0, "type": "BestAsk"},
{"price": 0.049, "size": 9.0, "type": "BestBid"}])
self.assertEqual(book.best(), (0.049, 0.04906))
self.assertEqual(book.bids[0.049], 9.0)
def test_best_price_marks_remove_stale_levels(self):
book = book_from({0.04849: 50.0, 0.04891: 20.0, 0.04895: 30.0}, {0.04845: 10.0})
book.apply_updates([{"price": 0.04891, "size": 20.0, "type": "BestAsk"},
{"price": 0.04889, "size": 15.0, "type": "BestBid"}])
self.assertNotIn(0.04849, book.asks) # consumed ask without an explicit removal
self.assertEqual(book.best(), (0.04889, 0.04891))
def test_book_out_of_sync_with_tape_waits(self):
book = book_from(levels(0.04849, 10, TICK, 100.0), levels(0.04845, 10, -TICK, 100.0))
tape = tape_from([(0.0490, 10.0, "Buy") for _ in range(6)], 1_000.0)
hint = sh.evaluate(book, tape, TICK, sh.HintSettings(), 1_000.0)
self.assertEqual(hint.side, "WAIT")
self.assertIn("расходится", hint.reasons[0])
def test_crossed_bids_are_dropped(self):
book = book_from({0.04905: 10.0}, {0.049: 5.0})
book.apply_updates([{"price": 0.04906, "size": 3.0, "type": "Bid"}])
self.assertEqual(book.best()[0], 0.049)
class EvaluateTests(unittest.TestCase):
settings = sh.HintSettings(min_target_pct=0.05)
def test_heavy_sellers_give_short_with_stop_behind_density(self):
asks = levels(0.04905, 12, TICK, 300.0)
asks[0.04910] = 5000.0 # resistance density
bids = levels(0.04900, 12, -TICK, 60.0)
bids[0.04870] = 3000.0 # support density further away
now = 1_000.0
tape = tape_from([(0.04906 - i * 0.000005, 200.0, "Sell") for i in range(8)], now)
hint = sh.evaluate(book_from(asks, bids), tape, TICK, self.settings, now)
self.assertEqual(hint.side, "SHORT")
self.assertAlmostEqual(hint.entry, 0.04909)
self.assertGreater(hint.stop, 0.04910) # behind the density, not in front of it
self.assertGreater(hint.target, 0.04870) # exits before the opposite density
self.assertGreaterEqual(hint.rr, self.settings.min_rr)
def test_balanced_book_waits(self):
asks = levels(0.04905, 12, TICK, 100.0)
bids = levels(0.04900, 12, -TICK, 100.0)
now = 1_000.0
tape = tape_from([(0.04903, 50.0, "Buy" if i % 2 else "Sell") for i in range(10)], now)
hint = sh.evaluate(book_from(asks, bids), tape, TICK, self.settings, now)
self.assertEqual(hint.side, "WAIT")
def test_few_trades_are_ignored(self):
asks = levels(0.04905, 12, TICK, 100.0)
bids = levels(0.04900, 12, -TICK, 100.0)
now = 1_000.0
tape = tape_from([(0.04905, 5000.0, "Buy")], now)
hint = sh.evaluate(book_from(asks, bids), tape, TICK, self.settings, now)
self.assertEqual(hint.metrics["tape_delta"], 0.0)
self.assertEqual(hint.side, "WAIT")
def test_small_move_is_rejected(self):
asks = levels(0.04905, 12, TICK, 300.0)
bids = levels(0.04900, 12, -TICK, 60.0)
now = 1_000.0
tape = tape_from([(0.04903, 200.0, "Sell") for _ in range(8)], now)
strict = sh.HintSettings(min_target_pct=5.0)
hint = sh.evaluate(book_from(asks, bids), tape, TICK, strict, now)
self.assertEqual(hint.side, "WAIT")
self.assertIn("невыгодна", hint.reasons[0])
class JournalTests(unittest.TestCase):
def test_fill_then_target(self):
with tempfile.TemporaryDirectory() as folder:
journal = sh.Journal(sh.HintSettings(), Path(folder) / "j.csv")
hint = sh.Hint("SHORT", "средняя", -0.5, entry=0.04910, stop=0.04915, target=0.04890, rr=4.0)
journal.offer("PUFFERUSDT", hint, 0.0)
journal.on_trade(sh.Trade(1.0, 0.04911, 10, "Buy")) # trades through the limit -> filled
journal.on_trade(sh.Trade(2.0, 0.04889, 10, "Sell")) # target
self.assertIsNone(journal.active)
self.assertEqual(journal.done[-1].result, "цель")
self.assertGreater(journal.done[-1].pnl_pct, 0)
self.assertTrue((Path(folder) / "j.csv").exists())
def test_unfilled_expires(self):
with tempfile.TemporaryDirectory() as folder:
journal = sh.Journal(sh.HintSettings(fill_minutes=1), Path(folder) / "j.csv")
hint = sh.Hint("LONG", "низкая", 0.3, entry=0.049, stop=0.0489, target=0.0492, rr=2.0)
journal.offer("X", hint, 0.0)
journal.on_trade(sh.Trade(30.0, 0.04905, 1, "Buy"))
journal.on_trade(sh.Trade(61.0, 0.04905, 1, "Buy"))
self.assertEqual(journal.done[-1].result, "не исполнился")
if __name__ == "__main__":
unittest.main()