Python 盈透证券 ibapi

Python Interactive Brokers ibapi

我在使用修改后的 IB 示例代码为每个股票订单使用和递增 "orderId" 时遇到问题。我有一个在 class 中生成 nextValidId 并将其打印到标准输出的方法,但我不确定如何访问在我的 main() 程序中创建的定义的 属性 (self.nextValidOrderId) body。我能够实例化 EWrapper 和 EClient Class 并下订单(如果我手动输入 orderId)。在示例代码中,我将其硬编码为 126。我认为我可以在我的 main() 程序中使用以下代码 body。 "orderId = app.nextValidOrderId" 但它不起作用。

`__author__ = 'noone'

from Testbed.OrderSamples import OrderSamples
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *

class OrderApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self,self)

    def error(self,reqId:TickerId, errorCode:int, errorString:str):
        print("Error:",reqId," ", errorCode, " ", errorString)

    # This is the initial response after connection to TS from the API providing next available OrderID
    @iswrapper        
    def nextValidId(self, orderId: int):
    super().nextValidId(orderId)

    print("setting nextValidOrderId: %d", orderId)
    self.nextValidOrderId = orderId

    def contractDetails(self, reqId:int, contractDetails:ContractDetails):
        print("contractDetails: ", reqId, " ", contractDetails)

def main():
    app=OrderApp()
    app.connect("127.0.0.1",7497,0)

    ## Build the contract object to be passed to the order Method

    stock_contract = Contract()
    stock_contract.symbol = 'AAPL'
    stock_contract.secType = 'STK'
    stock_contract.exchange = 'SMART'
    stock_contract.currency = 'USD'
    stock_contract.primaryExchange = 'NASDAQ'

    # reqID must be provided to the Order. This method gets the reqID from IB DB's
    app.reqContractDetails(10, stock_contract)

    try:
        # Now place the order in Paper Money Account
        app.placeOrder(126, stock_contract, OrderSamples.LimitOrder("BUY", 50, 12))

    except:
        raise

    app.run()

if __name__ == "__main__":
    main()`

您的方法在语法上不正确。它应该有缩进如下

@iswrapper        
def nextValidId(self, orderId: int):
    super().nextValidId(orderId)

    print("setting nextValidOrderId: %d" % orderId)
    self.nextValidOrderId = orderId

此外,您没有导入函数装饰器 iswrapper

from ibapi.utils import iswrapper

希望对您有所帮助