ibsync

package module
v0.10.37 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2025 License: MIT Imports: 19 Imported by: 0

README

Go Report Card Go Reference

Interactive Brokers Synchronous Golang Client

ibsync is a Go package designed to simplify interaction with the Interactive Brokers API. It is inspired by the great ib_insync Python library and based on ibapi. It provides a synchronous, easy-to-use interface for account management, trade execution, real-time and historical market data within the IB ecosystem.

[!CAUTION] This package is in the beta phase. While functional, it may still have bugs or incomplete features. Please test extensively in non-production environments.

Getting Started

Prerequisites
  • Go version 1.23 or higher (recommended)
  • An Interactive Brokers account with TWS or IB Gateway installed and running
Installation

Install the package via go get:

go get -u github.com/scmhub/ibsync

Quick start

Here’s a basic example to connect and get the managed accounts list:

package main

import "github.com/scmhub/ibsync"

func main() {
	// Get the logger (zerolog)
	log := ibapi.Logger()
	ibsync.SetConsoleWriter() // pretty logs to console, for dev and test.

	// New IB client & Connect
	ib := ibsync.NewIB()

	err := ib.Connect()
	if err != nil {
		log.Error().Err(err).Msg("Connect")
		return
	}
	defer ib.Disconnect()

	managedAccounts := ib.ManagedAccounts()
	log.Info().Strs("accounts", managedAccounts).Msg("Managed accounts list")
}

Usage guide

Configuration

Connect with a different configuration.

// New IB client & Connect
ib := ibsync.NewIB()

err := ib.Connect(
    ibsync.NewConfig(
        ibsync.WithHost("10.74.0.9"),       // Default: "127.0.0.1".
        ibsync.WithPort(4002),              // Default: 7497.
        ibsync.WithClientID(5),             // Default: a random number. If set to 0 it will also retreive manual orders.
        ibsync.WithTimeout(1*time.Second),  // Default is 30 seconds.
    ),
)
if err != nil {
	log.Error().Err(err).Msg("Connect")
	return
}
defer ib.Disconnect()
Account

Account value, summary, positions, trades...

// Account Values
accountValues := ib.AccountValues()

// Account Summary
accountSummary := ib.AccountSummary()

// Portfolio
portfolio := ib.Portfolio()

// Positions
// Subscribe to Postion
ib.ReqPositions()
// Position Channel
posChan := ib.PositionChan()

// Trades
trades := ib.Trades()
openTrades := ib.OpenTrades()

Contract details

Request contract details from symbol, exchange

// NewStock("AMD", "", "")
amd := ibsync.NewStock("AMD", "", "")
cd, err := ib.ReqContractDetails(amd)
if err != nil {
	log.Error().Err(err).Msg("request contract details")
	return
}
fmt.Println("number of contract found for request NewStock(\"AMD\", \"\", \"\") :", len(cd))
Pnl

Subscribe to the pnl stream

// Request PnL subscription for the account.
ib.ReqPnL(account, modelCode)

// Get a PnL channel to receive updates...
pnlChan := ib.PnlChan(account, modelCode)

go func() {
	for pnl := range pnlChan {
		fmt.Println("Received PnL from channel:", pnl)
	}
}()

//... Or read the last PnL on the client state
pnl := ib.Pnl(account, modelCode)
fmt.Println("Current PnL:", pnl)
Orders

Place an order and create a new trade. Modify or cancel the trade. Cancel all trades

// Create the contract
eurusd := ibsync.NewForex("EUR", "IDEALPRO", "USD")

// Create the order
order := ibsync.LimitOrder("BUY", ibsync.StringToDecimal("20000"), 1.05)

// Place the order
trade := ib.PlaceOrder(eurusd, order)

go func() {
		<-trade.Done()
		fmt.Println("The trade is done!!!")
	}()

// Cancel the order
ib.CancelOrder(Order, ibsync.NewOrderCancel())

// Cancel all orders
ib.ReqGlobalCancel()
Bar data

Real time and historical bar data.

// Historical data
barChan, _ := ib.ReqHistoricalData(eurusd, endDateTime, duration, barSize, whatToShow, useRTH, formatDate)
var bars []ibsync.Bar
for bar := range barChan {
    bars = append(bars, bar)
}

// Historical data up to date
barChan, cancel := ib.ReqHistoricalDataUpToDate(eurusd, duration, barSize, whatToShow, useRTH, formatDate)
go func() {
    for bar := range barChan {
        bars = append(bars, bar)
    }
}()
time.Sleep(10 * time.Second)
cancel()

// Real time bars
rtBarChan, cancel := ib.ReqRealTimeBars(eurusd, 5, "MIDPOINT", useRTH)
<-rtBarChan
cancel()
Tick data

Real time and historical tick data.

// Snapshot - Market price
snapshot, err := ib.Snapshot(eurusd)
if err != nil {
    panic(fmt.Errorf("snapshot eurusd: %v", err))
}
fmt.Println("Snapshot market price", snapshot.MarketPrice())

// Tick by tick data
tickByTick := ib.ReqTickByTickData(eurusd, "BidAsk", 100, true)
time.Sleep(5 * time.Second)
ib.CancelTickByTickData(eurusd, "BidAsk")

// HistoricalTicks
historicalTicks, err, done := ib.ReqHistoricalTicks(aapl, startDateTime, time.Time{}, 100, true, true)
Scanner

Request scanner parameters and scanner subscritpion

// Scanner Parameters
xml, err := ib.ReqScannerParameters()

// Scanner subscription
scanSubscription := ibsync.NewScannerSubscription()
scanSubscription.Instrument = "STK"
scanSubscription.LocationCode = "STK.US.MAJOR"
scanSubscription.ScanCode = "TOP_PERC_GAIN"

scanData, err := ib.ReqScannerSubscription(scanSubscription)

// Scanner subcscription with filter option
opts := ibsync.ScannerSubscriptionOptions{
	FilterOptions: []ibsync.TagValue{
		{Tag: "changePercAbove", Value: "20"},
		{Tag: "priceAbove", Value: "5"},
		{Tag: "priceBelow", Value: "50"},
	},
}

filterScanData, err := ib.ReqScannerSubscription(scanSubscription, opts)

Documentation

For more information on how to use this package, please refer to the GoDoc documentation and check the examples directory. You can also have a look at the ib_test.go file

Acknowledgments

Notice of Non-Affiliation and Disclaimer

[!CAUTION] This project is in the beta phase and is still undergoing testing and development. Users are advised to thoroughly test the software in non-production environments before relying on it for live trading. Features may be incomplete, and bugs may exist. Use at your own risk.

[!IMPORTANT] This project is not affiliated with Interactive Brokers Group, Inc. All references to Interactive Brokers, including trademarks, logos, and brand names, belong to their respective owners. The use of these names is purely for informational purposes and does not imply endorsement by Interactive Brokers.

[!IMPORTANT] The authors of this package make no guarantees regarding the software's reliability, accuracy, or suitability for any particular purpose, including trading or financial decisions. No liability will be accepted for any financial losses, damages, or misinterpretations arising from the use of this software.

License

Distributed under the MIT License. See LICENSE for more information.

Author

Philippe Chavanne - contact

Documentation

Overview

The primary aim of this file is to re-export all structs, constants, and functions from the ibapi package, allowing developers to access them through a single cohesive package. This simplifies the process of integrating with the Interactive Brokers API by reducing the need to manage multiple imports and providing a more straightforward API surface for developers.

Index

Constants

View Source
const (
	// Default values for the connection parameters.
	TIMEOUT = 30 * time.Second // Default timeout duration
	HOST    = "127.0.0.1"      // Default host
	PORT    = 7497             // Default port
)
View Source
const (
	UNSET_INT       = ibapi.UNSET_INT
	UNSET_LONG      = ibapi.UNSET_LONG
	UNSET_FLOAT     = ibapi.UNSET_FLOAT
	INFINITY_STRING = ibapi.INFINITY_STRING
)
View Source
const (
	// TickType
	BID_SIZE                  = ibapi.BID_SIZE
	BID                       = ibapi.BID
	ASK                       = ibapi.ASK
	ASK_SIZE                  = ibapi.ASK_SIZE
	LAST                      = ibapi.LAST
	LAST_SIZE                 = ibapi.LAST_SIZE
	HIGH                      = ibapi.HIGH
	LOW                       = ibapi.LOW
	VOLUME                    = ibapi.VOLUME
	CLOSE                     = ibapi.CLOSE
	BID_OPTION_COMPUTATION    = ibapi.BID_OPTION_COMPUTATION
	ASK_OPTION_COMPUTATION    = ibapi.ASK_OPTION_COMPUTATION
	LAST_OPTION_COMPUTATION   = ibapi.LAST_OPTION_COMPUTATION
	MODEL_OPTION              = ibapi.MODEL_OPTION
	OPEN                      = ibapi.OPEN
	LOW_13_WEEK               = ibapi.LOW_13_WEEK
	HIGH_13_WEEK              = ibapi.HIGH_13_WEEK
	LOW_26_WEEK               = ibapi.LOW_26_WEEK
	HIGH_26_WEEK              = ibapi.HIGH_26_WEEK
	LOW_52_WEEK               = ibapi.LOW_52_WEEK
	HIGH_52_WEEK              = ibapi.HIGH_52_WEEK
	AVG_VOLUME                = ibapi.AVG_VOLUME
	OPEN_INTEREST             = ibapi.OPEN_INTEREST
	OPTION_HISTORICAL_VOL     = ibapi.OPTION_HISTORICAL_VOL
	OPTION_IMPLIED_VOL        = ibapi.OPTION_IMPLIED_VOL
	OPTION_BID_EXCH           = ibapi.OPTION_BID_EXCH
	OPTION_ASK_EXCH           = ibapi.OPTION_ASK_EXCH
	OPTION_CALL_OPEN_INTEREST = ibapi.OPTION_CALL_OPEN_INTEREST
	OPTION_PUT_OPEN_INTEREST  = ibapi.OPTION_PUT_OPEN_INTEREST
	OPTION_CALL_VOLUME        = ibapi.OPTION_CALL_VOLUME
	OPTION_PUT_VOLUME         = ibapi.OPTION_PUT_VOLUME
	INDEX_FUTURE_PREMIUM      = ibapi.INDEX_FUTURE_PREMIUM
	BID_EXCH                  = ibapi.BID_EXCH
	ASK_EXCH                  = ibapi.ASK_EXCH
	AUCTION_VOLUME            = ibapi.AUCTION_VOLUME
	AUCTION_PRICE             = ibapi.AUCTION_PRICE
	AUCTION_IMBALANCE         = ibapi.AUCTION_IMBALANCE
	MARK_PRICE                = ibapi.MARK_PRICE
	BID_EFP_COMPUTATION       = ibapi.BID_EFP_COMPUTATION
	ASK_EFP_COMPUTATION       = ibapi.ASK_EFP_COMPUTATION
	LAST_EFP_COMPUTATION      = ibapi.LAST_EFP_COMPUTATION
	OPEN_EFP_COMPUTATION      = ibapi.OPEN_EFP_COMPUTATION
	HIGH_EFP_COMPUTATION      = ibapi.HIGH_EFP_COMPUTATION
	LOW_EFP_COMPUTATION       = ibapi.LOW_EFP_COMPUTATION
	CLOSE_EFP_COMPUTATION     = ibapi.CLOSE_EFP_COMPUTATION
	LAST_TIMESTAMP            = ibapi.LAST_TIMESTAMP
	SHORTABLE                 = ibapi.SHORTABLE
	FUNDAMENTAL_RATIOS        = ibapi.FUNDAMENTAL_RATIOS
	RT_VOLUME                 = ibapi.RT_VOLUME
	HALTED                    = ibapi.HALTED
	BID_YIELD                 = ibapi.BID_YIELD
	ASK_YIELD                 = ibapi.ASK_YIELD
	LAST_YIELD                = ibapi.LAST_YIELD
	CUST_OPTION_COMPUTATION   = ibapi.CUST_OPTION_COMPUTATION
	TRADE_COUNT               = ibapi.TRADE_COUNT
	TRADE_RATE                = ibapi.TRADE_RATE
	VOLUME_RATE               = ibapi.VOLUME_RATE
	LAST_RTH_TRADE            = ibapi.LAST_RTH_TRADE
	RT_HISTORICAL_VOL         = ibapi.RT_HISTORICAL_VOL
	IB_DIVIDENDS              = ibapi.IB_DIVIDENDS
	BOND_FACTOR_MULTIPLIER    = ibapi.BOND_FACTOR_MULTIPLIER
	REGULATORY_IMBALANCE      = ibapi.REGULATORY_IMBALANCE
	NEWS_TICK                 = ibapi.NEWS_TICK
	SHORT_TERM_VOLUME_3_MIN   = ibapi.SHORT_TERM_VOLUME_3_MIN
	SHORT_TERM_VOLUME_5_MIN   = ibapi.SHORT_TERM_VOLUME_5_MIN
	SHORT_TERM_VOLUME_10_MIN  = ibapi.SHORT_TERM_VOLUME_10_MIN
	DELAYED_BID               = ibapi.DELAYED_BID
	DELAYED_ASK               = ibapi.DELAYED_ASK
	DELAYED_LAST              = ibapi.DELAYED_LAST
	DELAYED_BID_SIZE          = ibapi.DELAYED_BID_SIZE
	DELAYED_ASK_SIZE          = ibapi.DELAYED_ASK_SIZE
	DELAYED_LAST_SIZE         = ibapi.DELAYED_LAST_SIZE
	DELAYED_HIGH              = ibapi.DELAYED_HIGH
	DELAYED_LOW               = ibapi.DELAYED_LOW
	DELAYED_VOLUME            = ibapi.DELAYED_VOLUME
	DELAYED_CLOSE             = ibapi.DELAYED_CLOSE
	DELAYED_OPEN              = ibapi.DELAYED_OPEN
	RT_TRD_VOLUME             = ibapi.RT_TRD_VOLUME
	CREDITMAN_MARK_PRICE      = ibapi.CREDITMAN_MARK_PRICE
	CREDITMAN_SLOW_MARK_PRICE = ibapi.CREDITMAN_SLOW_MARK_PRICE
	DELAYED_BID_OPTION        = ibapi.DELAYED_BID_OPTION
	DELAYED_ASK_OPTION        = ibapi.DELAYED_ASK_OPTION
	DELAYED_LAST_OPTION       = ibapi.DELAYED_LAST_OPTION
	DELAYED_MODEL_OPTION      = ibapi.DELAYED_MODEL_OPTION
	LAST_EXCH                 = ibapi.LAST_EXCH
	LAST_REG_TIME             = ibapi.LAST_REG_TIME
	FUTURES_OPEN_INTEREST     = ibapi.FUTURES_OPEN_INTEREST
	AVG_OPT_VOLUME            = ibapi.AVG_OPT_VOLUME
	DELAYED_LAST_TIMESTAMP    = ibapi.DELAYED_LAST_TIMESTAMP
	SHORTABLE_SHARES          = ibapi.SHORTABLE_SHARES
	DELAYED_HALTED            = ibapi.DELAYED_HALTED
	REUTERS_2_MUTUAL_FUNDS    = ibapi.REUTERS_2_MUTUAL_FUNDS
	ETF_NAV_CLOSE             = ibapi.ETF_NAV_CLOSE
	ETF_NAV_PRIOR_CLOSE       = ibapi.ETF_NAV_PRIOR_CLOSE
	ETF_NAV_BID               = ibapi.ETF_NAV_BID
	ETF_NAV_ASK               = ibapi.ETF_NAV_ASK
	ETF_NAV_LAST              = ibapi.ETF_NAV_LAST
	ETF_FROZEN_NAV_LAST       = ibapi.ETF_FROZEN_NAV_LAST
	ETF_NAV_HIGH              = ibapi.ETF_NAV_HIGH
	ETF_NAV_LOW               = ibapi.ETF_NAV_LOW
	SOCIAL_MARKET_ANALYTICS   = ibapi.SOCIAL_MARKET_ANALYTICS
	ESTIMATED_IPO_MIDPOINT    = ibapi.ESTIMATED_IPO_MIDPOINT
	FINAL_IPO_LAST            = ibapi.FINAL_IPO_LAST
	DELAYED_YIELD_BID         = ibapi.DELAYED_YIELD_BID
	DELAYED_YIELD_ASK         = ibapi.DELAYED_YIELD_ASK
	NOT_SET                   = ibapi.NOT_SET
)
View Source
const MaxSyncedSubAccounts = 50

