Howwise RSS
Trading Software6 min read

ibapi: Get a Value From a Callback in Python Safely

Short answer

To do an ibapi get value from callback in Python, store the data on self inside the callback, set a threading.Event there, and have the requesting method wait on it with a timeout before returning the value, because ibapi requests return immediately.

Key takeaways
  • reqMktData returns at once; tickPrice runs later on the reader thread, so a print right after the call sees the initial None.
  • Use an Event with wait(timeout) for one value, or a Queue for many values or repeated requests.
  • Under delayed data (reqMarketDataType(3)) prices arrive as tick types 66, 67, 68 and 75, so a callback that checks only 1, 2, 4 stores nothing.
  • Errors 10167 and 10090 are informational warnings; WinError 10038 is socket-close noise from disconnecting while the reader is still in recv.
  • Shut down in order: get data, cancelMktData, disconnect, then join the thread, and wait for nextValidId before sending any request.

Copy-paste class: ibapi get value from callback in Python

This class subclasses EWrapper and EClient, runs the message loop in a daemon thread, waits for nextValidId (the signal that the connection is ready), and exposes get_price(), which requests, waits and returns a value. It accepts live ticks (1, 2, 4) and delayed ticks (66, 67, 68, 75).

Ports: 7497 is TWS paper, 7496 TWS live, 4002 Gateway paper, 4001 Gateway live. Use a unique clientId per connection.

import threading, time
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

LIVE = {1: 'bid', 2: 'ask', 4: 'last', 9: 'close'}
DELAYED = {66: 'bid', 67: 'ask', 68: 'last', 75: 'close'}

