goibcp

package module
v0.0.0-...-69bd969 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2020 License: GPL-3.0 Imports: 6 Imported by: 0

README

goibcp

Go lang wrapper for interactive brokers Client Portal (CP) web gateway

Install

go get -u github.com/sachinbhutani/goibcp

Usage Example

TODO

Coverage

Session
  • Tickle
  • Logout
  • Validate SSO
  • Authentication Status
  • Reauthenticate
IBCust
  • Entity Info
Portfolio Analyst
  • Account Performance
  • Account Balance Summary
Account
  • Portfolio Accounts
  • List of Subaccounts
  • Account Information
  • Account Summary
  • Account Ledger
  • Brokerage Accounts
  • Update Selected Account
  • PnL for selected Account
Portfolio
  • Portfolio Accounts
  • List of Subaccounts
  • Account Information
  • Account Allocation
  • Portfolio Positions
  • Position by conid per account
  • Invalidate Cache
  • Account Summary
  • Account Ledger
  • Position by conid
Trades
  • List of Trades
Order
  • Live Order
  • Place Order
  • Place Order (Support Bracket Order)
  • Place Order Reply
  • Preview Order
  • Modify Order
  • Delete Order
Market Data
  • Market Data
  • Market Data Cancel (Single)
  • Market Data Cancel (All)
  • Market Data History
Contract
  • Contract Info
  • Search by Symbol Name
  • Get strikes for options/warrants
  • Get available conids of future/option/warrant/cash/CFD
  • Secdef by Conid
  • Security Futures by Symbol
Scanner
  • get lists of available scanners
  • run scanner
PnL
  • PnL for the selected account

FAQs

Could not connect to IB CP Gateway, Ensure the CP gateway is running and logged in before connecting

X509 Certificate error

Please refer to the interactive brokers CP Web gateway FAQq in common question section at https://interactivebrokers.github.io/cpwebapi/faq.html

Since the gateway is running on your premises the certificate needs to be created/self-signed by you, or officially signed by a 3rd party. The gateway is similar to another webserver such as Tomcat which doesn’t provide a certificate along with the release.

https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-using-java-keytool.html

Documentation

Index

Constants

View Source
const (
	ERROR   = 0
	WARNING = 1
	INFO    = 2
	DEBUG   = 3
)

ERROR, WARNING or INFO constants for Log Levels

View Source
const Version = "0.0.8"

Version - the version of go-ib-cp

Variables

View Source
var KAStatus = false

KAStatus - Keep Alive status to start/stop the tickle process

View Source
var Settings = &Config{CPURL: "https://localhost:5000", LogLevel: 2, KeepAlive: true}

Settings - Default settings if no setting are provided to the Connect() function.

Functions

func KeepAlive

func KeepAlive(c *IBClient) error

KeepAlive - Keeps the sesssion alive by tickeling the server every minute unless an error is encountered or session expires reauthorize session on nobridge error

Types

type Config

type Config struct {
	CPURL     string
	LogLevel  int
	KeepAlive bool
}

Config to connect to CP Web gateway LogInfo 0=> Log Errors only , 1=> log warnings, 2=> log information (default)

type IBAccountLedger

type IBAccountLedger struct {
	BASE struct {
		Commoditymarketvalue      float64 `json:"commoditymarketvalue"`
		Futuremarketvalue         float64 `json:"futuremarketvalue"`
		Settledcash               float64 `json:"settledcash"`
		Exchangerate              int64   `json:"exchangerate"`
		Sessionid                 int64   `json:"sessionid"`
		Cashbalance               float64 `json:"cashbalance"`
		Corporatebondsmarketvalue float64 `json:"corporatebondsmarketvalue"`
		Warrantsmarketvalue       float64 `json:"warrantsmarketvalue"`
		Netliquidationvalue       float64 `json:"netliquidationvalue"`
		Interest                  int64   `json:"interest"`
		Unrealizedpnl             float64 `json:"unrealizedpnl"`
		Stockmarketvalue          float64 `json:"stockmarketvalue"`
		Moneyfunds                float64 `json:"moneyfunds"`
		Currency                  string  `json:"currency"`
		Realizedpnl               float64 `json:"realizedpnl"`
		Funds                     float64 `json:"funds"`
		Acctcode                  string  `json:"acctcode"`
		Issueroptionsmarketvalue  float64 `json:"issueroptionsmarketvalue"`
		Key                       string  `json:"key"`
		Timestamp                 int64   `json:"timestamp"`
		Severity                  int64   `json:"severity"`
		Stockoptionmarketvalue    float64 `json:"stockoptionmarketvalue"`
		Tbondsmarketvalue         float64 `json:"tbondsmarketvalue"`
		Futureoptionmarketvalue   float64 `json:"futureoptionmarketvalue"`
		Cashbalancefxsegment      float64 `json:"cashbalancefxsegment"`
		Secondkey                 string  `json:"secondkey"`
		Tbillsmarketvalue         float64 `json:"tbillsmarketvalue"`
		Dividends                 float64 `json:"dividends"`
	} `json:"BASE"`
}