Variables

View Source
var (
	ErrNotPaperTrading     = errors.New("this account is not a paper trading account")
	ErrNotFinancialAdvisor = errors.New("this account is not a financial advisor account")
	ErrAmbiguousContract   = errors.New("ambiguous contract")
	ErrNoDataSubscription  = errors.New("no data subscription")
)

Exported Errors

View Source
var (
	// Errors
	ErrMaxNbTickerReached             = ibapi.CodeMsgPair{Code: 101, Msg: "Max number of tickers has been reached."}
	ErrMissingReportType              = ibapi.CodeMsgPair{Code: 430, Msg: "The fundamentals data for the security specified is not available."}
	ErrNewsFeedNotAllowed             = ibapi.CodeMsgPair{Code: 10276, Msg: "News feed is not allowed."}
	ErrAdditionalSubscriptionRequired = ibapi.CodeMsgPair{Code: 10089, Msg: "Requested market data requires additional subscription for API."}
	ErrPartlyNotSubsribed             = ibapi.CodeMsgPair{Code: 10090, Msg: "Part of requested market data is not subscribed."}

	// Warnings
	WarnDelayedMarketData    = ibapi.CodeMsgPair{Code: 10167, Msg: "Requested market data is not subscribed. Displaying delayed market data."}
	WarnCompetingLiveSession = ibapi.CodeMsgPair{Code: 10197, Msg: "No market data during competing live session."}
)
View Source
var (
	UNSET_DECIMAL    = ibapi.UNSET_DECIMAL
	ZERO             = ibapi.ZERO
	StringToDecimal  = ibapi.StringToDecimal
	DecimalToString  = ibapi.DecimalToString
	IntMaxString     = ibapi.IntMaxString
	LongMaxString    = ibapi.LongMaxString
	FloatMaxString   = ibapi.FloatMaxString
	DecimalMaxString = ibapi.DecimalMaxString
	Logger           = ibapi.Logger
	SetLogLevel      = ibapi.SetLogLevel
	SetConsoleWriter = ibapi.SetConsoleWriter
	TickName         = ibapi.TickName
)
View Source
var (
	NewBar                     = ibapi.NewBar
	NewRealTimeBar             = ibapi.NewRealTimeBar
	NewCommissionAndFeesReport = ibapi.NewCommissionAndFeesReport
	NewComboLeg                = ibapi.NewComboLeg
	NewContract                = ibapi.NewContract
	NewContractDescription     = ibapi.NewContractDescription
	NewContractDetails         = ibapi.NewContractDetails
	NewDeltaNeutralContract    = ibapi.NewDeltaNeutralContract
	NewDepthMktDataDescription = ibapi.NewDepthMktDataDescription
	NewExecution               = ibapi.NewExecution
	NewExecutionFilter         = ibapi.NewExecutionFilter
	NewFamilyCode              = ibapi.NewFamilyCode
	NewHistogramData           = ibapi.NewHistogramData
	NewHistoricalSession       = ibapi.NewHistoricalSession
	NewHistoricalTick          = ibapi.NewHistoricalTick
	NewHistoricalTickBidAsk    = ibapi.NewHistoricalTickBidAsk
	NewHistoricalTickLast      = ibapi.NewHistoricalTickLast
	NewNewsProvider            = ibapi.NewNewsProvider
	NewOrder                   = ibapi.NewOrder
	NewOrderCancel             = ibapi.NewOrderCancel
	NewOrderState              = ibapi.NewOrderState
	NewPriceIncrement          = ibapi.NewPriceIncrement
	NewScannerSubscription     = ibapi.NewScannerSubscription
	NewSmartComponent          = ibapi.NewSmartComponent
	NewSoftDollarTier          = ibapi.NewSoftDollarTier
	NewTagValue                = ibapi.NewTagValue
	NewTickAttrib              = ibapi.NewTickAttrib
	NewTickAttribLast          = ibapi.NewTickAttribLast
	NewTickAttribBidAsk        = ibapi.NewTickAttribBidAsk
	NewWshEventData            = ibapi.NewWshEventData
)
View Source
var (
	// ibapi custom contracts
	AtAuction                       = ibapi.AtAuction
	Discretionary                   = ibapi.Discretionary
	MarketOrder                     = ibapi.MarketOrder
	MarketIfTouched                 = ibapi.MarketIfTouched
	MarketOnClose                   = ibapi.MarketOnClose
	MarketOnOpen                    = ibapi.MarketOnOpen
	MidpointMatch                   = ibapi.MidpointMatch
	Midprice                        = ibapi.Midprice
	PeggedToMarket                  = ibapi.PeggedToMarket
	PeggedToStock                   = ibapi.PeggedToStock
	RelativePeggedToPrimary         = ibapi.RelativePeggedToPrimary
	SweepToFill                     = ibapi.SweepToFill
	AuctionLimit                    = ibapi.AuctionLimit
	AuctionPeggedToStock            = ibapi.AuctionPeggedToStock
	AuctionRelative                 = ibapi.AuctionRelative
	Block                           = ibapi.Block
	BoxTop                          = ibapi.BoxTop
	LimitOrder                      = ibapi.LimitOrder
	LimitOrderWithCashQty           = ibapi.LimitOrderWithCashQty
	LimitIfTouched                  = ibapi.LimitIfTouched
	LimitOnClose                    = ibapi.LimitOnClose
	LimitOnOpen                     = ibapi.LimitOnOpen
	PassiveRelative                 = ibapi.PassiveRelative
	PeggedToMidpoint                = ibapi.PeggedToMidpoint
	BracketOrder                    = ibapi.BracketOrder
	MarketToLimit                   = ibapi.MarketToLimit
	MarketWithProtection            = ibapi.MarketWithProtection
	Stop                            = ibapi.Stop
	StopLimit                       = ibapi.StopLimit
	StopWithProtection              = ibapi.StopWithProtection
	TrailingStop                    = ibapi.TrailingStop
	TrailingStopLimit               = ibapi.TrailingStopLimit
	ComboLimitOrder                 = ibapi.ComboLimitOrder
	ComboMarketOrder                = ibapi.ComboMarketOrder
	LimitOrderForComboWithLegPrices = ibapi.LimitOrderForComboWithLegPrices
	RelativeLimitCombo              = ibapi.RelativeLimitCombo
	RelativeMarketCombo             = ibapi.RelativeMarketCombo
	OneCancelsAll                   = ibapi.OneCancelsAll
	Volatility                      = ibapi.Volatility
	MarketFHedge                    = ibapi.MarketFHedge
	PeggedToBenchmark               = ibapi.PeggedToBenchmark
	AttachAdjustableToStop          = ibapi.AttachAdjustableToStop
	AttachAdjustableToStopLimit     = ibapi.AttachAdjustableToStopLimit
	AttachAdjustableToTrail         = ibapi.AttachAdjustableToTrail
	WhatIfLimitOrder                = ibapi.WhatIfLimitOrder
	NewPriceCondition               = ibapi.NewPriceCondition
	NewExecutionCondition           = ibapi.NewExecutionCondition
	NewMarginCondition              = ibapi.NewMarginCondition
	NewPercentageChangeCondition    = ibapi.NewPercentageChangeCondition
	NewTimeCondition                = ibapi.NewTimeCondition
	NewVolumeCondition              = ibapi.NewVolumeCondition
	LimitIBKRATS                    = ibapi.LimitIBKRATS
	LimitOrderWithManualOrderTime   = ibapi.LimitOrderWithManualOrderTime
	PegBestUpToMidOrder             = ibapi.PegBestUpToMidOrder
	PegBestOrder                    = ibapi.PegBestOrder
	PegMidOrder                     = ibapi.PegMidOrder
	LimitOrderWithCustomerAccount   = ibapi.LimitOrderWithCustomerAccount
	LimitOrderWithIncludeOvernight  = ibapi.LimitOrderWithIncludeOvernight
	CancelOrderEmpty                = ibapi.CancelOrderEmpty
	CancelOrderWithManualTime       = ibapi.CancelOrderWithManualTime
	LimitOrderWithCmeTaggingFields  = ibapi.LimitOrderWithCmeTaggingFields
	OrderCancelWithCmeTaggingFields = ibapi.OrderCancelWithCmeTaggingFields
)

Functions

func Decode

func Decode(e any, data string) error

Decode deserializes a gob-encoded string back into a Go value.

Parameters:

  • e: A pointer to the target value where decoded data will be stored
  • data: The gob-encoded string to be decoded

func Encode

func Encode(e any) string

Encode serializes an input value to a gob-encoded string.

func FormatIBTime

func FormatIBTime(t time.Time) string

FormatIBTime formats a time.Time value into the string format required by IB API.

The returned string is in the format "YYYYMMDD HH:MM:SS", which is used by Interactive Brokers for specifying date and time. As no time zone is provided IB will use your local time zone so we enforce local time zone first. It returns "" if time is zero.

func FormatIBTimeUSEastern

func FormatIBTimeUSEastern(t time.Time) string

FormatIBTimeUSEastern sets a time.Time value to US/Eastern time zone and formats into the string format required by IB API.

The returned string is in the format "YYYYMMDD HH:MM:SS US/Eastern", which is used by Interactive Brokers for specifying date and time. It returns "" if time is zero.

func FormatIBTimeUTC

func FormatIBTimeUTC(t time.Time) string

FormatIBTimeUTC sets a time.Time value to UTC time zone and formats into the string format required by IB API.

Note that there is a dash between the date and time in UTC notation. The returned string is in the format "YYYYMMDD HH:MM:SS UTC", which is used by Interactive Brokers for specifying date and time. It returns "" if time is zero.

