"""Offline regression tests: python3 -m unittest test_risk_controls -v""" import copy import unittest from unittest.mock import patch import bot class RiskControls(unittest.TestCase): def setUp(self): self.cfg = bot.load_config() self.st = bot.default_state(self.cfg) def test_daily_unrealized_loss_latches(self): self.assertEqual(bot.daily_loss_blocked(self.st,self.cfg,97), (True,'daily_loss_limit')) self.assertTrue(bot.daily_loss_blocked(self.st,self.cfg,100)[0]) def test_rollover_before_exit(self): self.st['daily']={'date':'2020-01-01','realized_pnl_usd':-10} bot.roll_daily(self.st,98) self.assertEqual(self.st['daily']['realized_pnl_usd'],0) self.assertEqual(self.st['daily']['starting_equity_usd'],98) def test_exit_slippage_and_fees(self): self.st['positions']['TST-USD']={'qty':10,'avg_entry':1,'buy_fee_usd':.04} self.st['cash_usd']=89.96 with patch.object(bot,'log_event'): ev=bot.close_position_if_needed(self.st,self.cfg,'TST-USD',1.04) expected=10*1.04*(1-.0015)*(1-.004)-10-.04 self.assertAlmostEqual(ev['realized_pnl_usd'],expected) self.assertAlmostEqual(self.st['cash_usd'],100+expected) def test_shadow_exit_slippage(self): self.st['shadow_positions']['TST-USD']={'qty':10,'avg_entry':1,'buy_fee_usd':.04} with patch.object(bot,'log_event'): ev=bot.close_shadow_position_if_needed(self.st,self.cfg,'TST-USD',1.04) self.assertAlmostEqual(ev['price'],1.04*(1-.0015)) def test_fee_edge_counts_two_sides(self): cfg={**self.cfg,'require_rebound_confirmation':False,'min_candles_24h':0,'min_dollar_volume_24h':0} self.assertFalse(bot.signal_has_fee_aware_edge(cfg,{'gap_pct':2.55})) self.assertTrue(bot.signal_has_fee_aware_edge(cfg,{'gap_pct':2.66})) def test_risk_cap(self): cfg={**self.cfg,'max_risk_per_trade_pct':.05,'min_trade_usd':.01} sig={'symbol':'TST-USD','price':1,'gap_pct':5,'volatility_pct':1} with patch.object(bot,'log_event'),patch.object(bot,'recent_symbol_loss_blocked',return_value=(False,None)),patch.object(bot,'signal_has_fee_aware_edge',return_value=True),patch.object(bot,'symbol_performance_multiplier',return_value=2): ev=bot.maybe_open_position(self.st,cfg,sig,100) self.assertLessEqual(ev['notional_usd']*.023,.05+1e-9) def test_missing_held_price_blocks_entries(self): cfg={**self.cfg,'symbols':['TST-USD'],'watch_only_symbols':[]} self.st['positions']['TST-USD']={'qty':1,'avg_entry':1} with patch.object(bot,'fetch_coinbase_candles',side_effect=RuntimeError('offline')),patch.object(bot,'save_state'),patch.object(bot,'log_event'),patch.object(bot,'maybe_open_position') as opener: result=bot.scan_once(cfg,self.st) self.assertEqual(result['block_reason'],'missing_position_prices') opener.assert_not_called() def test_stale_candles_rejected(self): with patch.object(bot.time,'time',return_value=100000),patch.object(bot,'http_json',return_value=[[100,1,2,1.5,1.5,10]]*20): with self.assertRaisesRegex(RuntimeError,'stale candles'): bot.fetch_coinbase_candles('TST-USD',24,300) def test_incomplete_candle_excluded(self): rows=[[100000-i*300,1,2,1.5,1.5,10] for i in range(20)] with patch.object(bot.time,'time',return_value=100010),patch.object(bot,'http_json',return_value=rows): candles=bot.fetch_coinbase_candles('TST-USD',24,300) self.assertEqual(len(candles),19) self.assertEqual(candles[-1].ts,99700) if __name__=='__main__': unittest.main()