ib

package module
v0.0.0-...-626c23e Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2021 License: GPL-3.0 Imports: 8 Imported by: 0

README

ibclient

GitHub Workflow Status GoDoc Twitter

IBKR Client Portal Web API Wrapper for Go

The simple solution to creating trading algorithms for IBKR accounts.

Example

Retrieve all positions in a portfolio, filter by asset class and get historical data.

package main

import (
	"fmt"
	"time"
	ib "github.com/tomlister/ibclient"
)

func main() {
  	ib.SetBaseURL("https://localhost:5000/v1")
	ib.Authenticate()
	ib.Schedule(func() {
		ib.KeepAlive()
	}, time.Minute)
	broker := ib.Brokers().Selected()
	portfolios := ib.Portfolios()
	positions := portfolios[0].Positions()
	futures := positions.FilterAssets(ib.Futures)
	for _, p := range futures {
		sec := broker.Security(p)
		historical := sec.Historical(2, ib.Day, 1, ib.Hour)
		fmt.Println(historical)
	}
}

To run this example: go run -tags=example github.com/tomlister/ibclient/examples/historical

Installing

go get github.com/tomlister/ibclient

Prerequisites

In order to use this package the user must have the following:

  • An IBKR Pro Brokerage Account
  • The IBKR Client Portal Web API running locally

Running

Once the prerequisites are in place, the user must sign through the client portal SSO. Logging in with a dedicated paper trading username and password is recommended. More info about the client portal setup process can be found at https://interactivebrokers.github.io/cpwebapi/

Roadmap

As this is a fairly new package, a lot of the features you'd expect aren't implemented yet. Rest assured they will be implemented in due time.

  • Portfolio
  • Historical Data
  • Live Data
  • Trade Execution
  • Scanners

Disclaimers

This is an unofficial wrapper for IBKR's Client Portal Web API. As using any financial products naturally comes with risk, I'm not responsible for any financial damages or losses that may occur using this library to execute trades, etc... The licence also provides no warranty what so ever.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Authenticate

func Authenticate()

Authenticate initiates the brokerage session

func KeepAlive

func KeepAlive()

KeepAlive keeps the authenticated session active. Inactive sessions are timed out within a few minutes. By calling /tickle the client portal keeps the session alive.

func Schedule

func Schedule(callback func(), interval time.Duration) chan struct{}

Schedule runs a function periodically

func SetBaseURL

func SetBaseURL(baseURL string)

SetBaseURL sets the base api url

Types

type AssetClass

type AssetClass string

AssetClass represents the type of asset

const (
	// Futures are contracts that allow assets to be purchased at a market price for delivery and payment in the future.
	Futures AssetClass = "FUT"
	// Stocks represent a fractional ownership of a business and entitles the holder to dividends.
	Stocks AssetClass = "STK"
)

type BrokerAccount

type BrokerAccount struct {
	ID string
}

BrokerAccount stores the id of a brokerage account

func (BrokerAccount) Security

func (ba BrokerAccount) Security(p Position) Security

Security creates a security object from a position

type BrokerAccounts

type BrokerAccounts struct {
	Accounts     []string `json:"accounts"`
	ChartPeriods struct {
		STK   []string `json:"STK"`
		CFD   []string `json:"CFD"`
		OPT   []string `json:"OPT"`
		FOP   []string `json:"FOP"`
		WAR   []string `json:"WAR"`
		IOPT  []string `json:"IOPT"`
		FUT   []string `json:"FUT"`
		CASH  []string `json:"CASH"`
		IND   []string `json:"IND"`
		BOND  []string `json:"BOND"`
		FUND  []string `json:"FUND"`
		CMDTY []string `json:"CMDTY"`
		PHYSS []string `json:"PHYSS"`
	} `json:"chartPeriods"`
	SelectedAccount string `json:"selectedAccount"`
	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"`
}

BrokerAccounts stores information about a users available brokerage accounts

func Brokers

func Brokers() BrokerAccounts

Brokers retrieves all of an accounts brokerage accounts

func (BrokerAccounts) Selected

func (ba BrokerAccounts) Selected() BrokerAccount

Selected returns the default/active brokerage account

type Historical

type Historical struct {
	Symbol            string                `json:"symbol"`
	Text              string                `json:"text"`
	PriceFactor       int                   `json:"priceFactor"`
	StartTime         string                `json:"startTime"`
	High              string                `json:"high"`
	Low               string                `json:"low"`
	TimePeriod        string                `json:"timePeriod"`
	BarLength         int                   `json:"barLength"`
	MdAvailability    string                `json:"mdAvailability"`
	MktDataDelay      int                   `json:"mktDataDelay"`
	OutsideRth        bool                  `json:"outsideRth"`
	VolumeFactor      int                   `json:"volumeFactor"`
	PriceDisplayRule  int                   `json:"priceDisplayRule"`
	PriceDisplayValue string                `json:"priceDisplayValue"`
	NegativeCapable   bool                  `json:"negativeCapable"`
	MessageVersion    int                   `json:"messageVersion"`
	Data              []HistoricalDataFrame `json:"data"`
	Points            int                   `json:"points"`
	TravelTime        int                   `json:"travelTime"`
}