func IsWarning

func IsWarning(cmp ibapi.CodeMsgPair) bool

func Join

func Join(strs ...string) string

Join concatenates multiple strings using the package's default separator ("::").

func Key

func Key(keys ...any) string

Key constructs a unique string key from a variadic number of values, separated by a specified delimiter. default delimiter is "::"

func LastWednesday12EST

func LastWednesday12EST() time.Time

LastWednesday12EST returns time.Time correspondong to last wednesday 12:00 EST Without checking holidays this a high probability time for open market. Usefull for testing historical data

func NewState

func NewState() *ibState

NewState creates and initializes a new ibState instance.

func ParseIBTime

func ParseIBTime(s string) (time.Time, error)

ParseIBTime parses an IB string representation of time into a time.Time object. It supports various IB formats, including: 1. "YYYYMMDD" 2. Unix timestamp ("1617206400") 3. "YYYYMMDD HH:MM:SS Timezone" 4. // "YYYYmmdd HH:MM:SS", "YYYY-mm-dd HH:MM:SS.0" or "YYYYmmdd-HH:MM:SS"

func Split

func Split(str string) []string

Split divides a string into substrings using the package's default separator ("::").

func Stringify

func Stringify(obj interface{}) string

Stringify converts a struct or pointer to a struct into a string representation Skipping fields with zero or nil values and dereferencing pointers. It is recursive and will apply to nested structs. It can NOT handle unexported fields.

func TickTypesToString

func TickTypesToString(tt ...TickType) string

TickTypesToString converts a variadic number of TickType values to a comma-separated string representation.

func UpdateStruct

func UpdateStruct(dest, src any) error

UpdateStruct copies non-zero fields from src to dest. dest must be a pointer to a struct so that it can be updated; src can be either a struct or a pointer to a struct.

func WithClientID

func WithClientID(id int64) func(*Config)

WithClientID is a functional option to set a specific ClientID. Useful if you want to set a fixed client ID instead of a random one.

func WithClientZero

func WithClientZero() func(*Config)

WithClientZero is a shortcut functional option that sets the ClientID to 0. ClientID = 0 is a privileged ClientID that gives your API session access to all order updates, including those entered manually in the TWS or by other API clients.

func WithHost

func WithHost(host string) func(*Config)

WithHost is a functional option to set a custom host for the Config.

func WithPort

func WithPort(port int) func(*Config)

WithPort is a functional option to set a custom port for the Config.

func WithTimeout

func WithTimeout(timeout time.Duration) func(*Config)

WithTimeout is a functional option to customize the timeout for the connection.

func WithoutSync

func WithoutSync() func(*Config)

WithoutSync is a functional option that sets InSybc

Types

type AccountSummary

type AccountSummary []AccountValue

func (AccountSummary) String

func (as AccountSummary) String() string

type AccountValue

type AccountValue struct {
	Account  string
	Tag      string
	Value    string
	Currency string
}

type AccountValues

type AccountValues []AccountValue

func (AccountValues) String

func (avs AccountValues) String() string

type Bar

type Bar = ibapi.Bar

type CancelFunc

type CancelFunc func()

A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop. A CancelFunc may be called by multiple goroutines simultaneously. After the first call, subsequent calls to a CancelFunc do nothing.

type ComboLeg

type ComboLeg = ibapi.ComboLeg

type CommissionAndFeesReport

type CommissionAndFeesReport = ibapi.CommissionAndFeesReport

type Config

type Config struct {
	Host     string        // Host address for the connection
	Port     int           // Port number for the connection
	ClientID int64         // Client ID, default is randomized for uniqueness
	InSync   bool          // Stay in sync with server
	Timeout  time.Duration // Timeout for the connection
	ReadOnly bool          // Indicates if the client should be in read-only mode
	Account  string        // Optional account identifier
}

Config holds the connection parameters for the client. This struct centralizes all the configurable options for creating a connection.

func NewConfig

func NewConfig(options ...func(*Config)) *Config

NewConfig creates a new Config with default values, and applies any functional options. The functional options allow customization of the config without directly modifying fields.

type Contract

type Contract = ibapi.Contract

func NewBag

func NewBag() *Contract

NewBag creates a bag contract (BAG), which may represent a collection of contracts bundled together.

func NewBond

func NewBond(symbol, exchange, currency string) *Contract

NewBond creates a bond contract (Bond).

func NewCFD

func NewCFD(symbol, exchange, currency string) *Contract

NewCFD creates a contract for difference (CFD) for the specified symbol, exchange, and currency.

func NewCommodity

func NewCommodity(symbol, exchange, currency string) *Contract

NewCommodity creates a commodity contract (CMDTY) for the given symbol, exchange, and currency.

func NewContFuture added in v0.10.37

func NewContFuture(symbol, exchange, multiplier, currency string) *Contract

NewContFuture creates a continuous future contract (CONFUT) for the given symbol, exchange, contract size, and currency. A continuous future contract represents a series of futures contracts for the same asset.

func NewCrypto

func NewCrypto(symbol, exchange, currency string) *Contract

NewCrypto creates a cryptocurrency contract (CRYPTO) for the specified symbol, exchange, and currency. The symbol represents the cryptocurrency being traded (e.g., "BTC").

func NewForex

func NewForex(symbol, exchange, currency string) *Contract

NewForex creates a forex contract (CASH) for a currency pair. symbol is the base currency, and currency is the quote currency. For a pair like "EURUSD", "EUR" is the symbol and "USD" the currency.

func NewFuture

func NewFuture(symbol, lastTradeDateOrContractMonth string, exchange, multiplier, currency string) *Contract

NewFuture creates a future contract (FUT) based on the symbol of the underlying asset, expiration date, exchange, contract size (multiplier), and currency. lastTradeDateOrContractMonth is the expiration date. "YYYYMM" format will specify the last trading month or "YYYYMMDD" format the last trading day.

func NewFutureOption

func NewFutureOption(symbol, lastTradeDateOrContractMonth string, strike float64, right, exchange, multiplier, currency string) *Contract

NewFutureOption creates a future option contract (FOP) based on the symbol of the underlying asset, expiration date, strike price, option right, exchange, contract size, and currency. lastTradeDateOrContractMonth is the expiration date. "YYYYMM" format will specify the last trading month or "YYYYMMDD" format the last trading day. The right specifies if it's a call ("C" or "CALL") or a put ("P" or "PUT") option.

func NewIndex

func NewIndex(symbol, exchange, currency string) *Contract

NewIndex creates an index contract (IND) for the given index symbol, exchange, and currency. The symbol typically represents a stock index (e.g., "SPX").

func NewMutualFund

func NewMutualFund() *Contract

NewMutualFund creates a mutual fund contract (FUND).

func NewOption

func NewOption(symbol, lastTradeDateOrContractMonth string, strike float64, right, exchange, multiplier, currency string) *Contract

NewOption creates an option contract (OPT) based on the symbol of the underlying asset, expiration date, strike price, option right, exchange, contract size, and currency. lastTradeDateOrContractMonth is the expiration date. "YYYYMM" format will specify the last trading month or "YYYYMMDD" format the last trading day. The right specifies if it's a call ("C" or "CALL") or a put ("P" or "PUT") option.

func NewStock

func NewStock(symbol, exchange, currency string) *Contract

NewStock creates a stock contract (STK) for the specified symbol, exchange, and currency. The symbol represents the stock ticker (e.g., "AAPL"), the exchange is where the stock is traded (e.g., "NASDAQ"), and the currency is the denomination of the stock (e.g., "USD").

func NewWarrant

func NewWarrant() *Contract

NewWarrant creates a warrant contract (WAR).

type ContractDescription

type ContractDescription = ibapi.ContractDescription

type ContractDetails

type ContractDetails = ibapi.ContractDetails

type DOMLevel

type DOMLevel struct {
	Price       float64
	Size        Decimal
	MarketMaker string
}

DOMLevel represents a single level in the order book

func (DOMLevel) String

func (dl DOMLevel) String() string

String provides a readable representation of a DOM level

type Decimal

type Decimal = ibapi.Decimal

type DeltaNeutralContract

type DeltaNeutralContract = ibapi.DeltaNeutralContract

type DepthMktDataDescription

type DepthMktDataDescription = ibapi.DepthMktDataDescription

type Dividends

type Dividends struct {
	Past12Months float64
	Next12Months float64
	NextDate     time.Time
	NextAmount   float64
}

type Execution

type Execution = ibapi.Execution

type ExecutionFilter

type ExecutionFilter = ibapi.ExecutionFilter

type FaDataType

type FaDataType = ibapi.FaDataType

type FamilyCode

type FamilyCode = ibapi.FamilyCode

type Fill

type Fill struct {
	Contract                *Contract               // Contract details for the filled order
	Execution               *Execution              // Execution details of the fill
	CommissionAndFeesReport CommissionAndFeesReport // Commission and fees information for the fill
	Time                    time.Time               // Timestamp of the fill
}

Fill represents a single execution fill of an order, including contract details, execution information, and commission data.

func (*Fill) Matches

func (f *Fill) Matches(filter *ExecutionFilter) bool

PassesExecutionFilter checks if the fill matches the specified execution filter criteria.

type FundDistributionPolicyIndicator

type FundDistributionPolicyIndicator = ibapi.FundDistributionPolicyIndicator

type FundamentalRatios

type FundamentalRatios map[string]float64

type HistogramData

type HistogramData = ibapi.HistogramData

type HistoricalNews

type HistoricalNews struct {
	Time         time.Time
	ProviderCode string
	ArticleID    string
	Headline     string
}

type HistoricalSchedule

type HistoricalSchedule struct {
	StartDateTime string
	EndDateTime   string
	TimeZone      string
	Sessions      []HistoricalSession
}

type HistoricalSession

type HistoricalSession = ibapi.HistoricalSession

type HistoricalTick

type HistoricalTick = ibapi.HistoricalTick

type HistoricalTickBidAsk

type HistoricalTickBidAsk = ibapi.HistoricalTickBidAsk

type HistoricalTickLast

type HistoricalTickLast = ibapi.HistoricalTickLast

type IB

type IB struct {
	// contains filtered or unexported fields
}

IB struct offers direct access to the current state, such as orders, executions, positions, tickers etc. This state is automatically kept in sync with the TWS/IBG application. IB has most request methods of EClient, with the same names and parameters (except for the reqId parameter which is not needed anymore).

func NewIB

func NewIB(config ...*Config) *IB

func (*IB) AccountSummary

func (ib *IB) AccountSummary(account ...string) AccountSummary

AccountSumary returns a slice of account values for the given accounts.

If no account is provided it will return values of all accounts. On the first run it is calling ReqAccountSummary and is blocking, after it returns the last summary requested. To request a new summary call ReqAccountSummary.

func (*IB) AccountValues

func (ib *IB) AccountValues(account ...string) AccountValues

AccountValues returns a slice of account values for the given accounts.

If no account is provided it will return values of all accounts. Account values need to be subscribed by ReqAccountUpdates. This is done at start up unless WithoutSync option is used.

func (*IB) CalculateImpliedVolatility

func (ib *IB) CalculateImpliedVolatility(contract *Contract, optionPrice float64, underPrice float64, impVolOptions ...TagValue) (*TickOptionComputation, error)

CalculateImpliedVolatility calculates the implied volatility given the option price.

func (*IB) CalculateOptionPrice

func (ib *IB) CalculateOptionPrice(contract *Contract, volatility float64, underPrice float64, optPrcOptions ...TagValue) (*TickOptionComputation, error)

CalculateOptionPrice calculates the price of the option given the volatility.

func (*IB) CancelAccountUpdatesMulti

func (ib *IB) CancelAccountUpdatesMulti(reqID int64)

CancelAccountUpdatesMulti cancels account update for reqID.

func (*IB) CancelMktData

func (ib *IB) CancelMktData(contract *Contract)

CancelMktData stops the market data stream for the specified contract.

Do not use CancelMktData for Snapshot() calls

func (*IB) CancelMktDepth

func (ib *IB) CancelMktDepth(contract *Contract, isSmartDepth bool) error

CancelMktDepth cancels market depth updates.

func (*IB) CancelNewsBulletins

func (ib *IB) CancelNewsBulletins()

CancelNewsBulletins cancels the subscription to news bulletins.

It stops receiving updates for news bulletins that were previously requested with ReqNewsBulletins.

func (*IB) CancelOrder

func (ib *IB) CancelOrder(order *Order, orderCancel OrderCancel)

CancelOrder cancels the given order. orderCancel is an OrderCancel struct. You can pass NewOrderCancel()

func (*IB) CancelPnL

func (ib *IB) CancelPnL(account string, modelCode string)

CancelPnL cancels the PnL update of assigned account.

func (*IB) CancelPnLSingle

func (ib *IB) CancelPnLSingle(account string, modelCode string, contractID int64)

CancelPnLSingle cancels the single contract PnL update of assigned account.

func (*IB) CancelPositions

func (ib *IB) CancelPositions()

CancelPositions cancels real-time position subscription.

func (*IB) CancelPositionsMulti

