ibapi

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2022 License: MIT Imports: 16 Imported by: 0

README

Interactive Brokers API - GoLang Implement

  • Interactive Brokers API 9.80
  • pure golang Implement
  • Unofficial, use at you own risk

INSTALL

go get -u github.com/hadrianl/ibapi


USAGE

Implement IbWrapper to handle datas delivered via tws or gateway, Wrapper in demo is a default implement that just output data to std. Go to IbWrapper

  1. implement your own IbWrapper
  2. connect to TWS or Gateway
  3. handshake with TWS or Gateway
  4. run the loop
  5. do some request
Demo 1
import (
    . "github.com/hadrianl/ibapi"
    "time"
)

func main(){
    // internal api log is zap log, you could use GetLogger to get the logger
    // besides, you could use SetAPILogger to set you own log option
    // or you can just use the other logger  
    log := GetLogger().Sugar()
    defer log.Sync()
    // implement your own IbWrapper to handle the msg delivered via tws or gateway
    // Wrapper{} below is a default implement which just log the msg 
    ic := NewIbClient(&Wrapper{})

    // tcp connect with tws or gateway
    // fail if tws or gateway had not yet set the trust IP
    if err := ic.Connect("127.0.0.1", 4002, 0);err != nil {
        log.Panic("Connect failed:", err)
    }

    // handshake with tws or gateway, send handshake protocol to tell tws or gateway the version of client
    // and receive the server version and connection time from tws or gateway.
    // fail if someone else had already connected to tws or gateway with same clientID
    if err := ic.HandShake();err != nil {
        log.Panic("HandShake failed:", err)
    }

    // make some request, msg would be delivered via wrapper.
    // req will not send to TWS or Gateway until ic.Run()
    // you could just call ic.Run() before these
    ic.ReqCurrentTime()
    ic.ReqAutoOpenOrders(true)
    ic.ReqAccountUpdates(true, "")
    ic.ReqExecutions(ic.GetReqID(), ExecutionFilter{})

    // start to send req and receive msg from tws or gateway after this
    ic.Run()
    <-time.After(time.Second * 60)
    ic.Disconnect()
}

Demo 2 with context
import (
    . "github.com/hadrianl/ibapi"
    "time"
    "context"
)

func main(){
    var err error
    SetAPILogger(zap.NewDevelopmentConfig()) // log is default for production(json encode, info level), set to development(console encode, debug level) here
    log := GetLogger().Sugar()
    defer log.Sync()
    ibwrapper := &Wrapper{}
    ctx, _ := context.WithTimeout(context.Background(), time.Second*30)
    ic := NewIbClient(ibwrapper)
    ic.SetContext(ctx)
    err = ic.Connect("127.0.0.1", 4002, 0)
    if err != nil {
        log.Panic("Connect failed:", err)
    }

    err = ic.HandShake()
    if err != nil {
        log.Panic("HandShake failed:", err)
    }

    ic.ReqCurrentTime()
    ic.ReqAutoOpenOrders(true)
    ic.ReqAccountUpdates(true, "")
    ic.ReqExecutions(ic.GetReqID(), ExecutionFilter{})

    ic.Run()
    err = ic.LoopUntilDone()  // block until ctx or ic is done
    log.Info(err)
}


Reference

  1. Offical Document
  2. Order Types
  3. Product
  4. Margin
  5. Market Data
  6. Commissions

Documentation

Index

Constants

View Source
const (
	// MaxRequests is the max request that tws or gateway could take pre second.
	MaxRequests = 95
	// RequestInternal is the internal microseconds between requests.
	RequestInternal = 2
	// MaxClientVersion is the max client version that this implement could support.
	MaxClientVersion = 148
)
View Source
const (
	SAME_POS       ComboLegOpenClose     = 0
	OPEN_POS                             = 1
	CLOSE_POS                            = 2
	UNKNOWN_POS                          = 3
	ClearingBroker ComboLegShortSaleSlot = 1
	ThirdParty                           = 2
)
View Source
const (
	BID_SIZE = iota
	BID
	ASK
	ASK_SIZE
	LAST
	LAST_SIZE
	HIGH
	LOW
	VOLUME
	CLOSE
	BID_OPTION_COMPUTATION
	ASK_OPTION_COMPUTATION
	LAST_OPTION_COMPUTATION
	MODEL_OPTION
	OPEN
	LOW_13_WEEK
	HIGH_13_WEEK
	LOW_26_WEEK
	HIGH_26_WEEK
	LOW_52_WEEK
	HIGH_52_WEEK
	AVG_VOLUME
	OPEN_INTEREST
	OPTION_HISTORICAL_VOL
	OPTION_IMPLIED_VOL
	OPTION_BID_EXCH
	OPTION_ASK_EXCH
	OPTION_CALL_OPEN_INTEREST
	OPTION_PUT_OPEN_INTEREST
	OPTION_CALL_VOLUME
	OPTION_PUT_VOLUME
	INDEX_FUTURE_PREMIUM
	BID_EXCH
	ASK_EXCH
	AUCTION_VOLUME
	AUCTION_PRICE
	AUCTION_IMBALANCE
	MARK_PRICE
	BID_EFP_COMPUTATION
	ASK_EFP_COMPUTATION
	LAST_EFP_COMPUTATION
	OPEN_EFP_COMPUTATION
	HIGH_EFP_COMPUTATION
	LOW_EFP_COMPUTATION
	CLOSE_EFP_COMPUTATION
	LAST_TIMESTAMP
	SHORTABLE
	FUNDAMENTAL_RATIOS
	RT_VOLUME
	HALTED
	BID_YIELD
	ASK_YIELD
	LAST_YIELD
	CUST_OPTION_COMPUTATION
	TRADE_COUNT
	TRADE_RATE
	VOLUME_RATE
	LAST_RTH_TRADE
	RT_HISTORICAL_VOL
	IB_DIVIDENDS
	BOND_FACTOR_MULTIPLIER
	REGULATORY_IMBALANCE
	NEWS_TICK
	SHORT_TERM_VOLUME_3_MIN
	SHORT_TERM_VOLUME_5_MIN
	SHORT_TERM_VOLUME_10_MIN
	DELAYED_BID
	DELAYED_ASK
	DELAYED_LAST
	DELAYED_BID_SIZE
	DELAYED_ASK_SIZE
	DELAYED_LAST_SIZE
	DELAYED_HIGH
	DELAYED_LOW
	DELAYED_VOLUME
	DELAYED_CLOSE
	DELAYED_OPEN
	RT_TRD_VOLUME
	CREDITMAN_MARK_PRICE
	CREDITMAN_SLOW_MARK_PRICE
	DELAYED_BID_OPTION
	DELAYED_ASK_OPTION
	DELAYED_LAST_OPTION
	DELAYED_MODEL_OPTION
	LAST_EXCH
	LAST_REG_TIME
	FUTURES_OPEN_INTEREST
	AVG_OPT_VOLUME
	DELAYED_LAST_TIMESTAMP
	SHORTABLE_SHARES
	NOT_SET
)

tick const

View Source
const (
	DISCONNECTED = iota
	CONNECTING
	CONNECTED
	REDIRECT
)

ConnectionState

View Source
const (
	CUSTOMER int64 = iota
	FIRM
	UNKNOWN
)
View Source
const (
	AUCTION_UNSET int64 = iota
	AUCTION_MATCH
	AUCTION_IMPROVEMENT
	AUCTION_TRANSPARENT
)
View Source
const (

	// UNSETFLOAT represent unset value of float64.
	UNSETFLOAT float64 = math.MaxFloat64
	// UNSETINT represent unset value of int64.
	UNSETINT int64 = math.MaxInt64
	// NO_VALID_ID represent that the callback func of wrapper is not attached to any request.
	NO_VALID_ID int64 = -1
	// MAX_MSG_LEN is the max length that receiver could take.
	MAX_MSG_LEN int = 0xFFFFFF
)
View Source
const (
	TIME_FORMAT string = "2006-01-02 15:04:05 +0700 CST"
)

Variables

View Source
var (
	ALREADY_CONNECTED = IbError{501, "Already connected."}
	CONNECT_FAIL      = IbError{502, `Couldn't connect to TWS. Confirm that "Enable ActiveX and Socket EClients" 
	is enabled and connection port is the same as "Socket Port" on the 
	TWS "Edit->Global Configuration...->API->Settings" menu. Live Trading ports: 
	TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations 
	of version 954.1 or newer:  TWS: 7497; IB Gateway: 4002`}
	UPDATE_TWS          = IbError{503, "The TWS is out of date and must be upgraded."}
	NOT_CONNECTED       = IbError{504, "Not connected"}
	UNKNOWN_ID          = IbError{505, "Fatal Error: Unknown message id."}
	UNSUPPORTED_VERSION = IbError{506, "Unsupported version"}
	BAD_LENGTH          = IbError{507, "Bad message length"}
	BAD_MESSAGE         = IbError{508, "Bad message"}
	SOCKET_EXCEPTION    = IbError{509, "Exception caught while reading socket - "}
	FAIL_CREATE_SOCK    = IbError{520, "Failed to create socket"}
	SSL_FAIL            = IbError{530, "SSL specific error: "}
)