IBAccountLedger - account ledger in base currency

type IBClient

type IBClient struct {
	UserID          int      `json:"userId"`
	IsConnected     bool     `json:"connected"`
	IsAuthenticated bool     `json:"authenticated"`
	IsCompeting     bool     `json:"competing"`
	Fail            string   `json:"fail"`
	Message         string   `json:"message"`
	Prompts         []string `json:"prompts"`
}

IBClient - Represents the IB API client which executes all API functions

var Client IBClient

Client - IB Client which can be used to call all api functions

func Connect

func Connect(userSettings ...*Config) (*IBClient, error)

Connect to CP Web gateway. Returns a ib api client if successful or an error if connection is not established. If a session is established, auto-tickle function would be triggered to keep the session active using tickle api every minute.

func (*IBClient) GetAccountLedger

func (c *IBClient) GetAccountLedger(ledger *IBAccountLedger) error

GetAccountLedger - Information regarding settled cash, cash balances, etc. in the account's base currency and any other cash balances held in other currencies https://interactivebrokers.com/api/doc.html#tag/Portfolio/paths/~1portfolio~1{accountId}~1summary/get

func (*IBClient) GetEndpoint

func (c *IBClient) GetEndpoint(endp string, res interface{}, qs ...string) error

GetEndpoint - Get an endpoint from IBCP and return a map

func (*IBClient) GetFutresContractBySymbols

func (c *IBClient) GetFutresContractBySymbols(symbols []string, res interface{}) error

GetFutresContractBySymbols - Gte list of futures contract by symbols Functions related to fetching IB contract informaion

func (*IBClient) GetLiveOrders

func (c *IBClient) GetLiveOrders(liveOrders *IBLiveOrders) error

GetLiveOrders - Update live order to the order list struct

func (*IBClient) GetPortfolioAccount

func (c *IBClient) GetPortfolioAccount() (string, error)

GetPortfolioAccount - Gets the portfolio TODO: gets only a single account , may not work for multiple accounts

func (*IBClient) GetPortfolioPositions

func (c *IBClient) GetPortfolioPositions(openPositions *IBPortfolioPositions, pageID int) error

GetPortfolioPositions - Get current open positions for an account Its required to call portfolio accounts before getting open positions, so account would be determined based on 1st account in portfolio accounts TODO: may not work for multiple accounts/subaccounts situations

func (*IBClient) GetSelectedAccount

func (c *IBClient) GetSelectedAccount() (string, error)

GetSelectedAccount - Get selected trade account ID , returns accountID as string or an error

func (*IBClient) GetSessionInfo

func (c *IBClient) GetSessionInfo(user *IBSession) error

GetSessionInfo - Returns information about the current login session

func (*IBClient) GetSessionStatus

func (c *IBClient) GetSessionStatus() error

GetSessionStatus - Returns session status

func (*IBClient) GetTradeAccount

func (c *IBClient) GetTradeAccount(res interface{}) error

GetTradeAccount Get TradeAccount Information for the current trade account

func (*IBClient) GetTrades

func (c *IBClient) GetTrades(trades *IBTrades) error

GetTrades - Returns a list of trades for the currently selected account for current day and six previous days. portfolioAccounts endpoint must be called for the session before calling this endpoint by user application function GetPortfolioAccount can be used for this purpose

func (*IBClient) Logout

func (c *IBClient) Logout() error

Logout - Logout the current session

func (*IBClient) PlaceOrder

func (c *IBClient) PlaceOrder(order IBOrder) (IBOrderReply, error)

PlaceOrder - posts and order

func (*IBClient) PostEndpoint

func (c *IBClient) PostEndpoint(endp string, res interface{}) error

PostEndpoint - Post to an endpoint from IBCP

func (*IBClient) Reauthenticate

func (c *IBClient) Reauthenticate() error

Reauthenticate - Reauthenticate existing client

func (*IBClient) Tickle

func (c *IBClient) Tickle() error

Tickle - Keeps the sesssion alive by tickeling the server, should be called by user application if KeepAlive if off

type IBFutContract

type IBFutContract struct {
	Symbol          string `json:"symbol"`
	Conid           int    `json:"conid"`
	UnderlyingConid int    `json:"underlyingConid"`
	ExpirationDate  int    `json:"expirationDate"`
	Ltd             int    `json:"ltd"`
}