func (ib *IB) CancelPositionsMulti(reqID int64)

CancelPositionsMulti cancels the positions update of assigned account.

func (*IB) CancelTickByTickData

func (ib *IB) CancelTickByTickData(contract *Contract, tickType string) error

CancelTickByTickData unsubscribes from tick-by-tick for given contract and tick type.

func (*IB) Connect

func (ib *IB) Connect(config ...*Config) error

Connect must be called before any other. There is no feedback for a successful connection, but a subsequent attempt to connect will return the message "Already connected."

func (*IB) ConnectWithGracefulShutdown added in v0.10.37

func (ib *IB) ConnectWithGracefulShutdown(config ...*Config) error

ConnectWithGracefulShutdown connects and sets up signal handling for graceful shutdown. This is a convenience for simple apps. Advanced users should handle signals themselves.

func (*IB) Context

func (ib *IB) Context() context.Context

Context returns the ibsync Context

func (*IB) Disconnect

func (ib *IB) Disconnect() error

Disconnect terminates the connections with TWS. Calling this function does not cancel orders that have already been sent.

func (*IB) Executions

func (ib *IB) Executions(execFilter ...*ExecutionFilter) []Execution

Executions returns a slice of all the executions from this session. To get executions from previous sessions of the day you must call reqExecutions.

func (*IB) Fills

func (ib *IB) Fills(execFilter ...*ExecutionFilter) []Fill

Fills returns a slice of all the fills from this session. To get fills from previous sessions of the day you must call reqFills.

func (*IB) IsConnected

func (ib *IB) IsConnected() bool

IsConnected checks if there is a connection to TWS or GateWay

func (*IB) IsFinancialAdvisorAccount

func (ib *IB) IsFinancialAdvisorAccount() bool

IsFinancialAdvisorAccount checks if the accounts is a financial advisor account.

func (*IB) IsPaperAccount

func (ib *IB) IsPaperAccount() bool

IsPaperAccount checks if the accounts are paper accounts

func (*IB) ManagedAccounts

func (ib *IB) ManagedAccounts() []string

ManagedAccounts returns a list of account names.

func (*IB) MidPoint

func (ib *IB) MidPoint(contract *Contract) (TickByTickMidPoint, error)

MidPoint requests and returns the last Mid Point

No more than one request can be made for the same instrument within 15 seconds.

func (*IB) NewsBulletins

func (ib *IB) NewsBulletins() []NewsBulletin

NewsBulletins returns a slice of all received NewsBulletin instances.

func (*IB) NewsBulletinsChan

func (ib *IB) NewsBulletinsChan() chan NewsBulletin

NewsBulletinsChan returns a channel that receives a continuous feed of NewsBulletin updates.

Do not close the channel.

func (*IB) NewsTick

func (ib *IB) NewsTick() []NewsTick

NewTick returns the list of NewsTick

func (*IB) NextID

func (ib *IB) NextID() int64

NextID returns a local next ID. It is initialised at connection. NextID = -1 if non initialised.

func (*IB) OpenOrders

func (ib *IB) OpenOrders() []Order

OpenOrders returns a slice of all open orders from this session

func (*IB) OpenTrades

func (ib *IB) OpenTrades() []*Trade

OpenTrades returns a slice of copies of all open trades from this session

func (*IB) Orders

func (ib *IB) Orders() []Order

Orders returns a slice of all orders from this session

func (*IB) PlaceOrder

func (ib *IB) PlaceOrder(contract *Contract, order *Order) *Trade

PlaceOrder places a new order or modify an existing order. It returns a *Trade that is kept live updated with status changes, fils, etc.

contract is the *Contract to use for order. order contains the details of the order to be placed.

func (*IB) Pnl

func (ib *IB) Pnl(account string, modelCode string) []Pnl

Pnl returns a slice of Pnl values based on the specified account and model code.

If account is an empty string, it returns Pnls for all accounts. If modelCode is an empty string, it returns Pnls for all model codes.

func (*IB) PnlChan

func (ib *IB) PnlChan(account string, modelCode string) chan Pnl

PnlChan returns a channel that receives a continuous feed of Pnl updates.

Do NOT close the channel.

func (*IB) PnlSingle

func (ib *IB) PnlSingle(account string, modelCode string, contractID int64) []PnlSingle

PnlSingle returns a slice of PnlSingle values based on the specified account, model code, and contract ID.

If account is an empty string, it returns PnlSingles for all accounts. If modelCode is an empty string, it returns PnlSingles for all model codes. If contractID is zero, it returns PnlSingles for all contracts.

func (*IB) PnlSingleChan

func (ib *IB) PnlSingleChan(account string, modelCode string, contractID int64) chan PnlSingle

PnlSingleChan returns a channel that receives a continuous feed of PnlSingle updates.

Do NOT close the channel.

func (*IB) Portfolio

func (ib *IB) Portfolio(account ...string) []PortfolioItem

Portfolio returns a slice of portfolio item for the given accounts.

If no account is provided it will return items of all accounts. Portfolios need to be subscribed by ReqAccountUpdates. This is done at start up unless WithoutSync option is used.

func (*IB) PositionChan

func (ib *IB) PositionChan(account ...string) chan Position

PositionChan returns a channel that receives a continuous feed of Position updates.

You need to subscribe to positions by calling ReqPositions. Do NOT close the channel.

func (*IB) Positions

func (ib *IB) Positions(account ...string) []Position

Position returns a slice of the last positions received for the given accounts.

If no account is provided it will return positions of all accounts. Positions need to be subscribed with ReqPositions first.

func (*IB) QualifyContract

func (ib *IB) QualifyContract(contracts ...*Contract) error

QualifyContract qualifies the given contracts by retrieving their details from the Interactive Brokers API. This method takes one or more contracts as input and checks each contract to determine if it is unambiguous.

Parameters:

  • contracts: One or more *Contract structs that need to be qualified.

Returns:

  • An error if any of the contracts cannot be qualified or if any are ambiguous (ErrAmbiguousContract).
  • If successful, the contracts are updated in place with their corresponding details.

QualifyContract fetches and qualifies contract details in parallel

func (*IB) QueryDisplayGroups

func (ib *IB) QueryDisplayGroups() (groups string, err error)

QueryDisplayGroups requests the display groups in TWS.

func (*IB) ReplaceFA

func (ib *IB) ReplaceFA(faDataType FaDataType, cxml string) (string, error)

ReplaceFA replaces the FA configuration information from the API. Note that this can also be done manually in TWS itself. faData specifies the type of Financial Advisor configuration data being requested. 1 = GROUPS 3 = ACCOUNT ALIASES cxml is the XML string containing the new FA configuration information.

func (*IB) ReqAccountSummary

func (ib *IB) ReqAccountSummary(groupName string, tags string) (AccountSummary, error)

ReqAccountSummary requests and keep up to date the data that appears on the TWS Account Window Summary tab. The data is returned by accountSummary(). This request is designed for an FA managed account but can be used for any multi-account structure. reqId is the ID of the data request. it Ensures that responses are matched to requests If several requests are in process. groupName sets to All to return account summary data for all

accounts, or set to a specific Advisor Account Group name that has
already been created in TWS Global Configuration.

tags:str - A comma-separated list of account tags. Available tags are:

accountountType
NetLiquidation,
TotalCashValue - Total cash including futures pnl
SettledCash - For cash accounts, this is the same as
TotalCashValue
AccruedCash - Net accrued interest
BuyingPower - The maximum amount of marginable US stocks the account can buy
EquityWithLoanValue - Cash + stocks + bonds + mutual funds
PreviousDayEquityWithLoanValue,
GrossPositionValue - The sum of the absolute value of all stock and equity option positions
RegTEquity,
RegTMargin,
SMA - Special Memorandum Account
InitMarginReq,
MaintMarginReq,
AvailableFunds,
ExcessLiquidity,
Cushion - Excess liquidity as a percentage of net liquidation value
FullInitMarginReq,
FullMaintMarginReq,
FullAvailableFunds,
FullExcessLiquidity,
LookAheadNextChange - Time when look-ahead values take effect
LookAheadInitMarginReq,
LookAheadMaintMarginReq,
LookAheadAvailableFunds,
LookAheadExcessLiquidity,
HighestSeverity - A measure of how close the account is to liquidation
DayTradesRemaining - The Number of Open/Close trades a user could put on before Pattern Day Trading is detected.
	A value of "-1"	means that the user can put on unlimited day trades.
Leverage - GrossPositionValue / NetLiquidation
$LEDGER - Single flag to relay all cash balance tags*, only in base	currency.
$LEDGER:CURRENCY - Single flag to relay all cash balance tags*, only in	the specified currency.
$LEDGER:ALL - Single flag to relay all cash balance tags* in all currencies.

func (*IB) ReqAccountUpdates

func (ib *IB) ReqAccountUpdates(subscribe bool, accountName string) error

ReqAccountUpdates will start getting account values, portfolio, and last update time information.

func (*IB) ReqAccountUpdatesMulti

func (ib *IB) ReqAccountUpdatesMulti(reqID int64, account string, modelCode string, ledgerAndNLV bool)

ReqAccountUpdatesMulti requests account updates for account and/or model.

func (*IB) ReqAllOpenOrders

func (ib *IB) ReqAllOpenOrders() error

ReqAllOpenOrders requests the open orders placed from all clients and also from TWS. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper. No association is made between the returned orders and the requesting client.

func (*IB) ReqAutoOpenOrders

func (ib *IB) ReqAutoOpenOrders(autoBind bool)

ReqAutoOpenOrders requests that newly created TWS orders be implicitly associated with the client. This request can only be made from a client with clientId of 0. if autoBind is set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made.

func (*IB) ReqCompletedOrders

func (ib *IB) ReqCompletedOrders(apiOnly bool) error

ReqCompletedOrders requests the completed orders If apiOnly parameter is true, then only completed orders placed from API are requested.

func (*IB) ReqContractDetails

func (ib *IB) ReqContractDetails(contract *Contract) ([]ContractDetails, error)

ReqContractDetails downloads all details for a particular underlying. If the returned list is empty then the contract is not known. If the list has multiple values then the contract is ambiguous.

func (*IB) ReqCurrentTime

func (ib *IB) ReqCurrentTime() (currentTime time.Time, err error)

ReqCurrentTime asks the current system time on the server side. A second call within a secund will not be answered.

func (*IB) ReqCurrentTimeInMillis

func (ib *IB) ReqCurrentTimeInMillis() (int64, error)

ReqCurrentTime asks the current system time on the server side. A second call within a secund will not be answered.

func (*IB) ReqExecutions

func (ib *IB) ReqExecutions(execFilter ...*ExecutionFilter) ([]Execution, error)

ReqExecutions downloads the execution reports that meet the filter criteria to the client via the execDetails() function. To view executions beyond the past 24 hours, open the Trade Log in TWS and, while the Trade Log is displayed, request the executions again from the API. execFilter contains attributes that describe the filter criteria used to determine which execution reports are returned NOTE: Time format must be 'yyyymmdd-hh:mm:ss' Eg: '20030702-14:55'

func (*IB) ReqFamilyCodes

func (ib *IB) ReqFamilyCodes() ([]FamilyCode, error)

ReqFamilyCodes requests family codes.

func (*IB) ReqFills

func (ib *IB) ReqFills(execFilter ...*ExecutionFilter) ([]Fill, error)

func (*IB) ReqFundamentalData

func (ib *IB) ReqFundamentalData(contract *Contract, reportType string, fundamentalDataOptions ...TagValue) (data string, err error)

ReqFundamentalData requests fundamental data for stocks. The appropriate market data subscription must be set up in Account Management before you can receive this data. Result will be delivered via wrapper.FundamentalData(). this func can handle conid specified in the Contract object, but not tradingClass or multiplier. This is because this func is used only for stocks and stocks do not have a multiplier and trading class. reqId is the ID of the data request. Ensures that responses are matched to requests if several requests are in process. contract contains a description of the contract for which fundamental data is being requested. reportType is one of the following XML reports:

ReportSnapshot (company overview)
ReportsFinSummary (financial summary)
ReportRatios (financial ratios)
ReportsFinStatements (financial statements)
RESC (analyst estimates)
CalendarReport (company calendar)

func (*IB) ReqGlobalCancel

func (ib *IB) ReqGlobalCancel()

ReqGlobalCancel cancels all open orders globally. It cancels both API and TWS open orders.

func (*IB) ReqHeadTimeStamp

func (ib *IB) ReqHeadTimeStamp(contract *Contract, whatToShow string, useRTH bool, formatDate int) (time.Time, error)

ReqHeadTimeStamp retrieves the earliest available historical data timestamp for a contract.

Parameters:

  • contract: Contract specification containing symbol, type, expiry, etc.
  • whatToShow: Type of data to retrieve (e.g., "TRADES", "MIDPOINT", "BID", "ASK")
  • useRTH: When true, queries only Regular Trading Hours data
  • formatDate: Determines the format of returned dates (1: utc, 2: local)

func (*IB) ReqHistogramData

func (ib *IB) ReqHistogramData(contract *Contract, useRTH bool, timePeriod string) ([]HistogramData, error)

