0

I'm having a bit of a disaster trying to do something simple - in short getting ib api to work. I'd like to get the current market prices for a stock on the LSE, I've subscribed to the correct market feed and ran this code:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
import threading
import time

from ibapi.contract import Contract

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
    def tickPrice(self, reqId, tickType, price, attrib):
        if tickType == 2 and reqId == 1:
            print('The current ask price is: ', price)

def run_loop():
    app.run()

app = IBapi()

app.connect('127.0.0.1', 7497, 4002)

#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1) #Sleep interval to allow time for connection to server

#Create contract object
apple_contract = Contract()
apple_contract.symbol = 'BARC'
apple_contract.secType = 'STK'
apple_contract.exchange = 'LSE'
apple_contract.currency = 'GBP'

#Request Market Data
app.reqMktData(1, apple_contract, '', False, False, [])

time.sleep(10) #Sleep interval to allow time for incoming price data
app.disconnect()

However I'm getting this error back:

The current ask price is:  -100.0
unhandled exception in EReader thread
Traceback (most recent call last):
  File "C:\TWS API\source\pythonclient\ibapi\reader.py", line 34, in run
    data = self.conn.recvMsg()
  File "C:\TWS API\source\pythonclient\ibapi\connection.py", line 99, in recvMsg
    buf = self._recvAllMsg()
  File "C:\TWS API\source\pythonclient\ibapi\connection.py", line 119, in _recvAllMsg
    buf = self.socket.recv(4096)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

If anyone can help, it'd be greatly appreciated! Thanks,

Allan W MacLeod
  • 39
  • 1
  • 1
  • 3

1 Answers1

0

I'm guessing the -100 is because the exchange is closed. The error can be ignored, see https://stackoverflow.com/a/58684561/2855515

It seems like your code is working fine even if a little unorthodox.

brian
  • 10,619
  • 4
  • 21
  • 79
  • My lord! That's akin to not turning the computer on! Works perfectly, thanks Brian. Out of interest why do you say a "little unorthodox"? – Allan W MacLeod May 27 '20 at 10:54
  • sleep() is ok for testing code but I wouldn't use it. You should start the requests after getting a nextValidId callback so you know the connection is working. Then I would disconnect after getting an ask price or some timeout, not a sleep. I also wouldn't use 4002 as a client Id since you might get confused with ports but technically no problem. – brian May 27 '20 at 14:58