Вызов функции внутри функции с использованием IB API Python

#python #algorithm #future #trading #interactive-brokers

Вопрос:

Я получаю цены bid/ask от Интерактивных брокеров, а затем вызываю функцию, чтобы указать цену предложения на основе цены предложения, и функцию, чтобы указать цену предложения на основе цены предложения. Прямо сейчас я могу получить текущую ставку/запрос, но не могу понять, как вызвать функции bid и ask, которые будут указывать пару заказов с каждой стороны, начиная с текущей лучшей цены. Я могу запустить его, поместив логику функций bid и ask непосредственно в метод tickPrice, но я хочу, чтобы они были разделены. Кто-нибудь может помочь?

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

i = 0
lotSize = 1

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.last = 0
        
    def nextValidId(self, orderId:int):    
        self.reqMarketDataType(MarketDataTypeEnum.REALTIME)
        global contract
        contract = Contract()
        contract.symbol = "ES"
        contract.lastTradeDateOrContractMonth = "202109"
        contract.secType = "FUT"
        contract.exchange = "GLOBEX"
        contract.currency = "USD"
        self.reqMktData(1, contract, "", False, False, None)

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

    def tickPrice(self, reqId, tickType, price, attrib):
        if tickType == 1:
            print("Bid: ", price)
            return price

        if tickType == 2:
            print("Ask: ", price)
            return price

    def bids(self, price):
        increment = 0
        i = 0
        global id
        id = 340
        while i < 3:
            order = Order()
            order.action = "BUY"
            order.orderType = "LMT"
            order.totalQuantity = lotSize
            order.lmtPrice = price - increment
            self.placeOrder(id, contract, order)
            increment  = 0.25
            id  = 1
            i  = 1

    def asks():
        increment = 0
        i = 0
        while i < 3:
            order = Order()
            order.action = "SELL"
            order.orderType = "LMT"
            order.totalQuantity = lotSize
            order.lmtPrice = price   increment
            self.placeOrder(id, contract, order)
            increment  = 0.25
            id  = 1
            i  = 1

    # if tickType == TickTypeEnum.LAST or tickType == TickTypeEnum.DELAYED_LAST :
    #     self.last = price
    #     print("disconnecting")
    #     self.disconnect() # just for testing, normally the program would do something

def main():
    app = TestApp()
    app.connect('127.0.0.1', 7498, 123)
    app.run() # this blocks the program until disconnect()
    print("app.last:", app.last) # now you refer to the variable by class.var

if __name__ == '__main__':
    main()
 

Комментарии:

1. Я не понимаю, что ты пытаешься сделать. Почему бы вам не позвонить bids , если tickType это 1, и не позвонить asks , если tickType это 2?