ReqHistogramData requests histogram data. histograms return data as a function of price level

contract: Contract to query. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. period: Period of which data is being requested, for example "3 days".

func (*IB) ReqHistoricalData

func (ib *IB) ReqHistoricalData(contract *Contract, endDateTime string, duration string, barSize string, whatToShow string, useRTH bool, formatDate int, chartOptions ...TagValue) (chan Bar, CancelFunc)

func (*IB) ReqHistoricalDataUpToDate

func (ib *IB) ReqHistoricalDataUpToDate(contract *Contract, duration string, barSize string, whatToShow string, useRTH bool, formatDate int, chartOptions ...TagValue) (chan Bar, CancelFunc)

ReqHistoricalDataUpToDate requests historical data and returns a channel of `Bar` structs.

This function continuously receives historical data updates for a given contract and returns a channel that streams `Bar` data updates.

Parameters:

  • contract: The contract for which historical data is being requested.
  • duration: Defines the duration of the query. Examples of valid values include "60 S", "30 D", "13 W", "6 M", "10 Y". The unit must be specified (S for seconds, D for days, W for weeks, etc.).
  • barSize: Specifies the size of the bars to be returned. Valid values include "1 sec", "5 secs", "10 secs", "15 secs", "30 secs", "1 min", "2 mins", "5 mins", etc.
  • whatToShow: Determines the type of data being requested. Valid values include "TRADES", "BID", "ASK", "BID_ASK", "HISTORICAL_VOLATILITY", etc.
  • useRTH: A boolean value to indicate if only data within regular trading hours (RTH) should be returned. `true` limits data to RTH, `false` includes all data.
  • formatDate: Defines the date format for the returned bars. Valid values are `1` for the "yyyymmdd HH:mm:ss" format, or `2` for Unix timestamps.
  • chartOptions: Reserved for internal use, generally set to the default value.

Returns:

A `chan Bar` that streams incoming historical data. The caller must read from this channel until it is closed. The channel should be properly closed once the caller is done processing the data to prevent resource leaks.

Do NOT close the channel.

func (*IB) ReqHistoricalNews

func (ib *IB) ReqHistoricalNews(contractID int64, providerCode string, startDateTime time.Time, endDateTime time.Time, totalResults int64, historicalNewsOptions ...TagValue) ([]HistoricalNews, error, bool)

ReqHistoricalNews requests historical news headlines.

params: contractID: Search news articles for contract with this conId. providerCodes: A '+'-separated list of provider codes, like 'BZ+FLY'. startDateTime: The (exclusive) start of the date range. endDateTime: The (inclusive) end of the date range. totalResults: Maximum number of headlines to fetch (300 max). historicalNewsOptions: Unknown.

func (*IB) ReqHistoricalSchedule

func (ib *IB) ReqHistoricalSchedule(contract *Contract, endDateTime string, duration string, useRTH bool) (HistoricalSchedule, error)

ReqHistoricalSchedule requests historical schedule.

func (*IB) ReqHistoricalTickBidAsk

func (ib *IB) ReqHistoricalTickBidAsk(contract *Contract, startDateTime, endDateTime time.Time, numberOfTicks int, useRTH bool, ignoreSize bool, miscOptions ...TagValue) ([]HistoricalTickBidAsk, error, bool)

ReqHistoricalTickBidAsk requests historical bid ask tick. The time resolution of the ticks is one second.

contract: Contract to query. startDateTime: the start time. endDateTime: One of “startDateTime“ or “endDateTime“ can be given, the other must be blank. numberOfTicks: Number of ticks to request (1000 max). The actual result can contain a bit more to accommodate all ticks in the latest second. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. ignoreSize: Ignore bid/ask ticks that only update the size. miscOptions: Unknown.

func (*IB) ReqHistoricalTickLast

func (ib *IB) ReqHistoricalTickLast(contract *Contract, startDateTime, endDateTime time.Time, numberOfTicks int, useRTH bool, ignoreSize bool, miscOptions ...TagValue) ([]HistoricalTickLast, error, bool)

ReqHistoricalTickLast requests historical last ticks. The time resolution of the ticks is one second.

contract: Contract to query. startDateTime: the start time. endDateTime: One of “startDateTime“ or “endDateTime“ can be given, the other must be blank. numberOfTicks: Number of ticks to request (1000 max). The actual result can contain a bit more to accommodate all ticks in the latest second. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. ignoreSize: Ignore bid/ask ticks that only update the size. miscOptions: Unknown.

func (*IB) ReqHistoricalTicks

func (ib *IB) ReqHistoricalTicks(contract *Contract, startDateTime, endDateTime time.Time, numberOfTicks int, useRTH bool, ignoreSize bool, miscOptions ...TagValue) ([]HistoricalTick, error, bool)

ReqHistoricalTicks requests historical ticks data. The time resolution of the ticks is one second.

contract: Contract to query. startDateTime: the start time. endDateTime: One of “startDateTime“ or “endDateTime“ can be given, the other must be blank. numberOfTicks: Number of ticks to request (1000 max). The actual result can contain a bit more to accommodate all ticks in the latest second. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. ignoreSize: Ignore bid/ask ticks that only update the size. miscOptions: Unknown.

func (*IB) ReqMarketDataType

func (ib *IB) ReqMarketDataType(marketDataType int64)

ReqMarketDataType changes the market data type.

The API can receive frozen market data from Trader Workstation. Frozen market data is the last data recorded in our system. During normal trading hours, the API receives real-time market data. If you use this function, you are telling TWS to automatically switch to frozen market data after the close. Then, before the opening of the next trading day, market data will automatically switch back to real-time market data. marketDataType:

1 -> realtime streaming market data
2 -> frozen market data
3 -> delayed market data
4 -> delayed frozen market data

func (*IB) ReqMarketRule

func (ib *IB) ReqMarketRule(marketRuleID int64) ([]PriceIncrement, error)

ReqMarketRule requests the price increments rules.

Note: market rule ids can be obtained by invoking reqContractDetails on a particular contract

func (*IB) ReqMatchingSymbols

func (ib *IB) ReqMatchingSymbols(pattern string) ([]ContractDescription, error)

ReqMatchingSymbols requests matching symbols.

func (*IB) ReqMktData

func (ib *IB) ReqMktData(contract *Contract, genericTickList string, mktDataOptions ...TagValue) *Ticker

ReqMktData request market data stream. It returns a *Ticker that will be updated.

contract contains a description of the Contract for which market data is being requested. genericTickList is a commma delimited list of generic tick types. Tick types can be found in the Generic Tick Types page. Prefixing w/ 'mdoff' indicates that top mkt data shouldn't tick. You can specify the news source by postfixing w/ ':<source>. Example: "mdoff,292:FLY+BRF" For snapshots requests use Snapshot(). mktDataOptions is for internal use only.Use default value XYZ.

func (*IB) ReqMktDepth

func (ib *IB) ReqMktDepth(contract *Contract, numRows int, isSmartDepth bool, mktDepthOptions ...TagValue) (*Ticker, error)

ReqMktDepth requests the market depth for a specific contract.

Requests the contract's market depth (order book). Note this request must be direct-routed to an exchange and not smart-routed. The number of simultaneous market depth requests allowed in an account is calculated based on a formula that looks at an accounts equity, commissions, and quote booster packs. contract contains a description of the contract for which market depth data is being requested. numRows specifies the numRowsumber of market depth rows to display. isSmartDepth if true consolidates order book across exchanges. mktDepthOptions is for internal use only. Use default value XYZ.

func (*IB) ReqMktDepthExchanges

func (ib *IB) ReqMktDepthExchanges() ([]DepthMktDataDescription, error)

ReqMktDepthExchanges requests market depth exchanges.

func (*IB) ReqNewsArticle

func (ib *IB) ReqNewsArticle(providerCode string, articleID string, newsArticleOptions ...TagValue) (*NewsArticle, error)

ReqNewsArticle gets the body of a news article. providerCode: Code indicating news provider, like 'BZ' or 'FLY'. articleId: ID of the specific article. You can get it from ReqHistoricalNews

func (*IB) ReqNewsBulletins

func (ib *IB) ReqNewsBulletins(allMsgs bool)

ReqNewsBulletins requests and subscribes to news bulletins from the IB API.

If allMsgs is set to true, it returns all existing bulletins for the current day as well as any new ones. If allMsgs is set to false, it only returns new bulletins. This method initiates the feed of news bulletins from the IB API.

func (*IB) ReqNewsProviders

func (ib *IB) ReqNewsProviders() ([]NewsProvider, error)

ReqNewsProviders requests a slice of news providers.

func (*IB) ReqOpenOrders

func (ib *IB) ReqOpenOrders() error

ReqOpenOrders requests the open orders that were placed from this client. The client with a clientId of 0 will also receive the TWS-owned open orders. These orders will be associated with the client and a new orderId will be generated. This association will persist over multiple API and TWS sessions.

func (*IB) ReqPnL

func (ib *IB) ReqPnL(account string, modelCode string)

ReqPnL requests and subscribe the PnL of assigned account.

func (*IB) ReqPnLSingle

func (ib *IB) ReqPnLSingle(account string, modelCode string, contractID int64)

ReqPnLSingle requests and subscribe the single contract PnL of assigned account.

func (*IB) ReqPositions

func (ib *IB) ReqPositions()

ReqPositions subscribes to real-time position stream for all accounts.

func (*IB) ReqPositionsMulti

func (ib *IB) ReqPositionsMulti(reqID int64, account string, modelCode string)

ReqPositionsMulti requests the positions for account and/or model. Results are delivered via EWrapper.positionMulti() and EWrapper.positionMultiEnd()

func (*IB) ReqRealTimeBars

func (ib *IB) ReqRealTimeBars(contract *Contract, barSize int, whatToShow string, useRTH bool, realTimeBarsOptions ...TagValue) (chan RealTimeBar, CancelFunc)

ReqRealTimeBars requests realtime bars and returns a channel of Bar. reqId, the ticker ID, must be a unique value. When the data is received, it will be identified by this Id. This is also used when canceling the request. contract contains a description of the contract for which real time bars are being requested barSize, Currently only supports 5 second bars, if any other value is used, an exception will be thrown. whatToShow determines the nature of the data extracted. Valid includes:

TRADES
BID
ASK
MIDPOINT

useRTH sets regular Trading Hours only. Valid values include:

0 = all data available during the time span requested is returned,
	including time intervals when the market in question was
	outside of regular trading hours.
1 = only data within the regular trading hours for the product
	requested is returned, even if the time time span falls
	partially or completely outside.

realTimeBarOptions is for internal use only. Use default value XYZ.

func (*IB) ReqScannerParameters

func (ib *IB) ReqScannerParameters() (xml string, err error)

ReqScannerParameters requests an XML string that describes all possible scanner queries.

func (*IB) ReqScannerSubscription

func (ib *IB) ReqScannerSubscription(subscription *ScannerSubscription, scannerSubscriptionOptions ...ScannerSubscriptionOptions) ([]ScanData, error)

ReqScannerSubscription subcribes a scanner that matched the subcription. scannerSubscription contains possible parameters used to filter results. scannerSubscriptionOptions, scannerSubscriptionOptions is for internal use only.Use default value XYZ.

func (*IB) ReqSecDefOptParams

func (ib *IB) ReqSecDefOptParams(underlyingSymbol string, futFopExchange string, underlyingSecurityType string, underlyingContractID int64) ([]OptionChain, error)

ReqSecDefOptParams requests security definition option parameters. futFopExchange is the exchange on which the returned options are trading. Can be set to the empty string "" for all exchanges. underlyingSecType is the type of the underlying security, i.e. STK. underlyingConId is the contract ID of the underlying security.

func (*IB) ReqSmartComponents

func (ib *IB) ReqSmartComponents(bboExchange string) ([]SmartComponent, error)

ReqSmartComponents requests the smartComponents.

SmartComponents provide mapping from single letter codes to exchange names. Note: The exchanges must be open when using this request, otherwise an empty list is returned.

func (*IB) ReqSoftDollarTiers

func (ib *IB) ReqSoftDollarTiers() ([]SoftDollarTier, error)

ReqSoftDollarTiers requests pre-defined Soft Dollar Tiers. This is only supported for registered professional advisors and hedge and mutual funds who have configured Soft Dollar Tiers in Account Management.

func (*IB) ReqTickByTickData

func (ib *IB) ReqTickByTickData(contract *Contract, tickType string, numberOfTicks int64, ignoreSize bool) *Ticker

ReqTickByTickData subscribe to tick-by-tick data stream and returns the *Ticker.

contract is the *Contract you want subsciption for. tickType is one of "Last", "AllLast", "BidAsk" or "MidPoint". numberOfTicks is the number of ticks or 0 for unlimited. ignoreSize ignores bid/ask ticks that only update the size. No more than one request can be made for the same instrument within 15 seconds.

func (*IB) ReqUserInfo

func (ib *IB) ReqUserInfo() (whiteBrandingId string, err error)

ReqUserInfo returns user white branding info with timeout and error handling.

