"""Offline regression cases for recovery, shared collateral and partial paper fills.""" import json import tempfile import unittest from pathlib import Path from unittest.mock import patch import algo_hunter as ah import scalp_hint as sh import scalp_paper as sp from virtual_account import VirtualAccount def trader(folder=None, mode="simple", stake=6.0, leverage=1.0): paths = (Path(folder) / "paper.json", Path(folder) / "trades.csv") if folder else (None, None) return sp.PaperTrader(sp.PaperSettings(mode=mode, stake=stake, leverage=leverage), sh.HintSettings(), *paths) def open_position(t, price=100, now=100): return t.ledger.open("AAA", "LONG", price, now, 0.1, 110, 90, price) def book(bid=100, ask=101): result = sh.OrderBook() result.bids, result.asks = {bid: 1000}, {ask: 1000} return result class RecoveryTests(unittest.TestCase): def test_corrupt_snapshot_is_not_overwritten_by_new_entry(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "paper.json" path.write_text('{"balance": 299, "positions": [', encoding="utf-8") previous = path.read_bytes() t = trader(folder) self.assertIsNone(open_position(t)) self.assertEqual(path.read_bytes(), previous) self.assertEqual(t.balance, 300) self.assertIn("восстановить", t.ledger.storage_error) def test_open_position_survives_restart_and_closes_once(self): with tempfile.TemporaryDirectory() as folder: first = trader(folder) position = open_position(first) restored = trader(folder) self.assertEqual(restored.position, position) restored.close(105, 110, "manual", 0.1) again = trader(folder) self.assertIsNone(again.position) self.assertEqual(len(again.trades), 1) self.assertAlmostEqual(again.balance, 300 + again.trades[0].net_usd) next_position = open_position(again, now=120) self.assertGreater(next_position.uid, position.uid) def test_atomic_write_failure_preserves_snapshot_and_memory(self): with tempfile.TemporaryDirectory() as folder: t = trader(folder) open_position(t) path = Path(folder) / "paper.json" previous = path.read_bytes() previous_balance = t.balance with patch("scalp_paper.atomic_write_json", side_effect=OSError("disk full")): t.close(105, 110, "manual", 0.1) self.assertEqual(path.read_bytes(), previous) self.assertIsNotNone(t.position) self.assertEqual(t.trades, []) self.assertEqual(t.balance, previous_balance) self.assertIn("disk full", t.message) def test_hunter_restores_exit_levels_and_risk_guard(self): with tempfile.TemporaryDirectory() as folder: t = trader(folder, mode="algo_hunter") policy = t.policy policy.tick, policy.ticker = 1.0, "AAA" policy.guard.daily_pnl = -7.5 policy.guard.pause_until = 1000 policy.guard.disabled_reason = "risk test" policy.order = ah.HunterOrder("LONG", 100, 6, 99, 99, "test", ah.AlgoSignature("bid", [100], [10], .9, 99, ["test"], 10), ahead=0) policy._fill(t, 100, 2) t.last_close = 80 t.ledger.save() restored = trader(folder, mode="algo_hunter") self.assertEqual(restored.position.qty, .02) self.assertEqual(restored.policy.stop, t.policy.stop) self.assertEqual(restored.policy.target, t.policy.target) self.assertEqual(restored.policy.filled_at, 100) self.assertEqual(restored.last_close, 80) self.assertEqual(restored.policy.guard.daily_pnl, -7.5) self.assertEqual(restored.policy.guard.pause_until, 1000) self.assertEqual(restored.policy.guard.disabled_reason, "risk test") self.assertIsNone(restored.policy.order) restored.policy._close(restored, 101, 110, "manual", 0.1) self.assertIsNone(restored.position) class PartialFillTests(unittest.TestCase): def pending(self, ahead=100): t = trader(mode="algo_hunter", stake=20) t.policy.tick, t.policy.ticker = 1, "AAA" signature = ah.AlgoSignature("bid", [100], [ahead], .9, 99, ["test"], ahead) t.policy.order = ah.HunterOrder("LONG", 100, 20, 99, 99, "test", signature, ahead=ahead) return t def test_trade_equal_to_queue_does_not_fill_us(self): t = self.pending() t.on_trade(sh.Trade(100, 100, 100, "Sell")) self.assertIsNone(t.position) self.assertEqual(t.policy.order.ahead, 0) t.on_trade(sh.Trade(101, 100, 3, "Sell")) self.assertAlmostEqual(t.position.qty * t.position.entry, 3) self.assertAlmostEqual(t.position.fee_in, 3 * sh.MAKER_FEE_PCT / 100) self.assertEqual(t.position.margin, 3) self.assertIsNone(t.policy.order) # conservative cancellation of unfilled remainder def test_only_volume_after_queue_can_fill(self): t = self.pending() t.on_trade(sh.Trade(100, 100, 102, "Sell")) self.assertAlmostEqual(t.position.qty * t.position.entry, 2) self.assertEqual(t.policy.entry_order.size_usd, 2) def test_fill_cannot_exceed_requested_size(self): t = self.pending() t.on_trade(sh.Trade(100, 100, 200, "Sell")) self.assertAlmostEqual(t.position.qty * t.position.entry, 20) def test_wrong_trade_side_does_not_consume_queue(self): t = self.pending() t.on_trade(sh.Trade(100, 100, 200, "Buy")) self.assertIsNone(t.position) self.assertEqual(t.policy.order.ahead, 100) class SharedAccountTests(unittest.TestCase): def test_common_top_up_unblocks_policy_despite_old_local_balance(self): with tempfile.TemporaryDirectory() as folder: account = VirtualAccount(Path(folder) / "account.json", 1) t = trader() t.ledger.balance = 1 t.bind_account(account, "coin") hint = sh.Hint("LONG", "test", .9, target=110) t.on_tick(100, "AAA", hint, book(), 1) self.assertIsNone(t.position) account.adjust(10, "test-top-up") t.on_tick(101, "AAA", hint, book(), 1) self.assertIsNotNone(t.position) self.assertLess(t.balance, 1) # accounting baseline is separate from the common spending limit def test_two_coins_share_capital_and_close_releases_margin(self): with tempfile.TemporaryDirectory() as folder: account = VirtualAccount(Path(folder) / "account.json", 10) first, second = trader(), trader() first.bind_account(account, "first") second.bind_account(account, "second") self.assertIsNotNone(open_position(first)) first.mark_account(book()) self.assertIsNone(open_position(second)) self.assertIn("Недостаточно", second.ledger.storage_error) self.assertEqual(second.ledger.positions, []) self.assertEqual(account.view()["reserved"], 6) first.close(100, 110, "manual", 0.1) self.assertEqual(account.view()["reserved"], 0) self.assertIsNotNone(open_position(second)) self.assertAlmostEqual(account.view()["balance"], 10 - .006 * 3) def test_failed_shared_commit_does_not_trigger_hooks_or_change_exposure(self): with tempfile.TemporaryDirectory() as folder: account = VirtualAccount(Path(folder) / "account.json", 10) t = trader() t.bind_account(account, "coin") events = [] t.ledger.hooks.append(lambda event, pos: events.append(event)) with patch("virtual_account.atomic_write_json", side_effect=OSError("disk full")): self.assertIsNone(open_position(t)) self.assertEqual(events, []) self.assertEqual(t.balance, 300) self.assertEqual(account.view()["reserved"], 0) self.assertEqual(account.view()["balance"], 10) def test_account_snapshot_restores_position_and_is_idempotent(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "account.json" account = VirtualAccount(path, 10) t = trader() t.bind_account(account, "coin") position = open_position(t) balance = account.view()["balance"] restarted = VirtualAccount(path, 999) again = trader() again.bind_account(restarted, "coin") again.ledger.save() self.assertEqual(again.position, position) self.assertEqual(restarted.view()["balance"], balance) self.assertEqual(restarted.view()["reserved"], 6) def test_reset_never_erases_shared_position_or_creates_money(self): with tempfile.TemporaryDirectory() as folder: account = VirtualAccount(Path(folder) / "account.json", 10) t = trader(leverage=2) t.bind_account(account, "coin") position = open_position(t) t.settings.leverage = 20 t.ledger.save() self.assertEqual(account.view()["reserved"], 6) self.assertFalse(t.ledger.reset()) self.assertEqual(t.position, position) t.close(101, 110, "manual", .1) previous = account.view()["balance"] self.assertTrue(t.ledger.reset()) self.assertEqual(account.view()["balance"], previous) def test_migration_debits_only_fees_of_existing_positions(self): with tempfile.TemporaryDirectory() as folder: account = VirtualAccount(Path(folder) / "account.json", 10) t = trader() t.ledger.balance = 321 # historic results do not seed the new common account position = open_position(t) t.bind_account(account, "coin") self.assertAlmostEqual(account.view()["balance"], 10 - position.fee_in) self.assertEqual(account.view()["reserved"], 6) if __name__ == "__main__": unittest.main()