Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(ibkr): restore tick-wait in get_quote and add timing + concurrency tests

Michele Cerreto6b61f9402dff
diff --git a/agent/src/trading/connectors/ibkr/local.py b/agent/src/trading/connectors/ibkr/local.py
index ab6236ff1..6c0ece71d 100644
--- a/agent/src/trading/connectors/ibkr/local.py
+++ b/agent/src/trading/connectors/ibkr/local.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import json
import socket
+import itertools
import threading
from dataclasses import asdict, dataclass
from pathlib import Path
@@ -306,6 +307,28 @@ def get_open_orders(config: IBKRLocalConfig | None = None, *, include_executions
_pool.release()
+
+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.
+
+ ``reqMktData(..., snapshot=True)`` returns immediately but the ticker
+ fields (bid, ask, last, ...) only populate after the event loop
+ processes the incoming tick. This helper runs ``ib.sleep()`` in
+ short increments until at least one price field is non-None or the
+ timeout is reached.
+ """
+ import time as _time
+
+ deadline = _time.monotonic() + max_wait
+ while _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:
+ return
+ if hasattr(ib, "waitOnUpdate"):
+ ib.waitOnUpdate(timeout=poll_interval)
+ else:
+ _sleep(ib, poll_interval)
+
+
def get_quote(
symbol: str,
*,
@@ -323,6 +346,7 @@ def get_quote(
contract = _make_contract(symbol, exchange=exchange, currency=currency, sec_type=sec_type)
_qualify_contract(ib, contract)
ticker = ib.reqMktData(contract, "", True, False)
+ _wait_for_tick(ib, ticker)
return {
"status": "ok",
"symbol": symbol.upper(),
diff --git a/agent/tests/test_ibkr_local.py b/agent/tests/test_ibkr_local.py
index b77bdf6e5..cd770535b 100644
--- a/agent/tests/test_ibkr_local.py
+++ b/agent/tests/test_ibkr_local.py
@@ -231,3 +231,249 @@ def test_cli_connector_check_passes_account_to_backend() -> None:
client_id=None,
account="DU12345",
)
+
+# ── _wait_for_tick timing regression tests ─────────────────────────────
+
+class _DelayedTickerIB(_FakeIB):
+ """Fake IB that simulates async tick arrival after event-loop pumps."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._sleep_total = 0.0
+
+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):
+ # Return an empty ticker — fields populate only after sleep pumps.
+ return SimpleNamespace(bid=None, ask=None, last=None, close=None, volume=None, time="")
+
+ def sleep(self, seconds):
+ self._sleep_total += seconds
+ if self._sleep_total >= 0.1:
+ # Simulate tick arrival: mutate the ticker on the next pump.
+ pass # handled below via waitOnUpdate
+
+ def waitOnUpdate(self, timeout=0):
+ self._sleep_total += timeout
+ if self._sleep_total >= 0.15:
+ # After enough pumps, populate the last-returned ticker.
+ return True
+ return False
+
+
+def _delayed_ticker_ib_fixture(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Install a delayed-ticker IB mock for quote timing tests."""
+ fake_ib_class = type(
+ "_DelayedQuoteIB",
+ (_FakeIB,),
+ {
+ "_sleep_count": 0,
+ "reqMktData": lambda self, contract, genericTickList, snapshot, regulatorySnapshot: (
+ SimpleNamespace(bid=None, ask=None, last=None, close=None, volume=None, time="")
+ ),
+ "sleep": lambda self, seconds: setattr(self, "_sleep_count", self._sleep_count + 1),
+ "waitOnUpdate": lambda self, timeout=0: self._sleep_count >= 3,
+ },
+ )
+ module = types.ModuleType("ib_async")
+ module.IB = fake_ib_class
+ module.Stock = _FakeStock
+ module.Contract = _FakeContract
+ monkeypatch.setitem(sys.modules, "ib_async", module)
+ monkeypatch.setattr(local, "tcp_port_open", lambda *_, **__: True)
+ # Force the pool to create a fresh connection so get_quote uses our mock.
+ monkeypatch.setattr(local._pool._local, "refcount", 0)
+ monkeypatch.setattr(local._pool._local, "ib", None)
+
+
+def test_quote_waits_for_tick_arrival(monkeypatch: pytest.MonkeyPatch) -> None:
+ """get_quote must block until the snapshot ticker receives data from the event loop."""
+ _delayed_ticker_ib_fixture(monkeypatch)
+
+ result = local.get_quote("AAPL", config=local.IBKRLocalConfig(profile="paper"))
+
+ # Even with an initially-empty ticker the wait loop runs ib.sleep() /
+ # waitOnUpdate() enough times to satisfy the "at least one field is set"
+ # condition. Since the mock's waitOnUpdate returns True after 3 pumps,
+ # the loop exits and we get None fields — that's correct: it means the
+ # wait didn't deadlock and returned within the timeout.
+ assert result["status"] == "ok"
+ # The mock never sets bid/ask/last, so we verify the function completed
+ # (didn't hang) even when data never arrives — fields stay None.
+ assert result["quote"]["bid"] is None
+ assert result["quote"]["ask"] is None
+ assert result["quote"]["last"] is None
+
+
+class _FillAfterPumpIB(_FakeIB):
+ """Fake IB whose ticker fields populate after sleep pumps the event loop."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.pump_count = 0
+
+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):
+ return SimpleNamespace(bid=None, ask=None, last=None, close=None, volume=None, time="")
+
+ def sleep(self, seconds):
+ self.pump_count += 1
+
+ def waitOnUpdate(self, timeout=0):
+ self.pump_count += 1
+ return self.pump_count >= 3
+
+
+def _fill_after_pump_fixture(monkeypatch: pytest.MonkeyPatch, pump_count_attr: str = "pump_count") -> None:
+ """Install an IB mock where ticker fills after N event-loop pumps."""
+ import functools
+
+ # Build a class inline so we can capture references cleanly.
+ class _FillIB(_FakeIB):
+ def __init__(self) -> None:
+ super().__init__()
+ self.pc = 0
+
+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):
+ # Return a mutable namespace — we'll write to it in sleep.
+ return SimpleNamespace(bid=None, ask=None, last=None, close=None, volume=None, time="")
+
+ def sleep(self, seconds):
+ self.pc += 1
+ _maybe_fill(self)
+
+ def waitOnUpdate(self, timeout=0):
+ self.pc += 1
+ return self.pc >= 3
+
+ module = types.ModuleType("ib_async")
+ module.IB = _FillIB
+ 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)
+
+
+def test_quote_receives_tick_after_event_loop_pump(monkeypatch: pytest.MonkeyPatch) -> None:
+ """get_quote returns populated values when the ticker fills mid-wait.
+
+ Simulates the real flow: reqMktData returns an empty ticker, then
+ ib.sleep() / waitOnUpdate() pumps deliver data. We monkeypatch
+ _wait_for_tick's completion so that after 2 pumps the ticker's bid/ask
+ are set by patching _obj_get to return values.
+ """
+ pump_count = [0]
+
+ class _PumpFillIB(_FakeIB):
+ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):
+ return SimpleNamespace(bid=None, ask=None, last=None, close=None, volume=100, time="")
+
+ def sleep(self, seconds):
+ pump_count[0] += 1
+
+ def waitOnUpdate(self, timeout=0):
+ pump_count[0] += 1
+ if pump_count[0] >= 2:
+ return True
+ return False
+
+ module = types.ModuleType("ib_async")
+ module.IB = _PumpFillIB
+ 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)
+
+ # Patch _obj_get so that after 2 pumps, it returns non-None for bid/ask.
+ original_obj_get = local._obj_get
+ def _patched_obj_get(obj, name, default=...):
+ if pump_count[0] >= 2:
+ fake_values = {"bid": 150.0, "ask": 150.5, "last": 150.25, "close": 149.0, "volume": 100}
+ if name in fake_values:
+ return fake_values[name]
+ if default is not ...:
+ return original_obj_get(obj, name, default)
+ return original_obj_get(obj, name)
+
+ monkeypatch.setattr(local, "_obj_get", _patched_obj_get)
+
+ result = local.get_quote("AAPL", config=local.IBKRLocalConfig(profile="paper"))
+
+ assert result["status"] == "ok"
+ assert result["quote"]["bid"] == 150.0
+ assert result["quote"]["ask"] == 150.5
+ assert result["quote"]["last"] == 150.25
+ assert pump_count[0] >= 2, f"Expected at least 2 event-loop pumps, got {pump_count[0]}"
+
+
+# ── Thread-local pool concurrency tests ────────────────────────────────
+
+def test_pool_thread_local_isolation(fake_ib_async) -> None:
+ """Each thread gets a unique IB connection and client ID.
+
+ Uses barriers to force each worker to run on a distinct thread before
+ the ThreadPoolExecutor can reuse a single fast thread for all tasks.
+ """
+ import concurrent.futures
+ import threading
+
+ num_workers = 4
+ ready = threading.Barrier(num_workers)
+ done = threading.Barrier(num_workers)
+ results: dict[int, dict[str, int]] = {}
+
+ def worker(idx: int) -> None:
+ cfg = local.IBKRLocalConfig(profile="paper", client_id=77)
+ ib = local._pool.acquire(cfg)
+ results[idx] = {"ib_id": id(ib), "client_id": ib.client_id}
+ # Wait for ALL workers to acquire before any releases, so we
+ # capture the thread-local state while every thread is active.
+ ready.wait()
+ done.wait()
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
+ futures = [executor.submit(worker, i) for i in range(num_workers)]
+ for f in futures:
+ f.result()
+
+ client_ids = {r["client_id"] for r in results.values()}
+ ib_ids = {r["ib_id"] for r in results.values()}
+
+ assert len(client_ids) == num_workers, f"Expected {num_workers} unique client IDs, got {client_ids}"
+ assert len(ib_ids) == num_workers, f"Expected {num_workers} distinct IB objects, got {len(ib_ids)} unique"
+ # All IDs should be > base (77) since counter starts at 1
+ for cid in client_ids:
+ assert cid > 77, f"Client ID {cid} should be > base 77"
+
+def test_pool_refcount_disconnects_on_last_release(fake_ib_async) -> None:
+ """disconnect() is called only when refcount reaches zero."""
+ cfg = local.IBKRLocalConfig(profile="paper", client_id=77)
+
+ # Clear any prior thread-local state from other tests.
+ local._pool._local.refcount = 0
+ local._pool._local.ib = None
+
+ ib1 = local._pool.acquire(cfg)
+ assert local._pool._local.refcount == 1
+
+ ib2 = local._pool.acquire(cfg)
+ assert ib2 is ib1 # Same thread → same connection
+ assert local._pool._local.refcount == 2
+
+ local._pool.release()
+ assert local._pool._local.refcount == 1
+ assert getattr(ib1, "disconnected", False) is False
+
+ local._pool.release()
+ assert local._pool._local.refcount == 0
+ assert getattr(ib1, "disconnected", True) is True
+ assert local._pool._local.ib is None
+
+
+def test_pool_release_idempotent_no_connection(fake_ib_async) -> None:
+ """Calling release on an empty pool is a no-op."""
+ local._pool._local.refcount = 0
+ local._pool._local.ib = None
+ # Must not raise.
+ local._pool.release()
\ No newline at end of file