Customizing the sample Python IBAPI code provided in the testbed

Discussion in 'Automated Trading' started by Aron, Dec 21, 2020.

  1. Aron

    Aron

    Hi I am new to the IBAPI, creating this thread to customize understand the pre-built sample python code and use it for real world trading. The samples are well coded and efficient though cryptic. Need some help on understanding the function calls and libraries, that don't seem to have any documentation or help.
     
    C99 likes this.
  2. You might get better answers on Stack Overflow, since your question is more programming related than trading.
     
  3. Instead of dumping a large text file it would be better to specify which specific function calls you have questions about. And detail what those questions are.
     
    d08 likes this.
  4. Aron

    Aron

    Sorry for the lengthy dump, but it was important as the functions/classes are heavily nested, of course I will post specific questions with specific references. Thanks
     
  5. sef88

    sef88

    ib_isync package is multiple times easier to use.
     
    globalarbtrader likes this.
  6. Aron

    Aron

    Yes I have tried that multiple times and it is extremely easy, however there is a limitation on market depth data (operations) lines, we can choose only max 5 data lines i.e. level 1 (which means we never get to see the full order book), the other feature (that it is asynchronous) is not what I intend on using for my trading app.

    Having said that, my first task is to add Pandas data frames and convert all of this data into a dataframe and subsequently write it to Postgresql using Sql Alchemy, the latter is easy, real challenge is to get the data frames ready. I am posting the exact issue and function in the next response.
     
    sef88 likes this.
  7. sef88

    sef88

    I believe the official API is also asynchronous. And you have to comb through their official API pages to figure out all the overriding stuff. ib_insync - you can use it in a non asynchronous manner. For me, I'm not running tick by tick algos, so I'm using cron jobs to trigger the various scripts.

    May be more useful for you to post in the tws api forum: https://groups.io/g/twsapi

    Writing pandas data frames to Postgresql should be pretty trivial. Though I'm not a fan on Sql Alchemy; rather just write the SQL code directly.
     
  8. Aron

    Aron

    Okay I will have to check again on the async part, thanks for this group info, I will surely put a post there.

    The part I'm not sure is that where do we build the dataframe, inside the TestWrapper class where the callbacks happen (that is where we print the data to the console) or inside the app function. Where exactly are we operating on the data? Within the app function or the TestWrapper class that we defined?
     
  9. sef88

    sef88

    Was mucking around last time. Wonder if this helps. Under strategy class, define the method. Then below, add a prefix of req (check against official API page). I'm unfamiliar with order book depth stuff; you have to explore.

    # Import necessary libraries
    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract
    from threading import Timer
    import pandas as pd
    import time

    # Define strategy class - inherits from EClient and EWrapper
    class Strategy(EClient, EWrapper):

    # Initialize the class - and inherited classes
    def __init__(self):
    EClient.__init__(self, self)
    self.df = pd.DataFrame(columns=['Time', 'Open', 'Close'])

    # Receive historical bars from TWS
    def historicalData(self, reqId, bar):
    dictionary = {'Time':bar.date,'Open': bar.open, 'Close': bar.close}
    self.df = self.df.append(dictionary, ignore_index=True)
    print(f'Time: {bar.date}, Open: {bar.open}, Close: {bar.close}')

    # Display a message once historical data is retreived
    def historicalDataEnd(self, reqId, start, end):
    print('\nHistorical Data Retrieved\n')
    print(self.df.head())
    # elf.df.to_csv('Historical_data.csv')

    # -------------------------x-----------------------x---------------------------

    # Create object of the strategy class
    app = Strategy()

    # Connect strategy to IB TWS
    app.connect(host='127.0.0.1', port=7497, clientId=2)
    print('Is application connected to IB TWS:', app.isConnected())

    # Wait for sometime to connect to the server
    time.sleep(1)

    # Create object for contract
    eurusd_contract = Contract()
    eurusd_contract.symbol = 'EUR'
    eurusd_contract.currency = 'USD'
    eurusd_contract.secType = 'CASH'
    eurusd_contract.exchange = 'IDEALPRO'

    # Request for historical data
    app.reqHistoricalData(reqId=33,
    contract=eurusd_contract,
    endDateTime='',
    durationStr='300 S',
    barSizeSetting='1 secs',
    whatToShow='MIDPOINT',
    useRTH=0,
    formatDate=1,
    keepUpToDate=False,
    chartOptions=[])

    # Invoke another thread that will disconnect the strategy from TWS
    Timer(10, app.disconnect).start()

    # Run the strategy
    app.run()
     
  10. Aron

    Aron

    Thanks a million , this is extremely helpful, lemme try this out !!
     
    #10     Dec 22, 2020
    sef88 likes this.