### Install IBAPI Go Library Source: https://context7.com/scmhub/ibapi/llms.txt Use 'go get' to install the IBAPI library. This command fetches and installs the specified package and its dependencies. ```go go get github.com/scmhub/ibapi ``` -------------------------------- ### Install ibapi Package Source: https://github.com/scmhub/ibapi/blob/main/README.md Install the ibapi package using go get. Ensure you have Go version 1.26 or later. ```bash go get -u github.com/scmhub/ibapi ``` -------------------------------- ### Basic IBAPI Connection Example Source: https://context7.com/scmhub/ibapi/llms.txt Connect to TWS or IB Gateway and request the server time. Ensure the logger is initialized and console output is set. ```go package main import ( "time" "github.com/scmhub/ibapi" ) func main() { // Initialize logger with console output log := ibapi.Logger() ibapi.SetConsoleWriter() // Create new IB client with default wrapper ib := ibapi.NewEClient(nil) // Connect to TWS (port 7497) or Gateway (port 4001) if err := ib.Connect("localhost", 7497, 1); err != nil { log.Error().Err(err).Msg("Connection failed") return } defer ib.Disconnect() // Wait for connection to stabilize time.Sleep(100 * time.Millisecond) // Request current server time ib.ReqCurrentTime() // Connection info log.Info(). Bool("connected", ib.IsConnected()). Int("serverVersion", ib.ServerVersion()). Str("connectionTime", ib.TWSConnectionTime()). Msg("Connection established") time.Sleep(2 * time.Second) } ``` -------------------------------- ### Connect and Place Order with ibapi Source: https://github.com/scmhub/ibapi/blob/main/README.md Basic example demonstrating how to connect to Interactive Brokers, set up logging, and place a limit order. Requires TWS or IB Gateway running. ```go package main import ( "math/rand" "time" "github.com/scmhub/ibapi" ) const ( IB_HOST = "127.0.0.1" IB_PORT = 7497 ) func main() { // We set logger for pretty logs to console log := ibapi.Logger() ibapi.SetConsoleWriter() // New IB CLient ib := ibapi.NewEClient(nil) // Connect client if err := ib.Connect(IB_HOST, IB_PORT, rand.Int63n(999999)); err != nil { log.Error().Err(err) return } // Create and place order id := 1 eurusd := &ibapi.Contract{Symbol: "EUR", SecType: "CASH", Currency: "USD", Exchange: "IDEALPRO"} limitOrder := ibapi.LimitOrder("BUY", ibapi.StringToDecimal("20000"), 1.08) ib.PlaceOrder(id, eurusd, limitOrder) time.Sleep(1 * time.Second) err := ib.Disconnect() if err != nil { log.Error().Err(err).Msg("Disconnect") } } ``` -------------------------------- ### Configure Logging with SetLogLevel and SetConsoleWriter Source: https://context7.com/scmhub/ibapi/llms.txt Configure the built-in zerolog-based logger for pretty console output and set the desired log level. Use the Logger() function to get an instance for custom logging. ```go package main import ( "github.com/rs/zerolog" "github.com/scmhub/ibapi" ) func main() { // Enable pretty console output ibapi.SetConsoleWriter() // Set log level // Levels: TraceLevel, DebugLevel, InfoLevel, WarnLevel, ErrorLevel ibapi.SetLogLevel(int(zerolog.DebugLevel)) // Get logger instance for custom logging log := ibapi.Logger() log.Info().Str("component", "myapp").Msg("Application started") log.Debug().Int("value", 42).Msg("Debug message") log.Warn().Err(nil).Msg("Warning message") } ``` -------------------------------- ### Create and Place Limit Order Source: https://context7.com/scmhub/ibapi/llms.txt Use LimitOrder to specify a price for execution. Ensure NextValidID is received before placing orders. The example demonstrates placing and then cancelling a limit order. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type OrderWrapper struct { ibapi.Wrapper nextOrderID int64 } func (w *OrderWrapper) NextValidID(reqID int64) { w.nextOrderID = reqID ibapi.Logger().Info().Int64("nextOrderID", reqID).Msg("NextValidID") } func (w *OrderWrapper) OrderStatus(orderID int64, status string, filled, remaining ibapi.Decimal, avgFillPrice float64, permID, parentID int64, lastFillPrice float64, clientID int64, whyHeld string, mktCapPrice float64) { ibapi.Logger().Info(). Int64("orderID", orderID). Str("status", status). Stringer("filled", filled). Stringer("remaining", remaining). Float64("avgFillPrice", avgFillPrice). Msg("OrderStatus") } func (w *OrderWrapper) OpenOrder(orderID int64, contract *ibapi.Contract, order *ibapi.Order, orderState *ibapi.OrderState) { ibapi.Logger().Info(). Int64("orderID", orderID). Str("symbol", contract.Symbol). Str("action", order.Action). Str("orderType", order.OrderType). Str("status", orderState.Status). Msg("OpenOrder") } func main() { ibapi.SetConsoleWriter() wrapper := &OrderWrapper{} ib := ibapi.NewEClient(wrapper) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(1 * time.Second) // Wait for NextValidID contract := &ibapi.Contract{ Symbol: "EUR", SecType: "CASH", Exchange: "IDEALPRO", Currency: "USD", } // Create limit order using helper function quantity := ibapi.StringToDecimal("20000") limitPrice := 1.08 order := ibapi.LimitOrder("BUY", quantity, limitPrice) // Place order ib.PlaceOrder(wrapper.nextOrderID, contract, order) time.Sleep(5 * time.Second) // Cancel order ib.CancelOrder(wrapper.nextOrderID, ibapi.NewOrderCancel()) } ``` -------------------------------- ### Custom IBAPI Wrapper Implementation Source: https://context7.com/scmhub/ibapi/llms.txt Implement the EWrapper interface to handle asynchronous callbacks from TWS. This example overrides CurrentTime, TickPrice, and Error methods. ```go package main import ( "time" "github.com/scmhub/ibapi" ) var log = ibapi.Logger() var timeChan = make(chan int64) // Custom wrapper embeds default wrapper and overrides specific methods type MyWrapper struct { ibapi.Wrapper } // Override CurrentTime to receive server time responses func (w MyWrapper) CurrentTime(t int64) { log.Info().Time("serverTime", time.Unix(t, 0)).Msg("CurrentTime received") timeChan <- t } // Override TickPrice to receive real-time price updates func (w MyWrapper) TickPrice(reqID int64, tickType ibapi.TickType, price float64, attrib ibapi.TickAttrib) { log.Info(). Int64("reqID", reqID). Int64("tickType", tickType). Float64("price", price). Msg("Price tick received") } // Override Error to handle error messages func (w MyWrapper) Error(reqID int64, errTime int64, errCode int64, errString string, advancedOrderRejectJson string) { log.Error(). Int64("reqID", reqID). Int64("errCode", errCode). Str("errString", errString). Msg("Error received") } func main() { ibapi.SetConsoleWriter() // Create client with custom wrapper wrapper := &MyWrapper{} ib := ibapi.NewEClient(wrapper) if err := ib.Connect("localhost", 7497, 1); err != nil { log.Fatal().Err(err).Msg("Connect failed") } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) // Request time and wait for response via channel ib.ReqCurrentTime() serverTime := <-timeChan log.Info().Int64("unixTime", serverTime).Msg("Server time received") } ``` -------------------------------- ### Create Price-Based Order Conditions in Go Source: https://context7.com/scmhub/ibapi/llms.txt Use NewPriceCondition to create order conditions that trigger based on price movements. This example adds a condition to buy if AAPL price goes above $155 and another to execute only after a specific time. ```go package main import "github.com/scmhub/ibapi" func main() { quantity := ibapi.StringToDecimal("100") // Create a limit order with price condition order := ibapi.LimitOrder("BUY", quantity, 150.0) // Add condition: Trigger when AAPL price > $155 priceCondition := ibapi.NewPriceCondition( 265598, // AAPL conID "SMART", // Exchange 155.0, // Trigger price ibapi.TriggerMethodDefault, // Trigger method true, // isMore (price > trigger) true, // isConjunction (AND with next condition) ) order.Conditions = append(order.Conditions, priceCondition) // Add time condition: Only execute after specific time timeCondition := ibapi.NewTimeCondition( "20240101 09:30:00 US/Eastern", true, // isMore (after this time) false, // isConjunction ) order.Conditions = append(order.Conditions, timeCondition) // Settings for conditions order.ConditionsCancelOrder = false // Don't cancel if conditions not met order.ConditionsIgnoreRth = false // Respect regular trading hours } ``` -------------------------------- ### ReqSecDefOptParams - Get Option Chain Parameters Source: https://context7.com/scmhub/ibapi/llms.txt Requests option chain parameters, including expiration dates and strike prices for a given underlying asset. ```APIDOC ## ReqSecDefOptParams - Get Option Chain Parameters ### Description Request option chain parameters including expirations and strikes. ### Method Not specified (function call in Go) ### Endpoint Not applicable (local function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage within the Go program reqID := int64(1) underlyingSymbol := "AAPL" futFopExchange := "" underlyingSecType := "STK" underlyingConID := int64(265598) ib.ReqSecDefOptParams(reqID, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConID) ``` ### Response #### Success Response (200) Option chain parameters are logged. #### Response Example ``` INFO[0000] SecurityDefinitionOptionParameter reqID=1 exchange=SMART underlyingConID=265598 tradingClass= options expirations=[20240119,20240126,20240202,20240209,20240216] strikes=[150,151,152,153,154,155,156,157,158,159] ``` ``` -------------------------------- ### ReqContractDetails - Get Contract Specifications Source: https://context7.com/scmhub/ibapi/llms.txt Requests detailed information about a specific financial contract. ```APIDOC ## ReqContractDetails - Get Contract Specifications ### Description Request detailed information about a contract. ### Method Not specified (function call in Go) ### Endpoint Not applicable (local function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage within the Go program contract := &ibapi.Contract{ Symbol: "AAPL", SecType: "STK", Exchange: "SMART", Currency: "USD", } ib.ReqContractDetails(1, contract) ``` ### Response #### Success Response (200) Information about the contract details is logged. #### Response Example ``` INFO[0000] ContractDetails reqID=1 symbol=AAPL longName=Apple Inc. minTick=0.01 validExchanges=SMART,NYSE,NASDAQ tradingHours=09:30-16:00 ``` ``` -------------------------------- ### Request Option Chain Parameters in Go Source: https://context7.com/scmhub/ibapi/llms.txt Use ReqSecDefOptParams to get option chain parameters like expirations and strikes for a given underlying symbol. Requires the underlying symbol, security type, and optionally its conID. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type OptionWrapper struct { ibapi.Wrapper } func (w OptionWrapper) SecurityDefinitionOptionParameter(reqID int64, exchange string, underlyingConID int64, tradingClass, multiplier string, expirations []string, strikes []float64) { ibapi.Logger().Info(). Int64("reqID", reqID). Str("exchange", exchange). Int64("underlyingConID", underlyingConID). Str("tradingClass", tradingClass). Strs("expirations", expirations[:min(5, len(expirations))]). Floats64("strikes", strikes[:min(10, len(strikes))]). Msg("SecurityDefinitionOptionParameter") } func (w OptionWrapper) SecurityDefinitionOptionParameterEnd(reqID int64) { ibapi.Logger().Info().Int64("reqID", reqID).Msg("SecurityDefinitionOptionParameterEnd") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&OptionWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) reqID := int64(1) underlyingSymbol := "AAPL" futFopExchange := "" // Leave empty for options underlyingSecType := "STK" underlyingConID := int64(265598) // AAPL conID // Request option chain parameters ib.ReqSecDefOptParams(reqID, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConID) time.Sleep(5 * time.Second) } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Create Volume-Based Order Conditions in Go Source: https://context7.com/scmhub/ibapi/llms.txt Use NewVolumeCondition to create order conditions based on trading volume. This example sets a condition to trigger a buy order when AAPL's volume exceeds 1 million shares. ```go package main import "github.com/scmhub/ibapi" func main() { quantity := ibapi.StringToDecimal("100") order := ibapi.LimitOrder("BUY", quantity, 150.0) // Trigger when volume exceeds 1 million shares volumeCondition := ibapi.NewVolumeCondition( 265598, // AAPL conID "SMART", // Exchange true, // isMore (volume > threshold) 1000000, // Volume threshold false, // isConjunction ) order.Conditions = append(order.Conditions, volumeCondition) } ``` -------------------------------- ### Generate Protobuf Files with protoc Source: https://github.com/scmhub/ibapi/blob/main/proto/proto.md Run this command from the 'ibapi' directory to generate Go protobuf files. Ensure the proto definitions are in the 'proto' directory and the output will be placed in 'protobuf'. ```bash protoc --proto_path=proto --go_out=protobuf proto/*.proto --experimental_allow_proto3_optional ``` -------------------------------- ### Create Market Order Source: https://context7.com/scmhub/ibapi/llms.txt Use MarketOrder for immediate execution. Properties like TIF, OutsideRTH, and Account can be set on the order object. ```go package main import "github.com/scmhub/ibapi" func main() { // Create a market order quantity := ibapi.StringToDecimal("100") order := ibapi.MarketOrder("BUY", quantity) // Market order properties order.TIF = "DAY" // Time in force: DAY, GTC, IOC, etc. order.OutsideRTH = false // Execute outside regular trading hours order.Account = "DU123456" // Specify account for FA accounts // Place order with client // ib.PlaceOrder(orderID, contract, order) } ``` -------------------------------- ### Create Combination Orders with ComboLimitOrder Source: https://context7.com/scmhub/ibapi/llms.txt Create multi-leg combination orders for spreads, such as option spreads. Define contract details and add legs with their respective ratios, actions, and exchanges. The ComboLimitOrder function creates a net debit/credit order for the spread. ```go package main import "github.com/scmhub/ibapi" func main() { // Create combo contract for option spread combo := ibapi.NewContract() combo.Symbol = "SPY" combo.SecType = "BAG" combo.Currency = "USD" combo.Exchange = "SMART" // Add legs leg1 := ibapi.NewComboLeg() leg1.ConID = 123456789 // Long call conID leg1.Ratio = 1 leg1.Action = "BUY" leg1.Exchange = "SMART" leg2 := ibapi.NewComboLeg() leg2.ConID = 987654321 // Short call conID leg2.Ratio = 1 leg2.Action = "SELL" leg2.Exchange = "SMART" combo.ComboLegs = []ibapi.ComboLeg{leg1, leg2} // Create combo order quantity := ibapi.StringToDecimal("1") limitPrice := 2.50 // Net debit/credit for spread nonGuaranteed := true order := ibapi.ComboLimitOrder("BUY", quantity, limitPrice, nonGuaranteed) // For leg prices, use: // legPrices := []float64{5.00, 2.50} // order := ibapi.LimitOrderForComboWithLegPrices("BUY", quantity, legPrices, nonGuaranteed) } ``` -------------------------------- ### Request Account Summary in Go Source: https://context7.com/scmhub/ibapi/llms.txt Request account summary information using ReqAccountSummary. Define specific tags to retrieve and specify 'All' for all accounts. Remember to cancel the subscription with CancelAccountSummary. ```go package main import ( "strings" "time" "github.com/scmhub/ibapi" ) type AccountWrapper struct { ibapi.Wrapper } func (w AccountWrapper) AccountSummary(reqID int64, account, tag, value, currency string) { ibapi.Logger().Info(). Int64("reqID", reqID). Str("account", account). Str("tag", tag). Str("value", value). Str("currency", currency). Msg("AccountSummary") } func (w AccountWrapper) AccountSummaryEnd(reqID int64) { ibapi.Logger().Info().Int64("reqID", reqID).Msg("AccountSummaryEnd") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&AccountWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) reqID := int64(1) // Define tags to request tags := []string{ "AccountType", "NetLiquidation", "TotalCashValue", "BuyingPower", "AvailableFunds", "ExcessLiquidity", "Cushion", } // Request account summary for all accounts ib.ReqAccountSummary(reqID, "All", strings.Join(tags, ",")) time.Sleep(5 * time.Second) // Cancel subscription ib.CancelAccountSummary(reqID) } ``` -------------------------------- ### Create Trailing Stop Orders in Go Source: https://context7.com/scmhub/ibapi/llms.txt Use TrailingStop and TrailingStopLimit to create trailing stop orders. Specify quantity, trailing percentage or amount, and an initial stop price. ```go package main import "github.com/scmhub/ibapi" func main() { quantity := ibapi.StringToDecimal("100") trailingPercent := 5.0 // Trail by 5% trailStopPrice := 145.0 // Initial stop price // Trailing stop order order := ibapi.TrailingStop("SELL", quantity, trailingPercent, trailStopPrice) // Alternative: Trailing stop limit lmtPriceOffset := 0.50 // Limit price offset from stop trailingAmount := 2.0 // Trail by $2 stopOrder := ibapi.TrailingStopLimit("SELL", quantity, lmtPriceOffset, trailingAmount, trailStopPrice) _ = stopOrder } ``` -------------------------------- ### Request 5-Second Real-Time Bars with IBAPI Go Source: https://context7.com/scmhub/ibapi/llms.txt Subscribe to real-time 5-second bars using ReqRealTimeBars. Implement the RealtimeBar wrapper function to process incoming bar data. Remember to cancel the subscription with CancelRealTimeBars. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type RealTimeBarWrapper struct { ibapi.Wrapper } func (w RealTimeBarWrapper) RealtimeBar(reqID int64, barTime int64, open, high, low, close float64, volume, wap ibapi.Decimal, count int64) { ibapi.Logger().Info(). Int64("reqID", reqID). Time("time", time.Unix(barTime, 0)). Float64("open", open). Float64("high", high). Float64("low", low). Float64("close", close). Stringer("volume", volume). Int64("count", count). Msg("RealtimeBar") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&RealTimeBarWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) aapl := &ibapi.Contract{ ConID: 265598, Symbol: "AAPL", SecType: "STK", Exchange: "SMART", } reqID := int64(1) // Request real-time bars (always 5-second bars) // whatToShow: "TRADES", "MIDPOINT", "BID", "ASK" // useRTH: true for regular trading hours only ib.ReqRealTimeBars(reqID, aapl, 5, "TRADES", false, nil) time.Sleep(30 * time.Second) ib.CancelRealTimeBars(reqID) } ``` -------------------------------- ### NewContract - Create Contract Definitions Source: https://context7.com/scmhub/ibapi/llms.txt Demonstrates how to create contract objects for various financial instruments like stocks, forex, options, futures, and cryptocurrencies. ```APIDOC ## NewContract - Create Contract Definitions ### Description Create contract objects to specify instruments for market data or trading. ### Method `NewContract()` (Conceptual - this is a constructor/factory function in Go) ### Endpoint N/A (Client-side object creation) ### Parameters This function creates a contract object. Fields are set directly on the returned object. - **Symbol** (string) - The symbol of the security (e.g., "AAPL", "EUR", "ES", "BTC") - **SecType** (string) - The type of security (e.g., "STK", "CASH", "OPT", "FUT", "CRYPTO") - **Exchange** (string) - The exchange where the security is traded (e.g., "SMART", "IDEALPRO", "CME", "PAXOS") - **Currency** (string) - The currency of the security (e.g., "USD") - **LastTradeDateOrContractMonth** (string) - For options and futures, the expiration date or contract month (e.g., "202512", "202503") - **Strike** (float64) - For options, the strike price. - **Right** (string) - For options, "C" for Call, "P" for Put. - **Multiplier** (string) - For options, the contract multiplier (e.g., "100"). - **SecIDType** (string) - Type of security ID (e.g., "ISIN") when using SecID. - **SecID** (string) - The security ID (e.g., "US45841N1072") when using SecIDType. ### Request Example ```go // US Stock appleStock := ibapi.NewContract() appleStock.Symbol = "AAPL" appleStock.SecType = "STK" appleStock.Exchange = "SMART" appleStock.Currency = "USD" // Forex pair eurusd := ibapi.NewContract() eurusd.Symbol = "EUR" eurusd.SecType = "CASH" eurusd.Exchange = "IDEALPRO" eurusd.Currency = "USD" // Stock option option := ibapi.NewContract() option.Symbol = "GOOG" option.SecType = "OPT" option.Exchange = "SMART" option.Currency = "USD" option.LastTradeDateOrContractMonth = "202512" option.Strike = 150.0 option.Right = "C" // Call option option.Multiplier = "100" // Futures contract esFuture := ibapi.NewContract() esFuture.Symbol = "ES" esFuture.SecType = "FUT" esFuture.Exchange = "CME" esFuture.Currency = "USD" esFuture.LastTradeDateOrContractMonth = "202503" // Cryptocurrency bitcoin := ibapi.NewContract() bitcoin.Symbol = "BTC" bitcoin.SecType = "CRYPTO" bitcoin.Exchange = "PAXOS" bitcoin.Currency = "USD" // Contract by ISIN byIsin := ibapi.NewContract() byIsin.SecIDType = "ISIN" byIsin.SecID = "US45841N1072" byIsin.Exchange = "SMART" byIsin.Currency = "USD" byIsin.SecType = "STK" ``` ### Response N/A (This is a client-side object creation function, no direct API response) ### Response Example N/A ``` -------------------------------- ### Create Stop Limit Order Source: https://context7.com/scmhub/ibapi/llms.txt Use StopLimit to create an order that triggers at a stop price and executes at a specified limit price. Set TIF for order duration. ```go package main import "github.com/scmhub/ibapi" func main() { quantity := ibapi.StringToDecimal("100") limitPrice := 148.0 // Price at which to execute once triggered stopPrice := 150.0 // Trigger price // Stop limit sell order order := ibapi.StopLimit("SELL", quantity, limitPrice, stopPrice) // Properties order.TIF = "GTC" // Good till cancelled } ``` -------------------------------- ### Request Real-time PnL Updates in Go Source: https://context7.com/scmhub/ibapi/llms.txt Subscribe to real-time Profit and Loss (PnL) updates using ReqPnL. Provide a request ID and account number. Implement the Pnl wrapper method to receive updates. Cancel the subscription with CancelPnL. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type PnLWrapper struct { ibapi.Wrapper } func (w PnLWrapper) Pnl(reqID int64, dailyPnL, unrealizedPnL, realizedPnL float64) { ibapi.Logger().Info(). Int64("reqID", reqID). Float64("dailyPnL", dailyPnL). Float64("unrealizedPnL", unrealizedPnL). Float64("realizedPnL", realizedPnL). Msg("PnL") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&PnLWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) reqID := int64(1) account := "DU123456" // Your account number // Subscribe to PnL updates ib.ReqPnL(reqID, account, "") time.Sleep(30 * time.Second) ib.CancelPnL(reqID) } ``` -------------------------------- ### ReqRealTimeBars - Request 5-Second Real-Time Bars Source: https://context7.com/scmhub/ibapi/llms.txt Subscribe to real-time 5-second bars for a contract. This allows for continuous streaming of market data. ```APIDOC ## POST /api/realTimeBars ### Description Subscribes to real-time 5-second bars for a specified contract. ### Method POST ### Endpoint /api/realTimeBars ### Parameters #### Request Body - **reqID** (int64) - Required - Unique identifier for the request. - **contract** (object) - Required - Contract details. - **ConID** (integer) - Optional - The contract identifier. - **Symbol** (string) - Optional - The symbol of the financial instrument. - **SecType** (string) - Optional - The security type (e.g., "STK"). - **Exchange** (string) - Optional - The exchange to trade on (e.g., "SMART"). - **barSize** (integer) - Required - The size of the bar in seconds (must be 5 for this endpoint). - **whatToShow** (string) - Required - Type of data to show (e.g., "TRADES", "MIDPOINT", "BID", "ASK"). - **useRTH** (boolean) - Required - Whether to use regular trading hours only. ### Request Example ```json { "reqID": 1, "contract": { "ConID": 265598, "Symbol": "AAPL", "SecType": "STK", "Exchange": "SMART" }, "barSize": 5, "whatToShow": "TRADES", "useRTH": false } ``` ### Response #### Success Response (200) - **reqID** (int64) - The request ID. - **barTime** (integer) - The Unix timestamp of the bar. - **open** (float64) - The opening price. - **high** (float64) - The highest price. - **low** (float64) - The lowest price. - **close** (float64) - The closing price. - **volume** (Decimal) - The trading volume. - **wap** (Decimal) - The weighted average price. - **count** (int64) - The number of ticks in the bar. #### Response Example ```json { "reqID": 1, "barTime": 1678886400, "open": 150.50, "high": 151.00, "low": 150.25, "close": 150.75, "volume": "50000", "wap": "150.60", "count": 100 } ``` ### Cancel Real-Time Bars #### Method DELETE #### Endpoint /api/realTimeBars/{reqID} ### Description Cancels the real-time bar subscription for a given request ID. ``` -------------------------------- ### TrailingStop - Create Trailing Stop Orders Source: https://context7.com/scmhub/ibapi/llms.txt This section details how to create trailing stop orders and trailing stop limit orders. Trailing stop orders automatically adjust the stop price as the market moves in your favor, while trailing stop limit orders add a limit price to further control execution. ```APIDOC ## TrailingStop - Create Trailing Stop Orders ### Description Create a trailing stop order that follows price movement. ### Method Not applicable (function call within Go code) ### Endpoint Not applicable (function call within Go code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import "github.com/scmhub/ibapi" func main() { quantity := ibapi.StringToDecimal("100") trailingPercent := 5.0 // Trail by 5% trailStopPrice := 145.0 // Initial stop price // Trailing stop order order := ibapi.TrailingStop("SELL", quantity, trailingPercent, trailStopPrice) // Alternative: Trailing stop limit lmtPriceOffset := 0.50 // Limit price offset from stop trailingAmount := 2.0 // Trail by $2 stopOrder := ibapi.TrailingStopLimit("SELL", quantity, lmtPriceOffset, trailingAmount, trailStopPrice) _ = stopOrder } ``` ### Response #### Success Response (200) None (function returns an order object) #### Response Example None ``` -------------------------------- ### Request Contract Details in Go Source: https://context7.com/scmhub/ibapi/llms.txt Use ReqContractDetails to fetch detailed information about a specific contract. Ensure the IB API is connected and a wrapper is provided to handle the response. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type ContractWrapper struct { ibapi.Wrapper } func (w ContractWrapper) ContractDetails(reqID int64, contractDetails *ibapi.ContractDetails) { ibapi.Logger().Info(). Int64("reqID", reqID). Str("symbol", contractDetails.Contract.Symbol). Str("longName", contractDetails.LongName). Float64("minTick", contractDetails.MinTick). Str("validExchanges", contractDetails.ValidExchanges). Str("tradingHours", contractDetails.TradingHours). Msg("ContractDetails") } func (w ContractWrapper) ContractDetailsEnd(reqID int64) { ibapi.Logger().Info().Int64("reqID", reqID).Msg("ContractDetailsEnd") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&ContractWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) // Query contract details contract := &ibapi.Contract{ Symbol: "AAPL", SecType: "STK", Exchange: "SMART", Currency: "USD", } ib.ReqContractDetails(1, contract) time.Sleep(5 * time.Second) } ``` -------------------------------- ### Create Contract Definitions with NewContract Source: https://context7.com/scmhub/ibapi/llms.txt Use NewContract to create contract objects for various financial instruments like stocks, forex, options, futures, and cryptocurrencies. Specify details such as symbol, security type, exchange, currency, and other relevant parameters like strike price and expiration dates. ```go package main import "github.com/scmhub/ibapi" func main() { // US Stock appleStock := ibapi.NewContract() appleStock.Symbol = "AAPL" appleStock.SecType = "STK" appleStock.Exchange = "SMART" appleStock.Currency = "USD" // Forex pair eurusd := ibapi.NewContract() eurusd.Symbol = "EUR" eurusd.SecType = "CASH" eurusd.Exchange = "IDEALPRO" eurusd.Currency = "USD" // Stock option option := ibapi.NewContract() option.Symbol = "GOOG" option.SecType = "OPT" option.Exchange = "SMART" option.Currency = "USD" option.LastTradeDateOrContractMonth = "202512" option.Strike = 150.0 option.Right = "C" // Call option option.Multiplier = "100" // Futures contract esFuture := ibapi.NewContract() esFuture.Symbol = "ES" esFuture.SecType = "FUT" esFuture.Exchange = "CME" esFuture.Currency = "USD" esFuture.LastTradeDateOrContractMonth = "202503" // Cryptocurrency bitcoin := ibapi.NewContract() bitcoin.Symbol = "BTC" bitcoin.SecType = "CRYPTO" bitcoin.Exchange = "PAXOS" bitcoin.Currency = "USD" // Contract by ISIN byIsin := ibapi.NewContract() byIsin.SecIDType = "ISIN" byIsin.SecID = "US45841N1072" byIsin.Exchange = "SMART" byIsin.Currency = "USD" byIsin.SecType = "STK" } ``` -------------------------------- ### Request Current Positions in Go Source: https://context7.com/scmhub/ibapi/llms.txt Retrieve all current positions across accounts using ReqPositions. Implement the Position and PositionEnd wrapper methods to handle the data. Remember to cancel updates with CancelPositions. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type PositionWrapper struct { ibapi.Wrapper } func (w PositionWrapper) Position(account string, contract *ibapi.Contract, position ibapi.Decimal, avgCost float64) { ibapi.Logger().Info(). Str("account", account). Str("symbol", contract.Symbol). Str("secType", contract.SecType). Stringer("position", position). Float64("avgCost", avgCost). Msg("Position") } func (w PositionWrapper) PositionEnd() { ibapi.Logger().Info().Msg("PositionEnd") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&PositionWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) // Request all positions ib.ReqPositions() time.Sleep(5 * time.Second) // Cancel position updates ib.CancelPositions() } ``` -------------------------------- ### Create Bracket Order Source: https://context7.com/scmhub/ibapi/llms.txt BracketOrder creates a parent order with attached take profit and stop loss orders. The parent order is typically set with Transmit=false. ```go package main import ( "time" "github.com/scmhub/ibapi" ) func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(nil) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(1 * time.Second) contract := &ibapi.Contract{ Symbol: "AAPL", SecType: "STK", Exchange: "SMART", Currency: "USD", } parentOrderID := int64(100) quantity := ibapi.StringToDecimal("100") entryPrice := 150.0 takeProfitPrice := 160.0 stopLossPrice := 145.0 // Create bracket order - returns parent, take profit, and stop loss orders parent, takeProfit, stopLoss := ibapi.BracketOrder( parentOrderID, "BUY", quantity, entryPrice, takeProfitPrice, stopLossPrice, ) // Place all three orders // Parent order has Transmit=false, so orders are held until stopLoss (Transmit=true) is sent ib.PlaceOrder(parent.OrderID, contract, parent) ib.PlaceOrder(takeProfit.OrderID, contract, takeProfit) ib.PlaceOrder(stopLoss.OrderID, contract, stopLoss) time.Sleep(10 * time.Second) } ``` -------------------------------- ### Request Real-Time Market Data with ReqMktData Source: https://context7.com/scmhub/ibapi/llms.txt Subscribe to streaming market data for a contract by calling ReqMktData. Ensure the Wrapper implementation handles TickPrice and TickSize callbacks. The snapshot parameter controls whether to receive streaming data or a single snapshot. ```go package main import ( "time" "github.com/scmhub/ibapi" ) type MarketDataWrapper struct { ibapi.Wrapper } func (w MarketDataWrapper) TickPrice(reqID int64, tickType ibapi.TickType, price float64, attrib ibapi.TickAttrib) { // TickType: 1=Bid, 2=Ask, 4=Last, 6=High, 7=Low, 9=Close ibapi.Logger().Info(). Int64("reqID", reqID). Int64("tickType", tickType). Float64("price", price). Msg("TickPrice") } func (w MarketDataWrapper) TickSize(reqID int64, tickType ibapi.TickType, size ibapi.Decimal) { ibapi.Logger().Info(). Int64("reqID", reqID). Int64("tickType", tickType). Stringer("size", size). Msg("TickSize") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&MarketDataWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) // Define contract eurusd := &ibapi.Contract{ Symbol: "EUR", SecType: "CASH", Exchange: "IDEALPRO", Currency: "USD", } reqID := int64(1) // Request streaming market data // genericTickList: "" for default ticks, or comma-separated tick types // snapshot: false for streaming, true for single snapshot // regulatorySnapshot: true for regulatory snapshot (additional fees apply) ib.ReqMktData(reqID, eurusd, "", false, false, nil) // Let data stream for 10 seconds time.Sleep(10 * time.Second) // Cancel market data subscription ib.CancelMktData(reqID) } ``` -------------------------------- ### ReqAccountSummary - Request Account Summary Source: https://context7.com/scmhub/ibapi/llms.txt This endpoint allows you to request account-level summary information. It provides key financial metrics for your trading accounts. ```APIDOC ## ReqAccountSummary - Request Account Summary ### Description Request account-level summary information. ### Method Not applicable (function call within Go code) ### Endpoint Not applicable (function call within Go code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "strings" "time" "github.com/scmhub/ibapi" ) type AccountWrapper struct { ibapi.Wrapper } func (w AccountWrapper) AccountSummary(reqID int64, account, tag, value, currency string) { ibapi.Logger().Info(). Int64("reqID", reqID). Str("account", account). Str("tag", tag). Str("value", value). Str("currency", currency). Msg("AccountSummary") } func (w AccountWrapper) AccountSummaryEnd(reqID int64) { ibapi.Logger().Info().Int64("reqID", reqID).Msg("AccountSummaryEnd") } func main() { ibapi.SetConsoleWriter() ib := ibapi.NewEClient(&AccountWrapper{}) if err := ib.Connect("localhost", 7497, 1); err != nil { return } defer ib.Disconnect() time.Sleep(100 * time.Millisecond) reqID := int64(1) // Define tags to request tags := []string{ "AccountType", "NetLiquidation", "TotalCashValue", "BuyingPower", "AvailableFunds", "ExcessLiquidity", "Cushion", } // Request account summary for all accounts ib.ReqAccountSummary(reqID, "All", strings.Join(tags, ",")) time.Sleep(5 * time.Second) // Cancel subscription ib.CancelAccountSummary(reqID) } ``` ### Response #### Success Response (200) - **reqID** (int64) - Request identifier. - **account** (string) - Account identifier. - **tag** (string) - Summary tag (e.g., "NetLiquidation"). - **value** (string) - The value associated with the tag. - **currency** (string) - The currency of the value. #### Response Example ```json { "reqID": 1, "account": "DU123456", "tag": "NetLiquidation", "value": "100000.00", "currency": "USD" } ``` ``` -------------------------------- ### NewVolumeCondition - Create Volume-Based Conditions Source: https://context7.com/scmhub/ibapi/llms.txt Creates order conditions that are triggered when the trading volume of an asset reaches a specified threshold. ```APIDOC ## NewVolumeCondition - Create Volume-Based Conditions ### Description Create conditions based on trading volume. ### Method Not specified (function call in Go) ### Endpoint Not applicable (local function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage within the Go program volumeCondition := ibapi.NewVolumeCondition( 265598, // AAPL conID "SMART", // Exchange true, // isMore (volume > threshold) 1000000, // Volume threshold false, // isConjunction ) order.Conditions = append(order.Conditions, volumeCondition) ``` ### Response #### Success Response (200) Volume condition is added to the order. #### Response Example None provided, as this is a condition creation function. ```