test_codex_analyzer.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import subprocess
  2. import pytest
  3. from okx_codex_trader.codex_analyzer import analyze_with_codex
  4. from okx_codex_trader.models import Candle
  5. def sample_candles() -> list[Candle]:
  6. return [
  7. Candle(symbol="BTC-USDT-SWAP", ts=1, open=100.0, high=105.0, low=99.0, close=104.0, volume=10.0),
  8. Candle(symbol="BTC-USDT-SWAP", ts=2, open=104.0, high=106.0, low=103.0, close=105.0, volume=12.0),
  9. Candle(symbol="BTC-USDT-SWAP", ts=3, open=105.0, high=107.0, low=104.0, close=106.0, volume=11.0),
  10. ]
  11. def fake_runner(stdout: str):
  12. calls: list[tuple[object, bool, bool, bool]] = []
  13. def runner(command, capture_output: bool, text: bool, check: bool):
  14. calls.append((command, capture_output, text, check))
  15. return subprocess.CompletedProcess(command, 0, stdout=stdout, stderr="")
  16. runner.calls = calls
  17. return runner
  18. def missing_which(name: str) -> None:
  19. assert name == "codex"
  20. return None
  21. def test_analyzer_fails_when_codex_is_missing():
  22. with pytest.raises(FileNotFoundError):
  23. analyze_with_codex(candles=sample_candles(), symbol="BTC-USDT-SWAP", bar="1H", which=missing_which)
  24. def test_analyzer_rejects_non_json_output():
  25. runner = fake_runner(stdout="not json")
  26. with pytest.raises(ValueError):
  27. analyze_with_codex(candles=sample_candles(), symbol="BTC-USDT-SWAP", bar="1H", runner=runner)
  28. def test_analyzer_rejects_json_leverage_out_of_range():
  29. runner = fake_runner(
  30. stdout='{"action":"long","confidence":0.8,"leverage":4,"entry_price":null,"take_profit_price":null,"stop_loss_price":null,"reason":"x"}'
  31. )
  32. with pytest.raises(ValueError):
  33. analyze_with_codex(candles=sample_candles(), symbol="BTC-USDT-SWAP", bar="1H", runner=runner)
  34. def test_analyzer_returns_valid_trade_signal():
  35. runner = fake_runner(
  36. stdout='{"action":"short","confidence":0.6,"leverage":2,"entry_price":101.5,"take_profit_price":99.0,"stop_loss_price":103.0,"reason":"trend"}'
  37. )
  38. signal = analyze_with_codex(candles=sample_candles(), symbol="BTC-USDT-SWAP", bar="1H", runner=runner)
  39. assert signal.action == "short"
  40. assert signal.confidence == 0.6
  41. assert signal.leverage == 2
  42. assert signal.entry_price == 101.5
  43. assert signal.take_profit_price == 99.0
  44. assert signal.stop_loss_price == 103.0
  45. assert signal.reason == "trend"
  46. assert runner.calls
  47. assert runner.calls[0][0][0:2] == ["codex", "exec"]
  48. assert runner.calls[0][1:] == (True, True, False)