ibapi

package module
v0.0.0-...-083206f Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2020 License: MIT Imports: 14 Imported by: 0

README

Interactive Brokers API - GoLang Version

Interactive Brokers API 9.79 pure golang, Unofficial version, smilar to the official python version

INSTALL

go get -u github.com/hadrianl/ibapi

USAGE

import (
    . "github.com/hadrianl/ibapi"
    "time"
    log "github.com/sirupsen/logrus"
)

func main(){
    var err error
    ibwrapper := &Wrapper{}
    ic := NewIbClient(ibwrapper)
    err = ic.Connect("172.0.0.1", 4002, 0)
    if err != nil {
        log.Panic("Connect failed:", err)
        return
    }

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

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

    ic.Run()
    time.Sleep(time.Second * 10)
    ic.Disconnect()
}

Reference

1.Offical Document

Documentation

Index

Constants

View Source
const (
	MaxRequests      = 95
	RequestInternal  = 2
	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 (
	MIN_CLIENT_VER = 100
	MAX_CLIENT_VER = mMIN_SERVER_VER_NO_DEFAULT_OPEN_CLOSE
)
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  float64 = math.MaxFloat64
	UNSETINT    int64   = math.MaxInt64
	NO_VALID_ID int64   = -1
	MAX_MSG_LEN int     = 0xFFFFFF
)
View Source
const (
	TIME_FORMAT string = "2006-01-02 15:04:05 +0700 CST"
)

Variables

This section is empty.

Functions

func InitDefault

func InitDefault(o interface{})

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

func NewMsgBuffer

func NewMsgBuffer(bs []byte) *msgBuffer

Types

type Account

type Account struct {
	Name string
}

type AlgoParams

type AlgoParams struct {
}

type BarData

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

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"`
}

func NewComboLeg

func NewComboLeg() ComboLeg

func (ComboLeg) String

func (c ComboLeg) String() string

type ComboLegOpenClose

type ComboLegOpenClose int64

------------ComboLeg--------------------

type ComboLegShortSaleSlot

type ComboLegShortSaleSlot int64

type CommissionReport

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

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 is the base struct about the information of specified symbol(identify by ContractID)

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
}

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
}

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"`
}

func (DepthMktDataDescription) String

func (d DepthMktDataDescription) String() string

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 trade detail

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
}

type FamilyCode

type FamilyCode struct {
	AccountID  string
	FamilyCode string
}

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
}

func (HistogramData) String

func (hgd HistogramData) String() string

type HistoricalTick

type HistoricalTick struct {
	Time  int64
	Price float64
	Size  int64
}

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
}

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
}

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 Call this function to calculate volatility for a supplied

option price and underlying price. Result will be delivered
via EWrapper.tickOptionComputation()

reqId:TickerId -  The request id.
contract:Contract -  Describes the contract.
optionPrice:double - The price of the option.
underPrice:double - Price of the underlying.

func (*IbClient) CalculateOptionPrice

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

func (*IbClient) CancelAccountSummary

func (ic *IbClient) CancelAccountSummary(reqID int64)

func (*IbClient) CancelAccountUpdatesMulti

func (ic *IbClient) CancelAccountUpdatesMulti(reqID int64)

func (*IbClient) CancelCalculateOptionPrice

func (ic *IbClient) CancelCalculateOptionPrice(reqID int64)

func (*IbClient) CancelFundamentalData

func (ic *IbClient) CancelFundamentalData(reqID int64)

func (*IbClient) CancelHeadTimeStamp

func (ic *IbClient) CancelHeadTimeStamp(reqID int64)

func (*IbClient) CancelHistogramData

func (ic *IbClient) CancelHistogramData(reqID int64)

func (*IbClient) CancelHistoricalData

func (ic *IbClient) CancelHistoricalData(reqID int64)

CancelHistoricalData 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.

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

func (*IbClient) CancelMktData

func (ic *IbClient) CancelMktData(reqID int64)

CancelMktData

func (*IbClient) CancelMktDepth

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