Functions

func GetLogger

func GetLogger() *zap.Logger

GetLogger gets a clone of the internal logger with the option, see uber.org/zap for more information

func InitDefault

func InitDefault(o interface{})

InitDefault try to init the object with the default tag, that is a common way but not a efficent way

func SetAPILogger

func SetAPILogger(cfg zap.Config, opts ...zap.Option) error

APILogger sets the options of internal logger for API, such as level, encoder, output, see uber.org/zap for more information

Types

type Account

type Account struct {
	Name string
}

Account ...

type AlgoParams

type AlgoParams struct {
}

AlgoParams ...

type BarData

type BarData struct {
	Date     string
	Open     float64
	High     float64
	Low      float64
	Close    float64
	Volume   float64
	BarCount int64
	Average  float64
}

BarData ...

func (BarData) String

func (b BarData) String() string

type ComboLeg

type ComboLeg struct {
	ContractID int64
	Ratio      int64
	Action     string
	Exchange   string
	OpenClose  int64

	// for stock legs when doing short sale
	ShortSaleSlot      int64
	DesignatedLocation string
	ExemptCode         int64 `default:"-1"`
}

ComboLeg ...

func NewComboLeg

func NewComboLeg() ComboLeg

NewComboLeg create a default comboleg

func (ComboLeg) String

func (c ComboLeg) String() string

type ComboLegOpenClose

type ComboLegOpenClose int64

ComboLegOpenClose ...

type ComboLegShortSaleSlot

type ComboLegShortSaleSlot int64

ComboLegShortSaleSlot ...

type CommissionReport

type CommissionReport struct {
	ExecID              string
	Commission          float64
	Currency            string
	RealizedPNL         float64
	Yield               float64
	YieldRedemptionDate int64 //YYYYMMDD
}

CommissionReport ...

func (CommissionReport) String

func (cr CommissionReport) String() string

type Contract

type Contract struct {
	ContractID      int64
	Symbol          string
	SecurityType    string
	Expiry          string
	Strike          float64
	Right           string
	Multiplier      string
	Exchange        string
	Currency        string
	LocalSymbol     string
	TradingClass    string
	PrimaryExchange string // pick an actual (ie non-aggregate) exchange that the contract trades on.  DO NOT SET TO SMART.
	IncludeExpired  bool
	SecurityIDType  string // CUSIP;SEDOL;ISIN;RIC
	SecurityID      string

	// combos les
	ComboLegsDescription string
	ComboLegs            []ComboLeg

	DeltaNeutralContract *DeltaNeutralContract
}

Contract describes an instrument's definition

func (Contract) String

func (c Contract) String() string

type ContractCondition

type ContractCondition struct {
	OperatorCondition
	ConID    int64
	Exchange string
}

type ContractDescription

type ContractDescription struct {
	Contract           Contract
	DerivativeSecTypes []string
}

ContractDescription includes contract and DerivativeSecTypes

type ContractDetails

type ContractDetails struct {
	Contract       Contract
	MarketName     string
	MinTick        float64
	OrderTypes     string
	ValidExchanges string
	PriceMagnifier int64

	UnderContractID    int64
	LongName           string
	ContractMonth      string
	Industry           string
	Category           string
	Subcategory        string
	TimezoneID         string
	TradingHours       string
	LiquidHours        string
	EVRule             string
	EVMultiplier       int64
	MdSizeMultiplier   int64
	AggGroup           int64
	UnderSymbol        string
	UnderSecurityType  string
	MarketRuleIDs      string
	SecurityIDList     []TagValue
	RealExpirationDate string
	LastTradeTime      string
	StockType          string

	// BOND values
	Cusip             string
	Ratings           string
	DescAppend        string
	BondType          string
	CouponType        string
	Callable          bool
	Putable           bool
	Coupon            int64
	Convertible       bool
	Maturity          string
	IssueDate         string
	NextOptionDate    string
	NextOptionType    string
	NextOptionPartial bool
	Notes             string
}

ContractDetails contain a Contract and other details about this contract, can be request by ReqContractDetails

func (ContractDetails) String

func (c ContractDetails) String() string

type DeltaNeutralContract

type DeltaNeutralContract struct {
	ContractID int64
	Delta      float64
	Price      float64
}

DeltaNeutralContract is Delta-Neutral Contract

func (DeltaNeutralContract) String

func (c DeltaNeutralContract) String() string

type DepthMktDataDescription

type DepthMktDataDescription struct {
	Exchange        string
	SecurityType    string
	ListingExchange string
	ServiceDataType string
	AggGroup        int64 `default:"UNSETINT"`
}

DepthMktDataDescription ...

func (DepthMktDataDescription) String

func (d DepthMktDataDescription) String() string

DepthMktDataDescription ...

type Execution

type Execution struct {
	ExecID        string
	Time          string
	AccountCode   string
	Exchange      string
	Side          string
	Shares        float64
	Price         float64
	PermID        int64
	ClientID      int64
	OrderID       int64
	Liquidation   int64
	CumQty        float64
	AveragePrice  float64
	OrderRef      string
	EVRule        string
	EVMultiplier  float64
	ModelCode     string
	LastLiquidity int64
}

