gofinance / ib

Pure Go interface to Interactive Brokers IB API
391 stars 121 forks source link

RequestRealTimeBars Example #23

Open ghost opened 7 years ago

ghost commented 7 years ago

I have created a "Contract" and a "RequestRealTimeBars" struct, and also an active "Engine" connected to IB gateway on my machine, but I am not getting how to receive a reply into "RealTimeBars" struct. Any example will be much appreciated.

dsouzae commented 7 years ago

Can you post what you have implement? Make sure you subscribe to get a response for request ID or all responses.

I have example code available here for other types of requests: https://github.com/dsouzae/ibstockcli

I do not have an example for RequestRealtimeBars, but I will see if I can get a working example ready for tomorrow.

ghost commented 7 years ago

Thank you @dsouzae, your repo really helped me out. I would suggest anyone looking for examples to check out the code for the same.

dsouzae commented 7 years ago

I have pushed some changes in the ibstockcli. Here are some details.

Make sure you either call SubscribeAll(...) or Subscribe(...,id) with the request id to get the responses on your reply change.

Make the request:

func doRequestRealTimeBars(mgr *IBManager, symbol string) {
       request := ib.RequestRealTimeBars{
               Contract:   NewContract(symbol),
               BarSize:    5,
               WhatToShow: ib.RealTimeTrades,
               UseRTH:     true,
       }

       id := mgr.NextOrderID()
       request.SetID(id)
       mgr.realtimeMap[id] = symbol

       mgr.engine.Send(&request)

       log.Printf("%s: Sending RealTime Bars For %s", mgr.label, symbol)
}

I added a map to save the request id to get the symbol string.

In your engineLoop add support to output realtime bars. Also using the map to get the symbol name:

case (*ib.RealtimeBars):
        r := r.(*ib.RealtimeBars)

        symbol, ok := ibmanager.realtimeMap[r.ID()]
        if !ok {
                symbol = "???"
        }

        log.Printf("%10s: %v - Open: %10.2f Close: %10.2f Low %10.2f High %10.2f Volume %10.2f Count %10v WAP %10.2f\n",
                symbol,
                time.Unix(r.Time, 0).Format("15:04:05"),
                r.Open,
                r.Close,
                r.Low,
                r.High,
                r.Volume,
                r.Count,
                r.WAP)