"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(ibkr): reject NaN ticker values in _wait_for_tick
Michele Cerretocf26d30aab65
diff --git a/agent/src/trading/connectors/ibkr/local.py b/agent/src/trading/connectors/ibkr/local.pyindex 6c0ece71d..687390dcf 100644--- a/agent/src/trading/connectors/ibkr/local.py+++ b/agent/src/trading/connectors/ibkr/local.py@@ -308,6 +308,24 @@ def get_open_orders(config: IBKRLocalConfig | None = None, *, include_executions++def _tick_has_data(ticker: Any) -> bool:+ """Return True if the ticker has received at least one real price field.++ ib_async tickers start with None and populate to either a float or+ ``float('nan')`` (when no trade has occurred in the current session).+ This function rejects both None and NaN so the wait loop continues+ pumping until actual market data arrives.+ """+ import math++ for field in ("bid", "ask", "last"):+ value = _obj_get(ticker, field)+ if value is not None and not (isinstance(value, float) and math.isnan(value)):+ return True+ return False++def _wait_for_tick(ib: Any, ticker: Any, *, max_wait: float = 2.0, poll_interval: float = 0.1) -> None:"""Pump the ib_async event loop until the snapshot ticker fills.@@ -321,7 +339,7 @@ def _wait_for_tick(ib: Any, ticker: Any, *, max_wait: float = 2.0, poll_intervaldeadline = _time.monotonic() + max_waitwhile _time.monotonic() < deadline:- if _obj_get(ticker, "bid") is not None or _obj_get(ticker, "ask") is not None or _obj_get(ticker, "last") is not None:+ if _tick_has_data(ticker):returnif hasattr(ib, "waitOnUpdate"):ib.waitOnUpdate(timeout=poll_interval)diff --git a/agent/tests/test_ibkr_local.py b/agent/tests/test_ibkr_local.pyindex cd770535b..8d5812ced 100644--- a/agent/tests/test_ibkr_local.py+++ b/agent/tests/test_ibkr_local.py@@ -476,4 +476,65 @@ def test_pool_release_idempotent_no_connection(fake_ib_async) -> None:local._pool._local.refcount = 0local._pool._local.ib = None# Must not raise.- local._pool.release()\ No newline at end of file+ local._pool.release()+# ── NaN rejection tests ─────────────────────────────────────────────────++class _NaNTickerIB(_FakeIB):+ """Fake IB whose ticker fields are NaN (not None) -- simulates after-hours."""++ def __init__(self) -> None:+ super().__init__()+ self._sleep_count = 0++ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):+ import math+ return SimpleNamespace(+ bid=float("nan"), ask=float("nan"), last=float("nan"),+ close=float("nan"), volume=float("nan"), time=""+ )++ def sleep(self, seconds):+ self._sleep_count += 1++ def waitOnUpdate(self, timeout=0):+ self._sleep_count += 1+ return True+++def test_quote_rejects_nan_and_waits_for_real_data(monkeypatch: pytest.MonkeyPatch) -> None:+ """get_quote must not exit with NaN -- it must wait for real numeric data."""+ import math++ pump_count = [0]++ class _NaNFillIB(_FakeIB):+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):+ return SimpleNamespace(+ bid=float("nan"), ask=float("nan"), last=float("nan"),+ close=float("nan"), volume=float("nan"), time=""+ )++ def sleep(self, seconds):+ pump_count[0] += 1++ def waitOnUpdate(self, timeout=0):+ pump_count[0] += 1+ return pump_count[0] >= 3++ module = types.ModuleType("ib_async")+ module.IB = _NaNFillIB+ module.Stock = _FakeStock+ module.Contract = _FakeContract+ monkeypatch.setitem(sys.modules, "ib_async", module)+ monkeypatch.setattr(local, "tcp_port_open", lambda *_, **__: True)+ monkeypatch.setattr(local._pool._local, "refcount", 0)+ monkeypatch.setattr(local._pool._local, "ib", None)++ # Even after pumps, the mock always returns NaN -- so the final fields+ # should stay NaN (no real data arrived). The key assertion: the function+ # did NOT exit early -- it pumped until timeout.+ result = local.get_quote("AAPL", config=local.IBKRLocalConfig(profile="paper"))+ assert result["status"] == "ok"+ assert pump_count[0] >= 3, f"Expected at least 3 pumps (NaN loop), got {pump_count[0]}"+ # Fields stay NaN since mock never provides real data+ assert math.isnan(float(result["quote"]["bid"]))