Easiest way for a noob to automate entries in Interactive Brokers?

Discussion in 'Order Execution' started by SteveM, Jul 23, 2020.

  1. zenlot

    zenlot

    You could really do this with their Python native API, or even more easily with ib_insync [ https://github.com/erdewit/ib_insync ].

    As @d08 mentioned, historical data request can be send to get opening price as you don't need streaming for it, then calculate your entry based on that.

    It's really simple Python script if you want to just do it, without including anything else into logic. If you'll struggle writing it yourself, I'll see if I can put few lines over the weekend together and paste it here. Such basic automation should be open source anyways.
     
    #11     Jul 23, 2020
  2. zenlot

    zenlot

    @SteveM here's the code to start with. Steps to get going(example on MSFT):

    1. Enable API access in IB TWS
    2. Download and install Python 3 [if don't have already] and install ib_insync: python3 -m pip install ib_insync
    3. Save the following code to name.py or whatever name.
    4. Run the code: python3 name.py
    Code:
    import datetime, pytz
    from ib_insync import *
    
    
    ib = IB()
    ib.connect('127.0.0.1', 7497, clientId=1)
    
    
    contract = Stock('MSFT', 'SMART', 'USD')
    ib.qualifyContracts(contract)
    
    exchange_time = datetime.datetime.now(pytz.timezone('US/Eastern'))
    exchange_close = exchange_time.replace(hour=16, minute=00, second=00).strftime("%Y%m%d %H:%M:%S")
    
    bars = ib.reqHistoricalData(
      contract,
      endDateTime=exchange_close,
      durationStr='1 D',
      barSizeSetting='1 hour',
      whatToShow='TRADES',
      useRTH=True,
      formatDate=1)
    
    # Get bars
    df = util.df(bars)
    print(f"Today's bars:\n {df}")
    
    # Get open price
    open_price = float(df.iloc[[0], [1]].values[0])
    print(f"Today's open price: {open_price}")
    
    # Calculate entry price
    entry_price = f"{(open_price * 0.95):.2f}"
    print(f"Entry price: {entry_price}")
    
    # Create order
    order = LimitOrder('BUY', 200, entry_price)
    
    # Place order
    trade = ib.placeOrder(contract, order)
    
    # Wait and show log
    ib.sleep(2)
    print(trade.log)
    
    Notes: normally I would use IB native API, but to get you started ib_insync is more friendly than IB native one and could give you better understanding.

    Native API docs: https://interactivebrokers.github.io/tws-api/historical_bars.html#hd_request
    ib_insync docs: https://ib-insync.readthedocs.io/ap...toricaldata#ib_insync.ib.IB.reqHistoricalData

    Running this code will give you (based on UTC):
    Code:
    
    Today's bars:
      date  open  high  low  close  volume  average  barCount
    0 2020-07-24 14:30:00  200.42  200.76  197.65  198.09  38977  199.535  16538
    Today's open price: 200.42
    Entry price: 190.40
    [TradeLogEntry(time=datetime.datetime(2020, 7, 24, 13, 54, 20, 536054, tzinfo=datetime.timezone.utc), status='PendingSubmit', message=''), TradeLogEntry(time=datetime.datetime(2020, 7, 24, 13, 54, 20, 764145, tzinfo=datetime.timezone.utc), status='Submitted', message='')]
    
    In TWS orders you'll see: MSFT BUY LMT 190.40 0/200.

    You'll probably want to modify script to add more logic to it, errors catching, etc. Plus exit entry, depending on your requirements. And add logic to support input of stocks as a list, instead of hardcoding it, etc...

    PS: not selling anything. Purely for educational purposes.
     
    Last edited: Jul 24, 2020
    #12     Jul 24, 2020
    TooEffingOld and SteveM like this.
  3. SteveM

    SteveM

    Thank you so much for putting this together, Zenlot. I really do appreciate it.
     
    #13     Jul 24, 2020
    zenlot likes this.
  4. userque

    userque

    Easiest for non-programmer? Probably using Ninjatrader.
     
    #14     Jul 24, 2020
  5. Warren

    Warren

    Well, as for my own experience, I am done with Ninjatrader. I spent some time learning to code in C#, which is the language their platform use. Then, one day, I run into some error that no one can tell why. They have a support team on their forum, some of whom are professional programmers. But no body can solve the problem. I posted a thread here in ET. Then some guru told me that Ninja is a spaghetti code: as users demand more functionality, their codes grow day by day, and all stuffs are concealed in a dll file. After some time, de-bugging became an impossible task.

    Python, may require some serious investment of time. Perhaps, you need also be familiar with other packages such as pandas, backtrader, or backtesting.py, and IB api. But it worth the time. It will give great flexibility for what you want to do: research, like calculate some statistics of your stock; plotting; backtesting; and surely, fully automated trading.

    Like the guru once said: Learn some real coding, like python, that is what the professionals are doing !
     
    #15     Aug 14, 2022
  6. easymon1

    easymon1

    How much time do you plan to budget to get this off the ground?
    Will you be using any chart package after Ninja until you get your python flexibility project into the realm of 'now we're gettin somewhere'.
    Sounds like you know your way around C#, it will be interesting to learn how fast you get to somewhere. Break a Leg! Best part is "You wrote it, You Own It!" and you know it inside out upside down and backwards. Good on Ya!
    Do you plan to have any chart functionality down the road?
    What's this thing gonna look like and do? without showing your hole card of course...
     
    #16     Aug 14, 2022
  7. Warren

    Warren

    As for my own experience, 1 year for my spare time. Some basics about python, some time to familiar with packages like, numpy, pandas, bokeh(for plotting), backtesting packages like backtrader, backtesting.py...
     
    #17     Aug 16, 2022
    easymon1 likes this.
  8. easymon1

    easymon1

    Hopefully you can hook up with a likeminded gang and kick some bunn! Break a Leg!
     
    #18     Aug 16, 2022
  9. Bad_Badness

    Bad_Badness

    Basket Trader in TWS is what I used. Easy to manage when doing more than a couple instruments. Although not that automated, it does provide an easy way to submit all of them quickly and also a way to close them all out at once.
     
    #19     Aug 19, 2022
  10. writing bug free code is hard enough.

    you want some noob to write code that transacts with real money ?

    typical good advice thats often given here
     
    #20     Aug 22, 2022