pythonib-api

Export all open order record from IB trader station to csv file


I am working on the python program for Ibapi which I can automatedly place order. Moreover, I would like to export the current open orders from the trader station by the program.

self.reqAllOpenOrders() (Ref: https://interactivebrokers.github.io/tws-api/open_orders.html)

I am using this command to get all the open orders. It gives all the record in the terminal, and the type of the records are none type. So, I wonder how could I export that record to a csv file.

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import *

import threading
import time


class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def openOrder(self, orderId, contract, order, orderState):
        print('openOrder id:', orderId, contract.symbol, contract.secType, '@', contract.exchange,
              ':', order.action, order.orderType, order.totalQuantity, orderState.status)

        self.reqAllOpenOrders()

def run_loop():
    app.run()

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

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

time.sleep(3)
app.disconnect()

Solution

  • class IBapi(EWrapper, EClient):
        def __init__(self):
            EClient.__init__(self, self)
            self.file = open('file.csv', 'w')
    
        def openOrder(self, orderId, contract, order, orderState):
            mywriter = csv.writer(
                self.file, lineterminator='\n')
            mywriter.writerows([df])