"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(ibkr): replace fixed 2s sleep with ib.sleep() polling loop that exits on real data
Michele Cerretoc4aff5e10aaa
diff --git a/agent/src/trading/connectors/ibkr/local.py b/agent/src/trading/connectors/ibkr/local.pyindex 9269850dd..8e4dfcbca 100644--- a/agent/src/trading/connectors/ibkr/local.py+++ b/agent/src/trading/connectors/ibkr/local.py@@ -309,15 +309,44 @@ def get_open_orders(config: IBKRLocalConfig | None = None, *, include_executions-def _wait_for_tick(ib: Any, ticker: Any, *, wait_seconds: float = 2.0) -> None:- """Pump the ib_async event loop so the snapshot ticker fills.+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 polling continues+ 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, *, timeout: float = 5.0, poll_interval: float = 0.1) -> None:+ """Pump the ib_async event loop until the snapshot ticker fills.``reqMktData(..., snapshot=True)`` returns immediately but the ticker- fields only populate after the event loop processes the incoming tick.- A single ``ib.sleep()`` call processes all pending socket messages,- which is more reliable than incremental ``waitOnUpdate`` polling.+ fields (bid, ask, last, ...) only populate after the event loop+ processes the incoming tick. This helper calls ``ib.sleep()`` in+ short increments, checking ``_tick_has_data`` on each cycle, and+ exits as soon as real market data arrives.++ Uses ``ib.sleep()`` (not ``waitOnUpdate``) because ``ib.sleep``+ reliably processes all pending socket messages on each call, while+ ``waitOnUpdate`` can return True for unrelated messages, causing+ premature exit with NaN fields."""- _sleep(ib, wait_seconds)+ import time as _time++ deadline = _time.monotonic() + timeout+ while _time.monotonic() < deadline:+ if _tick_has_data(ticker):+ return+ _sleep(ib, poll_interval)def get_quote(diff --git a/agent/tests/test_ibkr_local.py b/agent/tests/test_ibkr_local.pyindex beb750ac0..964d7660f 100644--- a/agent/tests/test_ibkr_local.py+++ b/agent/tests/test_ibkr_local.py@@ -232,20 +232,87 @@ def test_cli_connector_check_passes_account_to_backend() -> None:account="DU12345",)-# -- _wait_for_tick timing regression test -------------------------------+# -- _wait_for_tick timing regression tests ------------------------------++def test_quote_waits_for_delayed_tick_arrival(monkeypatch: pytest.MonkeyPatch) -> None:+ """get_quote polls with ib.sleep() until the ticker receives real data."""+ import math+ from types import SimpleNamespace++ pump_count = [0]++ ticker_ns = SimpleNamespace(bid=None, ask=None, last=None, close=None, volume=None, time="")++ class _DelayedFillIB(_FakeIB):+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):+ # Reset fields each call so tests are independent.+ ticker_ns.bid = None+ ticker_ns.ask = None+ ticker_ns.last = None+ return ticker_ns++ def sleep(self, seconds):+ pump_count[0] += 1+ # After 5 pump cycles (0.5s), populate the ticker with real data.+ if pump_count[0] >= 5:+ ticker_ns.bid = 150.25+ ticker_ns.ask = 150.50+ ticker_ns.last = 150.30-def test_quote_calls_sleep_for_tick_arrival(monkeypatch: pytest.MonkeyPatch) -> None:- """get_quote calls ib.sleep(2.0) to wait for the snapshot tick."""module = types.ModuleType("ib_async")- module.IB = _FakeIB+ module.IB = _DelayedFillIB+ 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)++ result = local.get_quote("AAPL", config=local.IBKRLocalConfig(profile="paper"))+ assert result["status"] == "ok"+ assert result["quote"]["bid"] == 150.25+ assert result["quote"]["ask"] == 150.50+ assert result["quote"]["last"] == 150.30+ # Should have pumped at least 5 times before data arrived.+ assert pump_count[0] >= 5, f"Expected >=5 pumps, got {pump_count[0]}"+++def test_quote_keeps_polling_when_ticker_is_nan(monkeypatch: pytest.MonkeyPatch) -> None:+ """get_quote rejects NaN fields and continues polling for real data."""+ import math+ from types import SimpleNamespace++ pump_count = [0]++ ticker_ns = SimpleNamespace(+ bid=float("nan"), ask=float("nan"), last=float("nan"),+ close=None, volume=None, time="",+ )++ class _NanThenFillIB(_FakeIB):+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):+ return ticker_ns++ def sleep(self, seconds):+ pump_count[0] += 1+ if pump_count[0] >= 8:+ ticker_ns.bid = 200.0+ ticker_ns.ask = 201.0+ ticker_ns.last = 200.5++ module = types.ModuleType("ib_async")+ module.IB = _NanThenFillIBmodule.Stock = _FakeStockmodule.Contract = _FakeContractmonkeypatch.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)result = local.get_quote("AAPL", config=local.IBKRLocalConfig(profile="paper"))assert result["status"] == "ok"- assert result["quote"]["bid"] == 100.0+ assert result["quote"]["bid"] == 200.0+ assert pump_count[0] >= 8, f"Expected >=8 pumps (skipped NaN), got {pump_count[0]}"def test_pool_refcount_disconnects_on_last_release(fake_ib_async) -> None:"""disconnect() is called only when refcount reaches zero."""