func (*IbClient) CancelNewsBulletins

func (ic *IbClient) CancelNewsBulletins()

func (*IbClient) CancelOrder

func (ic *IbClient) CancelOrder(orderID int64)

func (*IbClient) CancelPnL

func (ic *IbClient) CancelPnL(reqID int64)

func (*IbClient) CancelPnLSingle

func (ic *IbClient) CancelPnLSingle(reqID int64)

func (*IbClient) CancelPositions

func (ic *IbClient) CancelPositions()

func (*IbClient) CancelPositionsMulti

func (ic *IbClient) CancelPositionsMulti(reqID int64)

func (*IbClient) CancelRealTimeBars

func (ic *IbClient) CancelRealTimeBars(reqID int64)

func (*IbClient) CancelScannerSubscription

func (ic *IbClient) CancelScannerSubscription(reqID int64)

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

func (*IbClient) CancelTickByTickData

func (ic *IbClient) CancelTickByTickData(reqID int64)

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() time.Time

func (*IbClient) Disconnect

func (ic *IbClient) Disconnect() error

Disconnect

func (*IbClient) ExerciseOptions

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

ExerciseOptions reqId:TickerId - The ticker id. multipleust be a unique value.

contract:Contract - This structure contains a description of the
    contract to be exercised
exerciseAction:int - Specifies whether you want the option to lapse
    or be exercised.
    Values are 1 = exercise, 2 = lapse.
exerciseQuantity:int - The quantity you want to exercise.
account:str - destination account
override:int - 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 are: 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

func (*IbClient) IsConnected

func (ic *IbClient) IsConnected() bool

IsConnected check if there is a connection to TWS or GateWay

func (*IbClient) PlaceOrder

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

PlaceOrder Call this function to place an order. The order status will

be returned by the orderStatus event.

orderId: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.
contract:Contract - This structure contains a description of the
    contract which is being traded.
order:Order - This structure contains the details of tradedhe order.
    Note: Each client MUST connect with a unique clientId.

func (*IbClient) QueryDisplayGroups

func (ic *IbClient) QueryDisplayGroups(reqID int64)

func (*IbClient) ReplaceFA

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

ReplaceFA Call this function to modify FA configuration information from the

API. Note that this can also be done manually in TWS itself.

faData:FaDataType - Specifies the type of Financial Advisor
    configuration data beingingg requested. Valid values include:
    1 = GROUPS
    2 = PROFILE
    3 = ACCOUNT ALIASES
cxml: str - The XML string containing the new FA configuration
    information.

func (*IbClient) ReqAccountSummary

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

ReqAccountSummary Call this method to request and keep up to date the data that appears

on the TWS Account Window Summary tab. The data is returned by
accountSummary().

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

reqId:int - The ID of the data request. Ensures that responses are matched
    to requests If several requests are in process.
groupName:str - 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.
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 (*IbClient) ReqAccountUpdates

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

func (*IbClient) ReqAccountUpdatesMulti

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

func (*IbClient) ReqAllOpenOrders

func (ic *IbClient) ReqAllOpenOrders()

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 Call this function to request the completed orders. If apiOnly parameter is true, then only completed orders placed from API are requested. Each completed order will be fed back through the completedOrder() function on the EWrapper.

func (*IbClient) ReqContractDetails

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

func (*IbClient) ReqCurrentTime

func (ic *IbClient) ReqCurrentTime()

ReqCurrentTime Asks the current system time on the server side.

func (*IbClient) ReqExecutions

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

ReqExecutions 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.

reqId:int - The ID of the data request. Ensures that responses are
    matched to requests if several requests are in process.
execFilter:ExecutionFilter - 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()

func (*IbClient) ReqFundamentalData

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

ReqFundamentalData Call this function to receive fundamental data for

stocks. The appropriate market data subscription must be set up in
Account Management before you can receive this data.
Fundamental data will be returned at EWrapper.fundamentalData().

reqFundamentalData() can handle conid specified in the Contract object,
but not tradingClass or multiplier. This is because reqFundamentalData()
is used only for stocks and stocks do not have a multiplier and
trading class.