func (*IB) ReqWshEventData

func (ib *IB) ReqWshEventData(wshEventData WshEventData) (dataJson string, err error)

ReqWshEventData requests Wall Street Horizon event data.

func (*IB) ReqWshMetaData

func (ib *IB) ReqWshMetaData() (dataJson string, err error)

ReqWshMetaData requests Wall Street Horizon Meta data

func (*IB) RequestFA

func (ib *IB) RequestFA(faDataType FaDataType) (cxml string, err error)

RequestFA requests fa. The data returns in an XML string via wrapper.ReceiveFA(). faData is 1->"GROUPS", 3->"ALIASES"

func (*IB) ServerVersion

func (ib *IB) ServerVersion() int

ServerVersion returns the version of the TWS instance to which the API application is connected.

func (*IB) SetClientLogLevel

func (ib *IB) SetClientLogLevel(logLevel int64)

SetClientLogLevel sets the log level of the client. logLevel can be: -1 = trace // zerolog.TraceLevel

0 = debug   // zerolog.DebugLevel
1 = info    // zerolog.InfoLevel
2 = warn    // zerolog.WarnLevel
3 = error   // zerolog.ErrorLevel
4 = fatal   // zerolog.FatalLevel
5 = panic   // zerolog.PanicLevel

func (*IB) SetConsoleWriter

func (in *IB) SetConsoleWriter()

SetConsoleWriter will set pretty log to the console.

func (*IB) SetLogLevel

func (ib *IB) SetLogLevel(logLevel int64)

SetServerLogLevel setups the log level of server. The default detail level is ERROR. For more details, see API Logging.

func (*IB) SetServerLogLevel

func (ib *IB) SetServerLogLevel(logLevel int64)

SetServerLogLevel sets the log level of the server. logLevel can be: 1 = SYSTEM 2 = ERROR (default) 3 = WARNING 4 = INFORMATION 5 = DETAIL

func (*IB) SetTimeout

func (ib *IB) SetTimeout(Timeout time.Duration)

SetTimeout sets the timeout for receiving messages from TWS/IBG. Default timeout duration is TIMEOUT = 30 * time.Second

func (*IB) Snapshot

func (ib *IB) Snapshot(contract *Contract, regulatorySnapshot ...bool) (*Ticker, error)

Snapshot return a market data snapshot.

contract contains a description of the Contract for which market data is being requested. regulatorySnapshot: With the US Value Snapshot Bundle for stocks, regulatory snapshots are available for 0.01 USD each.

func (*IB) SubscribeToGroupEvents

func (ib *IB) SubscribeToGroupEvents(reqID int64, groupID int)

SubscribeToGroupEvents subcribes the group events. reqId is the unique number associated with the notification. groupId is the ID of the group, currently it is a number from 1 to 7.

func (*IB) TWSConnectionTime

func (ib *IB) TWSConnectionTime() string

ConnectionTime is the time the API application made a connection to TWS.

func (*IB) Ticker

func (ib *IB) Ticker(contract *Contract) (*Ticker, bool)

Ticker returns a *Ticker for the provided and contract and a bool to tell if the ticker exists.

func (*IB) Tickers

func (ib *IB) Tickers() []*Ticker

Tickers returns a slice of all Tickers

func (*IB) Trades

func (ib *IB) Trades() []*Trade

Trades returns a slice of all trades from this session

func (*IB) UnsubscribeFromGroupEvents

func (ib *IB) UnsubscribeFromGroupEvents(reqID int64)

UnsubscribeFromGroupEvents unsubcribes the display group events.

func (*IB) UpdateDisplayGroup

func (ib *IB) UpdateDisplayGroup(reqID int64, contractInfo string)

UpdateDisplayGroup updates the display group in TWS. reqId is the requestId specified in subscribeToGroupEvents(). contractInfo is the encoded value that uniquely represents the contract in IB. Possible values include:

none = empty selection
contractID@exchange - any non-combination contract.
	Examples: 8314@SMART for IBM SMART; 8314@ARCA for IBM @ARCA.
combo = if any combo is selected.

type IneligibilityReason

type IneligibilityReason = ibapi.IneligibilityReason

type MktDepthData

type MktDepthData struct {
	Time         time.Time
	Position     int64
	MarketMaker  string
	Operation    int64
	Side         int64
	Price        float64
	Size         Decimal
	IsSmartDepth bool
}

type NewsArticle

type NewsArticle struct {
	ArticleType int64
	ArticleText string
}

type NewsBulletin

type NewsBulletin struct {
	MsgID       int64
	MsgType     int64
	NewsMessage string
	OriginExch  string
}

type NewsProvider

type NewsProvider = ibapi.NewsProvider

type NewsTick

type NewsTick struct {
	TimeStamp    int64
	ProviderCode string
	ArticleId    string
	Headline     string
	ExtraData    string
}

type OptionChain

type OptionChain struct {
	Exchange        string
	UnderlyingConId int64
	TradingClass    string
	Multiplier      string
	Expirations     []string
	Strikes         []float64
}

type Order

type Order = ibapi.Order

type OrderCancel

type OrderCancel = ibapi.OrderCancel

type OrderID

type OrderID = ibapi.OrderID

type OrderState

type OrderState = ibapi.OrderState

type OrderStatus

type OrderStatus struct {
	OrderID       int64   // Unique identifier for the order
	Status        Status  // Current status of the order
	Filled        Decimal // Amount of order that has been filled
	Remaining     Decimal // Amount of order remaining to be filled
	AvgFillPrice  float64 // Average price of filled portions
	PermID        int64   // Permanent ID assigned by IB
	ParentID      int64   // ID of parent order if this is a child order
	LastFillPrice float64 // Price of the last fill
	ClientID      int64   // Client identifier
	WhyHeld       string  // Reason why order is being held
	MktCapPrice   float64 // Market cap price
}

OrderStatus represents the current state and details of an order.

func (OrderStatus) IsActive

func (os OrderStatus) IsActive() bool

IsActive returns true if the order status indicates an active order.

func (OrderStatus) IsDone

func (os OrderStatus) IsDone() bool

IsDone returns true if the order status indicates the order has reached a terminal state.

type Pnl

type Pnl struct {
	Account       string
	ModelCode     string
	DailyPNL      float64
	UnrealizedPnl float64
	RealizedPNL   float64
}

type PnlSingle

type PnlSingle struct {
	Account       string
	ModelCode     string
	ConID         int64
	Position      Decimal
	DailyPNL      float64
	UnrealizedPnl float64
	RealizedPNL   float64
	Value         float64
}

type PortfolioItem

type PortfolioItem struct {
	Contract      *Contract
	Position      Decimal
	MarketPrice   float64
	MarketValue   float64
	AverageCost   float64
	UnrealizedPNL float64
	RealizedPNL   float64
	Account       string
}

type Position

type Position struct {
	Account  string
	Contract *Contract
	Position Decimal
	AvgCost  float64
}

type PriceIncrement

type PriceIncrement = ibapi.PriceIncrement

type PubSub

type PubSub struct {
	// contains filtered or unexported fields
}

PubSub is a thread-safe publish-subscribe implementation. It manages topic subscriptions and message distribution.

func NewPubSub

func NewPubSub() *PubSub

NewPubSub creates and initializes a new PubSub instance.

func (*PubSub) Publish

func (ps *PubSub) Publish(topic any, msg string)

Publish sends a message to all subscribers of a topic.

func (*PubSub) Subscribe

func (ps *PubSub) Subscribe(topic any, size ...int) (<-chan string, UnsubscribeFunc)

Subscribe creates a new subscriber for a topic and returns a channel to receive messages. It supports optional buffer size specification.

func (*PubSub) Unsubscribe

func (ps *PubSub) Unsubscribe(topic any, subscriberChan <-chan string)

Unsubscribe removes a specific subscriber channel from a topic. It closes the channel and removes the topic if no subscribers remain.

func (*PubSub) UnsubscribeAll

func (ps *PubSub) UnsubscribeAll(topic any)

UnsubscribeAll removes all subscribers from a topic. It closes all subscriber channels and deletes the topic from the topics map.

type RealTimeBar

type RealTimeBar = ibapi.RealTimeBar

type ReceiveFA

type ReceiveFA struct {
	FaDataType FaDataType
	Cxml       string
}

type ScanData

type ScanData = ibapi.ScanData

type ScannerSubscription

type ScannerSubscription = ibapi.ScannerSubscription

type ScannerSubscriptionOptions

type ScannerSubscriptionOptions struct {
	Options       []TagValue
	FilterOptions []TagValue
}

type SmartComponent

type SmartComponent = ibapi.SmartComponent

type SoftDollarTier

type SoftDollarTier = ibapi.SoftDollarTier

type Status

type Status string

Status represents the current state of an order in the trading system.

const (
	PendingSubmit Status = "PendingSubmit" // Order is pending submission to IB
	PendingCancel Status = "PendingCancel" // Order cancellation is pending
	PreSubmitted  Status = "PreSubmitted"  // Order has been sent but not yet confirmed
	Submitted     Status = "Submitted"     // Order has been submitted to IB
	ApiPending    Status = "ApiPending"    // Order is pending processing by the API
	ApiCancelled  Status = "ApiCancelled"  // Order was cancelled through the API
	Cancelled     Status = "Cancelled"     // Order has been cancelled
	Filled        Status = "Filled"        // Order has been completely filled
	Inactive      Status = "Inactive"      // Order is inactive
)

Order status constants define all possible states an order can be in.

func (Status) IsActive

func (s Status) IsActive() bool

IsActive returns true if the status indicates the order is still active in the market.

func (Status) IsDone

func (s Status) IsDone() bool

IsDone returns true if the status indicates the order has reached a terminal state.

type TagValue

type TagValue = ibapi.TagValue

type Tick

type Tick interface {
	Type() TickType
	String() string
}

type TickAttrib

type TickAttrib = ibapi.TickAttrib

type TickAttribBidAsk

type TickAttribBidAsk = ibapi.TickAttribBidAsk

type TickAttribLast

type TickAttribLast = ibapi.TickAttribLast

type TickByTick

type TickByTick interface {
	Timestamp() time.Time
	String() string
}

TickByTick

type TickByTickAllLast

type TickByTickAllLast struct {
	Time              int64
	TickType          int64
	Price             float64
	Size              Decimal
	TickAttribLast    TickAttribLast
	Exchange          string
	SpecialConditions string
}

func (TickByTickAllLast) String

func (t TickByTickAllLast) String() string

func (TickByTickAllLast) Timestamp

func (t TickByTickAllLast) Timestamp() time.Time

type TickByTickBidAsk

type TickByTickBidAsk struct {
	Time             int64
	BidPrice         float64
	AskPrice         float64
	BidSize          Decimal
	AskSize          Decimal
	TickAttribBidAsk TickAttribBidAsk
}

func (TickByTickBidAsk) String

func (t TickByTickBidAsk) String() string

func (TickByTickBidAsk) Timestamp

func (t TickByTickBidAsk) Timestamp() time.Time

type TickByTickMidPoint

type TickByTickMidPoint struct {
	Time     int64
	MidPoint float64
}

func (TickByTickMidPoint) String

func (t TickByTickMidPoint) String() string

func (TickByTickMidPoint) Timestamp

func (t TickByTickMidPoint) Timestamp() time.Time

type TickData

type TickData struct {
	Time     time.Time
	TickType TickType
	Price    float64
	Size     Decimal
}

type TickEFP

type TickEFP struct {
	TickType                 TickType
	BasisPoints              float64
	FormattedBasisPoints     string
	TotalDividends           float64
	HoldDays                 int64
	FutureLastTradeDate      string
	DividendImpact           float64
	DividendsToLastTradeDate float64
}

func (TickEFP) String

func (t TickEFP) String() string

func (TickEFP) Type

func (t TickEFP) Type() TickType

type TickGeneric

type TickGeneric struct {
	TickType TickType
	Value    float64
}

func (TickGeneric) String

func (t TickGeneric) String() string

func (TickGeneric) Type

func (t TickGeneric) Type() TickType

type TickOptionComputation

type TickOptionComputation struct {
	TickType   TickType
	TickAttrib int64
	ImpliedVol float64
	Delta      float64
	OptPrice   float64
	PvDividend float64
	Gamma      float64
	Vega       float64
	Theta      float64
	UndPrice   float64
}

func (TickOptionComputation) String

func (t TickOptionComputation) String() string

func (TickOptionComputation) Type

type TickPrice

type TickPrice struct {
	TickType TickType
	Price    float64
	Attrib   TickAttrib
}

func (TickPrice) String

func (t TickPrice) String() string

func (TickPrice) Type

func (t TickPrice) Type() TickType

type TickSize

type TickSize struct {
	TickType TickType
	Size     Decimal
}

func (TickSize) String

func (t TickSize) String() string

func (TickSize) Type

func (t TickSize) Type() TickType

type TickString

type TickString struct {
	TickType TickType
	Value    string
}

func (TickString) String

func (t TickString) String() string

func (TickString) Type

func (t TickString) Type() TickType

type TickType

