在InteractiveBroker的TWSAPI上下另一个订单之前,如何检查是否有未结订单?

d6kp6zgx  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(170)

我想测试一个algo机器人。我有它,它将读取数据和下订单,但我有麻烦,试图让它检查,看看是否有一个未结订单的第一,然后再下订单。目前,它只是堆积订单,直到我取消算法。
这是我试过的。


# Imports

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

# import ta

import numpy as np
import pandas as pd
import pytz
import math
from datetime import datetime, timedelta
import threading
import time
import collections
from calcs_helper import calculate_ema, atr_num,  rsi
from scipy.stats import norm

# Vars

orderId = 1
SLOW_PERIOD = 30
FAST_PERIOD = 6

# Class for Interactive Brokers Connection

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

    # Historical Backtest Data
    def historicalData(self, reqId, bar):
        try:
            bot.on_bar_update(reqId,bar,False)
        except Exception as e:
            print(e)
    # On Realtime Bar after historical data finishes
    def historicalDataUpdate(self, reqId, bar):
        try:
            bot.on_bar_update(reqId,bar,True)
        except Exception as e:
            print(e)
    # On Historical Data End
    def historicalDataEnd(self, reqId, start, end):
        print(reqId)
    # Get next order id we can use
    def nextValidId(self, nextorderId):
        global orderId
        orderId = nextorderId
    # # Listen for realtime bars
    # def realtimeBar(self, reqId, time, open_, high, low, close,volume, wap, count):
    #     super().realtimeBar(reqId, time, open_, high, low, close, volume, wap, count)
    #     try:
    #         bot.on_bar_update(reqId, time, open_, high, low, close, volume, wap, count)
        # except Exception as e:
        #     print(e)
    def error(self, id, errorCode, errorMsg):
        print(errorCode)
        print(errorMsg)

# Bot Logic

class Bot:
    ib = None
    reqId = 1
    SLOW_PERIOD = 30
    FAST_PERIOD = 6
    global orderId
    initialbartime = datetime.now().astimezone(pytz.timezone("America/New_York"))
    def __init__(self):
        #Connect to IB on init
        self.ib = IBApi()
        self.ib.connect("127.0.0.1", 7497,1)
        ib_thread = threading.Thread(target=self.run_loop, daemon=True)
        ib_thread.start()
        time.sleep(1)

        self.long_ema = collections.deque(maxlen=SLOW_PERIOD)
        self.short_ema = collections.deque(maxlen=FAST_PERIOD)
        self.nmc = 0
        self.account_value = 0

        #Create our IB Contract Object
        contract = Contract()
        contract.symbol = "ES"
        contract.secType = "FUT"
        contract.exchange = "GLOBEX"
        contract.currency = "USD"
        contract.lastTradeDateOrContractMonth = "202109"
        self.ib.reqIds(-1)

        self.ib.reqHistoricalData(self.reqId,contract,"","2 D","5 mins","TRADES",1,1,True,[])
        self.ib.reqPositions(self)
    #Listen to socket in seperate thread
    def run_loop(self):
        self.ib.run()
    #Bracet Order Setup
    def bracketOrder(self, parentOrderId, action, quantity, profitTarget, stopLoss):
        #Initial Entry
        #Create our IB Contract Object
        contract = Contract()
        contract.symbol = "ES"
        contract.secType = "FUT"
        contract.exchange = "GLOBEX"
        contract.currency = "USD"
        contract.lastTradeDateOrContractMonth = "202109"
        # Create Parent Order / Initial Entry
        parent = Order()
        parent.orderId = parentOrderId
        parent.orderType = "MKT"
        parent.action = action
        parent.totalQuantity = quantity
        parent.transmit = False
        # Profit Target
        profitTargetOrder = Order()
        profitTargetOrder.orderId = parent.orderId+1
        profitTargetOrder.orderType = "MKT"
        profitTargetOrder.action = "SELL"
        profitTargetOrder.totalQuantity = quantity
        profitTargetOrder.lmtPrice = round(profitTarget,2)
        profitTargetOrder.parentId = parentOrderId
        profitTargetOrder.transmit = False
        # Stop Loss
        stopLossOrder = Order()
        stopLossOrder.orderId = parent.orderId+2
        stopLossOrder.orderType = "STP"
        stopLossOrder.action = "SELL"
        stopLossOrder.totalQuantity = quantity
        stopLossOrder.parentId = parentOrderId
        stopLossOrder.auxPrice = round(stopLoss,2)
        stopLossOrder.transmit = True

        bracketOrders = [parent, profitTargetOrder, stopLossOrder]

        return bracketOrders
    #Pass realtime bar data back to our bot object
    def on_bar_update(self, reqId, bar,realtime):
        global orderId
        if self.ib.reqPositions() > 0:
             print("{} Position/s on in {}.".format(pos, contract.symbol))
        else:
            self.long_ema.append(bar.close)
            self.short_ema.append(bar.close)
            if len(self.long_ema) == SLOW_PERIOD:
                ema_15 = np.array(self.long_ema)
                ema_6 = np.array(self.short_ema)
                fast_avg =  calculate_ema(ema_6,SLOW_PERIOD)[-1]
                slow_avg = calculate_ema(ema_15[-SLOW_PERIOD:], 15)[-1]
                num = fast_avg-slow_avg
                If num > 1 and pos == 0:
                    #Bracket Order 2% Profit Target 1% Stop Loss
                    profitTarget = bar.close*1.02
                    stopLoss = bar.close*0.99
                    quantity = 1
                    bracket = self.bracketOrder(orderId,"BUY",quantity, profitTarget, stopLoss)
                    contract = Contract()
                    contract.symbol = "ES"
                    contract.secType = "FUT"
                    contract.exchange = "GLOBEX"
                    contract.currency = "USD"
                    contract.lastTradeDateOrContractMonth = "202109"
                    #Place Bracket Order
                    for o in bracket:
                        o.ocaGroup = "OCA_"+str(orderId)
                        self.ib.placeOrder(o.orderId,contract,o)
                        orderId += 3

# Start Bot

bot = Bot()

这并没有把位置还给我。我不知道如何把它们作为一个数字拉进来,在上面运行条件语句。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题