reqId:tickerId - The ID of the data request. Ensures that responses are
     matched to requests if several requests are in process.
contract:Contract - This structure contains a description of the
    contract for which fundamental data is being requested.
reportType:str - 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()

func (*IbClient) ReqHeadTimeStamp

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

func (*IbClient) ReqHistogramData

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

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 Requests contracts' historical data. When requesting historical data, a

finishing time and date is required along with a duration string. The
resulting bars will be returned in EWrapper.historicalData()

reqId:TickerId - 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.
contract:Contract - This object contains a description of the contract for which
    market data is being requested.
endDateTime:str - 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.
durationStr:str - 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.
barSizeSetting:str - 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
whatToShow:str - Determines the nature of data beinging extracted. Valid values include:

    TRADES
    MIDPOINT
    BID
    ASK
    BID_ASK
    HISTORICAL_VOLATILITY
    OPTION_IMPLIED_VOLATILITY
useRTH:int - 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.
formatDate: int - Determines the date format applied to returned bars. validd 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.
chartOptions:TagValueList - 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)

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)

func (*IbClient) ReqIDs

func (ic *IbClient) ReqIDs()

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).

numIds:int - deprecated

func (*IbClient) ReqManagedAccts

func (ic *IbClient) ReqManagedAccts()

ReqManagedAccts Call this function to request the list of managed accounts. The list

will be returned by the managedAccounts() function on the EWrapper.

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

func (*IbClient) ReqMarketDataType

func (ic *IbClient) ReqMarketDataType(marketDataType int64)
ReqMarketDataType

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:int -
			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)

func (*IbClient) ReqMatchingSymbols

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

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.

reqId: TickerId - 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.
contract:Contract - This structure contains a description of the
    Contractt for which market data is being requested.
genericTickList:str - 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"
snapshot:bool - 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.
regulatorySnapshot: bool - With the US Value Snapshot Bundle for stocks,
    regulatory snapshots are available for 0.01 USD each.
mktDataOptions:TagValueList - 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 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.

reqId:TickerId - 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

contract:Contact - This structure contains a description of the contract

for which market depth data is being requested.

numRows:int - Specifies the numRowsumber of market depth rows to display. isSmartDepth:bool - specifies SMART depth request mktDepthOptions:TagValueList - For internal use only. Use default value

XYZ.

func (*IbClient) ReqMktDepthExchanges

func (ic *IbClient) ReqMktDepthExchanges()

func (*IbClient) ReqNewsArticle

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

func (*IbClient) ReqNewsBulletins

func (ic *IbClient) ReqNewsBulletins(allMsgs bool)

ReqNewsBulletins Call this function to start receiving news bulletins. Each bulletin

will be returned by the updateNewsBulletin() event.

allMsgs:bool - 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()

func (*IbClient) ReqOpenOrders

func (ic *IbClient) ReqOpenOrders()

func (*IbClient) ReqPnL

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

func (*IbClient) ReqPnLSingle

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

func (*IbClient) ReqPositions

func (ic *IbClient) ReqPositions()

func (*IbClient) ReqPositionsMulti

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

func (*IbClient) ReqRealTimeBars

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

ReqRealTimeBars Call the reqRealTimeBars() function to start receiving real time bar

results through the realtimeBar() EWrapper function.

reqId:TickerId - 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.
contract:Contract - This object contains a description of the contract
    for which real time bars are being requested
barSize:int - Currently only 5 second bars are supported, if any other
    value is used, an exception will be thrown.
whatToShow:str - Determines the nature of the data extracted. Valid
    values include:
    TRADES
    BID
    ASK
    MIDPOINT
useRTH:bool - 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:TagValueList - 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 reqId:int - The ticker ID. Must be a unique value.

scannerSubscription:ScannerSubscription - This structure contains
    possible parameters used to filter results.
scannerSubscriptionOptions:TagValueList - 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 Requests security definition option parameters 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 EWrapper.securityDefinitionOptionParameter()

