cmarios
cmarios

Reputation: 185

My python code for downloading historical data from IB API does not work

Here is my code - it returns no results (no errors, it just returns "done"):

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


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 historicalData(self, reqId, bar):
        print(reqId, bar.date, bar.high, bar.low, bar.volume)


def run_loop():
    app.run()


app = IBapi()
app.connect('127.0.0.1', 7497, 123)
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

contract = Contract()
contract.symbol = "VIX"
contract.secType = "FUT"
contract.exchange = "CFE"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "20240117"
contract.multiplier = "1000"
contract.includeExpired = True

app.reqHistoricalData(1, contract, "", "1 M", "30 mins", "bid", 0, 1, False, [])

app.disconnect()

print("done")

I remember in the recent past i run a very similar code and it was ok. Can someone please let me know what i am doing wrong?

Many thanks.

Upvotes: 0

Views: 197

Answers (2)

cmarios
cmarios

Reputation: 185

I found how to do it. I made two adjustments:

  1. After api_thread.start() i added some waiting time, ie:
api_thread.start()
time.sleep(2)
  1. Then i noticed that while my TWS app was running, it was minimized, and thus it was not giving any results. Once it is not minimized, the code give me the results i want.

Thanks for your help.

Upvotes: 0

user23193273
user23193273

Reputation:

Your code is not waiting for the historical data to be received before it disconnects.

This code will help you:

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

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.data_received = threading.Event()

    def historicalData(self, reqId, bar):
        print(reqId, bar.date, bar.high, bar.low, bar.volume)
        self.data_received.set()

app = IBapi()
app.connect('127.0.0.1', 7497, 123)

api_thread = threading.Thread(target=app.run, daemon=True)
api_thread.start()

contract = Contract()
contract.symbol = "VIX"
contract.secType = "FUT"
contract.exchange = "CFE"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "20240117"
contract.multiplier = "1000"
contract.includeExpired = True

app.reqHistoricalData(1, contract, "", "1 M", "30 mins", "bid", 0, 1, 
False, [])

app.data_received.wait()
app.disconnect()

print("done")

Upvotes: 0

Related Questions