type TickType = ibapi.TickType

type Ticker

type Ticker struct {
	// contains filtered or unexported fields
}

Ticker represents real-time market data for a financial contract.

The Ticker struct captures comprehensive market information including: - Current price data (bid, ask, last price) - Historical price metrics (open, high, low, close) - Trading volume and statistics - Volatility indicators - Options-specific data like greeks

Thread-safe access is provided through mutex-protected getter methods.

Market Data Types: - Level 1 streaming ticks stored in 'ticks' - Level 2 market depth ticks stored in 'domTicks' - Order book (DOM) available in 'domBids' and 'domAsks' - Tick-by-tick data stored in 'tickByTicks'

Options Greeks: - Bid, ask, and last greeks stored in 'bidGreeks', 'askGreeks', and 'lastGreeks' - Model-calculated greeks available in 'modelGreeks'

func NewTicker

func NewTicker(contract *Contract) *Ticker

NewTicker creates a new Ticker instance for the given contract.

func (*Ticker) Ask

func (t *Ticker) Ask() float64

func (*Ticker) AskExchange

func (t *Ticker) AskExchange() string

func (*Ticker) AskGreeks

func (t *Ticker) AskGreeks() TickOptionComputation

func (*Ticker) AskSize

func (t *Ticker) AskSize() Decimal

func (*Ticker) AskYield

func (t *Ticker) AskYield() float64

func (*Ticker) AuctionImbalance

func (t *Ticker) AuctionImbalance() Decimal

func (*Ticker) AuctionPrice

func (t *Ticker) AuctionPrice() float64

func (*Ticker) AuctionVolume

func (t *Ticker) AuctionVolume() Decimal

func (*Ticker) AvOptionVolume

func (t *Ticker) AvOptionVolume() Decimal

func (*Ticker) AvVolume

func (t *Ticker) AvVolume() Decimal

func (*Ticker) BboExchange

func (t *Ticker) BboExchange() string

func (*Ticker) Bid

func (t *Ticker) Bid() float64

func (*Ticker) BidExchange

func (t *Ticker) BidExchange() string

func (*Ticker) BidGreeks

func (t *Ticker) BidGreeks() TickOptionComputation

func (*Ticker) BidSize

func (t *Ticker) BidSize() Decimal

func (*Ticker) BidYield

func (t *Ticker) BidYield() float64

func (*Ticker) CallOpenInterest

func (t *Ticker) CallOpenInterest() Decimal

func (*Ticker) CallVolume

func (t *Ticker) CallVolume() Decimal

func (*Ticker) Close

func (t *Ticker) Close() float64

func (*Ticker) Contract

func (t *Ticker) Contract() *Contract

Contract returns the financial contract associated with this Ticker.

func (*Ticker) Dividends

func (t *Ticker) Dividends() Dividends

func (*Ticker) DomAsks

func (t *Ticker) DomAsks() []DOMLevel

func (*Ticker) DomBids

func (t *Ticker) DomBids() []DOMLevel

func (*Ticker) DomTicks

func (t *Ticker) DomTicks() []MktDepthData

func (*Ticker) FundamentalRatios

func (t *Ticker) FundamentalRatios() FundamentalRatios

func (*Ticker) FuturesOpenInterest

func (t *Ticker) FuturesOpenInterest() Decimal

func (*Ticker) Greeks

func (t *Ticker) Greeks() TickOptionComputation

Greeks returns the most representative option Greeks.

Selection priority: 1. Midpoint Greeks (average of bid and ask Greeks) 2. Last trade Greeks 3. Model-calculated Greeks

func (*Ticker) Halted

func (t *Ticker) Halted() float64

func (*Ticker) HasBidAsk

func (t *Ticker) HasBidAsk() bool

func (*Ticker) High

func (t *Ticker) High() float64

func (*Ticker) High13Week

func (t *Ticker) High13Week() float64

func (*Ticker) High26Week

func (t *Ticker) High26Week() float64

func (*Ticker) High52Week

func (t *Ticker) High52Week() float64

func (*Ticker) HistVolatility

func (t *Ticker) HistVolatility() float64

func (*Ticker) ImpliedVolatility

func (t *Ticker) ImpliedVolatility() float64

func (*Ticker) IndexFuturePremium

func (t *Ticker) IndexFuturePremium() float64

func (*Ticker) Last

func (t *Ticker) Last() float64

func (*Ticker) LastExchange

func (t *Ticker) LastExchange() string

func (*Ticker) LastGreeks

func (t *Ticker) LastGreeks() TickOptionComputation

func (*Ticker) LastSize

func (t *Ticker) LastSize() Decimal

Getters pour les autres champs

func (*Ticker) LastYield

func (t *Ticker) LastYield() float64

func (*Ticker) Low

func (t *Ticker) Low() float64

func (*Ticker) Low13Week

func (t *Ticker) Low13Week() float64

func (*Ticker) Low26Week

func (t *Ticker) Low26Week() float64

func (*Ticker) Low52Week

func (t *Ticker) Low52Week() float64

func (*Ticker) MarkPrice

func (t *Ticker) MarkPrice() float64

func (*Ticker) MarketDataType

func (t *Ticker) MarketDataType() int64

func (*Ticker) MarketPrice

func (t *Ticker) MarketPrice() float64

MarketPrice determines the most appropriate current market price.

Price selection priority: 1. If last price is within the bid-ask spread, use last price. 2. If no last price fits the spread, use midpoint (average of bid and ask). 3. If no bid-ask available, return last price.

func (*Ticker) MidGreeks

func (t *Ticker) MidGreeks() TickOptionComputation

func (*Ticker) MidPoint

func (t *Ticker) MidPoint() float64

MidPoint calculates the average of the current bid and ask prices.

func (*Ticker) MinTick

func (t *Ticker) MinTick() float64

func (*Ticker) ModelGreeks

func (t *Ticker) ModelGreeks() TickOptionComputation

func (*Ticker) Open

func (t *Ticker) Open() float64

func (*Ticker) PrevAsk

func (t *Ticker) PrevAsk() float64

func (*Ticker) PrevAskSize

func (t *Ticker) PrevAskSize() Decimal

func (*Ticker) PrevBid

func (t *Ticker) PrevBid() float64

func (*Ticker) PrevBidSize

func (t *Ticker) PrevBidSize() Decimal

func (*Ticker) PrevLast

func (t *Ticker) PrevLast() float64

func (*Ticker) PrevLastSize

func (t *Ticker) PrevLastSize() Decimal

func (*Ticker) PutOpenInterest

func (t *Ticker) PutOpenInterest() Decimal

func (*Ticker) PutVolume

func (t *Ticker) PutVolume() Decimal

func (*Ticker) RegulatoryImbalance

func (t *Ticker) RegulatoryImbalance() Decimal

func (*Ticker) RtHistVolatility

func (t *Ticker) RtHistVolatility() float64

func (*Ticker) RtTime

func (t *Ticker) RtTime() time.Time

func (*Ticker) RtTradeVolume

func (t *Ticker) RtTradeVolume() float64

func (*Ticker) RtVolume

func (t *Ticker) RtVolume() float64

func (*Ticker) SetTickByTickAllLast

func (t *Ticker) SetTickByTickAllLast(tbt TickByTickAllLast)

func (*Ticker) SetTickByTickBidAsk

func (t *Ticker) SetTickByTickBidAsk(tbt TickByTickBidAsk)

func (*Ticker) SetTickByTickMidPoint

func (t *Ticker) SetTickByTickMidPoint(tbt TickByTickMidPoint)

func (*Ticker) SetTickEFP

func (t *Ticker) SetTickEFP(te TickEFP)

func (*Ticker) SetTickGeneric

func (t *Ticker) SetTickGeneric(tg TickGeneric)

func (*Ticker) SetTickOptionComputation

func (t *Ticker) SetTickOptionComputation(toc TickOptionComputation)

func (*Ticker) SetTickPrice

func (t *Ticker) SetTickPrice(tp TickPrice)

func (*Ticker) SetTickSize

func (t *Ticker) SetTickSize(ts TickSize)

func (*Ticker) SetTickString

func (t *Ticker) SetTickString(ts TickString)

func (*Ticker) ShortableShares

func (t *Ticker) ShortableShares() Decimal

func (*Ticker) SnapshotPermissions

func (t *Ticker) SnapshotPermissions() int64

func (*Ticker) String

func (t *Ticker) String() string

func (*Ticker) TickByTicks

func (t *Ticker) TickByTicks() []TickByTick

func (*Ticker) Ticks

func (t *Ticker) Ticks() []TickData

func (*Ticker) Time

func (t *Ticker) Time() time.Time

func (*Ticker) TradeCount

func (t *Ticker) TradeCount() float64

func (*Ticker) TradeRate

func (t *Ticker) TradeRate() float64

func (*Ticker) Volume

func (t *Ticker) Volume() Decimal

func (*Ticker) VolumeRate

func (t *Ticker) VolumeRate() float64

func (*Ticker) Vwap

func (t *Ticker) Vwap() float64

type TickerID

type TickerID = ibapi.TickerID

type Trade

type Trade struct {
	Contract    *Contract
	Order       *Order
	OrderStatus OrderStatus
	// contains filtered or unexported fields
}

Trade represents a complete trading operation, including the contract, order details, current status, and execution fills.

func NewTrade

func NewTrade(contract *Contract, order *Order, orderStatus ...OrderStatus) *Trade

NewTrade creates a new Trade instance with the specified contract and order details. Optional initial order status can be provided.

func (*Trade) Done

func (t *Trade) Done() <-chan struct{}

Done returns a channel that will be closed when the trade reaches a terminal state.

func (*Trade) Equal

func (t *Trade) Equal(other *Trade) bool

func (*Trade) Fills

func (t *Trade) Fills() []*Fill

Fills returns a copy of all fills for this trade

func (*Trade) IsActive

func (t *Trade) IsActive() bool

IsActive returns true if the trade is currently active in the market.

func (*Trade) IsDone

func (t *Trade) IsDone() bool

IsDone returns true if the trade has reached a terminal state.

func (*Trade) Logs

func (t *Trade) Logs() []TradeLogEntry

Logs returns a copy of all log entries for this trade

func (*Trade) String

func (t *Trade) String() string

type TradeLogEntry

type TradeLogEntry struct {
	Time      time.Time // Timestamp of the log entry
	Status    Status    // Status at the time of the log entry
	Message   string    // Descriptive message about the event
	ErrorCode int64     // Error code if applicable
}

TradeLogEntry represents a single entry in the trade's log, recording status changes and other significant events.

type UnsubscribeFunc

type UnsubscribeFunc func()

UnsubscribeFunc is a function type that can be used to unsubscribe from a topic.

type WrapperSync

type WrapperSync struct {
	// contains filtered or unexported fields
}

func NewWrapperSync

func NewWrapperSync(state *ibState, pubSub *PubSub) *WrapperSync

NewWrapperSync implements the ibapi EWrapper

func (*WrapperSync) AccountDownloadEnd

func (w *WrapperSync) AccountDownloadEnd(accountName string)

func (*WrapperSync) AccountSummary

func (w *WrapperSync) AccountSummary(reqID int64, account string, tag string, value string, currency string)

func (*WrapperSync) AccountSummaryEnd

func (w *WrapperSync) AccountSummaryEnd(reqID int64)

func (*WrapperSync) AccountUpdateMulti

func (w *WrapperSync) AccountUpdateMulti(reqID int64, account string, modelCode string, key string, value string, currency string)

func (*WrapperSync) AccountUpdateMultiEnd

func (w *WrapperSync) AccountUpdateMultiEnd(reqID int64)

func (*WrapperSync) BondContractDetails

func (w *WrapperSync) BondContractDetails(reqID int64, contractDetails *ContractDetails)

func (*WrapperSync) CommissionAndFeesReport

func (w *WrapperSync) CommissionAndFeesReport(commissionAndFeesReport CommissionAndFeesReport)

func (*WrapperSync) CompletedOrder

func (w *WrapperSync) CompletedOrder(contract *Contract, order *Order, orderState *OrderState)

func (WrapperSync) CompletedOrdersEnd

func (w WrapperSync) CompletedOrdersEnd()

func (*WrapperSync) ConnectAck

func (w *WrapperSync) ConnectAck()

func (*WrapperSync) ConnectionClosed

func (w *WrapperSync) ConnectionClosed()

func (*WrapperSync) ContractDetails

func (w *WrapperSync) ContractDetails(reqID int64, contractDetails *ContractDetails)

func (*WrapperSync) ContractDetailsEnd

func (w *WrapperSync) ContractDetailsEnd(reqID int64)

func (*WrapperSync) CurrentTime

func (w *WrapperSync) CurrentTime(t int64)

func (WrapperSync) CurrentTimeInMillis

func (w WrapperSync) CurrentTimeInMillis(timeInMillis int64)

func (*WrapperSync) DeltaNeutralValidation

func (w *WrapperSync) DeltaNeutralValidation(reqID int64, deltaNeutralContract DeltaNeutralContract)

func (*WrapperSync) DisplayGroupList