Historical stores historical market data returned from the brokerage server.

func (Historical) ToDataFrame

func (hd Historical) ToDataFrame() *dataframe.DataFrame

ToDataFrame converts historical market data to dataframes for technical analysis.

type HistoricalDataFrame

type HistoricalDataFrame struct {
	O float64 `json:"o"`
	C float64 `json:"c"`
	H float64 `json:"h"`
	L float64 `json:"l"`
	V int     `json:"v"`
	T int64   `json:"t"`
}

HistoricalDataFrame stores the OCHL, Volume and Time of a security for a single frame of historical market data.

type MarketDataField

type MarketDataField string

MarketDataField represents a field to request market data for. IB decided it was a fun idea to assign each field a number instead of a name. So now I must resort to this horrific mess

const (
	LastPrice                      MarketDataField = "31"
	Symbol                         MarketDataField = "55"
	Text                           MarketDataField = "58"
	High                           MarketDataField = "70"
	Low                            MarketDataField = "71"
	Pos                            MarketDataField = "72"
	MarketValue                    MarketDataField = "73"
	AveragePrice                   MarketDataField = "74"
	UnrealizedPnL                  MarketDataField = "75"
	FormattedPosition              MarketDataField = "76"
	FormattedUnrealizedPnL         MarketDataField = "77"
	DailyPnL                       MarketDataField = "78"
	ChangePrice                    MarketDataField = "82"
	ChangePercent                  MarketDataField = "83"
	BidPrice                       MarketDataField = "84"
	AskSize                        MarketDataField = "85"
	AskPrice                       MarketDataField = "86"
	Volume                         MarketDataField = "87"
	BidSize                        MarketDataField = "88"
	Exchange                       MarketDataField = "6004"
	Conid                          MarketDataField = "6008"
	SecurityType                   MarketDataField = "6070"
	Months                         MarketDataField = "6072"
	RegularExpiry                  MarketDataField = "6073"
	MarketDataDeliveryMethodMarker MarketDataField = "6119"
	UnderlyingConid                MarketDataField = "6457"
	MarketDataAvailability         MarketDataField = "6509"
	CompanyName                    MarketDataField = "7051"
	LastSize                       MarketDataField = "7059"
	ConidExchange                  MarketDataField = "7094"
	ContractDescription            MarketDataField = "7219"
	ContractDescriptionAlt         MarketDataField = "7220"
	ListingExchange                MarketDataField = "7221"
	Industry                       MarketDataField = "7280"
	Category                       MarketDataField = "7281"
	AverageDailyVolume             MarketDataField = "7282"
	HistoricVolume30D              MarketDataField = "7284"
	PutCallRatio                   MarketDataField = "7285"
	DividendAmount                 MarketDataField = "7286"
	DividendYieldPercentage        MarketDataField = "7287"
	DividendExDate                 MarketDataField = "7288"
	MarketCap                      MarketDataField = "7289"
	PE                             MarketDataField = "7290"
	EPS                            MarketDataField = "7291"
	CostBasis                      MarketDataField = "7292"
	WeekHigh52                     MarketDataField = "7293"
	WeekLow52                      MarketDataField = "7294"
	OpenPrice                      MarketDataField = "7295"
	ClosePrice                     MarketDataField = "7296"
	Delta                          MarketDataField = "7308"
	Gamma                          MarketDataField = "7309"
	Theta                          MarketDataField = "7310"
	Vega                           MarketDataField = "7311"
	ImpliedVolatilityOption        MarketDataField = "7633"
)

type Portfolio

type Portfolio struct {
	ID             string      `json:"id"`
	AccountID      string      `json:"accountId"`
	AccountVan     string      `json:"accountVan"`
	AccountTitle   string      `json:"accountTitle"`
	DisplayName    string      `json:"displayName"`
	AccountAlias   interface{} `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         interface{} `json:"parent"`
	Desc           string      `json:"desc"`
	Covestor       bool        `json:"covestor"`
}

Portfolio stores information about a specific account portfolio

func (Portfolio) Positions

func (p Portfolio) Positions() Positions

Positions retrieves a portfolios positions

type PortfoliosResponse

type PortfoliosResponse []Portfolio

PortfoliosResponse is an array of portfolio accounts

func Portfolios

func Portfolios() PortfoliosResponse

Portfolios retrieves portfolios attached to the account

type Position

type Position struct {
	AcctID            string        `json:"acctId"`
	Conid             int           `json:"conid"`
	ContractDesc      string        `json:"contractDesc"`
	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             interface{}   `json:"exchs"`
	Expiry            string        `json:"expiry"`
	PutOrCall         interface{}   `json:"putOrCall"`
	Multiplier        string        `json:"multiplier"`
	Strike            float64       `json:"strike"`
	ExerciseStyle     interface{}   `json:"exerciseStyle"`
	ConExchMap        []interface{} `json:"conExchMap"`
	AssetClass        string        `json:"assetClass"`
	UndConid          int           `json:"undConid"`
	Model             string        `json:"model"`
	BaseMktValue      float64       `json:"baseMktValue"`
	BaseMktPrice      float64       `json:"baseMktPrice"`
	BaseAvgCost       float64       `json:"baseAvgCost"`
	BaseAvgPrice      float64       `json:"baseAvgPrice"`
	BaseRealizedPnl   float64       `json:"baseRealizedPnl"`
	BaseUnrealizedPnl float64       `json:"baseUnrealizedPnl"`
	Time              int           `json:"time"`
	Name              string        `json:"name"`
	LastTradingDay    string        `json:"lastTradingDay"`
	Group             interface{}   `json:"group"`
	Sector            interface{}   `json:"sector"`
	SectorGroup       interface{}   `json:"sectorGroup"`
	Ticker            string        `json:"ticker"`
	Type              string        `json:"type"`
	UndComp           string        `json:"undComp,omitempty"`
	UndSym            string        `json:"undSym,omitempty"`
	FullName          string        `json:"fullName"`
	PageSize          int           `json:"pageSize"`
	ChineseName       string        `json:"chineseName,omitempty"`
}

Position stores information about a position

type Positions

type Positions []Position

Positions is an array of positions

func (Positions) FilterAssets

func (p Positions) FilterAssets(a AssetClass) Positions

FilterAssets filters positions by asset class

type Security

type Security struct {
	Broker BrokerAccount
	Conid  int
}

Security stores information about a security

func (Security) Historical

func (s Security) Historical(period int, unit TimeUnit, barSize int, barUnit TimeUnit) Historical

Historical retrieves historical market data for a security.

func (Security) Snapshot

func (s Security) Snapshot(fields ...MarketDataField) Snapshots

Snapshot retrieves a market data snapshot by fields

type Snapshot

type Snapshot struct {
	LastPrice                      float64 `json:"31,string,omitempty"`
	Symbol                         string  `json:"55,omitempty"`
	Text                           string  `json:"58,omitempty"`
	High                           float64 `json:"70,string,omitempty"`
	Low                            float64 `json:"71,string,omitempty"`
	Position                       float64 `json:"72,omitempty"`
	MarketValue                    string  `json:"73,omitempty"`
	AveragePrice                   float64 `json:"74,string,omitempty"`
	UnrealizedPnL                  float64 `json:"75,omitempty"`
	FormattedPosition              string  `json:"76,omitempty"`
	FormattedUnrealizedPnL         string  `json:"77,omitempty"`
	DailyPnL                       float64 `json:"78_raw,omitempty"`
	ChangePrice                    float64 `json:"82,string,omitempty"`
	ChangePercent                  float64 `json:"83,omitempty"`
	BidPrice                       float64 `json:"84,string,omitempty"`
	AskSize                        int     `json:"85,string,omitempty"`
	AskPrice                       float64 `json:"86,string,omitempty"`
	Volume                         float64 `json:"87_raw,omitempty"`
	BidSize                        int     `json:"88,string,omitempty"`
	SecurityType                   string  `json:"6070,omitempty"`
	MarketDataDeliveryMethodMarker string  `json:"6119,omitempty"`
	UnderlyingConid                int     `json:"6457,string,omitempty"`
	MarketDataAvailability         string  `json:"6509,omitempty"`
	CompanyName                    string  `json:"7051,omitempty"`
	LastSize                       int     `json:"7059,string,omitempty"`
	ContractDescription            string  `json:"7219,omitempty"`
	ListingExchange                string  `json:"7221,omitempty"`
	Industry                       string  `json:"7280,omitempty"`
	Category                       string  `json:"7281,omitempty"`
	AverageDailyVolume             string  `json:"7282,omitempty"`
	HistoricVolume30D              string  `json:"7284,omitempty"`
	DividendAmount                 float64 `json:"7286,string,omitempty"`
	DividendYieldPercentage        string  `json:"7287,omitempty"`
	DividendExDate                 string  `json:"7288,omitempty"`
	MarketCap                      string  `json:"7289,omitempty"`
	PE                             float64 `json:"7290,string,omitempty"`
	EPS                            float64 `json:"7291,string,omitempty"`
	CostBasis                      float64 `json:"7292_raw,omitempty"`
	WeekHigh52                     float64 `json:"7293,string,omitempty"`
	WeekLow52                      float64 `json:"7294,string,omitempty"`
	OpenPrice                      float64 `json:"7295,string,omitempty"`
	Conid                          int     `json:"conid"`
	ServerID                       string  `json:"server_id,omitempty"`
	Updated                        int64   `json:"_updated,omitempty"`
}

type Snapshots

type Snapshots []Snapshot

type TimeUnit

type TimeUnit string

TimeUnit represents a unit of time.

const (
	// Min - 1 to 30 minutes.
	Min TimeUnit = "min"
	// Hour - 1 to 8 hours.
	Hour TimeUnit = "h"
	// Day - 1 to 1000 days.
	Day TimeUnit = "d"
	// Week - 1 to 792 weeks.
	Week TimeUnit = "w"
	// Month - 1 to 182 months.
	Month TimeUnit = "m"
	// Year - 1 to 15 years.
	Year TimeUnit = "y"
)

Jump to

Keyboard shortcuts

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