【问题标题】:How to return positions from IBKR API (interactive brokers) consistently?如何始终如一地从 IBKR API(交互式经纪商)返回头寸?
【发布时间】:2023-01-05 16:27:34
【问题描述】:

到目前为止,IBKR 给我的结果非常不一致,我希望这只是因为我不明白某些事情。

这是我的代码,用于尝试获取我的帐户头寸,但它仅在我第一次运行时有效,并且不再有效。我发现我尝试在 IBKR 上做的一半事情都是这样的……有没有更简单的 API 不需要我实例化类来简单地获取我账户中的头寸列表?多谢你们。

def read_positions(): #读取所有账户头寸并返回 带有信息的DataFrame

from ibapi.client import EClient 
from ibapi.wrapper import EWrapper
from ibapi.common import TickerId
import pandas as pd

class ib_class(EWrapper, EClient): 
    def __init__(self): 
        EClient.__init__(self, self)
        self.all_positions = pd.DataFrame([], columns = ['Account','Symbol', 'Quantity', 'Average Cost'])

    def position(self, account, contract, pos, avgCost):
        index = str(account)+str(contract.symbol)
        self.all_positions.loc[index]=account,contract.symbol,pos,avgCost

    def error(self, reqId:TickerId, errorCode:int, errorString:str):
        if reqId > -1:
            print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

    def positionEnd(self):
        super().positionEnd()
        self.disconnect()

ib_api = ib_class() 
ib_api.connect("127.0.0.1", 7496, 0) 
ib_api.reqPositions()
current_positions = ib_api.all_positions
ib_api.run()

return(current_positions)

【问题讨论】:

  • 您可以分享 IBKR api 文档链接吗?
  • 您的代码按预期工作。如果它只工作一次,那么您要么没有正确断开连接,要么与网关的其他连接仍然连接。您收到的错误是什么? IB API 本身非常一致,这种问题并不常见。

标签: python algorithmic-trading interactive-brokers


【解决方案1】:

IB 不会立即回复reqPositions,因此您应该等待一两秒钟再访问结果。这对你有用吗?

import time
...

ib_api = ib_class() 
ib_api.connect("127.0.0.1", 7496, 0) 
ib_api.run()
ib_api.reqPositions()
time.sleep(2)
current_positions = ib_api.all_positions
return(current_positions)

我不在我的开发计算机旁,所以我无法验证它是否正常工作。

编辑:这是一个演示如何使用 reqPositions 的简短程序。我已经测试过它有效。

class ib_class(EWrapper, EClient):

    def __init__(self, addr, port, client_id):
        EClient. __init__(self, self)
        self.connect(addr, port, client_id)
        self.index = ''
        thread = Thread(target=self.run)
        thread.start()

    def position(self, account, contract, pos, avgCost):
        self.index = str(account) + str(contract.symbol)

ib_api = ib_class('127.0.0.1', 7497, 0)
ib_api.reqPositions()
time.sleep(0.5)
print('Index: ' + ib_api.index)
ib_api.disconnect()

【讨论】:

  • 好主意,但遗憾的是它并没有奏效
  • 我编辑了我的答案以包含一个简单的工作程序。
  • 为什么必须使用线程运行?看在上帝的份上,为什么我不能线性地运行它
  • 因为你不知道IB的数据什么时候到。您需要创建一个单独的线程来接收 IB 的数据。
【解决方案2】:

我有同样的问题,这似乎是由较新的 TWS 版本引起的。 TWS 1012 头寸在 100% 的时间内始终如一地返回,而 TWS 1019 在 50% 的时间内返回 0 个头寸。在这两种情况下我都等待 3 秒: ib_api.reqPositions() 时间.睡眠(3.0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多