func (w *WrapperSync) DisplayGroupList(reqID int64, groups string)

func (*WrapperSync) DisplayGroupUpdated

func (w *WrapperSync) DisplayGroupUpdated(reqID int64, contractInfo string)

func (*WrapperSync) Error

func (w *WrapperSync) Error(reqID TickerID, errorTime int64, errCode int64, errString string, advancedOrderRejectJson string)

func (WrapperSync) ErrorProtoBuf added in v0.10.37

func (w WrapperSync) ErrorProtoBuf(errorProto *protobuf.ErrorMessage)

func (*WrapperSync) ExecDetails

func (w *WrapperSync) ExecDetails(reqID int64, contract *Contract, execution *Execution)

func (*WrapperSync) ExecDetailsEnd

func (w *WrapperSync) ExecDetailsEnd(reqID int64)

func (WrapperSync) ExecDetailsEndProtoBuf added in v0.10.37

func (w WrapperSync) ExecDetailsEndProtoBuf(executionDetailsEndProto *protobuf.ExecutionDetailsEnd)

func (WrapperSync) ExecDetailsProtoBuf added in v0.10.37

func (w WrapperSync) ExecDetailsProtoBuf(executionDetailsProto *protobuf.ExecutionDetails)

func (*WrapperSync) FamilyCodes

func (w *WrapperSync) FamilyCodes(familyCodes []FamilyCode)

func (*WrapperSync) FundamentalData

func (w *WrapperSync) FundamentalData(reqID int64, data string)

func (*WrapperSync) HeadTimestamp

func (w *WrapperSync) HeadTimestamp(reqID int64, headTimestamp string)

func (*WrapperSync) HistogramData

func (w *WrapperSync) HistogramData(reqID int64, data []HistogramData)

func (*WrapperSync) HistoricalData

func (w *WrapperSync) HistoricalData(reqID int64, bar *Bar)

func (*WrapperSync) HistoricalDataEnd

func (w *WrapperSync) HistoricalDataEnd(reqID int64, startDateStr string, endDateStr string)

func (*WrapperSync) HistoricalDataUpdate

func (w *WrapperSync) HistoricalDataUpdate(reqID int64, bar *Bar)

func (*WrapperSync) HistoricalNews

func (w *WrapperSync) HistoricalNews(requestID int64, time string, providerCode string, articleID string, headline string)

func (*WrapperSync) HistoricalNewsEnd

func (w *WrapperSync) HistoricalNewsEnd(requestID int64, hasMore bool)

func (*WrapperSync) HistoricalSchedule

func (w *WrapperSync) HistoricalSchedule(reqID int64, startDarteTime, endDateTime, timeZone string, sessions []HistoricalSession)

func (*WrapperSync) HistoricalTicks

func (w *WrapperSync) HistoricalTicks(reqID int64, ticks []HistoricalTick, done bool)

func (*WrapperSync) HistoricalTicksBidAsk

func (w *WrapperSync) HistoricalTicksBidAsk(reqID int64, ticks []HistoricalTickBidAsk, done bool)

func (*WrapperSync) HistoricalTicksLast

func (w *WrapperSync) HistoricalTicksLast(reqID int64, ticks []HistoricalTickLast, done bool)

func (*WrapperSync) ManagedAccounts

func (w *WrapperSync) ManagedAccounts(accountsList []string)

func (*WrapperSync) MarketDataType

func (w *WrapperSync) MarketDataType(reqID int64, marketDataType int64)

func (*WrapperSync) MarketRule

func (w *WrapperSync) MarketRule(marketRuleID int64, priceIncrements []PriceIncrement)

func (*WrapperSync) MktDepthExchanges

func (w *WrapperSync) MktDepthExchanges(depthMktDataDescriptions []DepthMktDataDescription)

func (*WrapperSync) NewsArticle

func (w *WrapperSync) NewsArticle(requestID int64, articleType int64, articleText string)

func (*WrapperSync) NewsProviders

func (w *WrapperSync) NewsProviders(newsProviders []NewsProvider)

func (*WrapperSync) NextValidID

func (w *WrapperSync) NextValidID(reqID int64)

func (*WrapperSync) OpenOrder

func (w *WrapperSync) OpenOrder(orderID OrderID, contract *Contract, order *Order, orderState *OrderState)

func (*WrapperSync) OpenOrderEnd

func (w *WrapperSync) OpenOrderEnd()

func (WrapperSync) OpenOrderProtoBuf added in v0.10.37

func (w WrapperSync) OpenOrderProtoBuf(openOrderProto *protobuf.OpenOrder)

func (WrapperSync) OpenOrdersEndProtoBuf added in v0.10.37

func (w WrapperSync) OpenOrdersEndProtoBuf(openOrdersEndProto *protobuf.OpenOrdersEnd)

func (*WrapperSync) OrderBound

func (w *WrapperSync) OrderBound(permID int64, clientID int64, orderID int64)

func (*WrapperSync) OrderStatus

func (w *WrapperSync) OrderStatus(orderID OrderID, status string, filled Decimal, remaining Decimal, avgFillPrice float64, permID int64, parentID int64, lastFillPrice float64, clientID int64, whyHeld string, mktCapPrice float64)

func (WrapperSync) OrderStatusProtoBuf added in v0.10.37

func (w WrapperSync) OrderStatusProtoBuf(orderStatusProto *protobuf.OrderStatus)

func (*WrapperSync) Pnl

func (w *WrapperSync) Pnl(reqID int64, dailyPnL float64, unrealizedPnL float64, realizedPnL float64)

func (*WrapperSync) PnlSingle

func (w *WrapperSync) PnlSingle(reqID int64, pos Decimal, dailyPnL float64, unrealizedPnL float64, realizedPnL float64, value float64)

func (*WrapperSync) Position

func (w *WrapperSync) Position(account string, contract *Contract, position Decimal, avgCost float64)

func (*WrapperSync) PositionEnd

func (w *WrapperSync) PositionEnd()

func (*WrapperSync) PositionMulti

func (w *WrapperSync) PositionMulti(reqID int64, account string, modelCode string, contract *Contract, pos Decimal, avgCost float64)

func (*WrapperSync) PositionMultiEnd

func (w *WrapperSync) PositionMultiEnd(reqID int64)

func (*WrapperSync) RealtimeBar

func (w *WrapperSync) RealtimeBar(reqID int64, time int64, open float64, high float64, low float64, close float64, volume Decimal, wap Decimal, count int64)

func (*WrapperSync) ReceiveFA

func (w *WrapperSync) ReceiveFA(faDataType FaDataType, cxml string)

func (WrapperSync) ReplaceFAEnd

func (w WrapperSync) ReplaceFAEnd(reqID int64, text string)

func (*WrapperSync) RerouteMktDataReq

func (w *WrapperSync) RerouteMktDataReq(reqID int64, conID int64, exchange string)

func (*WrapperSync) RerouteMktDepthReq

func (w *WrapperSync) RerouteMktDepthReq(reqID int64, conID int64, exchange string)

func (*WrapperSync) ScannerData

func (w *WrapperSync) ScannerData(reqID int64, rank int64, contractDetails *ContractDetails, distance string, benchmark string, projection string, legsStr string)

func (*WrapperSync) ScannerDataEnd

func (w *WrapperSync) ScannerDataEnd(reqID int64)

func (*WrapperSync) ScannerParameters

func (w *WrapperSync) ScannerParameters(xml string)

func (*WrapperSync) SecurityDefinitionOptionParameter

func (w *WrapperSync) SecurityDefinitionOptionParameter(reqID int64, exchange string, underlyingConID int64, tradingClass string, multiplier string, expirations []string, strikes []float64)

func (*WrapperSync) SecurityDefinitionOptionParameterEnd

func (w *WrapperSync) SecurityDefinitionOptionParameterEnd(reqID int64)

func (*WrapperSync) SmartComponents

func (w *WrapperSync) SmartComponents(reqID int64, smartComponents []SmartComponent)

func (*WrapperSync) SoftDollarTiers

func (w *WrapperSync) SoftDollarTiers(reqID int64, tiers []SoftDollarTier)

func (*WrapperSync) SymbolSamples

func (w *WrapperSync) SymbolSamples(reqID int64, contractDescriptions []ContractDescription)

func (*WrapperSync) TickByTickAllLast

func (w *WrapperSync) TickByTickAllLast(reqID int64, tickType int64, time int64, price float64, size Decimal, tickAttribLast TickAttribLast, exchange string, specialConditions string)

func (*WrapperSync) TickByTickBidAsk

func (w *WrapperSync) TickByTickBidAsk(reqID int64, time int64, bidPrice float64, askPrice float64, bidSize Decimal, askSize Decimal, tickAttribBidAsk TickAttribBidAsk)

func (*WrapperSync) TickByTickMidPoint

func (w *WrapperSync) TickByTickMidPoint(reqID int64, time int64, midPoint float64)

func (*WrapperSync) TickEFP

func (w *WrapperSync) TickEFP(reqID TickerID, tickType TickType, basisPoints float64, formattedBasisPoints string, totalDividends float64, holdDays int64, futureLastTradeDate string, dividendImpact float64, dividendsToLastTradeDate float64)

func (*WrapperSync) TickGeneric

func (w *WrapperSync) TickGeneric(reqID TickerID, tickType TickType, value float64)

func (*WrapperSync) TickNews

func (w *WrapperSync) TickNews(TickerID TickerID, timeStamp int64, providerCode string, articleID string, headline string, extraData string)

func (*WrapperSync) TickOptionComputation

func (w *WrapperSync) TickOptionComputation(reqID TickerID, tickType TickType, tickAttrib int64, impliedVol float64, delta float64, optPrice float64, pvDividend float64, gamma float64, vega float64, theta float64, undPrice float64)

func (*WrapperSync) TickPrice

func (w *WrapperSync) TickPrice(reqID TickerID, tickType TickType, price float64, attrib TickAttrib)

func (*WrapperSync) TickReqParams

func (w *WrapperSync) TickReqParams(tickerID TickerID, minTick float64, bboExchange string, snapshotPermissions int64)

func (*WrapperSync) TickSize

func (w *WrapperSync) TickSize(reqID TickerID, tickType TickType, size Decimal)

func (*WrapperSync) TickSnapshotEnd

func (w *WrapperSync) TickSnapshotEnd(reqID int64)

func (*WrapperSync) TickString

func (w *WrapperSync) TickString(reqID TickerID, tickType TickType, value string)

func (*WrapperSync) UpdateAccountTime

func (w *WrapperSync) UpdateAccountTime(timeStamp string)

func (*WrapperSync) UpdateAccountValue

func (w *WrapperSync) UpdateAccountValue(tag string, value string, currency string, accountName string)

func (*WrapperSync) UpdateMktDepth

func (w *WrapperSync) UpdateMktDepth(TickerID TickerID, position int64, operation int64, side int64, price float64, size Decimal)

func (*WrapperSync) UpdateMktDepthL2

func (w *WrapperSync) UpdateMktDepthL2(TickerID TickerID, position int64, marketMaker string, operation int64, side int64, price float64, size Decimal, isSmartDepth bool)

func (*WrapperSync) UpdateNewsBulletin

func (w *WrapperSync) UpdateNewsBulletin(msgID int64, msgType int64, newsMessage string, originExch string)

func (*WrapperSync) UpdatePortfolio

func (w *WrapperSync) UpdatePortfolio(contract *Contract, position Decimal, marketPrice float64, marketValue float64, averageCost float64, unrealizedPNL float64, realizedPNL float64, accountName string)

func (*WrapperSync) UserInfo

func (w *WrapperSync) UserInfo(reqID int64, whiteBrandingId string)

func (*WrapperSync) VerifyAndAuthCompleted

func (w *WrapperSync) VerifyAndAuthCompleted(isSuccessful bool, errorText string)

func (*WrapperSync) VerifyAndAuthMessageAPI

func (w *WrapperSync) VerifyAndAuthMessageAPI(apiData string, xyzChallange string)

func (*WrapperSync) VerifyCompleted

func (w *WrapperSync) VerifyCompleted(isSuccessful bool, errorText string)

func (*WrapperSync) VerifyMessageAPI

func (w *WrapperSync) VerifyMessageAPI(apiData string)

func (*WrapperSync) WinError

func (w *WrapperSync) WinError(text string, lastError int64)

func (*WrapperSync) WshEventData

func (w *WrapperSync) WshEventData(reqID int64, dataJson string)

func (*WrapperSync) WshMetaData

func (w *WrapperSync) WshMetaData(reqID int64, dataJson string)

type WshEventData

type WshEventData = ibapi.WshEventData

Directories

Path Synopsis
examples
basics
the basics file demonstrates the usage of the ibsync library for connecting to Interactive Brokers API and retrieving various financial account and market information.
the basics file demonstrates the usage of the ibsync library for connecting to Interactive Brokers API and retrieving various financial account and market information.
orders
This package demonstrates how to interact with ibsunc f for forex trading operations including placing, modifying, and canceling orders.
This package demonstrates how to interact with ibsunc f for forex trading operations including placing, modifying, and canceling orders.
pnl

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL