"""Unit tests for the shared strategy rules and the historical backtest engine. Run from the project folder: py -3 -m unittest discover -s tests """ 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 historical_backtest as hb # noqa: E402 import strategy # noqa: E402 MIN = 60_000 def flat(start: int, price: float, count: int) -> list[list[float]]: return [[start + i * MIN, price, price, price, price] for i in range(count)] def cfg(**overrides) -> dict[str, float]: base = {"stake": 10.0, "leverage": 1.0, "trigger": 1.0, "add_step": 5.0, "max_adds": 1, "stop_loss": 0.0, "take_profit": 10.0} base.update(overrides) return base def run(candles, strategies, **kwargs): # Entries are always allowed unless a test passes its own selection windows. kwargs.setdefault("universe_windows", {symbol: [(0, 10**15)] for symbol in candles}) kwargs.setdefault("min_equity_pct", 0.0) return hb.run_backtest(candles, strategies, 100.0, fee_pct=0.0, **kwargs) class StrategyFormulaTests(unittest.TestCase): def test_fee_cover(self): self.assertAlmostEqual(strategy.fee_cover_pct(0.0), 0.0) self.assertGreater(strategy.fee_cover_pct(0.055), 0.11) def test_take_profit_is_raised_to_cover_fees(self): self.assertAlmostEqual(strategy.effective_take_profit_pct(0.01, 0.055), strategy.fee_cover_pct(0.055)) self.assertEqual(strategy.effective_take_profit_pct(0, 0.055), 0.0) def test_liquidation_only_with_leverage(self): self.assertIsNone(strategy.liquidation_price(100, 1)) self.assertAlmostEqual(strategy.liquidation_price(100, 10, 0.5), 90.5) class MissingRangesTests(unittest.TestCase): def test_gaps(self): gaps = hb._missing_ranges(0, 10 * MIN, [(2 * MIN, 4 * MIN), (7 * MIN, 8 * MIN)], MIN) self.assertEqual(gaps, [(0, MIN), (5 * MIN, 6 * MIN), (9 * MIN, 10 * MIN)]) def test_fully_covered(self): self.assertEqual(hb._missing_ranges(0, 5 * MIN, [(0, 5 * MIN)], MIN), []) class BacktestTests(unittest.TestCase): def entry_then(self, *candles): """Baseline candle at 100, then an entry candle that rises to 101.5 (trigger 1%).""" rows = [[0, 100, 100, 100, 100], [MIN, 100, 101.5, 100, 101.5]] for i, c in enumerate(candles, start=2): rows.append([i * MIN, *c]) return {"AAA": rows} def test_entry_and_take_profit(self): candles = self.entry_then((101.5, 112, 101.5, 111)) result = run(candles, {"AAA": cfg()}) trades = [t for t in result["trades"] if t["status"] == "CLOSED"] self.assertEqual(len(trades), 1) self.assertAlmostEqual(trades[0]["exit"], 101.0 * 1.10) self.assertGreater(trades[0]["net_usdt"], 0) def test_average_down_then_open_loss_and_drawdown(self): candles = self.entry_then((101, 101, 90, 90)) result = run(candles, {"AAA": cfg()}) summary = result["summary"] open_rows = [t for t in result["trades"] if t["status"] == "OPEN"] self.assertEqual(len(open_rows), 1) self.assertEqual(open_rows[0]["entries"], 2) self.assertGreater(summary["max_drawdown_pct"], 0) self.assertEqual(summary["open_losing_positions"], 1) def test_gap_down_triggers_stop_at_open(self): candles = self.entry_then((80, 80, 79, 79)) result = run(candles, {"AAA": cfg(stop_loss=5.0, add_step=0.0, max_adds=0)}) closed = [t for t in result["trades"] if t["status"] == "CLOSED"] self.assertEqual(len(closed), 1) self.assertEqual(closed[0]["exit"], 80) self.assertIn("разрыв", closed[0]["reason"]) def test_liquidation_with_leverage(self): candles = self.entry_then((101, 101, 85, 85)) result = run(candles, {"AAA": cfg(leverage=10.0, add_step=0.0, max_adds=0)}) closed = [t for t in result["trades"] if t["status"] == "CLOSED"] self.assertEqual(len(closed), 1) self.assertTrue(closed[0]["reason"].startswith("Ликвидация")) self.assertAlmostEqual(closed[0]["net_usdt"], -10.0) self.assertEqual(result["summary"]["liquidations"], 1) def test_position_limit(self): rows = [[0, 100, 100, 100, 100], [MIN, 100, 101.5, 100, 101.5]] candles = {"AAA": rows, "BBB": [list(r) for r in rows]} result = run(candles, {"AAA": cfg(), "BBB": cfg()}, max_open_positions=1) self.assertEqual(result["summary"]["open_positions"], 1) self.assertEqual(result["summary"]["skipped_entries_position_limit"], 1) def test_universe_windows_gate_entries(self): candles = self.entry_then((101.5, 101.5, 101.5, 101.5)) blocked = run(candles, {"AAA": cfg()}, universe_windows={"AAA": [(10 * MIN, 20 * MIN)]}) allowed = run(candles, {"AAA": cfg()}, universe_windows={"AAA": [(0, 20 * MIN)]}) self.assertEqual(blocked["summary"]["open_positions"], 0) self.assertEqual(allowed["summary"]["open_positions"], 1) def test_equity_stop(self): candles = self.entry_then((101, 101, 5, 5)) result = hb.run_backtest(candles, {"AAA": cfg(stake=90.0, add_step=0.0, max_adds=0)}, 100.0, fee_pct=0.0, universe_windows={"AAA": [(0, 10**15)]}, min_equity_pct=50.0) self.assertTrue(result["summary"]["equity_stop_triggered"]) class FundingTests(unittest.TestCase): def test_long_pays_positive_funding(self): rows = [[0, 100, 100, 100, 100], [MIN, 100, 101.5, 100, 101.5], [2 * MIN, 101, 101, 101, 101], [3 * MIN, 101, 101, 101, 101]] result = run({"AAA": rows}, {"AAA": cfg(add_step=0.0, max_adds=0)}, funding_by_symbol={"AAA": {2 * MIN: 0.01}}) open_row = [t for t in result["trades"] if t["status"] == "OPEN"][0] # qty = 10 / 101 at entry 101; payment = qty × 101 × 1% = 0.1 USDT. self.assertAlmostEqual(open_row["funding_usdt"], -0.1) self.assertAlmostEqual(result["summary"]["funding_usdt"], -0.1) without = run({"AAA": rows}, {"AAA": cfg(add_step=0.0, max_adds=0)}) self.assertAlmostEqual(result["summary"]["total_net_including_open_usdt"], without["summary"]["total_net_including_open_usdt"] - 0.1) def test_funding_cache_roundtrip(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "cache.sqlite3" connection = hb._open_candle_cache(path) hb._cache_funding_page(connection, "AAA", 0, 10 * MIN, [(0, 0.0001), (8 * MIN, -0.0002)]) connection.close() # Fully covered: no network request is needed. rates = hb.fetch_funding_history("AAA", 0, 10 * MIN, cache_path=path) self.assertEqual(rates, {0: 0.0001, 8 * MIN: -0.0002}) def mode_params(mode: str, **overrides) -> dict[str, float]: raw = {key: f"{value:g}" for key, value in strategy.MODE_DEFAULTS[mode].items()} raw.update({key: str(value) for key, value in overrides.items()}) return strategy.parse_mode_params(mode, raw) class ModeSignalTests(unittest.TestCase): def test_parse_rejects_bad_timeframe(self): with self.assertRaises(ValueError): mode_params(strategy.STRATEGY_BREAKOUT, timeframe_min=7) def test_breakout_signal(self): params = mode_params(strategy.STRATEGY_BREAKOUT, timeframe_min=15, breakout_hours=1, atr_period=3, volume_mult=2, btc_filter=0) candles = [[i * 15 * MIN, 100, 101, 99, 100, 10.0] for i in range(6)] candles.append([6 * 15 * MIN, 100, 103, 100, 102.5, 30.0]) signal = strategy.evaluate_breakout(candles, params) self.assertIsNotNone(signal) self.assertEqual(signal["level"], 101) candles[-1][5] = 15.0 # volume spike too small self.assertIsNone(strategy.evaluate_breakout(candles, params)) def test_breakout_btc_filter(self): params = mode_params(strategy.STRATEGY_BREAKOUT, breakout_hours=1, atr_period=3, volume_mult=0) candles = [[i * 15 * MIN, 100, 101, 99, 100, 10.0] for i in range(6)] candles.append([6 * 15 * MIN, 100, 103, 100, 102.5, 30.0]) self.assertIsNone(strategy.evaluate_breakout(candles, params, btc_ok=False)) self.assertIsNotNone(strategy.evaluate_breakout(candles, params, btc_ok=True)) def test_fade_signal_and_plan(self): params = mode_params(strategy.STRATEGY_FADE, timeframe_min=60, min_growth_24h=30, min_funding_pct=0.05, high_lookback_hours=6, pullback_pct=3, vwap_hours=6, atr_period=3, stop_buffer_atr=0.5, max_stop_pct=30) candles = [[h * 60 * MIN, 100, 101, 99, 100, 1.0] for h in range(20)] for h, price in zip(range(20, 25), (110, 125, 140, 150, 146)): candles.append([h * 60 * MIN, price - 2, price + 2, price - 4, price, 5.0]) candles.append([25 * 60 * MIN, 146, 147, 128, 130, 5.0]) self.assertIsNone(strategy.evaluate_fade(candles, params, funding_rate_pct=0.01)) signal = strategy.evaluate_fade(candles, params, funding_rate_pct=0.1) self.assertIsNotNone(signal) self.assertEqual(signal["side"], "short") self.assertGreater(signal["stop"], signal["high"]) plan = strategy.entry_plan(signal, 130, params) self.assertLess(plan["partial_target"], 130) self.assertIsNone(strategy.entry_plan(signal, signal["stop"] + 1, params)) def test_trailing_only_tightens(self): self.assertEqual(strategy.trailing_stop("long", 95, 100, 2, 3), 95) self.assertEqual(strategy.trailing_stop("long", 95, 110, 2, 3), 104) self.assertEqual(strategy.trailing_stop("short", 105, 90, 2, 3), 96) self.assertEqual(strategy.trailing_stop("short", 105, 104, 2, 3), 105) def test_short_liquidation(self): self.assertAlmostEqual(strategy.liquidation_price(100, 10, 0.5, side="short"), 109.5) def minute_rows(prices_by_bucket: list[tuple[float, float, float, float, float]], tf_min: int = 15, start: int = 0) -> list[list[float]]: """One minute row per signal candle (enough for aggregation tests).""" return [[start + i * tf_min * MIN, *candle] for i, candle in enumerate(prices_by_bucket)] class ModeBacktestTests(unittest.TestCase): def breakout_rows(self, after: list[tuple[float, float, float, float, float]]): rows = [(100, 101, 99, 100, 10.0)] * 6 + [(100, 103, 100, 102.5, 40.0)] + after return {"AAA": minute_rows(rows)} def params(self, **overrides): base = dict(timeframe_min=15, breakout_hours=1, atr_period=3, volume_mult=2, btc_filter=0, stop_atr=1, partial_r=1, partial_pct=50, breakeven=1, trail_atr=0, take_profit_r=3, max_hold_hours=0, max_funding_pct=0) base.update(overrides) return mode_params(strategy.STRATEGY_BREAKOUT, **base) def run_mode(self, candles, params, **kwargs): kwargs.setdefault("min_equity_pct", 0.0) return hb.run_mode_backtest(candles, strategy.STRATEGY_BREAKOUT, params, 100.0, fee_pct=0.0, **kwargs) def test_breakout_enters_next_candle_and_hits_stop(self): candles = self.breakout_rows([(102.5, 102.6, 90, 91, 10.0)]) result = self.run_mode(candles, self.params()) closed = [t for t in result["trades"] if t["status"] == "CLOSED"] self.assertEqual(len(closed), 1) self.assertEqual(closed[0]["side"], "LONG") self.assertTrue(closed[0]["reason"].startswith("Стоп")) self.assertLess(closed[0]["net_usdt"], 0) self.assertEqual(result["summary"]["signals"], 1) def test_partial_breakeven_then_target(self): # ATR of the last 3 candles is 2.67; risk = 2.67, partial at +1R, final at +3R. candles = self.breakout_rows([(102.5, 106, 102.4, 105.5, 10.0), (105.5, 112, 105, 111, 10.0)]) result = self.run_mode(candles, self.params()) closed = [t for t in result["trades"] if t["status"] == "CLOSED"] self.assertEqual(len(closed), 1) self.assertTrue(closed[0]["reason"].startswith("TP")) self.assertGreater(closed[0]["net_usdt"], 0) def test_breakeven_stop_after_partial(self): candles = self.breakout_rows([(102.5, 106, 102.4, 105.5, 10.0), (105.5, 105.5, 95, 96, 10.0)]) result = self.run_mode(candles, self.params()) closed = [t for t in result["trades"] if t["status"] == "CLOSED"] self.assertEqual(len(closed), 1) self.assertIn("безубыток", closed[0]["reason"]) self.assertGreater(closed[0]["net_usdt"], 0) # half closed at +1R, the rest at breakeven def test_short_receives_positive_funding(self): params = mode_params(strategy.STRATEGY_FADE, timeframe_min=60, min_growth_24h=30, min_funding_pct=0, high_lookback_hours=6, pullback_pct=3, vwap_hours=6, atr_period=3, stop_buffer_atr=0.5, max_stop_pct=30, trail_atr=0, take_profit_r=0, partial_r=0, partial_pct=0, max_hold_hours=48) rows = [(100, 101, 99, 100, 1.0)] * 20 rows += [(price - 2, price + 2, price - 4, price, 5.0) for price in (110, 125, 140, 150, 146)] rows += [(146, 147, 128, 130, 5.0), (130, 131, 129, 130, 5.0), (130, 131, 129, 130, 5.0)] candles = {"AAA": minute_rows(rows, tf_min=60)} funding_stamp = 27 * 60 * MIN result = hb.run_mode_backtest(candles, strategy.STRATEGY_FADE, params, 100.0, fee_pct=0.0, min_equity_pct=0.0, funding_by_symbol={"AAA": {funding_stamp: 0.01}}) rows_out = result["trades"] self.assertEqual(len(rows_out), 1) self.assertEqual(rows_out[0]["side"], "SHORT") self.assertGreater(rows_out[0]["funding_usdt"], 0) def test_universe_window_blocks_entry(self): candles = self.breakout_rows([(102.5, 102.6, 102, 102.5, 10.0)]) result = self.run_mode(candles, self.params(), universe_windows={"AAA": []}) self.assertEqual(result["trades"], []) class UniverseTests(unittest.TestCase): def test_build_universe_windows(self): hour = 3_600_000 start = 48 * hour # PUMP doubles after the first day; FLAT never moves. Both are liquid. pump = [[t * hour, 1, 1, 1, 1.0 if t < 24 else 2.0, 1000.0] for t in range(0, 72)] flat_rows = [[t * hour, 1, 1, 1, 1.0, 500.0] for t in range(0, 72)] windows = hb.build_universe_windows({"PUMP": pump, "FLAT": flat_rows}, start, 70 * hour, 20.0) self.assertIn("PUMP", windows) self.assertNotIn("FLAT", windows) self.assertEqual(windows["PUMP"][0][0], start) def test_top_n_limits_selection(self): hour = 3_600_000 rich = [[t * hour, 1, 1, 1, 1.0 if t < 24 else 2.0, 1000.0] for t in range(60)] poor = [[t * hour, 1, 1, 1, 1.0 if t < 24 else 2.0, 1.0] for t in range(60)] windows = hb.build_universe_windows({"RICH": rich, "POOR": poor}, 48 * hour, 58 * hour, 20.0, top_n=1) self.assertEqual(set(windows), {"RICH"}) class CacheTests(unittest.TestCase): def test_turnover_migration_and_roundtrip(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "cache.sqlite3" connection = hb._open_candle_cache(path) hb._cache_page(connection, "AAA", 60, 0, 3_600_000, [[0, 1, 2, 0.5, 1.5, 123.0], [3_600_000, 1.5, 2, 1, 1.8, 50.0]], 3_600_000) connection.close() rows = hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path, with_turnover=True) self.assertEqual(rows[0][5], 123.0) self.assertEqual(len(hb.fetch_klines("AAA", 60, 0, 3_600_000, cache_path=path)[0]), 5) if __name__ == "__main__": unittest.main()