IBFutContract - Contracts returned for symbols searched

type IBFutContractList

type IBFutContractList map[string][]IBFutContract

IBFutContractList - A list of futures contract

type IBLiveOrders

type IBLiveOrders struct {
	Orders []struct {
		Acct               string  `json:"acct"`
		Exchange           string  `json:"exchange"`
		Conid              int     `json:"conid"`
		OrderID            int     `json:"orderId"`
		CashCcy            string  `json:"cashCcy"`
		SizeAndFills       string  `json:"sizeAndFills"`
		OrderDesc          string  `json:"orderDesc"`
		Description1       string  `json:"description1"`
		Ticker             string  `json:"ticker"`
		SecType            string  `json:"secType"`
		ListingExchange    string  `json:"listingExchange"`
		RemainingQuantity  float64 `json:"remainingQuantity"`
		FilledQuantity     float64 `json:"filledQuantity"`
		CompanyName        string  `json:"companyName"`
		Status             string  `json:"status"`
		AvgPrice           string  `json:"avgPrice"`
		OrigOrderType      string  `json:"origOrderType"`
		SupportsTaxOpt     string  `json:"supportsTaxOpt"`
		LastExecutionTime  string  `json:"lastExecutionTime"`
		LastExecutionTimeR int64   `json:"lastExecutionTime_r"`
		OrderType          string  `json:"orderType"`
		OrderRef           string  `json:"order_ref"`
		Side               string  `json:"side"`
		TimeInForce        string  `json:"timeInForce"`
		BgColor            string  `json:"bgColor"`
		FgColor            string  `json:"fgColor"`
	} `json:"orders"`
}

IBLiveOrders - List of live orders

type IBLogout

type IBLogout struct {
	Confirmed bool `json:"confirmed"`
}

IBLogout - struct for information recieved with logout endpoint

type IBOrder

type IBOrder struct {
	AcctID          string `json:"acctId"`
	Conid           int    `json:"conid"`
	SecType         string `json:"secType"`
	COID            string `json:"cOID"`
	ParentID        string `json:"parentId"`
	OrderType       string `json:"orderType"`
	ListingExchange string `json:"listingExchange"`
	OutsideRTH      bool   `json:"outsideRTH"`
	Price           int    `json:"price"`
	Side            string `json:"side"`
	Ticker          string `json:"ticker"`
	Tif             string `json:"tif"`
	Referrer        string `json:"referrer"`
	Quantity        int    `json:"quantity"`
	UseAdaptive     bool   `json:"useAdaptive"`
}

IBOrder - struct to prepare an order

type IBOrderReply

type IBOrderReply []struct {
	ID           string   `json:"id"`
	Message      []string `json:"message"`
	OrderID      string   `json:"order_id"`
	LocalOrderID string   `json:"local_order_id"`
	OrderStatus  string   `json:"order_status"`
}

IBOrderReply - Reply struct to order information

type IBPortfolioAccounts

type IBPortfolioAccounts []struct {
	ID             string `json:"id"`
	AccountID      string `json:"accountId"`
	AccountVan     string `json:"accountVan"`
	AccountTitle   string `json:"accountTitle"`
	DisplayName    string `json:"displayName"`
	AccountAlias   string `json:"accountAlias"`
	AccountStatus  int64  `json:"accountStatus"`
	Currency       string `json:"currency"`
	Type           string `json:"type"`
	TradingType    string `json:"tradingType"`
	Faclient       bool   `json:"faclient"`
	ClearingStatus string `json:"clearingStatus"`
	Parent         string `json:"parent"`
	Desc           string `json:"desc"`
	Covestor       bool   `json:"covestor"`
}

IBPortfolioAccounts - Accounts

type IBPortfolioPositions

type IBPortfolioPositions []struct {
	AcctID        string   `json:"acctId"`
	Conid         int      `json:"conid"`
	ContractDesc  string   `json:"contractDesc"`
	AssetClass    string   `json:"assetClass"`
	Position      float64  `json:"position"`
	MktPrice      float64  `json:"mktPrice"`
	MktValue      float64  `json:"mktValue"`
	Currency      string   `json:"currency"`
	AvgCost       float64  `json:"avgCost"`
	AvgPrice      float64  `json:"avgPrice"`
	RealizedPnl   float64  `json:"realizedPnl"`
	UnrealizedPnl float64  `json:"unrealizedPnl"`
	Exchs         string   `json:"exchs"`
	Expiry        string   `json:"expiry"`
	PutOrCall     string   `json:"putOrCall"`
	Multiplier    int      `json:"multiplier"`
	Strike        float64  `json:"strike"`
	ExerciseStyle string   `json:"exerciseStyle"`
	UndConid      int      `json:"undConid"`
	ConExchMap    []string `json:"conExchMap"`
	Model         string   `json:"model"`
}

