【问题标题】:How to use class method parameter (?) as input in code (IBKR / IB API / IB TWS) - Python如何在代码中使用类方法参数(?)作为输入(IBKR / IB API / IB TWS) - Python
【发布时间】:2022-01-10 22:13:15
【问题描述】:

(如果术语/解释不正确,请见谅) 我想打印“我的美元账户余额为:xxx”。目的是了解如何使用类方法参数(不确定这是否是正确的术语)作为代码输入 但是,结果是:“我的美元账户余额为:无”。帐户余额打印在单独的行上。

from ibapi.wrapper import EWrapper  # handles incoming messages
from ibapi.contract import Contract
from ibapi.order import *

import threading
import time


class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.contract_details = {}
        self.bardata = {}  # initialise directory to store bar data
        self.USD_cash_balance = 0

    def nextValidId(self, orderId: int):
        super().nextValidId(orderId)
        self.nextorderId = orderId
        print('The next valid order id is: ', self.nextorderId)

    def accountSummary(self, reqId: int, account: str, tag: str, value: str,
                       currency: str):
        if tag == "CashBalance":
            print(value)
        IBapi.USD_cash_balance = value
        if reqId == 131:
            return value

def run_loop():
    app.run()  # starts communication with TWS


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

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)  # Algo doesn't have "daemon=True"
api_thread.start()

# Check if the API is connected via orderid
while True:
    if isinstance(app.nextorderId,
                  int):  # the IB API sends out the next available order ID as soon as connection is made
        # The isinstance() function returns True if the specified object is of the specified type, otherwise False.
        print('connected')
        break
    else:
        print('waiting for connection')
        time.sleep(2)

print("My account balance in USD is: " + str(app.reqAccountSummary(131, "All", "$LEDGER:USD")))

【问题讨论】:

  • reqAccountSummary 接受 5 个参数,但您只传入 3 个。参数 4 是 value,这是返回的内容,但由于您什么都不传入,因此返回的是 None
  • @match IB API 回复由包装器决定,而不是请求,参数计数不必匹配。
  • 感谢您的解释。我知道@match 指出的不太正确,但不知道用什么术语来解释它

标签: python tws ib-api


【解决方案1】:

首先,您没有将 USD_cash_balance 分配给类,而是分配给类实例(使用 self 而不是类名)。 其次,你必须等待回复,有很多方法可以做到这一点。一种是等待该值并在其上休眠,如有必要,您可以通过实施超时/重试来扩展它。您也可以使用队列。 另外,完成后不要忘记断开会话。

from ibapi.client import EClient
from ibapi.wrapper import EWrapper  # handles incoming messages
from ibapi.contract import Contract
from ibapi.order import *

import threading
import time


class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.contract_details = {}
        self.bardata = {}  # initialise directory to store bar data
        self.USD_cash_balance = 0

    def nextValidId(self, orderId: int):
        super().nextValidId(orderId)
        self.nextorderId = orderId
        print('The next valid order id is: ', self.nextorderId)

    def accountSummary(self, reqId: int, account: str, tag: str, value: str,
                       currency: str):
        if tag == "CashBalance" and reqId == 131:
            self.USD_cash_balance = value

def run_loop():
    app.run()  # starts communication with TWS


app = IBapi()
app.nextorderId = None
app.connect('127.0.0.1', 7600, 123)

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)  # Algo doesn't have "daemon=True"
api_thread.start()

# Check if the API is connected via orderid
while True:
    if isinstance(app.nextorderId,
                  int):  # the IB API sends out the next available order ID as soon as connection is made
        # The isinstance() function returns True if the specified object is of the specified type, otherwise False.
        print('connected')
        break
    else:
        print('waiting for connection')
        time.sleep(2)

while not getattr(app, 'USD_cash_balance', None):
    app.reqAccountSummary(131, "All", "$LEDGER:USD")
    time.sleep(0.5)

print("My account balance in USD is: " + app.USD_cash_balance)

app.disconnect()

【讨论】:

  • 非常感谢!这很完美!花了几个小时搜索,没有你的帮助我完全被困住了。
  • 如果您对解决方案感到满意,请将其标记为已接受的答案。
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
相关资源
最近更新 更多