Execution is the information of an order`s execution

func (Execution) String

func (e Execution) String() string

type ExecutionCondition

type ExecutionCondition struct {
	OrderCondition
	SecType  string
	Exchange string
	Symbol   string
}

type ExecutionFilter

type ExecutionFilter struct {
	ClientID     int64
	AccountCode  string
	Time         string
	Symbol       string
	SecurityType string
	Exchange     string
	Side         string
}

ExecutionFilter ...

type FamilyCode

type FamilyCode struct {
	AccountID  string
	FamilyCode string
}

FamilyCode ...

func (FamilyCode) String

func (f FamilyCode) String() string

type FiledType

type FiledType = int64
const (
	INT FiledType = 1
	STR FiledType = 2
	FLT FiledType = 3
)

type HistogramData

type HistogramData struct {
	Price float64
	Count int64
}

HistogramData ...

func (HistogramData) String

func (hgd HistogramData) String() string

type HistoricalTick

type HistoricalTick struct {
	Time  int64
	Price float64
	Size  int64
}

HistoricalTick is the historical tick's description. Used when requesting historical tick data with whatToShow = MIDPOINT

func (HistoricalTick) String

func (h HistoricalTick) String() string

type HistoricalTickBidAsk

type HistoricalTickBidAsk struct {
	Time             int64
	TickAttirbBidAsk TickAttribBidAsk
	PriceBid         float64
	PriceAsk         float64
	SizeBid          int64
	SizeAsk          int64
}

HistoricalTickBidAsk is the historical tick's description. Used when requesting historical tick data with whatToShow = BID_ASK

func (HistoricalTickBidAsk) String

func (h HistoricalTickBidAsk) String() string

type HistoricalTickLast

type HistoricalTickLast struct {
	Time              int64
	TickAttribLast    TickAttribLast
	Price             float64
	Size              int64
	Exchange          string
	SpecialConditions string
}

HistoricalTickLast is the historical last tick's description. Used when requesting historical tick data with whatToShow = TRADES

func (HistoricalTickLast) String

func (h HistoricalTickLast) String() string

type IN

type IN = int64

IN identifies the msg type of the buf received from TWS or Gateway

type IbClient

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

IbClient is the key component which is used to send request to TWS ro Gateway , such subscribe market data or place order

func NewIbClient

func NewIbClient(wrapper IbWrapper) *IbClient

NewIbClient create IbClient with wrapper

func (*IbClient) CalculateImpliedVolatility

func (ic *IbClient) CalculateImpliedVolatility(reqID int64, contract *Contract, optionPrice float64, underPrice float64, impVolOptions []TagValue)

CalculateImpliedVolatility calculate the volatility of the option

Call this function to calculate volatility for a supplied option price and underlying price. Result will be delivered via wrapper.TickOptionComputation()

@param reqId:

The request id.

@param contract:

Describes the contract.

@param optionPrice:

The price of the option.

@param underPrice:

Price of the underlying.

func (*IbClient) CalculateOptionPrice

func (ic *IbClient) CalculateOptionPrice(reqID int64, contract *Contract, volatility float64, underPrice float64, optPrcOptions []TagValue)

CalculateOptionPrice calculate the price of the option

Call this function to calculate price for a supplied option volatility and underlying price. Result will be delivered via wrapper.TickOptionComputation()

@param reqId:

The request id.

@param contract:

Describes the contract.

@param volatility:

The volatility of the option.

@param underPrice:

Price of the underlying.

func (*IbClient) CancelAccountSummary

func (ic *IbClient) CancelAccountSummary(reqID int64)

CancelAccountSummary cancel the account summary.

func (*IbClient) CancelAccountUpdatesMulti

func (ic *IbClient) CancelAccountUpdatesMulti(reqID int64)

CancelAccountUpdatesMulti cancel the assigned account update.

func (*IbClient) CancelCalculateOptionPrice

func (ic *IbClient) CancelCalculateOptionPrice(reqID int64)

CancelCalculateOptionPrice cancels the calculation of option price

func (*IbClient) CancelFundamentalData

func (ic *IbClient) CancelFundamentalData(reqID int64)

CancelFundamentalData cancel fundamental data.

func (*IbClient) CancelHeadTimeStamp

func (ic *IbClient) CancelHeadTimeStamp(reqID int64)

CancelHeadTimeStamp cancel the head timestamp data.

func (*IbClient) CancelHistogramData

func (ic *IbClient) CancelHistogramData(reqID int64)

CancelHistogramData cancel histogram data.

func (*IbClient) CancelHistoricalData

func (ic *IbClient) CancelHistoricalData(reqID int64)

CancelHistoricalData cancel the update of historical data.

Used if an internet disconnect has occurred or the results of a query are otherwise delayed and the application is no longer interested in receiving the data.

@param reqId:

The ticker ID must be a unique value.

func (*IbClient) CancelMktData

func (ic *IbClient) CancelMktData(reqID int64)

CancelMktData cancels the market data

func (*IbClient) CancelMktDepth

func (ic *IbClient) CancelMktDepth(reqID int64, isSmartDepth bool)

CancelMktDepth cancel market depth.

func (*IbClient) CancelNewsBulletins

func (ic *IbClient) CancelNewsBulletins()

CancelNewsBulletins cancel the news bulletins

func (*IbClient) CancelOrder

func (ic *IbClient) CancelOrder(orderID int64)

CancelOrder cancel an order by orderId

func (*IbClient) CancelPnL

func (ic *IbClient) CancelPnL(reqID int64)

CancelPnL cancel the PnL update of assigned account.

func (*IbClient) CancelPnLSingle

func (ic *IbClient) CancelPnLSingle(reqID int64)

CancelPnLSingle cancel the single contract PnL update of assigned account.

func (*IbClient) CancelPositions

func (ic *IbClient) CancelPositions()

CancelPositions cancel the positions update

func (*IbClient) CancelPositionsMulti

func (ic *IbClient) CancelPositionsMulti(reqID int64)

CancelPositionsMulti cancel the positions update of assigned account.

func (*IbClient) CancelRealTimeBars

func (ic *IbClient) CancelRealTimeBars(reqID int64)

CancelRealTimeBars cancel realtime bars.

func (*IbClient) CancelScannerSubscription

func (ic *IbClient) CancelScannerSubscription(reqID int64)

CancelScannerSubscription cancel scanner.

reqId:int - The ticker ID. Must be a unique value.

func (*IbClient) CancelTickByTickData

func (ic *IbClient) CancelTickByTickData(reqID int64)

CancelTickByTickData cancel the tick-by-tick data

func (*IbClient) ConnState

func (ic *IbClient) ConnState() int

ConnState is the State of connection.

DISCONNECTED CONNECTING CONNECTED REDIRECT

func (*IbClient) Connect

func (ic *IbClient) Connect(host string, port int, clientID int64) error

Connect try to connect the TWS or IB GateWay, after this, handshake should be call to get the connection done

func (*IbClient) ConnectionTime

func (ic *IbClient) ConnectionTime() string

ConnectionTime is the time that connection is comfirmed

func (*IbClient) Disconnect

func (ic *IbClient) Disconnect() error

Disconnect disconnect the client

1.send terminatedSignal to receiver, decoder and requester 2.disconnect the connection 3.wait the 3 goroutine 4.callback ConnectionClosed 5.send the err to done chan 6.reset the IbClient

func (*IbClient) ExerciseOptions

func (ic *IbClient) ExerciseOptions(reqID int64, contract *Contract, exerciseAction int, exerciseQuantity int, account string, override int)

ExerciseOptions exercise the options.

call this func to exercise th options. @param reqId:

The ticker id must be a unique value.

@param contract:

This structure contains a description of the contract to be exercised

@param exerciseAction:

Specifies whether you want the option to lapse or be exercised.
Values: 1 = exercise, 2 = lapse.

@param exerciseQuantity:

The quantity you want to exercise.

@param account:

destination account

@param override:

Specifies whether your setting will override the system's natural action.
For example, if your action is "exercise" and the option is not in-the-money,
by natural action the option would not exercise.
If you have override set to "yes" the natural action would be overridden
and the out-of-the money option would be exercised.
Values: 0 = no, 1 = yes.

func (*IbClient) GetReqID

func (ic *IbClient) GetReqID() int64

GetReqID before request data or place order

func (*IbClient) HandShake

func (ic *IbClient) HandShake() error

HandShake with the TWS or GateWay to ensure the version, send the startApi header ,then receive serverVersion and connection time to comfirm the connection with TWS

func (*IbClient) IsConnected

func (ic *IbClient) IsConnected() bool

IsConnected check if there is a connection to TWS or GateWay

func (*IbClient) LoopUntilDone

func (ic *IbClient) LoopUntilDone(fs ...func()) error

LoopUntilDone will call goroutines and block until the client context is done or the client is disconnected. reconnection should do after this

func (*IbClient) PlaceOrder

func (ic *IbClient) PlaceOrder(orderID int64, contract *Contract, order *Order)

PlaceOrder place an order to tws or gateway

Call this function to place an order. The order status will be returned by the orderStatus event. @param orderId:

The order id.
You must specify a unique value. When the order START_APItus returns,
it will be identified by this tag.This tag is also used when canceling the order.

@param contract:

This structure contains a description of the contract which is being traded.

@param order:

This structure contains the details of tradedhe order.

func (*IbClient) QueryDisplayGroups

func (ic *IbClient) QueryDisplayGroups(reqID int64)

QueryDisplayGroups request the display groups in TWS.

func (*IbClient) ReplaceFA

func (ic *IbClient) ReplaceFA(faData int, cxml string)

ReplaceFA replace fa.

Call this function to modify FA configuration information from the API. Note that this can also be done manually in TWS itself.

@param faData:

Specifies the type of Financial Advisor configuration data beingingg requested.

Valid values include:

1 = GROUPS
2 = PROFILE
3 = ACCOUNT ALIASES

@param cxml:

The XML string containing the new FA configuration information.

func (*IbClient) ReqAccountSummary

func (ic *IbClient) ReqAccountSummary(reqID int64, groupName string, tags string)

ReqAccountSummary request the account summary.

Call this method to request and keep up to date the data that appears on the TWS Account Window Summary tab. Result will be delivered via wrapper.AccountSummary().

Note: This request is designed for an FA managed account but can be used for any multi-account structure.

@param reqId:

	The ID of the data request. Ensures that responses are matched
    to requests If several requests are in process.

@param groupName:

Set to All to returnrn account summary data for all accounts,
or set to a specific Advisor Account Group name that has already been created in TWS Global Configuration.

@param tags:

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 (*IbClient) ReqAccountUpdates

func (ic *IbClient) ReqAccountUpdates(subscribe bool, accName string)

ReqAccountUpdates request the account info.

Call this func to request the information of account, or subscribe the update by setting param:subscribe true. Result will be delivered via wrapper.UpdateAccountValue() and wrapper.UpdateAccountTime().

func (*IbClient) ReqAccountUpdatesMulti

func (ic *IbClient) ReqAccountUpdatesMulti(reqID int64, account string, modelCode string, ledgerAndNLV bool)

ReqAccountUpdatesMulti request and subscrie the assigned account update.

func (*IbClient) ReqAllOpenOrders

func (ic *IbClient) ReqAllOpenOrders()

ReqAllOpenOrders request all the open orders including the orders of other clients and tws

func (*IbClient) ReqAutoOpenOrders

func (ic *IbClient) ReqAutoOpenOrders(autoBind bool)

ReqAutoOpenOrders will make the client access to the TWS Orders (only if clientId=0)

func (*IbClient) ReqCompletedOrders

func (ic *IbClient) ReqCompletedOrders(apiOnly bool)

ReqCompletedOrders request the completed orders

If apiOnly parameter is true, then only completed orders placed from API are requested. Result will be delivered via wrapper.CompletedOrder().

func (*IbClient) ReqContractDetails

func (ic *IbClient) ReqContractDetails(reqID int64, contract *Contract)

ReqContractDetails request the contract details.

func (*IbClient) ReqCurrentTime

func (ic *IbClient) ReqCurrentTime()

ReqCurrentTime request the current system time on the server side.

func (*IbClient) ReqExecutions

func (ic *IbClient) ReqExecutions(reqID int64, execFilter ExecutionFilter)

ReqExecutions request and subscribe the executions filtered by execFilter.

When this function is called, the execution reports that meet the filter criteria are downloaded 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.

@param reqId:

The ID of the data request. Ensures that responses are matched to requests if several requests are in process.

@param execFilter:

This object 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 (*IbClient) ReqFamilyCodes

func (ic *IbClient) ReqFamilyCodes()

ReqFamilyCodes request family codes.

func (*IbClient) ReqFundamentalData

func (ic *IbClient) ReqFundamentalData(reqID int64, contract *Contract, reportType string, fundamentalDataOptions []TagValue)

ReqFundamentalData request fundamental data.

call this func to receive 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.

@param reqId:

The ID of the data request. Ensures that responses are matched to requests if several requests are in process.

@param contract:

This structure contains a description of the contract for which fundamental data is being requested.

@param reportType:

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 (*IbClient) ReqGlobalCancel

func (ic *IbClient) ReqGlobalCancel()

ReqGlobalCancel cancel all the orders including the orders of other clients and tws

func (*IbClient) ReqHeadTimeStamp

func (ic *IbClient) ReqHeadTimeStamp(reqID int64, contract *Contract, whatToShow string, useRTH bool, formatDate int)

ReqHeadTimeStamp request the head timestamp of assigned contract.

call this func to get the headmost data you can get

func (*IbClient) ReqHistogramData

func (ic *IbClient) ReqHistogramData(reqID int64, contract *Contract, useRTH bool, timePeriod string)

ReqHistogramData request histogram data.

func (*IbClient) ReqHistoricalData

func (ic *IbClient) ReqHistoricalData(reqID int64, contract *Contract, endDateTime string, duration string, barSize string, whatToShow string, useRTH bool, formatDate int, keepUpToDate bool, chartOptions []TagValue)

ReqHistoricalData request historical data and subcribe the new data if keepUpToDate is assigned.

Requests contracts' historical data. When requesting historical data, a finishing time and date is required along with a duration string. Result will be delivered via wrapper.HistoricalData()

@param reqId:

The id of the request. Must be a unique value.
When the market data returns, it whatToShowill be identified by this tag.
This is also used when canceling the market data.

@param contract:

This object contains a description of the contract for which market data is being requested.

@param endDateTime:

Defines a query end date and time at any point during the past 6 mos.
Valid values include any date/time within the past six months in the format:
yyyymmdd HH:mm:ss ttt where "ttt" is the optional time zone.

@param durationStr:

Set the query duration up to one week, using a time unit of seconds, days or weeks.
Valid values include any integer followed by a space and then S (seconds), D (days) or W (week).
If no unit is specified, seconds is used.

@param barSizeSetting:

Specifies the size of the bars that will be returned (within IB/TWS listimits).

Valid values include:

1 sec
5 secs
15 secs
30 secs
1 min
2 mins
3 mins
5 mins
15 mins
30 mins
1 hour
1 day

@param whatToShow:

Determines the nature of data beinging extracted.

Valid values include:

TRADES
MIDPOINT
BID
ASK
BID_ASK
HISTORICAL_VOLATILITY
OPTION_IMPLIED_VOLATILITY

@param useRTH:

Determines whether to return all data available during the requested time span,
or only data that falls within regular trading hours.

Valid values include:

0 - all data is returned even where the market in question was outside of its
regular trading hours.
1 - only data within the regular trading hours is returned, even if the
requested time span falls partially or completely outside of the RTH.

@param formatDate:

Determines the date format applied to returned bars.

Valid values include:

1 - dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd
2 - dates are returned as a long integer specifying the number of seconds since
	1/1/1970 GMT.

@param chartOptions:

For internal use only. Use default value XYZ.

func (*IbClient) ReqHistoricalNews

func (ic *IbClient) ReqHistoricalNews(reqID int64, contractID int64, providerCode string, startDateTime string, endDateTime string, totalResults int64, historicalNewsOptions []TagValue)

ReqHistoricalNews request historical news.

func (*IbClient) ReqHistoricalTicks

func (ic *IbClient) ReqHistoricalTicks(reqID int64, contract *Contract, startDateTime string, endDateTime string, numberOfTicks int, whatToShow string, useRTH bool, ignoreSize bool, miscOptions []TagValue)

ReqHistoricalTicks request historical ticks.

func (*IbClient) ReqIDs

func (ic *IbClient) ReqIDs()

ReqIDs request th next valid ID

Call this function to request from TWS the next valid ID that can be used when placing an order. After calling this function, the nextValidId() event will be triggered, and the id returned is that next valid ID. That ID will reflect any autobinding that has occurred (which generates new IDs and increments the next valid ID therein).

func (*IbClient) ReqManagedAccts

func (ic *IbClient) ReqManagedAccts()

ReqManagedAccts request the managed accounts.

Call this function to request the list of managed accounts. Result will be delivered via wrapper.ManagedAccounts().

Note:

This request can only be made when connected to a FA managed account.

func (*IbClient) ReqMarketDataType

func (ic *IbClient) 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.

@param marketDataType:

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

func (*IbClient) ReqMarketRule

func (ic *IbClient) ReqMarketRule(marketRuleID int64)

ReqMarketRule request the market rule.

func (*IbClient) ReqMatchingSymbols

func (ic *IbClient) ReqMatchingSymbols(reqID int64, pattern string)

ReqMatchingSymbols request matching symbols.

func (*IbClient) ReqMktData

func (ic *IbClient) ReqMktData(reqID int64, contract *Contract, genericTickList string, snapshot bool, regulatorySnapshot bool, mktDataOptions []TagValue)

ReqMktData Call this function to request market data. The market data will be returned by the tickPrice and tickSize events.

@param reqID:

The ticker id must be a unique value. When the market data returns.
It will be identified by this tag. This is also used when canceling the market data.

@param contract:

This structure contains a description of the Contractt for which market data is being requested.

@param genericTickList:

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"

@param snapshot:

Check to return a single snapshot of Market data and have the market data subscription cancel.
Do not enter any genericTicklist values if you use snapshots.

@param regulatorySnapshot:

With the US Value Snapshot Bundle for stocks, regulatory snapshots are available for 0.01 USD each.

@param mktDataOptions:

For internal use only.Use default value XYZ.

func (*IbClient) ReqMktDepth

func (ic *IbClient) ReqMktDepth(reqID int64, contract *Contract, numRows int, isSmartDepth bool, mktDepthOptions []TagValue)

ReqMktDepth request the market depth.

Call this function to request market depth for a specific contract. The market depth will be returned by the updateMktDepth() and updateMktDepthL2() events.

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.

@param reqId:

The ticker id must be a unique value. When the market depth data returns.
It will be identified by this tag. This is also used when canceling the market depth

@param contract:

This structure contains a description of the contract for which market depth data is being requested.

@param numRows:

Specifies the numRowsumber of market depth rows to display.

@param isSmartDepth:

specifies SMART depth request

@param mktDepthOptions:

For internal use only. Use default value XYZ.

func (*IbClient) ReqMktDepthExchanges

func (ic *IbClient) ReqMktDepthExchanges()

ReqMktDepthExchanges request the exchanges of market depth.

func (*IbClient) ReqNewsArticle

func (ic *IbClient) ReqNewsArticle(reqID int64, providerCode string, articleID string, newsArticleOptions []TagValue)

ReqNewsArticle request news article.

func (*IbClient) ReqNewsBulletins

func (ic *IbClient) ReqNewsBulletins(allMsgs bool)

ReqNewsBulletins request and subcribe the news bulletins

Call this function to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() event.

@param allMsgs:

If set to TRUE, returns all the existing bulletins for the currencyent day and any new ones.
If set to FALSE, will only return new bulletins.

func (*IbClient) ReqNewsProviders

func (ic *IbClient) ReqNewsProviders()

ReqNewsProviders request news providers.

func (*IbClient) ReqOpenOrders

func (ic *IbClient) ReqOpenOrders()

ReqOpenOrders request the open orders of this client

func (*IbClient) ReqPnL

func (ic *IbClient) ReqPnL(reqID int64, account string, modelCode string)

ReqPnL request and subscribe the PnL of assigned account.

func (*IbClient) ReqPnLSingle

func (ic *IbClient) ReqPnLSingle(reqID int64, account string, modelCode string, contractID int64)

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

func (*IbClient) ReqPositions

func (ic *IbClient) ReqPositions()

ReqPositions request and subcribe the positions of current account.

func (*IbClient) ReqPositionsMulti

func (ic *IbClient) ReqPositionsMulti(reqID int64, account string, modelCode string)

ReqPositionsMulti request the positions update of assigned account.

func (*IbClient) ReqRealTimeBars

func (ic *IbClient) ReqRealTimeBars(reqID int64, contract *Contract, barSize int, whatToShow string, useRTH bool, realTimeBarsOptions []TagValue)

ReqRealTimeBars request realtime bars.

call this func to start receiving real time bar. Result will be delivered via wrapper.RealtimeBar().

@param reqId:

The Id for the request. 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.

@param contract:

This object contains a description of the contract for which real time bars are being requested

@param barSize:

Currently only 5 second bars are supported, if any other
value is used, an exception will be thrown.

@param whatToShow:

Determines the nature of the data extracted.

Valid values include:

TRADES
BID
ASK
MIDPOINT

@param useRTH:

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.

@param realTimeBarOptions:

For internal use only. Use default value XYZ.

func (*IbClient) ReqScannerParameters

func (ic *IbClient) ReqScannerParameters()

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

func (*IbClient) ReqScannerSubscription

func (ic *IbClient) ReqScannerSubscription(reqID int64, subscription *ScannerSubscription, scannerSubscriptionOptions []TagValue, scannerSubscriptionFilterOptions []TagValue)

ReqScannerSubscription subcribes a scanner that matched the subcription.

call this func to subcribe a scanner which could scan the market. @param reqId:

The ticker ID must be a unique value.

@param scannerSubscription:

This structure contains possible parameters used to filter results.

@param scannerSubscriptionOptions:

For internal use only.Use default value XYZ.

func (*IbClient) ReqSecDefOptParams

func (ic *IbClient) ReqSecDefOptParams(reqID int64, underlyingSymbol string, futFopExchange string, underlyingSecurityType string, underlyingContractID int64)

ReqSecDefOptParams request security definition option parameters.

call this func for viewing a contract's option chain reqId the ID chosen for the request underlyingSymbol futFopExchange The exchange on which the returned options are trading. Can be set to the empty string "" for all exchanges. underlyingSecType The type of the underlying security, i.e. STK underlyingConId the contract ID of the underlying security. Response comes via wrapper.SecurityDefinitionOptionParameter()

func (*IbClient) ReqSmartComponents

func (ic *IbClient) ReqSmartComponents(reqID int64, bboExchange string)

ReqSmartComponents request the smartComponents.

func (*IbClient) ReqSoftDollarTiers

func (ic *IbClient) ReqSoftDollarTiers(reqID int64)

ReqSoftDollarTiers request 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 (*IbClient) ReqTickByTickData

func (ic *IbClient) ReqTickByTickData(reqID int64, contract *Contract, tickType string, numberOfTicks int64, ignoreSize bool)

ReqTickByTickData request the tick-by-tick data.

Call this func to requst tick-by-tick data.Result will be delivered via wrapper.TickByTickAllLast() wrapper.TickByTickBidAsk() wrapper.TickByTickMidPoint()

func (*IbClient) RequestFA

func (ic *IbClient) RequestFA(faData int)

RequestFA request fa.

@param faData:

0->"N/A", 1->"GROUPS", 2->"PROFILES", 3->"ALIASES"

func (*IbClient) Run

func (ic *IbClient) Run() error

Run make the event loop run, all make sense after run! Run is not blocked but just startup goRequest and goDecode use LoopUntilDone instead to block the main routine

func (*IbClient) ServerVersion

func (ic *IbClient) ServerVersion() Version

ServerVersion is the tws or gateway version returned by the API

func (*IbClient) SetConnectionOptions

func (ic *IbClient) SetConnectionOptions(opts string)

SetConnectionOptions setup the Connection Options

func (*IbClient) SetContext

func (ic *IbClient) SetContext(ctx context.Context)

SetContext setup the Connection Context

func (*IbClient) SetServerLogLevel

func (ic *IbClient) SetServerLogLevel(logLevel int64)

SetServerLogLevel setup the log level of server

func (*IbClient) SetWrapper

func (ic *IbClient) SetWrapper(wrapper IbWrapper)

SetWrapper setup the Wrapper

func (*IbClient) SubscribeToGroupEvents

func (ic *IbClient) SubscribeToGroupEvents(reqID int64, groupID int)

SubscribeToGroupEvents subcribe the group events.

call this func to subcribe the group event which is triggered by TWS

@param reqId:

The unique number associated with the notification.

@param groupId:

The ID of the group, currently it is a number from 1 to 7.
This is the display group subscription request sent by the API to TWS.

func (*IbClient) UnsubscribeFromGroupEvents

func (ic *IbClient) UnsubscribeFromGroupEvents(reqID int64)

UnsubscribeFromGroupEvents unsubcribe the display group events.

func (*IbClient) UpdateDisplayGroup

func (ic *IbClient) UpdateDisplayGroup(reqID int64, contractInfo string)

UpdateDisplayGroup update the display group in TWS.

call this func to change the display group in TWS.

@param reqId:

The requestId specified in subscribeToGroupEvents().

@param contractInfo:

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.

func (*IbClient) VerifyAndAuthMessage

func (ic *IbClient) VerifyAndAuthMessage(apiData string, xyzResponse string)

VerifyAndAuthMessage is just for IB's internal use.

For IB's internal purpose. Allows to provide means of verification between the TWS and third party programs.

func (*IbClient) VerifyAndAuthRequest

func (ic *IbClient) VerifyAndAuthRequest(apiName string, apiVersion string, opaqueIsvKey string)

VerifyAndAuthRequest is just for IB's internal use.

For IB's internal purpose. Allows to provide means of verification between the TWS and third party programs.

func (*IbClient) VerifyMessage

func (ic *IbClient) VerifyMessage(apiData string)

VerifyMessage is just for IB's internal use.

For IB's internal purpose. Allows to provide means of verification between the TWS and third party programs.

func (*IbClient) VerifyRequest

func (ic *IbClient) VerifyRequest(apiName string, apiVersion string)

VerifyRequest is just for IB's internal use.

For IB's internal purpose. Allows to provide means of verification between the TWS and third party programs.

type IbConnection

type IbConnection struct {
	*net.TCPConn
	// contains filtered or unexported fields
}

IbConnection wrap the tcp connection with TWS or Gateway

func (*IbConnection) Read

func (ibconn *IbConnection) Read(bs []byte) (int, error)

func (*IbConnection) Write

func (ibconn *IbConnection) Write(bs []byte) (int, error)

type IbError

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

IbError is ib internal errors

func (IbError) Error

func (ie IbError) Error() string

type IbWrapper

type IbWrapper interface {
	TickPrice(reqID int64, tickType int64, price float64, attrib TickAttrib)
	TickSize(reqID int64, tickType int64, size int64)
	OrderStatus(orderID int64, status string, filled float64, remaining float64, avgFillPrice float64, permID int64, parentID int64, lastFillPrice float64, clientID int64, whyHeld string, mktCapPrice float64)
	Error(reqID int64, errCode int64, errString string)
	OpenOrder(orderID int64, contract *Contract, order *Order, orderState *OrderState)
	UpdateAccountValue(tag string, val string, currency string, accName string)
	UpdatePortfolio(contract *Contract, position float64, marketPrice float64, marketValue float64, averageCost float64, unrealizedPNL float64, realizedPNL float64, accName string)
	UpdateAccountTime(accTime time.Time)
	NextValidID(reqID int64)
	ContractDetails(reqID int64, conDetails *ContractDetails)
	ExecDetails(reqID int64, contract *Contract, execution *Execution)
	UpdateMktDepth(reqID int64, position int64, operation int64, side int64, price float64, size int64)
	UpdateMktDepthL2(reqID int64, position int64, marketMaker string, operation int64, side int64, price float64, size int64, isSmartDepth bool)
	UpdateNewsBulletin(msgID int64, msgType int64, newsMessage string, originExchange string)
	ManagedAccounts(accountsList []string)
	ReceiveFA(faData int64, cxml string)
	HistoricalData(reqID int64, bar *BarData)
	HistoricalDataEnd(reqID int64, startDateStr string, endDateStr string)
	HistoricalDataUpdate(reqID int64, bar *BarData)
	BondContractDetails(reqID int64, conDetails *ContractDetails)
	ScannerParameters(xml string)
	ScannerData(reqID int64, rank int64, conDetails *ContractDetails, distance string, benchmark string, projection string, legs string)
	ScannerDataEnd(reqID int64)
	TickOptionComputation(reqID int64, tickType int64, tickAttrib int64, impliedVol float64, delta float64, optPrice float64, pvDiviedn float64, gamma float64, vega float64, theta float64, undPrice float64)
	TickGeneric(reqID int64, tickType int64, value float64)
	TickString(reqID int64, tickType int64, value string)
	TickEFP(reqID int64, tickType int64, basisPoints float64, formattedBasisPoints string, totalDividends float64, holdDays int64, futureLastTradeDate string, dividendImpact float64, dividendsToLastTradeDate float64)
	CurrentTime(t time.Time)
	RealtimeBar(reqID int64, time int64, open float64, high float64, low float64, close float64, volume int64, wap float64, count int64)
	FundamentalData(reqID int64, data string)
	ContractDetailsEnd(reqID int64)
	OpenOrderEnd()
	AccountDownloadEnd(accName string)
	ExecDetailsEnd(reqID int64)
	DeltaNeutralValidation(reqID int64, deltaNeutralContract DeltaNeutralContract)
	TickSnapshotEnd(reqID int64)
	MarketDataType(reqID int64, marketDataType int64)
	Position(account string, contract *Contract, position float64, avgCost float64)
	PositionEnd()
	AccountSummary(reqID int64, account string, tag string, value string, currency string)
	AccountSummaryEnd(reqID int64)
	VerifyMessageAPI(apiData string)
	VerifyCompleted(isSuccessful bool, err string)
	DisplayGroupList(reqID int64, groups string)
	DisplayGroupUpdated(reqID int64, contractInfo string)
	VerifyAndAuthMessageAPI(apiData string, xyzChallange string)
	VerifyAndAuthCompleted(isSuccessful bool, err string)
	PositionMulti(reqID int64, account string, modelCode string, contract *Contract, position float64, avgCost float64)
	PositionMultiEnd(reqID int64)
	AccountUpdateMulti(reqID int64, account string, modleCode string, tag string, value string, currency string)
	AccountUpdateMultiEnd(reqID int64)
	SecurityDefinitionOptionParameter(reqID int64, exchange string, underlyingContractID int64, tradingClass string, multiplier string, expirations []string, strikes []float64)
	SecurityDefinitionOptionParameterEnd(reqID int64)
	SoftDollarTiers(reqID int64, tiers []SoftDollarTier)
	FamilyCodes(famCodes []FamilyCode)
	SymbolSamples(reqID int64, contractDescriptions []ContractDescription)
	SmartComponents(reqID int64, smartComps []SmartComponent)
	TickReqParams(tickerID int64, minTick float64, bboExchange string, snapshotPermissions int64)
	MktDepthExchanges(depthMktDataDescriptions []DepthMktDataDescription)
	HeadTimestamp(reqID int64, headTimestamp string)
	TickNews(tickerID int64, timeStamp int64, providerCode string, articleID string, headline string, extraData string)
	NewsProviders(newsProviders []NewsProvider)
	NewsArticle(reqID int64, articleType int64, articleText string)
	HistoricalNews(reqID int64, time string, providerCode string, articleID string, headline string)
	HistoricalNewsEnd(reqID int64, hasMore bool)
	HistogramData(reqID int64, histogram []HistogramData)
	RerouteMktDataReq(reqID int64, contractID int64, exchange string)
	RerouteMktDepthReq(reqID int64, contractID int64, exchange string)
	MarketRule(marketRuleID int64, priceIncrements []PriceIncrement)
	Pnl(reqID int64, dailyPnL float64, unrealizedPnL float64, realizedPnL float64)
	PnlSingle(reqID int64, position int64, dailyPnL float64, unrealizedPnL float64, realizedPnL float64, value float64)
	HistoricalTicks(reqID int64, ticks []HistoricalTick, done bool)
	HistoricalTicksBidAsk(reqID int64, ticks []HistoricalTickBidAsk, done bool)
	HistoricalTicksLast(reqID int64, ticks []HistoricalTickLast, done bool)
	TickByTickAllLast(reqID int64, tickType int64, time int64, price float64, size int64, tickAttribLast TickAttribLast, exchange string, specialConditions string)
	TickByTickBidAsk(reqID int64, time int64, bidPrice float64, askPrice float64, bidSize int64, askSize int64, tickAttribBidAsk TickAttribBidAsk)
	TickByTickMidPoint(reqID int64, time int64, midPoint float64)
	OrderBound(reqID int64, apiClientID int64, apiOrderID int64)
	CompletedOrder(contract *Contract, order *Order, orderState *OrderState)
	CompletedOrdersEnd()
	CommissionReport(commissionReport CommissionReport)
	ConnectAck()
	ConnectionClosed()
	ReplaceFAEnd(reqID int64, text string)
}

IbWrapper contain the funcs to handle the msg from TWS or Gateway

type MarginCondition

type MarginCondition struct {
	OperatorCondition
	Percent float64
}

type MsgBuffer

type MsgBuffer struct {
	bytes.Buffer
	// contains filtered or unexported fields
}

MsgBuffer is the buffer that contains a whole msg

func NewMsgBuffer

func NewMsgBuffer(bs []byte) *MsgBuffer

NewMsgBuffer create a new MsgBuffer

func (*MsgBuffer) Reset

func (m *MsgBuffer) Reset()

Reset reset buffer, []byte, err

type NewsProvider

type NewsProvider struct {
	Code string
	Name string
}

NewsProvider ...

func (NewsProvider) String

func (np NewsProvider) String() string

type OUT

type OUT = int64

OUT identifies the msg type of the buf sended to TWS or Gateway

type OperatorCondition

type OperatorCondition struct {
	OrderCondition
	IsMore bool
}

type Order

type Order struct {
	OrderID                       int64
	ClientID                      int64
	PermID                        int64
	Action                        string
	TotalQuantity                 float64
	OrderType                     string
	LimitPrice                    float64 `default:"UNSETFLOAT"`
	AuxPrice                      float64 `default:"UNSETFLOAT"`
	TIF                           string
	ActiveStartTime               string
	ActiveStopTime                string
	OCAGroup                      string
	OCAType                       int64 // 1 = CANCEL_WITH_BLOCK, 2 = REDUCE_WITH_BLOCK, 3 = REDUCE_NON_BLOCK
	OrderRef                      string
	Transmit                      bool `default:"true"`
	ParentID                      int64
	BlockOrder                    bool
	SweepToFill                   bool
	DisplaySize                   int64
	TriggerMethod                 int64 // 0=Default, 1=Double_Bid_Ask, 2=Last, 3=Double_Last, 4=Bid_Ask, 7=Last_or_Bid_Ask, 8=Mid-point
	OutsideRTH                    bool
	Hidden                        bool
	GoodAfterTime                 string // Format: 20060505 08:00:00 {time zone}
	GoodTillDate                  string // Format: 20060505 08:00:00 {time zone}
	OverridePercentageConstraints bool
	Rule80A                       string // Individual = 'I', Agency = 'A', AgentOtherMember = 'W', IndividualPTIA = 'J', AgencyPTIA = 'U', AgentOtherMemberPTIA = 'M', IndividualPT = 'K', AgencyPT = 'Y', AgentOtherMemberPT = 'N'
	AllOrNone                     bool
	MinQty                        int64   `default:"UNSETINT"`
	PercentOffset                 float64 `default:"UNSETFLOAT"` // REL orders only
	TrailStopPrice                float64 `default:"UNSETFLOAT"`
	TrailingPercent               float64 `default:"UNSETFLOAT"` // TRAILLIMIT orders only
	//---- financial advisors only -----
	FAGroup      string
	FAProfile    string
	FAMethod     string
	FAPercentage string
	// ---------------------------------
	// ---------institutional only------
	OpenClose          string // O=Open, C=Close
	Origin             int64  // 0=Customer, 1=Firm
	ShortSaleSlot      int64  // 1 if you hold the shares, 2 if they will be delivered from elsewhere.  Only for Action=SSHORT
	DesignatedLocation string // used only when shortSaleSlot=2
	ExemptCode         int64  `default:"-1"`
	// ---------------------------------
	// ------- SMART routing only ------
	DiscretionaryAmount float64
	ETradeOnly          bool    `default:"true"`
	FirmQuoteOnly       bool    `default:"true"`
	NBBOPriceCap        float64 `default:"UNSETFLOAT"`
	OptOutSmartRouting  bool
	// --------------------------------
	// ---BOX exchange orders only ----
	AuctionStrategy int64
	StartingPrice   float64 `default:"UNSETFLOAT"`
	StockRefPrice   float64 `default:"UNSETFLOAT"`
	Delta           float64 `default:"UNSETFLOAT"`
	// --------------------------------
	// --pegged to stock and VOL orders only--
	StockRangeLower float64 `default:"UNSETFLOAT"`
	StockRangeUpper float64 `default:"UNSETFLOAT"`

	RandomizePrice bool
	RandomizeSize  bool

	// ---VOLATILITY ORDERS ONLY--------
	Volatility                     float64 `default:"UNSETFLOAT"`
	VolatilityType                 int64   `default:"UNSETINT"`
	DeltaNeutralOrderType          string
	DeltaNeutralAuxPrice           float64 `default:"UNSETFLOAT"`
	DeltaNeutralContractID         int64
	DeltaNeutralSettlingFirm       string
	DeltaNeutralClearingAccount    string
	DeltaNeutralClearingIntent     string
	DeltaNeutralOpenClose          string
	DeltaNeutralShortSale          bool
	DeltaNeutralShortSaleSlot      int64
	DeltaNeutralDesignatedLocation string
	ContinuousUpdate               bool
	ReferencePriceType             int64 `default:"UNSETINT"` // 1=Average, 2 = BidOrAsk
	// DeltaNeutral                  DeltaNeutralData `when:"DeltaNeutralOrderType" cond:"is" value:""`
	// -------------------------------------
	// ------COMBO ORDERS ONLY-----------
	BasisPoints     float64 `default:"UNSETFLOAT"` // EFP orders only
	BasisPointsType int64   `default:"UNSETINT"`   // EFP orders only
	// -----------------------------------
	//-----------SCALE ORDERS ONLY------------
	ScaleInitLevelSize        int64   `default:"UNSETINT"`
	ScaleSubsLevelSize        int64   `default:"UNSETINT"`
	ScalePriceIncrement       float64 `default:"UNSETFLOAT"`
	ScalePriceAdjustValue     float64 `default:"UNSETFLOAT"`
	ScalePriceAdjustInterval  int64   `default:"UNSETINT"`
	ScaleProfitOffset         float64 `default:"UNSETFLOAT"`
	ScaleAutoReset            bool
	ScaleInitPosition         int64 `default:"UNSETINT"`
	ScaleInitFillQty          int64 `default:"UNSETINT"`
	ScaleRandomPercent        bool
	ScaleTable                string
	NotSuppScaleNumComponents int64
	//--------------------------------------
	// ---------HEDGE ORDERS--------------
	HedgeType  string
	HedgeParam string
	//--------------------------------------
	//-----------Clearing info ----------------
	Account         string
	SettlingFirm    string
	ClearingAccount string // True beneficiary of the order
	ClearingIntent  string // "" (Default), "IB", "Away", "PTA" (PostTrade)
	// ----------------------------------------
	// --------- ALGO ORDERS ONLY --------------
	AlgoStrategy string

	AlgoParams              []TagValue
	SmartComboRoutingParams []TagValue
	AlgoID                  string

	// ----------what if order -------------------
	WhatIf bool

	// --------------Not Held ------------------
	NotHeld   bool
	Solictied bool

	// models
	ModelCode string

	// ------order combo legs -----------------
	OrderComboLegs   []OrderComboLeg
	OrderMiscOptions []TagValue
	//----------------------------------------
	//-----------VER PEG2BENCH fields----------
	ReferenceContractID          int64
	PeggedChangeAmount           float64
	IsPeggedChangeAmountDecrease bool
	ReferenceChangeAmount        float64
	ReferenceExchangeID          string
	AdjustedOrderType            string
	TriggerPrice                 float64 `default:"UNSETFLOAT"`
	AdjustedStopPrice            float64 `default:"UNSETFLOAT"`
	AdjustedStopLimitPrice       float64 `default:"UNSETFLOAT"`
	AdjustedTrailingAmount       float64 `default:"UNSETFLOAT"`
	AdjustableTrailingUnit       int64
	LimitPriceOffset             float64 `default:"UNSETFLOAT"`

	Conditions            []OrderConditioner
	ConditionsCancelOrder bool
	ConditionsIgnoreRth   bool

	//------ext operator--------------
	ExtOperator string

	//-----native cash quantity --------
	CashQty float64 `default:"UNSETFLOAT"`

	//--------------------------------
	Mifid2DecisionMaker   string
	Mifid2DecisionAlgo    string
	Mifid2ExecutionTrader string
	Mifid2ExecutionAlgo   string

	//-------------
	DontUseAutoPriceForHedge bool

	IsOmsContainer bool

	DiscretionaryUpToLimitPrice bool

	AutoCancelDate       string
	FilledQuantity       float64 `default:"UNSETFLOAT"`
	RefFuturesConID      int64
	AutoCancelParent     bool
	Shareholder          string
	ImbalanceOnly        bool
	RouteMarketableToBbo bool
	ParentPermID         int64

	UsePriceMgmtAlgo bool
	Duration         int64 `default:"UNSETINT"`
	PostToAts        int64 `default:"UNSETINT"`

	SoftDollarTier SoftDollarTier
}

Order is the origin type of order,do not try to new one unless you definitely know how to fill all the fields!Use NewDefaultOrder instead!

func NewLimitOrder

func NewLimitOrder(action string, lmtPrice float64, quantity float64) *Order

NewLimitOrder create a limit order with action, limit price and quantity

func NewMarketOrder

func NewMarketOrder(action string, quantity float64) *Order

NewMarketOrder create a market order with action and quantity

func NewOrder

func NewOrder() *Order

NewOrder create a default order

func (Order) String

func (o Order) String() string

type OrderComboLeg

type OrderComboLeg struct {
	Price float64 `default:"UNSETFLOAT"`
}

OrderComboLeg ...

func (OrderComboLeg) String

func (o OrderComboLeg) String() string

type OrderCondition

type OrderCondition struct {
	IsConjunctionConnection bool
	// contains filtered or unexported fields
}

func (OrderCondition) CondType

func (oc OrderCondition) CondType() int64

type OrderConditioner

type OrderConditioner interface {
	CondType() int64
	// contains filtered or unexported methods
}

func InitOrderCondition

func InitOrderCondition(conType int64) (OrderConditioner, int)

type OrderState

type OrderState struct {
	Status                  string
	InitialMarginBefore     string
	InitialMarginChange     string
	InitialMarginAfter      string
	MaintenanceMarginBefore string
	MaintenanceMarginChange string
	MaintenanceMarginAfter  string
	EquityWithLoanBefore    string
	EquityWithLoanChange    string
	EquityWithLoanAfter     string
	Commission              float64 `default:"UNSETFLOAT"`
	MinCommission           float64 `default:"UNSETFLOAT"`
	MaxCommission           float64 `default:"UNSETFLOAT"`
	CommissionCurrency      string
	WarningText             string
	CompletedTime           string
	CompletedStatus         string
}

OrderState is the state of Order

func (OrderState) String

func (state OrderState) String() string

type PercentChangeCondition

type PercentChangeCondition struct {
	ContractCondition
	ChangePercent float64
}

type PriceCondition

type PriceCondition struct {
	ContractCondition
	Price         float64
	TriggerMethod int64
}

type PriceIncrement

type PriceIncrement struct {
	LowEdge   float64
	Increment float64
}

PriceIncrement ...

func (PriceIncrement) String

func (p PriceIncrement) String() string

type RealTimeBar

type RealTimeBar struct {
	Time int64

	Open   float64
	High   float64
	Low    float64
	Close  float64
	Volume int64
	Wap    float64
	Count  int64
	// contains filtered or unexported fields
}

RealTimeBar ...

func (RealTimeBar) String

func (rb RealTimeBar) String() string

type ScanData

type ScanData struct {
	ContractDetails ContractDetails
	Rank            int64
	Distance        string
	Benchmark       string
	Projection      string
	Legs            string
}

ScanData is the data retureed by IB, which matches the ScannerSubscription

func (ScanData) String

func (s ScanData) String() string

type ScannerSubscription

type ScannerSubscription struct {
	NumberOfRows             int64 `default:"-1"`
	Instrument               string
	LocationCode             string
	ScanCode                 string
	AbovePrice               float64 `default:"UNSETFLOAT"`
	BelowPrice               float64 `default:"UNSETFLOAT"`
	AboveVolume              int64   `default:"UNSETINT"`
	MarketCapAbove           float64 `default:"UNSETFLOAT"`
	MarketCapBelow           float64 `default:"UNSETFLOAT"`
	MoodyRatingAbove         string
	MoodyRatingBelow         string
	SpRatingAbove            string
	SpRatingBelow            string
	MaturityDateAbove        string
	MaturityDateBelow        string
	CouponRateAbove          float64 `default:"UNSETFLOAT"`
	CouponRateBelow          float64 `default:"UNSETFLOAT"`
	ExcludeConvertible       bool
	AverageOptionVolumeAbove int64 `default:"UNSETINT"`
	ScannerSettingPairs      string
	StockTypeFilter          string
}

ScannerSubscription defines a market scanner request

func NewScannerSubscription

func NewScannerSubscription() *ScannerSubscription

NewScannerSubscription create a default ScannerSubscription

func (ScannerSubscription) String

func (s ScannerSubscription) String() string

type SmartComponent

type SmartComponent struct {
	BitNumber      int64
	Exchange       string
	ExchangeLetter string
}

SmartComponent ...

func (SmartComponent) String

func (s SmartComponent) String() string

type SoftDollarTier

type SoftDollarTier struct {
	Name        string
	Value       string
	DisplayName string
}

SoftDollarTier is a container for storing Soft Dollar Tier information

func (SoftDollarTier) String

func (s SoftDollarTier) String() string

type TagValue

type TagValue struct {
	Tag   string
	Value string
}

TagValue ...

func (TagValue) String

func (tv TagValue) String() string

type TickAttrib

type TickAttrib struct {
	CanAutoExecute bool
	PastLimit      bool
	PreOpen        bool
}

TickAttrib describes additional information for price ticks

func (TickAttrib) String

func (t TickAttrib) String() string

type TickAttribBidAsk

type TickAttribBidAsk struct {
	BidPastLow  bool
	AskPastHigh bool
}

TickAttribBidAsk ...

func (TickAttribBidAsk) String

func (t TickAttribBidAsk) String() string

type TickAttribLast

type TickAttribLast struct {
	PastLimit  bool
	Unreported bool
}

TickAttribLast ...

func (TickAttribLast) String

func (t TickAttribLast) String() string

type TimeCondition

type TimeCondition struct {
	OperatorCondition
	Time string
}

type Version

type Version = int
const (
	MIN_CLIENT_VER Version = 100
	MAX_CLIENT_VER Version = mMIN_SERVER_VER_POST_TO_ATS
)

type VolumeCondition

type VolumeCondition struct {
	ContractCondition
	Volume int64
}

type Wrapper

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

Wrapper is the default wrapper provided by this golang implement.

func (Wrapper) AccountDownloadEnd

func (w Wrapper) AccountDownloadEnd(accName string)

func (Wrapper) AccountSummary

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

func (Wrapper) AccountSummaryEnd

func (w Wrapper) AccountSummaryEnd(reqID int64)

func (Wrapper) AccountUpdateMulti

func (w Wrapper) AccountUpdateMulti(reqID int64, account string, modelCode string, tag string, value string, currency string)

func (Wrapper) AccountUpdateMultiEnd

func (w Wrapper) AccountUpdateMultiEnd(reqID int64)

func (Wrapper) BondContractDetails

func (w Wrapper) BondContractDetails(reqID int64, conDetails *ContractDetails)

func (Wrapper) CommissionReport

func (w Wrapper) CommissionReport(commissionReport CommissionReport)

func (Wrapper) CompletedOrder

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

func (Wrapper) CompletedOrdersEnd

func (w Wrapper) CompletedOrdersEnd()

func (Wrapper) ConnectAck

func (w Wrapper) ConnectAck()

func (Wrapper) ConnectionClosed

func (w Wrapper) ConnectionClosed()

func (Wrapper) ContractDetails

func (w Wrapper) ContractDetails(reqID int64, conDetails *ContractDetails)

func (Wrapper) ContractDetailsEnd

func (w Wrapper) ContractDetailsEnd(reqID int64)

func (Wrapper) CurrentTime

func (w Wrapper) CurrentTime(t time.Time)

func (Wrapper) DeltaNeutralValidation

func (w Wrapper) DeltaNeutralValidation(reqID int64, deltaNeutralContract DeltaNeutralContract)

func (Wrapper) DisplayGroupList

func (w Wrapper) DisplayGroupList(reqID int64, groups string)

func (Wrapper) DisplayGroupUpdated

func (w Wrapper) DisplayGroupUpdated(reqID int64, contractInfo string)

func (Wrapper) Error

func (w Wrapper) Error(reqID int64, errCode int64, errString string)

func (Wrapper) ExecDetails

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

func (Wrapper) ExecDetailsEnd

func (w Wrapper) ExecDetailsEnd(reqID int64)

func (Wrapper) FamilyCodes

func (w Wrapper) FamilyCodes(famCodes []FamilyCode)

func (Wrapper) FundamentalData

func (w Wrapper) FundamentalData(reqID int64, data string)

func (*Wrapper) GetNextOrderID

func (w *Wrapper) GetNextOrderID() (i int64)

func (Wrapper) HeadTimestamp

func (w Wrapper) HeadTimestamp(reqID int64, headTimestamp string)

func (Wrapper) HistogramData

func (w Wrapper) HistogramData(reqID int64, histogram []HistogramData)

func (Wrapper) HistoricalData

func (w Wrapper) HistoricalData(reqID int64, bar *BarData)

func (Wrapper) HistoricalDataEnd

func (w Wrapper) HistoricalDataEnd(reqID int64, startDateStr string, endDateStr string)

func (Wrapper) HistoricalDataUpdate

func (w Wrapper) HistoricalDataUpdate(reqID int64, bar *BarData)

func (Wrapper) HistoricalNews

func (w Wrapper) HistoricalNews(reqID int64, time string, providerCode string, articleID string, headline string)

func (Wrapper) HistoricalNewsEnd

func (w Wrapper) HistoricalNewsEnd(reqID int64, hasMore bool)

func (Wrapper) HistoricalTicks

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

func (Wrapper) HistoricalTicksBidAsk

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

func (Wrapper) HistoricalTicksLast

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

func (Wrapper) ManagedAccounts

func (w Wrapper) ManagedAccounts(accountsList []string)

func (Wrapper) MarketDataType

func (w Wrapper) MarketDataType(reqID int64, marketDataType int64)

func (Wrapper) MarketRule

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

func (Wrapper) MktDepthExchanges

func (w Wrapper) MktDepthExchanges(depthMktDataDescriptions []DepthMktDataDescription)

func (Wrapper) NewsArticle

func (w Wrapper) NewsArticle(reqID int64, articleType int64, articleText string)

func (Wrapper) NewsProviders

func (w Wrapper) NewsProviders(newsProviders []NewsProvider)

func (*Wrapper) NextValidID

func (w *Wrapper) NextValidID(reqID int64)

func (Wrapper) OpenOrder

func (w Wrapper) OpenOrder(orderID int64, contract *Contract, order *Order, orderState *OrderState)

func (Wrapper) OpenOrderEnd

func (w Wrapper) OpenOrderEnd()

func (Wrapper) OrderBound

func (w Wrapper) OrderBound(reqID int64, apiClientID int64, apiOrderID int64)

func (Wrapper) OrderStatus

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

func (Wrapper) Pnl

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

func (Wrapper) PnlSingle

func (w Wrapper) PnlSingle(reqID int64, position int64, dailyPnL float64, unrealizedPnL float64, realizedPnL float64, value float64)

func (Wrapper) Position

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

func (Wrapper) PositionEnd

func (w Wrapper) PositionEnd()

func (Wrapper) PositionMulti

func (w Wrapper) PositionMulti(reqID int64, account string, modelCode string, contract *Contract, position float64, avgCost float64)

func (Wrapper) PositionMultiEnd

func (w Wrapper) PositionMultiEnd(reqID int64)

func (Wrapper) RealtimeBar

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

func (Wrapper) ReceiveFA

func (w Wrapper) ReceiveFA(faData int64, cxml string)

func (Wrapper) ReplaceFAEnd

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

func (Wrapper) RerouteMktDataReq

func (w Wrapper) RerouteMktDataReq(reqID int64, contractID int64, exchange string)

func (Wrapper) RerouteMktDepthReq

func (w Wrapper) RerouteMktDepthReq(reqID int64, contractID int64, exchange string)

func (Wrapper) ScannerData

func (w Wrapper) ScannerData(reqID int64, rank int64, conDetails *ContractDetails, distance string, benchmark string, projection string, legs string)

func (Wrapper) ScannerDataEnd

func (w Wrapper) ScannerDataEnd(reqID int64)

func (Wrapper) ScannerParameters

func (w Wrapper) ScannerParameters(xml string)

func (Wrapper) SecurityDefinitionOptionParameter

func (w Wrapper) SecurityDefinitionOptionParameter(reqID int64, exchange string, underlyingContractID int64, tradingClass string, multiplier string, expirations []string, strikes []float64)

func (Wrapper) SecurityDefinitionOptionParameterEnd

func (w Wrapper) SecurityDefinitionOptionParameterEnd(reqID int64)

func (Wrapper) SmartComponents

func (w Wrapper) SmartComponents(reqID int64, smartComps []SmartComponent)

func (Wrapper) SoftDollarTiers

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

func (Wrapper) SymbolSamples

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

func (Wrapper) TickByTickAllLast

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

func (Wrapper) TickByTickBidAsk

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

func (Wrapper) TickByTickMidPoint

func (w Wrapper) TickByTickMidPoint(reqID int64, time int64, midPoint float64)

func (Wrapper) TickEFP

func (w Wrapper) TickEFP(reqID int64, tickType int64, basisPoints float64, formattedBasisPoints string, totalDividends float64, holdDays int64, futureLastTradeDate string, dividendImpact float64, dividendsToLastTradeDate float64)

func (Wrapper) TickGeneric

func (w Wrapper) TickGeneric(reqID int64, tickType int64, value float64)

func (Wrapper) TickNews

func (w Wrapper) TickNews(tickerID int64, timeStamp int64, providerCode string, articleID string, headline string, extraData string)

func (Wrapper) TickOptionComputation

func (w Wrapper) TickOptionComputation(reqID int64, tickType int64, tickAttrib int64, impliedVol float64, delta float64, optPrice float64, pvDiviedn float64, gamma float64, vega float64, theta float64, undPrice float64)

func (Wrapper) TickPrice

func (w Wrapper) TickPrice(reqID int64, tickType int64, price float64, attrib TickAttrib)

func (Wrapper) TickReqParams

func (w Wrapper) TickReqParams(reqID int64, minTick float64, bboExchange string, snapshotPermissions int64)

func (Wrapper) TickSize

func (w Wrapper) TickSize(reqID int64, tickType int64, size int64)

func (Wrapper) TickSnapshotEnd

func (w Wrapper) TickSnapshotEnd(reqID int64)

func (Wrapper) TickString

func (w Wrapper) TickString(reqID int64, tickType int64, value string)

func (Wrapper) UpdateAccountTime

func (w Wrapper) UpdateAccountTime(accTime time.Time)

func (Wrapper) UpdateAccountValue

func (w Wrapper) UpdateAccountValue(tag string, value string, currency string, account string)

func (Wrapper) UpdateMktDepth

func (w Wrapper) UpdateMktDepth(reqID int64, position int64, operation int64, side int64, price float64, size int64)

Returns the order book.

tickerId - the request's identifier position - the order book's row being updated operation - how to refresh the row:

0 = insert (insert this new order into the row identified by 'position')
1 = update (update the existing order in the row identified by 'position')
2 = delete (delete the existing order at the row identified by 'position').

side - 0 for ask, 1 for bid price - the order's price size - the order's size

func (Wrapper) UpdateMktDepthL2

func (w Wrapper) UpdateMktDepthL2(reqID int64, position int64, marketMaker string, operation int64, side int64, price float64, size int64, isSmartDepth bool)

func (Wrapper) UpdateNewsBulletin

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

func (Wrapper) UpdatePortfolio

func (w Wrapper) UpdatePortfolio(contract *Contract, position float64, marketPrice float64, marketValue float64, averageCost float64, unrealizedPNL float64, realizedPNL float64, accName string)

func (Wrapper) VerifyAndAuthCompleted

func (w Wrapper) VerifyAndAuthCompleted(isSuccessful bool, err string)

func (Wrapper) VerifyAndAuthMessageAPI

func (w Wrapper) VerifyAndAuthMessageAPI(apiData string, xyzChallange string)

func (Wrapper) VerifyCompleted

func (w Wrapper) VerifyCompleted(isSuccessful bool, err string)

func (Wrapper) VerifyMessageAPI

func (w Wrapper) VerifyMessageAPI(apiData string)

Jump to

Keyboard shortcuts

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