class App(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.ready = threading.Event()
        self.price_evt = threading.Event()
        self.price = None          # instance state, not class state
        self.ticks = {}

    # --- callbacks (run on the reader thread) ---
    def nextValidId(self, orderId):
        self.next_id = orderId
        self.ready.set()

    def tickPrice(self, reqId, tickType, price, attrib):
        name = LIVE.get(tickType) or DELAYED.get(tickType)
        if name is None or price <= 0:   # -1 means no data
            return
        self.ticks[name] = price
        if name in ('last', 'bid') and self.price is None:
            self.price = price
            self.price_evt.set()

    def error(self, reqId, errorCode, errorString, *args):
        print('msg', reqId, errorCode, errorString)

    # --- caller side ---
    def start(self, host='127.0.0.1', port=7497, client_id=7):
        self.connect(host, port, client_id)
        threading.Thread(target=self.run, daemon=True).start()
        if not self.ready.wait(10):
            raise TimeoutError('no nextValidId; is TWS API enabled?')

    def get_price(self, symbol, timeout=10):
        c = Contract()
        c.symbol, c.secType, c.exchange, c.currency = symbol, 'STK', 'SMART', 'USD'
        self.price = None
        self.price_evt.clear()           # clear before each request
        req_id = self.next_id; self.next_id += 1
        self.reqMarketDataType(3)        # 3 = delayed; 1 = live
        self.reqMktData(req_id, c, '', False, False, [])
        got = self.price_evt.wait(timeout)
        self.cancelMktData(req_id)
        return self.price if got else None

if __name__ == '__main__':
    app = App()
    app.start()
    print(app.get_price('AAPL'))
    time.sleep(0.5)
    app.disconnect()
Tip: Some ibapi versions pass an extra advancedOrderReject argument to error(); the *args in the signature keeps the class working across versions.

Why is my variable empty right after reqMktData?

ibapi is asynchronous. reqMktData only writes a message to the socket and returns. The reply is parsed by the EReader thread, queued, and dispatched to your callback by the loop in run(). The value therefore does not exist yet when the next line executes.

Timeline: t=0 ms reqMktData returns; t=1 ms print(self.price) shows None; t=50 to 500 ms tickPrice fires and sets self.price. The same applies to reqContractDetails, reqHistoricalData and similar calls.

Callbacks never return values to your code. Their return value goes to the dispatcher, so the only way out is shared state written by the callback, which is why the variable must live on self (set in __init__) and not in a local variable or a class attribute shared between instances.

Event or Queue: which wait pattern should I use?

Event suits one value per request. Queue suits streams, many values, or repeated requests, because items are not overwritten. Both need a timeout, since a missing subscription, a closed market or a dropped connection would otherwise block forever.

A bare time.sleep(1) is fragile: too short on a slow reply and you read None, too long and every call wastes time. It also gives no signal when the data never arrives.

Aspectthreading.Eventqueue.Queuetime.sleep
Best forOne value per requestMany values, repeated requestsNothing reliable
Wake-upImmediately on set()Immediately on put()After fixed delay
Timeoutwait(timeout) returns Falseget(timeout) raises queue.EmptyNone
RiskStale value if not clearedLeftover items from earlier requestsRace condition
import queue

# in __init__
self.q = queue.Queue()

# in callback
def contractDetails(self, reqId, details):
    self.q.put(details.contract.conId)

def contractDetailsEnd(self, reqId):
    self.q.put(None)             # sentinel: no more items

# caller
self.reqContractDetails(1, contract)
results = []
while True:
    item = self.q.get(timeout=10)   # raises queue.Empty on timeout
    if item is None:
        break
    results.append(item)
Warning: Drain or recreate the queue before a new request, otherwise late items from a previous request are read as the answer to the next one.

How do I know the data is complete?

For multi-row answers, use the end callbacks instead of guessing: contractDetailsEnd for reqContractDetails, historicalDataEnd for reqHistoricalData, and tickSnapshotEnd when reqMktData is called with snapshot=True. Collect rows in a list on self inside the data callback and set the Event in the end callback.

Snapshots are a request/response shape that fits the Event pattern well. Streaming ticks never end, so for them you decide your own condition, such as the first valid last or bid, then cancel with cancelMktData.

Why does the value stay empty under delayed data?

Tick types identify the field. Live prices use 1 (bid), 2 (ask) and 4 (last). With delayed data the same fields arrive as 66 (delayed bid), 67 (delayed ask), 68 (delayed last) and 75 (delayed close). A callback that tests only for 1, 2 and 4 ignores every delayed tick, so the Event is never set and the wait times out.

Also ignore non-positive prices: -1 is sent when no value is available.

Fix: map both sets of tick types, as in the class above, and call reqMarketDataType(3) before reqMktData.

FieldLive tickTypeDelayed tickType
Bid166
Ask267
Last468
Close975

What do errors 10167 and 10090 mean?

10167 is 'Requested market data is not subscribed. Displaying delayed market data'. 10090 is 'Part of requested market data is not subscribed'. Both are warnings delivered through error(), not exceptions, and they do not stop the script. They say you have no live subscription for that exchange, so the server falls back to delayed data.

To use delayed data deliberately, call reqMarketDataType(3) before reqMktData. For live data, subscribe to the exchange feed in Account Management and use type 1. If you filter error() output, treat 10167, 10090 and the 21xx connection-status codes (2104, 2106, 2158) as informational.

How do I stop the WinError 10038 EReader error and disconnect cleanly?

WinError 10038 ('an operation was attempted on something that is not a socket') appears when the socket is closed while the EReader thread is still blocked in recv. It happens if the main thread ends, or disconnect() runs, before the reader has finished. The trace is usually harmless, but it is avoidable.

The daemon thread plus a short grace period removes it in most cases.

  1. Connect, start run() in a daemon thread, and wait for nextValidId.
  2. Send the request and wait on the Event or Queue with a timeout.
  3. Call cancelMktData(reqId) for every streaming subscription.
  4. Sleep briefly (about 0.5 s) so pending messages drain.
  5. Call app.disconnect() as the last step, then optionally join the thread with a timeout.
  6. Never let the main thread fall off the end while requests are still pending.
Tip: If the script must keep running, keep the main thread alive with a loop or by waiting on an Event, rather than letting it exit.

Is ib_async easier than raw ibapi callbacks?

ib_insync and its maintained successor ib_async wrap the same TWS API in an event loop and return results directly, so no Event or Queue is needed. They also handle the nextValidId handshake and delayed data tick mapping for you.

Raw ibapi gives full control and no extra dependency, but you own the threading. Use the wrapper library when you want synchronous-looking code.

from ib_async import IB, Stock

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=8)
ib.reqMarketDataType(3)
[ticker] = ib.reqTickers(Stock('AAPL', 'SMART', 'USD'))
print(ticker.marketPrice())
ib.disconnect()

Common questions

Can a callback return a value to my function in ibapi?

No. The return value goes to the message dispatcher and is discarded. Write the data to self.<attribute> and signal with an Event or Queue.

Why does my script hang forever on wait()?

Event.wait() without a timeout blocks until set() is called. If no tick arrives, because of a missing subscription, ignored tick types or a closed market, it never returns. Always pass a timeout and handle False.

Do I need to call reqMarketDataType every time?

It applies to the connection until changed, so once after connecting is enough. Calling it before each reqMktData is harmless and makes the intent explicit.

Why must I wait for nextValidId before sending requests?

It confirms the socket handshake finished and gives the first usable order ID. Requests sent earlier can be dropped or fail. Wait on an Event set in nextValidId.

Is it safe to call a blocking wait inside a callback?

No. Callbacks run on the thread that processes messages, so blocking there stops all further callbacks, including the one that would unblock you. Keep callbacks short and wait only from the main thread.

Related topics:ibapiinteractive brokerspythonthreadingmarket data