如何将来自盈透证券原生 API 的消息返回保存为对象?

时间:2021-07-21 00:00:24

标签: python ib-api

我很难将来自 Interactive Brokers python api 的简单响应保存为稍后使用的对象。例如,如果我想打印当前时间,我会执行以下操作(摘自 Scarpino 的书《Algorithmic Trading with Interactive Brokers:

from datetime import datetime
from threading import Thread
import time

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.utils import iswrapper

class SimpleClient(EWrapper, EClient):
    ''' Serves as the client and the wrapper '''

    def __init__(self, addr, port, client_id):
        EClient. __init__(self, self)

        # Connect to TWS
        self.connect(addr, port, client_id)

        # Launch the client thread
        thread = Thread(target=self.run)
        thread.start()

    @iswrapper
    def currentTime(self, cur_time):
        t = datetime.fromtimestamp(cur_time)
        print('Current time: {}'.format(t))
        

    @iswrapper
    def error(self, req_id, code, msg):
        print('Error {}: {}'.format(code, msg))

def main():

    # Create the client and connect to TWS
    client = SimpleClient('127.0.0.1', 7497, 0)

    # Request the current time
    client.reqCurrentTime()

    # Sleep while the request is processed
    time.sleep(0.5)

    # Disconnect from TWS
    client.disconnect()

if __name__ == '__main__':
    main()

但是,如果我想将 return t 作为一个对象进行比较,作为在预定时间之前不发送订单的一种方式,这并不是那么简单。我试过了:

从日期时间导入日期时间 从线程导入线程 导入时间

从 ibapi.client 导入 EClient 从 ibapi.wrapper 导入 EWrapper 从 ibapi.utils 导入 iswrapper

class SimpleClient(EWrapper, EClient): ''' 作为客户端和包装器 '''

def __init__(self, addr, port, client_id):
    EClient. __init__(self, self)

    # Connect to TWS
    self.connect(addr, port, client_id)

    # Launch the client thread
    thread = Thread(target=self.run)
    thread.start()

@iswrapper
def currentTime(self, cur_time):
    t = datetime.fromtimestamp(cur_time)
    return t
    

@iswrapper
def error(self, req_id, code, msg):
    print('Error {}: {}'.format(code, msg))

定义 main():

# Create the client and connect to TWS
client = SimpleClient('127.0.0.1', 7497, 0)

# Request the current time
client.reqCurrentTime()

# Sleep while the request is processed
time.sleep(0.5)

# Disconnect from TWS
client.disconnect()

if name == 'ma​​in': main()

脚本运行但返回 None

同样,如果我想根据我的帐户价值确定订单大小,我必须返回帐户价值。

以下打印帐户值:

@iswrapper
def accountSummary(self, req_id, account, tag, value, currency):
    ''' Read information about the account '''
    print('Account {}: {} = {}'.format(account, tag, value))

但如果我只想交易价值的 5%,我需要将价值作为对象返回。我该怎么做?

0 个答案:

没有答案