[Python] ibapi (Python) - get data from the option Chain

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I am starting to work with Python & the IBKR API and have a problem with receiving data from the option chain:

    Within the option chain I am trying to find a strike based an a specific delta (or close to it). So, let's say I want to find the strike price where delta ~ 0.20. Additionally, I want to return the mid price of this strike (this is a future step, still struggling with the delta)

    This is how I tried it so far, however I do not receive data back (process finished with exit code 0).

    import threading
    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract
    import time


    class TestApp(EWrapper, EClient):
    def __init__(self):
    EClient.__init__(self, self)
    self.nextOrderId = 0
    self.permId2ord = {}
    self.strike = 160

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

    def nextValidId(self, orderId: int):
    self.req_data(orderId)

    def req_data(self, orderId):
    optcontract = Contract()
    optcontract.symbol = "AAPL"
    optcontract.secType = "OPT"
    optcontract.exchange = "SMART"
    optcontract.currency = "USD"
    optcontract.lastTradeDateOrContractMonth = "20240419"
    optcontract.strike = self.strike
    optcontract.right = "P"

    self.reqMarketDataType(4)
    self.reqMktData(orderId, optcontract, '106', False, False, [])

    def tickOptionComputation(self, reqId: int, tickType: int, impliedVol,
    delta, optPrice, pvDividend,
    gamma, vega, theta, undPrice):
    print(f"Delta: {delta} for option with reqId {reqId}")
    if delta > 0.22:
    self.strike -= 5
    self.req_data(reqId + 1)
    elif delta < 0.18:
    self.strike += 5
    self.req_data(reqId + 1)
    else:
    print(f"Found an option with Delta in the desired range. Strike: {self.strike} Delta: {delta}")
    self.cancelMktData(reqId)


    def main():
    app = TestApp()
    app.connect('127.0.0.1', 7497, 0)
    app.nextOrderId = 0
    # Call an initial request for OrderId increments
    app.reqIds(-1)
    # Initialize the run loop
    api_thread = threading.Thread(target=lambda: app.run(), daemon=True)
    api_thread.start()

    time.sleep(10)
    app.disconnect()


    if __name__ == "__main__":
    main()

    Continue reading...

Compartilhe esta Página