0

我很难将来自 Interactive Brokers pythonapi 的简单响应保存为对象以供以后使用。例如,如果我想打印当前时间,我会执行以下操作(取自 Scarpino 的书,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()

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

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

从 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))

定义主():

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

如果名称== '主要': main()

脚本运行但返回None.

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

以下打印帐户值:

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

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

4

0 回答 0