func (*IbClient) ReqSmartComponents

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

func (*IbClient) ReqSoftDollarTiers

func (ic *IbClient) ReqSoftDollarTiers(reqID int64)

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

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

func (*IbClient) RequestFA

func (ic *IbClient) RequestFA(faData int)

RequestFA 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!

func (IbClient) ServerVersion

func (ic IbClient) ServerVersion() Version

func (*IbClient) SetConnectionOptions

func (ic *IbClient) SetConnectionOptions(opts string)

Set the Connection Options to IbClient

func (*IbClient) SetContext

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

Set the Connection Context to IbClient

func (*IbClient) SetServerLogLevel

func (ic *IbClient) SetServerLogLevel(logLevel int64)

func (*IbClient) SetWrapper

func (ic *IbClient) SetWrapper(wrapper IbWrapper)

Set the Wrapper to IbClient

func (*IbClient) SubscribeToGroupEvents

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

SubscribeToGroupEvents reqId:int - The unique number associated with the notification.

groupId:int - 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)

func (*IbClient) UpdateDisplayGroup

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

UpdateDisplayGroup reqId:int - The requestId specified in subscribeToGroupEvents().

contractInfo:str - 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 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 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 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 For IB's internal purpose. Allows to provide means of verification

between the TWS and third party programs.

type IbConnection

type IbConnection struct {
	// 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
}
var (
	ALREADY_CONNECTED   IbError
	CONNECT_FAIL        IbError
	UPDATE_TWS          IbError
	NOT_CONNECTED       IbError
	UNKNOWN_ID          IbError
	UNSUPPORTED_VERSION IbError
	BAD_LENGTH          IbError
	BAD_MESSAGE         IbError
	SOCKET_EXCEPTION    IbError
	FAIL_CREATE_SOCK    IbError
	SSL_FAIL            IbError
)

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, 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()
}

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

type MarginCondition

type MarginCondition struct {
	OperatorCondition
	Percent float64
}

type NewsProvider

type NewsProvider struct {
	Code string
	Name string
}

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
	ParenPermID          int64
	UsePriceMgmtAlgo     bool

	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

func NewMarketOrder

func NewMarketOrder(action string, quantity float64) *Order

func NewOrder

func NewOrder() *Order

func (Order) String

func (o Order) String() string

type OrderComboLeg

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

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

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
}

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
}

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
}

func NewScanData

func NewScanData(contractDetails ContractDetails, rank int64, distance string, benchmark string, projection string, legsStr string) *ScanData

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
}

func NewScannerSubscription

func NewScannerSubscription() *ScannerSubscription

func (ScannerSubscription) String

func (s ScannerSubscription) String() string

type SmartComponent

type SmartComponent struct {
	BitNumber      int64
	Exchange       string
	ExchangeLetter string
}

func (SmartComponent) String

func (s SmartComponent) String() string

type SoftDollarTier

type SoftDollarTier struct {
	Name        string
	Value       string
	DisplayName string
}

func (SoftDollarTier) String

func (s SoftDollarTier) String() string

type TagValue

type TagValue struct {
	Tag   string
	Value string
}

func (TagValue) String

func (tv TagValue) String() string

type TickAttrib

type TickAttrib struct {
	CanAutoExecute bool
	PastLimit      bool
	PreOpen        bool
}

func (TickAttrib) String

func (t TickAttrib) String() string

type TickAttribBidAsk

type TickAttribBidAsk struct {
	BidPastLow  bool
	AskPastHigh bool
}

func (TickAttribBidAsk) String

func (t TickAttribBidAsk) String() string

type TickAttribLast

type TickAttribLast struct {
	PastLimit  bool
	Unreported bool
}

func (TickAttribLast) String

func (t TickAttribLast) String() string

type TimeCondition

type TimeCondition struct {
	OperatorCondition
	Time string
}

type Version

type Version int

type VolumeCondition

type VolumeCondition struct {
	ContractCondition
	Volume int64
}

type Wrapper

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

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() 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) 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, 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(tickerID 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