从 IB 交易站导出所有未结订单记录到 csv 文件

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

我正在开发 Ibapi 的 python 程序,我可以自动下订单。 另外,我想通过程序导出交易员站当前的未结订单。

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

我正在使用此命令获取所有未结订单。它给出了终端中的所有记录,记录的类型是none类型。所以,我想知道如何将该记录导出到 csv 文件。

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()
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])