IBPositions - current open positions

type IBSSOValidate

type IBSSOValidate struct {
	USERID        int    `json:"USER_ID"`
	USERNAME      string `json:"USER_NAME"`
	RESULT        bool   `json:"RESULT"`
	SFENABLED     bool   `json:"SF_ENABLED"`
	ISFREETRIAL   bool   `json:"IS_FREE_TRIAL"`
	IP            string `json:"IP"`
	EXPIRES       int    `json:"EXPIRES"`
	LastAccessed  int64  `json:"lastAccessed"`
	LoginType     int    `json:"loginType"`
	PAPERUSERNAME string `json:"PAPER_USER_NAME"`
}

IBSSOValidate - reply from sso/validate URL

type IBSession

type IBSession struct {
	PaperUsername      string `json:"PAPER_USER_NAME"`
	LoginType          int    `json:"loginType"`
	IsPendingApplicant bool   `json:"IS_PENDING_APPLICANT"`
	SFEnabled          bool   `json:"SF_ENABLED"`
	AuthTime           int64  `json:"AUTH_TIME"`
	Credential         string `json:"CREDENTIAL"`
	SFConfig           string `json:"SF_CONFIG"`
	Username           string `json:"USER_NAME"`
	CredentialType     int    `json:"CREDENTIAL_TYPE"`
	Result             bool   `json:"RESULT"`
	IsFreeTrial        bool   `json:"IS_FREE_TRIAL"`
	IP                 string `json:"IP"`
	UserID             int    `json:"USER_ID"`
	Expires            int64  `json:"EXPIRES"`
	Token              string `json:"TOKEN"`
	IsGw               bool   `json:"isGw"`
}

IBSession -Represents the IB user currently logged in

var Session IBSession

Session - IBSession

type IBTickle

type IBTickle struct {
	SsoExpires int    `json:"ssoExpires"`
	Collission bool   `json:"collission"`
	UserID     int    `json:"userId"`
	Session    string `json:"session"`
	Iserver    struct {
		Error      string `json:"error"`
		Tickle     bool   `json:"tickle"`
		AuthStatus struct {
			Authenticated bool   `json:"authenticated"`
			Competing     bool   `json:"competing"`
			Connected     bool   `json:"connected"`
			Message       string `json:"message"`
			MAC           string `json:"MAC"`
		} `json:"authStatus"`
	} `json:"iserver"`
}

IBTickle - reply recieved from server when tickled

type IBTradeAccount

type IBTradeAccount struct {
	SelectedAccount    string `json:"selectedAccount"`
	TradingPermissions struct {
	} `json:"tradingPermissions"`
	AllowFeatures struct {
		ShowGFIS               bool `json:"showGFIS"`
		AllowFXConv            bool `json:"allowFXConv"`
		AllowTypeAhead         bool `json:"allowTypeAhead"`
		SnapshotRefreshTimeout int  `json:"snapshotRefreshTimeout"`
		LiteUser               bool `json:"liteUser"`
		ShowWebNews            bool `json:"showWebNews"`
		Research               bool `json:"research"`
		DebugPnl               bool `json:"debugPnl"`
		ShowTaxOpt             bool `json:"showTaxOpt"`
	} `json:"allowFeatures"`
	ServerInfo struct {
		ServerName    string `json:"serverName"`
		ServerVersion string `json:"serverVersion"`
	} `json:"serverInfo"`
}

IBTradeAccount - Gets information about the current trading account

type IBTrades

type IBTrades []struct {
	ExecutionID          string  `json:"execution_id"`
	Symbol               string  `json:"symbol"`
	Side                 string  `json:"side"`
	OrderDescription     string  `json:"order_description"`
	TradeTime            string  `json:"trade_time"`
	TradeTimeR           int64   `json:"trade_time_r"`
	Size                 float64 `json:"size"`
	Price                string  `json:"price"`
	Submitter            string  `json:"submitter"`
	Exchange             string  `json:"exchange"`
	Comission            string  `json:"comission"`
	NetAmount            float64 `json:"net_amount"`
	Account              string  `json:"account"`
	CompanyName          string  `json:"company_name"`
	ContractDescription1 string  `json:"contract_description_1"`
	SecType              string  `json:"sec_type"`
	Conidex              string  `json:"conidex"`
	Position             string  `json:"position"`
	ClearingID           string  `json:"clearing_id"`
	ClearingName         string  `json:"clearing_name"`
	OrderRef             string  `json:"order_ref"`
}

IBTrades - array of trades from trades endpoint

Jump to

Keyboard shortcuts

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