INTERACTIVE BROKERS - PYTHON SOFTWARE FOR USING THEIR APIS
One of the most powerful trading platforms for stocks, options and
commodities is that of
Interactive Brokers. And for hard-core traders such as KukaXoco Finance,
we like to be able to integrate out signal generation systems with the
IB platform using their Application Programming Interface (API). This
allows us to focus all of our attention on execution, and using our software
for the nitty-gritty details of placing orders.
What follows is some of the Python software we have written, for your use
as well.
from decimal import Decimal from ibapi.client import * from ibapi.contract import Contract from ibapi.wrapper import * from ibapi.contract import * import IBparameters class TestApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def nextValidId(self, orderId: int): self.reqPositions() def position(self, account: str, contract: Contract, position: Decimal, avgCost: float): order_string = f"Positions. Account: {account}, Contract: {contract}, Position: {position}, Average Cost: {avgCost}"; # print(order_string); order_string = order_string + '\n'; orders_file.write(order_string); def positionEnd(self): self.cancelPositions() # print("End of positions") orders_file.write("End of positions\n") app.disconnect() orders_file.close() def error(self, reqId: TickerId, errorTime: int, errorCode: int, errorString: str, advancedOrderRejectJson=""): # print(f"Error., Time of Error: {errorTime}, Error Code: {errorCode}, Error Message: {errorString}") if advancedOrderRejectJson != "": print(f"AdvancedOrderRejectJson: {advancedOrderRejectJson}") i_host = '127.0.0.1' #paper_trade_port = 4002 #live_trade_port = 4001 i_port = 4002 client_ID_orderlist = 123 i_clientID = client_ID_orderlist req_ID = 1 # request ID orders_file = open("CurrentPositions.temp", "w") app = TestApp() app.connect(i_host, i_port, 0) app.run()