简体   繁体   English

在盈透证券下多个订单

[英]Placing Multiple Orders in Interactive Brokers

This question is insipired by the following one:这个问题受到以下问题的启发:

Interactive Brokers Python API - Executing multiple trades Interactive Brokers Python API - 执行多笔交易

I am trying to place 3 orders but the code is only placing 3 orders for the stock CRM rather than placing 1 order for AAPL, 1 for AMD and one for CRM.我正在尝试下 3 个订单,但代码只为股票 CRM 下了 3 个订单,而不是为 AAPL 下了 1 个订单,为 AMD 下了 1 个订单,为 CRM 下了 1 个订单。 This is the code:这是代码:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import *
from threading import Timer

t = ['AAPL', 'AMD', 'CRM']

n = [10, 12, 10]

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

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

    def nextValidId(self, orderId ):
        self.nextOrderId = orderId
        self.start()

    def orderStatus(self, orderId , status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice):
        print("OrderStatus. Id: ", orderId, ", Status: ", status, ", Filled: ", filled, ", Remaining: ", remaining, ", LastFillPrice: ", lastFillPrice)

    def openOrder(self, orderId, contract, order, orderState):
        print("OpenOrder. ID:", orderId, contract.symbol, contract.secType, "@", contract.exchange, ":", order.action, order.orderType, order.totalQuantity, orderState.status)

    def execDetails(self, reqId, contract, execution):
        print("ExecDetails. ", reqId, contract.symbol, contract.secType, contract.currency, execution.execId,
              execution.orderId, execution.shares, execution.lastLiquidity)

    def start(self):
        for i in t: 
            contract = Contract()
            contract.symbol = i
            contract.secType = "STK"
            contract.exchange = "SMART"
            contract.currency = "USD"
            contract.primaryExchange = "NASDAQ"
        for j in n:
            order = Order()
            order.action = "BUY"
            order.totalQuantity = j
            order.orderType = "Market"
            self.placeOrder(self.nextOrderId, contract, order)
            self.nextOrderId = self.nextOrderId + 1
            
    


    def stop(self):
        self.done = True
        self.disconnect()

def main():
    app = TestApp()
    app.nextOrderId = 0
    
    app.connect("127.0.0.1", 7497, 9)

    Timer(3, app.stop).start()
    app.run()

if __name__ == "__main__":
    main()

I believe my error is in the incrementation.我相信我的错误在于增量。 I perhaps placed it at the wrong spot:我可能把它放在了错误的位置:

self.nextOrderId = self.nextOrderId + 1

I am not very good when it comes to using classes.在使用类方面,我不是很好。 Can someone help me correct my error?有人可以帮我纠正我的错误吗?

Here is a working example looping through your arrays and sending orders.这是一个循环通过您的 arrays 并发送订单的工作示例。

Setup the details of a contract inside a function which takes arguments, Stock(symbol, sec_type="STK", currency="USD", exchange="ISLAND") therefore can loop through the stock list t and input the ticker symbol into that function - contract object is in input in app.placeOrder() .在需要 arguments 的 function 中设置合约的详细信息, Stock(symbol, sec_type="STK", currency="USD", exchange="ISLAND")因此可以遍历股票列表t并将股票代码输入其中function - 合同 object 在app.placeOrder()中输入。

Setup a function to buy each stock BuyStocks(app) .设置一个 function 来购买每只股票BuyStocks(app) A for loop going through each ticker and each quantity.遍历每个代码和每个数量的 for 循环。 Key thing and per the IB docs is to make sure incrementing the next valid order id.根据 IB 文档,关键是确保递增下一个有效订单 ID。

Placed the trading app in its own thread as well as the main function. You could just build a full application inside main() with all logic checks for a strategy, pnl, order management, positions, executions etc..将交易应用程序放在它自己的线程以及主线程 function 中。您可以在 main() 中构建一个完整的应用程序,对策略、盈亏、订单管理、头寸、执行等进行所有逻辑检查。

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
from ibapi.execution import *
import time
import threading

t = ['AAPL', 'AMD', 'CRM']

n = [10, 12, 10]


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

        # define variables
        self.done = False

    # note all these functions below handle the incoming server requests.
    def error(self, reqId, errorCode, errorString, advancedOrderRejectJson):
        super().error(reqId, errorCode, errorString, advancedOrderRejectJson)

    def nextValidId(self, orderId):
        super().nextValidId(orderId)
        self.nextValidOrderId = orderId
        print("NextValidId:", orderId)

    def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId,
                    whyHeld, mktCapPrice):
        print("OrderStatus. Id: ", orderId, ", Status: ", status, ", Filled: ", filled, ", Remaining: ", remaining,
              ", LastFillPrice: ", lastFillPrice)

    def openOrder(self, orderId, contract, order, orderState):
        super().openOrder(orderId, contract, order, orderState)

    def openOrderEnd(self):
        super().openOrderEnd()
        print("OpenOrderEnd")
        #logging.debug("Received %d openOrders", len(self.permId2ord))

    def execDetails(self, reqId, contract, execution):
        super().execDetails(reqId, contract, execution)
        print("ExecDetails. ReqId:", reqId, "Symbol:", contract.symbol, "SecType:", contract.secType, "Currency:",
              contract.currency, execution)

    def execDetailsEnd(self, reqId):
        super().execDetailsEnd(reqId)
        print("ExecDetailsEnd. ReqId:", reqId)


# define some functions to help make requests to IB servers (outgoing)
## define the contract, in this case US stock
def Stock(symbol, sec_type="STK", currency="USD", exchange="ISLAND"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.currency = currency
    contract.exchange = exchange
    return contract

## market order
def marketOrder(action, quantity):
    order = Order()
    order.action = action # buy or sell
    order.orderType = "MKT"
    order.totalQuantity = quantity
    order.tif = "DAY" # time in force day - cancel order if not filled - will cancel at the close
    #order.orderRef = order_ref
    order.optOutSmartRouting = False
    return order


## function to buy stocks
def BuyStocks(app):
    for i in range(0,len(t),1):
        print("This is i",i)
        print("stock is, ", t[i])
        print("qty is, ", n[i])
        app.reqIds(-1)
        time.sleep(.2)
        order_id = app.nextValidOrderId
        app.placeOrder(order_id, Stock(t[i]), marketOrder("BUY", n[i]))
        time.sleep(1)

    # disconnect when operation completed
    if i == len(t)-1:
        app.done = True
        print("Orders have been placed disconnect")
        app.disconnect()


def main(app):
    # buy function
    BuyStocks(app)


def websocket_con():
    app.run()

# setup the threads
app = TestApp()
app.connect(host='127.0.0.1', port=7497, clientId=9)  # port 4002 for ib gateway paper trading/7497 for TWS paper trading
con_thread = threading.Thread(target=websocket_con, args=())  # , daemon=True
con_thread.start()
time.sleep(5) # some lag added to ensure that streaming has started

# thread for main()
MainThread = threading.Thread(target = main, args =(app,))
MainThread.start()


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM