I have made numerous attempts to write IB API code which all are producing the -1 504 Not Connected error
. Even with code directly and exactly from the IBKR academy training videos (which i have pasted below). I have checked and rechecked over and over the Global Settings Enable ActiveX & Socket
is ticked, Socket Port # is 7497, Client ID's match btw API code & TWS, Allow Connections from localhost is selected, input '127.0.0.1'and localhost:5000 into trusted IP's
The Data Connections table in TWS shows API connections listening on 7497 Peer-to-Peer Port 127.0.0.1.60104 Client ID 1 as Accepted; which indicates the API is connected...however when I select Run nothing happens - I just get a print of the file link in the VS Code Python terminal, and when I execute Run Python Debugger - I receive the following:
PS C:\TWS API\source\pythonclient\ibapi> & 'c:\Users\JV\AppData\Local\Programs\Python\Python312\python.exe' 'c:\Users\JV\.vscode\extensions\ms-python.debugpy-2024.2.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '60548' '--' 'c:\TWS API\source\pythonclient\tests\TestApp.py'
ERROR -1 504 Not connected
PS C:\TWS API\source\pythonclient\ibapi>
I have searched and searched for answers on this and other forums. Can somebody please help this newbie who seems to be pinned down and struggling to get off the first base with IB API? Thank you.
from ibapi.client import *
from ibapi.wrapper import *
import time
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def contractDetails(self, reqId, contractDetails):
print(f"contract details: {contractDetails}")
def contractDetailsEnd(self, reqId):
print("End of contractDetails")
self.disconnect()
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 1)
mycontract = Contract()
mycontract.symbol = "AAPL"
mycontract.secType = "STK"
mycontract.exchange = "SMART"
mycontract.currency = "USD"
mycontract.primaryExchange = "ISLAND"
time.sleep(3)
app.reqContractDetails(1, mycontract)
app.run
if __name__ == "__main__":
main()
The simple answer is app.run
is a method call so needs to be app.run()
.
Your code has other common ib-api problems and you should search here by clicking my name then the relevant issue. Most examples are like yours and are incorrect.