igmarkets

package module
v0.0.0-...-5b5b077 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2021 License: MIT Imports: 13 Imported by: 0

README

igmarkets - Unofficial IG Markets Trading API for Golang

This is an unofficial API for IG Markets Trading REST API. The StreamingAPI is not part of this project.

Disclaimer: This library is not associated with IG Markets Limited or any of its affiliates or subsidiaries. If you use this library, you should contact them to make sure they are okay with how you intend to use it. Use this lib at your own risk.

Reference: https://labs.ig.com/rest-trading-api-reference

Currently supported endpoints

Lightstreamer
  • Create session, add subscription(control), bind session
Session
  • POST /session (version 2 + 3)
Markets
  • GET /markets/{epic}
  • GET /markets?searchTerm=...
Client sentiment
  • GET /clientsentiment/{marketID}
Positions
  • POST /positions/otc
  • PUT /positions/otc/{dealId}
  • GET /positions
  • DELETE /positions
  • GET /confirms/{dealReference}
Workingorders
  • GET /workingorders
  • POST /workingorders/otc
  • DELETE /workingorders/otc/{dealId}
Prices
  • GET /prices/{epic}/{resolution}/{startDate}/{endDate}
Watchlists
  • POST /watchlists/ (Create watchlist)

  • GET /watchlists/{watchlistid}

  • DELETE /watchlists/{watchlistid} (Delete watchlist)

  • GET /watchlists (Get all watchlists)

  • PUT /watchlists/{watchlistid} (Add epic)

  • DELETE /watchlists/{watchlistid}/{epic} (Delete epic)

History
  • GET /history/activity
  • GET /history/transactions

Example

package main

import (
        "fmt"
        "github.com/sklinkert/igmarkets"
        "time"
)

var ig *igmarkets.IGMarkets

func main() {
        httpTimeout := time.Duration(5 * time.Second)

        ig = igmarkets.New(igmarkets.DemoAPIURL, "APIKEY", "ACCOUNTID", "USERNAME/IDENTIFIER", "PASSWORD", httpTimeout)
        if err := ig.Login(); err != nil {
                fmt.Println("Unable to login into IG account", err)
        }

        // Get current open ask, open bid, close ask, close bid, high ask, high bid, low ask, and low bid
        prices, _ := ig.GetPrice("CS.D.EURUSD.CFD.IP")

        fmt.Println(prices)

        // Place a new order
        order := igmarkets.OTCOrderRequest{
                Epic:           "CS.D.EURUSD.CFD.IP",
                OrderType:      "MARKET",
                CurrencyCode:   "USD",
                Direction:      "BUY",
                Size:           1.0,
                Expiry:         "-",
                StopDistance:   "10", // Pips
                LimitDistance:  "5",  // Pips
                GuaranteedStop: true,
                ForceOpen:      true,
        }
        dealRef, err := ig.PlaceOTCOrder(order)
        if err != nil {
                fmt.Println("Unable to place order:", err)
                return
        }
        fmt.Println("New order placed with dealRef", dealRef)

        // Check order status
        confirmation, err := ig.GetDealConfirmation(dealRef)
        if err != nil {
                fmt.Println("Cannot get deal confirmation for:", dealRef, err)
                return
        }

        fmt.Println("Order dealRef", dealRef)
        fmt.Println("DealStatus", confirmation.DealStatus) // "ACCEPTED"
        fmt.Println("Profit", confirmation.Profit, confirmation.ProfitCurrency)
        fmt.Println("Status", confirmation.Status) // "OPEN"
        fmt.Println("Reason", confirmation.Reason)
        fmt.Println("Level", confirmation.Level) // Buy price

        // List transactions
        transactionResponse, err := ig.GetTransactions("ALL", time.Now().AddDate(0, 0, -30).UTC()) // last 30 days
        if err != nil {
                fmt.Println("Unable to get transactions: ", err)
        }
        for _, transaction := range transactionResponse.Transactions {
                fmt.Println("Found new transaction")
                fmt.Println("Epic:", transaction.InstrumentName)
                fmt.Println("Type:", transaction.TransactionType)
                fmt.Println("OpenDate:", transaction.OpenDateUtc)
                fmt.Println("CloseDate:", transaction.DateUTC)
                fmt.Println("OpenLevel:", transaction.OpenLevel)
                fmt.Println("CloseLevel:", transaction.CloseLevel)
                fmt.Println("Profit/Loss:", transaction.ProfitAndLoss)
	}

        // Example of getting client sentiment
        sentiment, _ := ig.GetClientSentiment("F-US") //Ford
        fmt.Println("Sentiment example:", sentiment)
}
LightStreamer API Subscription Example
	for {
		tickChan := make(chan igmarkets.LightStreamerTick)
    err := igHandle.OpenLightStreamerSubscription([]string{"CS.D.BITCOIN.CFD.IP"}, tickChan)
		if err != nil {
      log.WithError(err).Error("OpenLightStreamerSubscription() failed")
		}

		for tick := range tickChan {
			log.Infof("tick: %+v", tick)
		}

		log.Infof("Server closed stream, restarting...")
  }

Output:

INFO[0003] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:15 +0000 UTC Bid:18230.35 Ask:18266.35} 
INFO[0003] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:15 +0000 UTC Bid:18230.45 Ask:18266.45} 
INFO[0003] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:16 +0000 UTC Bid:18231.14 Ask:18267.14} 
INFO[0003] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:16 +0000 UTC Bid:18231.04 Ask:18267.04} 
INFO[0004] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:16 +0000 UTC Bid:18231.53 Ask:18267.53} 
INFO[0004] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:16 +0000 UTC Bid:18231.35 Ask:18267.35} 
INFO[0004] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:17 +0000 UTC Bid:18230.64 Ask:18266.64} 
INFO[0004] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:17 +0000 UTC Bid:18231.08 Ask:18267.08} 
INFO[0005] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:17 +0000 UTC Bid:18231.36 Ask:18267.36} 
INFO[0005] tick: {Epic:CS.D.BITCOIN.CFD.IP Time:2020-11-22 14:14:17 +0000 UTC Bid:18230.93 Ask:18266.93} 

TODOs

  • Write basic tests

Feel free to send PRs.

Documentation

Index

Constants

View Source
const (
	// ResolutionSecond - 1 second price snapshot
	ResolutionSecond = "SECOND"
	// ResolutionMinute - 1 minute price snapshot
	ResolutionMinute = "MINUTE"
	// ResolutionMinute - 5 minute price snapshot
	ResolutionFiveMinute = "MINUTE_5"
	// ResolutionMinute - 15 minute price snapshot
	ResolutionFifteenMinute = "MINUTE_15"
	// ResolutionMinute - 30 minute price snapshot
	ResolutionThirtyMinute = "MINUTE_30"
	// ResolutionHour - 1 hour price snapshot
	ResolutionHour = "HOUR"
	// ResolutionTwoHour - 2 hour price snapshot
	ResolutionTwoHour = "HOUR_2"
	// ResolutionThreeHour - 3 hour price snapshot
	ResolutionThreeHour = "HOUR_3"
	// ResolutionFourHour - 4 hour price snapshot
	ResolutionFourHour = "HOUR_4"
	// ResolutionDay - 1 day price snapshot
	ResolutionDay = "DAY"
	// ResolutionWeek - 1 week price snapshot
	ResolutionWeek = "WEEK"
	// ResolutionMonth - 1 month price snapshot
	ResolutionMonth = "MONTH"

	// DemoAPIURL - Demo API URL
	DemoAPIURL = "https://demo-api.ig.com"
	// LiveAPIURL - Live API URL - Real trading!
	LiveAPIURL = "https://api.ig.com"
)

Variables

This section is empty.

Functions

func LightStreamErrorHandler

func LightStreamErrorHandler(resp *http.Response, err error) error

Types

type Account

type Account struct {
	AccountID       string `json:"accountId"`
	AccountName     string `json:"accountName"`
	AccountAlias    string `json:"accountAlias"`
	AccountType     string `json:"accountType"`
	Balance         AccountBalance
	Currency        string `json:"currency"`
	CanTransferFrom bool   `json:"canTransferFrom"`
	CanTranferTo    bool   `json:"canTranferTo"`
	Prefered        bool   `json:"prefered"`
	Status          string `json:"status"`
}

type AccountBalance

type AccountBalance struct {
	Available  float64 `json:"available"`
	Balance    float64 `json:"balance"`
	Deposit    float64 `json:"deposit"`
	ProfitLoss float64 `json:"profitLoss"`
}

type AccountResponse

type AccountResponse struct {
	Accounts []Account `json:"accounts"`
}

type AffectedDeal

type AffectedDeal struct {
	DealID   string `json:"dealId"`
	Constant string `json:"constant"` // "FULLY_CLOSED"
}

AffectedDeal - part of order confirmation

type ClientSentimentResponse

type ClientSentimentResponse struct {
	LongPositionPercentage  float64 `json:"longPositionPercentage"`
	ShortPositionPercentage float64 `json:"shortPositionPercentage"`
}

ClientSentimentResponse - Response for client sentiment

type CreateWatchlistRequest

type CreateWatchlistRequest struct {
	Epics []string `json:"epics"`
	Name  string   `json:"name"`
}

CreateWatchlistRequest - Request for creating new watchlist

type CreateWatchlistResponse

type CreateWatchlistResponse struct {
	Status      string `json:"status"`
	WatchlistID string `json:"watchlistId"`
}

CreateWatchlistResponse - Response for creating new watchlist

type Currency

type Currency struct {
	BaseExchangeRate float64 `json:"baseExchangeRate"`
	Code             string  `json:"code"`
	ExchangeRate     float64 `json:"exchangeRate"`
	IsDefault        bool    `json:"isDefault"`
	Symbol           string  `json:"symbol"`
}

Currency - Part of MarketsResponse

type DealReference

type DealReference struct {
	DealReference string `json:"dealReference"`
}

DealReference - deal reference struct for responses

type DealingRules

type DealingRules struct {
	MarketOrderPreference         string         `json:"marketOrderPreference"`
	TrailingStopsPreference       string         `json:"trailingStopsPreference"`
	MaxStopOrLimitDistance        UnitValueFloat `json:"maxStopOrLimitDistance"`
	MinControlledRiskStopDistance UnitValueFloat `json:"minControlledRiskStopDistance"`
	MinDealSize                   UnitValueFloat `json:"minDealSize"`
	MinNormalStopOrLimitDistance  UnitValueFloat `json:"minNormalStopOrLimitDistance"`
	MinStepDistance               UnitValueFloat `json:"minStepDistance"`
}

DealingRules - Part of MarketsResponse

type HistoryTransactionResponse

type HistoryTransactionResponse struct {
	Transactions []Transaction `json:"transactions"`
	MetaData     struct {
		PageData struct {
			PageNumber int `json:"pageNumber"`
			PageSize   int `json:"pageSize"`
			TotalPages int `json:"totalPages"`
		} `json:"pageData"`
		Size int `json:"size"`
	} `json:"metaData"`
}

HistoryTransactionResponse - Response for transactions endpoint

type IGMarkets

type IGMarkets struct {
	APIURL          string
	APIKey          string
	AccountID       string
	Identifier      string
	Password        string
	OAuthToken      OAuthToken
	SessionVersion2 SessionVersion2
	SessionID       string

	AutoRefreshToken bool

	sync.RWMutex
	// contains filtered or unexported fields
}

IGMarkets - Object with all information we need to access IG REST API

func New

func New(apiURL, apiKey, accountID, identifier, password string, autoRefreshToken bool, httpTimeout time.Duration) (*IGMarkets, error)

New - Create new instance of igmarkets

func (*IGMarkets) AddToWatchlist

func (ig *IGMarkets) AddToWatchlist(watchListID, epic string) error

AddToWatchlist - Add epic to existing watchlist

func (*IGMarkets) CloseLightStreamerSubscription

func (ig *IGMarkets) CloseLightStreamerSubscription() error

func (*IGMarkets) CloseOTCPosition

func (ig *IGMarkets) CloseOTCPosition(close OTCPositionCloseRequest) (*DealReference, error)

CloseOTCPosition - Close an OTC position

func (*IGMarkets) CreateWatchlist

func (ig *IGMarkets) CreateWatchlist(name string, epics []string) (watchlistID string, err error)

CreateWatchlist - Create new watchlist

func (*IGMarkets) DeleteFromWatchlist

func (ig *IGMarkets) DeleteFromWatchlist(watchListID, epic string) error

DeleteFromWatchlist - Delete epic from watchlist

func (*IGMarkets) DeleteOTCWorkingOrder

func (ig *IGMarkets) DeleteOTCWorkingOrder(dealRef string) error

DeleteOTCWorkingOrder - Delete workingorder

func (*IGMarkets) DeletePositionsOTC

func (ig *IGMarkets) DeletePositionsOTC() error

DeletePositionsOTC - Closes one or more OTC positions

func (*IGMarkets) DeleteWatchlist

func (ig *IGMarkets) DeleteWatchlist(watchListID string) error

DeleteWatchlist - Delete whole watchlist

func (*IGMarkets) GetAccounts

func (ig *IGMarkets) GetAccounts() (*AccountResponse, error)

GetAccounts - Returns the accounts details

func (*IGMarkets) GetAllWatchlists

func (ig *IGMarkets) GetAllWatchlists() (*[]Watchlist, error)

GetAllWatchlists - Get all watchlist

func (*IGMarkets) GetClientSentiment

func (ig *IGMarkets) GetClientSentiment(MarketID string) (*ClientSentimentResponse, error)

GetClientSentiment - Get the client sentiment for the given instrument's market

func (*IGMarkets) GetDealConfirmation

func (ig *IGMarkets) GetDealConfirmation(dealRef string) (*OTCDealConfirmation, error)

GetDealConfirmation - Check if the given order was closed/filled

func (*IGMarkets) GetMarkets

func (ig *IGMarkets) GetMarkets(epic string) (*MarketsResponse, error)

GetMarkets - Return markets information for given epic

func (*IGMarkets) GetOTCWorkingOrders

func (ig *IGMarkets) GetOTCWorkingOrders() (*WorkingOrders, error)

GetOTCWorkingOrders - Get all working orders

func (*IGMarkets) GetPosition

func (ig *IGMarkets) GetPosition(dealRef string) (*Position, error)

GetPosition - Get the open position by reference

func (*IGMarkets) GetPositions

func (ig *IGMarkets) GetPositions() (*PositionsResponse, error)

GetPositions - Get all open positions

func (*IGMarkets) GetPrice

func (ig *IGMarkets) GetPrice(epic string) (*PriceResponse, error)

GetPrice - Return the minute prices for the last 10 minutes for the given epic.

func (*IGMarkets) GetPriceHistory

func (ig *IGMarkets) GetPriceHistory(epic, resolution string, max int, from, to time.Time) (*PriceResponse, error)

GetPriceHistory - Return the minute prices for the last 10 minutes for the given epic.

func (*IGMarkets) GetTransactions

func (ig *IGMarkets) GetTransactions(transactionType string, from time.Time) (*HistoryTransactionResponse, error)

GetTransactions - Return all transaction

func (*IGMarkets) GetWatchlist

func (ig *IGMarkets) GetWatchlist(watchListID string) (*WatchlistData, error)

GetWatchlist - Get specific watchlist

func (*IGMarkets) IsConnected

func (ig *IGMarkets) IsConnected() bool

func (*IGMarkets) Login

func (ig *IGMarkets) Login() error

Login - Get new OAuthToken from API and set it to IGMarkets object

func (*IGMarkets) LoginVersion2

func (ig *IGMarkets) LoginVersion2() (*SessionVersion2, error)

LoginVersion2 - use old login version. contains required data for LightStreamer API

func (*IGMarkets) Logout

func (ig *IGMarkets) Logout() error

func (*IGMarkets) LogoutLightStreamer

func (ig *IGMarkets) LogoutLightStreamer() error

func (*IGMarkets) MarketSearch

func (ig *IGMarkets) MarketSearch(term string) (*MarketSearchResponse, error)

MarketSearch - Search for ISIN or share names to get the epic.

func (*IGMarkets) OpenLightStreamerSubscription

func (ig *IGMarkets) OpenLightStreamerSubscription(
	ctx context.Context,
	o LightStreamOptions) (<-chan LightStreamChartTick, <-chan error, error)

GetOTCWorkingOrders - Get all working orders epic: e.g. CS.D.BITCOIN.CFD.IP tickReceiver: receives all ticks from lightstreamer API

func (*IGMarkets) PlaceOTCOrder

func (ig *IGMarkets) PlaceOTCOrder(order OTCOrderRequest) (*DealReference, error)

PlaceOTCOrder - Place an OTC order

func (*IGMarkets) PlaceOTCWorkingOrder

func (ig *IGMarkets) PlaceOTCWorkingOrder(order OTCWorkingOrderRequest) (*DealReference, error)

PlaceOTCWorkingOrder - Place an OTC workingorder

func (*IGMarkets) RefreshToken

func (ig *IGMarkets) RefreshToken() error

RefreshToken - Get new OAuthToken from API and set it to IGMarkets object

func (*IGMarkets) UpdateOTCOrder

func (ig *IGMarkets) UpdateOTCOrder(dealID string, order OTCUpdateOrderRequest) (*DealReference, error)

UpdateOTCOrder - Update an exisiting OTC order

type Instrument

type Instrument struct {
	ChartCode                string         `json:"chartCode"`
	ControlledRiskAllowed    bool           `json:"controlledRiskAllowed"`
	Country                  string         `json:"country"`
	Currencies               []Currency     `json:"currencies"`
	Epic                     string         `json:"epic"`
	Expiry                   string         `json:"expiry"`
	StreamingPricesAvailable bool           `json:"streamingPricesAvailable"`
	ForceOpenAllowed         bool           `json:"forceOpenAllowed"`
	Unit                     string         `json:"unit"`
	Type                     string         `json:"type"`
	MarketID                 string         `json:"marketID"`
	LotSize                  float64        `json:"lotSize"`
	MarginFactor             float64        `json:"marginFactor"`
	MarginFactorUnit         string         `json:"marginFactorUnit"`
	SlippageFactor           UnitValueFloat `json:"slippageFactor"`
	LimitedRiskPremium       UnitValueFloat `json:"limitedRiskPremium"`
	NewsCode                 string         `json:"newsCode"`
	ValueOfOnePip            string         `json:"valueOfOnePip"`
	OnePipMeans              string         `json:"onePipMeans"`
	ContractSize             string         `json:"contractSize"`
	SpecialInfo              []string       `json:"specialInfo"`
}

Instrument - Part of MarketsResponse

type LightStreamChartTick

type LightStreamChartTick struct {
	EPIC             string     `json:"EPIC,omitempty"`
	LTV              float64    `json:"LTV,omitempty"`              //Last traded volume
	TTV              float64    `json:"TTV,omitempty"`              //Incremental volume
	UTM              *time.Time `json:"UTM,omitempty"`              //Update time (as milliseconds from the Epoch)
	DAY_OPEN_MID     float64    `json:"DAY_OPEN_MID,omitempty"`     //Mid open price for the day
	DAY_NET_CHG_MID  float64    `json:"DAY_NET_CHG_MID,omitempty"`  //Change from open price to current (MID price)
	DAY_PERC_CHG_MID float64    `json:"DAY_PERC_CHG_MID,omitempty"` //Daily percentage change (MID price)
	DAY_HIGH         float64    `json:"DAY_HIGH,omitempty"`         //Daily high price (MID)
	DAY_LOW          float64    `json:"DAY_LOW,omitempty"`          //Daily low price (MID)
	OFR_OPEN         float64    `json:"OFR_OPEN,omitempty"`         //Candle open price (OFR)
	OFR_HIGH         float64    `json:"OFR_HIGH,omitempty"`         //Candle high price (OFR)
	OFR_LOW          float64    `json:"OFR_LOW,omitempty"`          //Candle low price (OFR)
	OFR_CLOSE        float64    `json:"OFR_CLOSE,omitempty"`        //Candle close price (OFR)
	BID_OPEN         float64    `json:"BID_OPEN,omitempty"`         //Candle open price (BID)
	BID_HIGH         float64    `json:"BID_HIGH,omitempty"`         //Candle high price (BID)
	BID_LOW          float64    `json:"BID_LOW,omitempty"`          //Candle low price (BID)
	BID_CLOSE        float64    `json:"BID_CLOSE,omitempty"`        //Candle close price (BID)
	LTP_OPEN         float64    `json:"LTP_OPEN,omitempty"`         //Candle open price (Last Traded Price)
	LTP_HIGH         float64    `json:"LTP_HIGH,omitempty"`         //Candle high price (Last Traded Price)
	LTP_LOW          float64    `json:"LTP_LOW,omitempty"`          //Candle low price (Last Traded Price)
	LTP_CLOSE        float64    `json:"LTP_CLOSE,omitempty"`        //Candle close price (Last Traded Price)
	CONS_END         float64    `json:"CONS_END,omitempty"`         //1 when candle ends, otherwise 0
	CONS_TICK_COUNT  float64    `json:"CONS_TICK_COUNT,omitempty"`  //Number of ticks in candle
}

func NewLightStreamChartTick

func NewLightStreamChartTick(epic string, fields []string, values []string) (tick LightStreamChartTick, err error)

func (*LightStreamChartTick) Merge

func (dest *LightStreamChartTick) Merge(src LightStreamChartTick)

type LightStreamOptions

type LightStreamOptions struct {
	Epics, Fields                     []string
	SubType, Interval, Mode           string
	ReconnectionTime, MaxReconnection int
}

type LightStreamerTick

type LightStreamerTick struct {
	Epic             string
	Time             time.Time
	OpenPrice        float64
	MaxPrice         float64
	MinPrice         float64
	ClosePrice       float64
	LastTradedVolume float64
}

type MarketData

type MarketData struct {
	Bid                      float64 `json:"bid"`
	DelayTime                int     `json:"delayTime"`
	Epic                     string  `json:"epic"`
	ExchangeID               string  `json:"exchangeId"`
	Expiry                   string  `json:"expiry"`
	High                     float64 `json:"high"`
	InstrumentName           string  `json:"instrumentName"`
	InstrumentType           string  `json:"instrumentType"`
	LotSize                  float64 `json:"lotSize"`
	Low                      float64 `json:"low"`
	MarektStatus             string  `json:"marketStatus"`
	NetChange                float64 `json:"netChange"`
	Offer                    float64 `json:"offer"`
	PercentageChange         float64 `json:"percentageChange"`
	ScalingFactor            int     `json:"scalingFactor"`
	StreamingPricesAvailable bool    `json:"streamingPricesAvailable"`
	UpdateTime               string  `json:"updateTime"`
	UpdateTimeUTC            string  `json:"updateTimeUTC"`
}

MarketData - Subset of OTCWorkingOrder

type MarketPrice

type MarketPrice struct {
	SnapshotTime     string `json:"snapshotTime"`
	SnapshotTimeUTC  string `json:"snapshotTimeUTC"`
	OpenPrice        Price  `json:"openPrice"`
	LowPrice         Price  `json:"lowPrice"`
	HighPrice        Price  `json:"highPrice"`
	ClosePrice       Price  `json:"closePrice"`
	LastTradedVolume int    `json:"lastTradedVolume"`
}

MarketPrice - Epic Price from IG Markets

type MarketSearchResponse

type MarketSearchResponse struct {
	Markets []MarketData `json:"markets"`
}

MarketSearchResponse - Contains the response data for MarketSearch()

type MarketsResponse

type MarketsResponse struct {
	DealingRules DealingRules `json:"dealingRules"`
	Instrument   Instrument   `json:"instrument"`
	Snapshot     Snapshot     `json:"snapshot"`
}

MarketsResponse - Market response for /markets/{epic}

type OAuthToken

type OAuthToken struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    string `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
	TokenType    string `json:"token_type"`
}

OAuthToken - part of the session

type OTCDealConfirmation

type OTCDealConfirmation struct {
	Epic                  string         `json:"epic"`
	Date                  Time           `json:"date"`
	AffectedDeals         []AffectedDeal `json:"affectedDeals"`
	Level                 float64        `json:"level"`
	ForceOpen             bool           `json:"forceOpen"`
	DealStatus            string         `json:"dealStatus"`
	Reason                string         `json:"reason"`
	Status                string         `json:"status"`
	OrderType             string         `json:"orderType"`
	Profit                float64        `json:"profit"`
	ProfitCurrency        string         `json:"profitCurrency"`
	CurrencyCode          string         `json:"currencyCode"`
	Direction             string         `json:"direction"` // "BUY" or "SELL"
	Expiry                string         `json:"expiry,omitempty"`
	Size                  float64        `json:"size"` // Deal size
	StopDistance          float64        `json:"stopDistance"`
	StopLevel             float64        `json:"stopLevel"`
	LimitDistance         string         `json:"limitDistance,omitempty"`
	LimitLevel            float64        `json:"limitLevel"`
	QuoteID               string         `json:"quoteId,omitempty"`
	TimeInForce           string         `json:"timeInForce,omitempty"` // "EXECUTE_AND_ELIMINATE" or "FILL_OR_KILL"
	TrailingStop          bool           `json:"trailingStop"`
	TrailingStopIncrement float64        `json:"trailingIncrement"`
	GuaranteedStop        bool           `json:"guaranteedStop"`
	DealReference         string         `json:"dealReference,omitempty"`
	DealID                string         `json:"dealId,omitempty"`
}

OTCDealConfirmation - Deal confirmation

type OTCOrderRequest

type OTCOrderRequest struct {
	Epic                  string  `json:"epic"`
	Level                 string  `json:"level,omitempty"`
	ForceOpen             bool    `json:"forceOpen"`
	OrderType             string  `json:"orderType"`
	CurrencyCode          string  `json:"currencyCode"`
	Direction             string  `json:"direction"` // "BUY" or "SELL"
	Expiry                string  `json:"expiry"`
	Size                  float64 `json:"size"` // Deal size
	StopDistance          string  `json:"stopDistance,omitempty"`
	StopLevel             string  `json:"stopLevel,omitempty"`
	LimitDistance         string  `json:"limitDistance,omitempty"`
	LimitLevel            string  `json:"limitLevel,omitempty"`
	QuoteID               string  `json:"quoteId,omitempty"`
	TimeInForce           string  `json:"timeInForce,omitempty"` // "EXECUTE_AND_ELIMINATE" or "FILL_OR_KILL"
	TrailingStop          bool    `json:"trailingStop"`
	TrailingStopIncrement string  `json:"trailingStopIncrement,omitempty"`
	GuaranteedStop        bool    `json:"guaranteedStop"`
	DealReference         string  `json:"dealReference,omitempty"`
}

OTCOrderRequest - request struct for placing orders

type OTCPositionCloseRequest

type OTCPositionCloseRequest struct {
	DealID      string  `json:"dealId,omitempty"`
	Direction   string  `json:"direction"` // "BUY" or "SELL"
	Epic        string  `json:"epic,omitempty"`
	Expiry      string  `json:"expiry,omitempty"`
	Level       string  `json:"level,omitempty"`
	OrderType   string  `json:"orderType"`
	QuoteID     string  `json:"quoteId,omitempty"`
	Size        float64 `json:"size"`                  // Deal size
	TimeInForce string  `json:"timeInForce,omitempty"` // "EXECUTE_AND_ELIMINATE" or "FILL_OR_KILL"
}

OTCPositionCloseRequest - request struct for closing positions

type OTCUpdateOrderRequest

type OTCUpdateOrderRequest struct {
	StopLevel             float64 `json:"stopLevel"`
	LimitLevel            float64 `json:"limitLevel"`
	TrailingStop          bool    `json:"trailingStop"`
	TrailingStopIncrement string  `json:"trailingStopIncrement,omitempty"`
}

OTCUpdateOrderRequest - request struct for updating orders

type OTCWorkingOrder

type OTCWorkingOrder struct {
	MarketData       MarketData       `json:"marketData"`
	WorkingOrderData WorkingOrderData `json:"workingOrderData"`
}

OTCWorkingOrder - Part of WorkingOrders

type OTCWorkingOrderRequest

type OTCWorkingOrderRequest struct {
	CurrencyCode   string  `json:"currencyCode"`
	DealReference  string  `json:"dealReference,omitempty"`
	Direction      string  `json:"direction"` // "BUY" or "SELL"
	Epic           string  `json:"epic"`
	Expiry         string  `json:"expiry"`
	ForceOpen      bool    `json:"forceOpen"`
	GoodTillDate   string  `json:"goodTillDate,omitempty"`
	GuaranteedStop bool    `json:"guaranteedStop"`
	Level          float64 `json:"level"`
	LimitDistance  string  `json:"limitDistance,omitempty"`
	LimitLevel     string  `json:"limitLevel,omitempty"`
	Size           float64 `json:"size"` // Deal size
	StopDistance   string  `json:"stopDistance,omitempty"`
	StopLevel      string  `json:"stopLevel,omitempty"`
	TimeInForce    string  `json:"timeInForce,omitempty"` // "GOOD_TILL_CANCELLED", "GOOD_TILL_DATE"
	Type           string  `json:"type"`
}

OTCWorkingOrderRequest - request struct for placing workingorders

type Position

type Position struct {
	MarketData MarketData `json:"market"`
	Position   struct {
		ContractSize         float64 `json:"contractSize"`
		ControlledRisk       bool    `json:"controlledRisk"`
		CreatedDate          string  `json:"createdDate"`
		CreatedDateUTC       string  `json:"createdDateUTC"`
		Currencry            string  `json:"currency"`
		DealID               string  `json:"dealId"`
		DealReference        string  `json:"dealReference"`
		Direction            string  `json:"direction"`
		Level                float64 `json:"level"`
		LimitLevel           float64 `json:"limitLevel"`
		Size                 float64 `json:"size"`
		StopLevel            float64 `json:"stopLevel"`
		TrailingStep         float64 `json:"trailingStep"`
		TrailingStopDistance float64 `json:"trailingStopDistance"`
	} `json:"position"`
}

Position - part of PositionsResponse

type PositionsResponse

type PositionsResponse struct {
	Positions []Position `json:"positions"`
}

PositionsResponse - Response from positions endpoint

type Price

type Price struct {
	Bid        float64 `json:"bid"`
	Ask        float64 `json:"ask"`
	LastTraded float64 `json:"lastTraded"` // Last traded price
}

Price - Subset of PriceResponse

type PriceResponse

type PriceResponse struct {
	Prices         []MarketPrice
	InstrumentType string   `json:"instrumentType"`
	MetaData       struct{} `json:"-"`
}

PriceResponse - Response for price query

type SessionVersion2

type SessionVersion2 struct {
	AccountType           string `json:"accountType"`      // "CFD"
	CurrencyIsoCode       string `json:"currencyIsoCode"`  // "EUR"
	CurrencySymbol        string `json:"currencySymbol"`   // "E"
	CurrentAccountId      string `json:"currentAccountId"` // "ABDGS"
	LightstreamerEndpoint string `json:"lightstreamerEndpoint"`
	ClientID              string `json:"clientId"`
	TimezoneOffset        int    `json:"timezoneOffset"` // In seconds
	HasActiveDemoAccounts bool   `json:"hasActiveDemoAccounts"`
	HasActiveLiveAccounts bool   `json:"hasActiveLiveAccounts"`
	TrailingStopsEnabled  bool   `json:"trailingStopsEnabled"`
	DealingEnabled        bool   `json:"dealingEnabled"`

	// Extracted from HTTP Header
	CSTToken string
	XSTToken string
}

SessionVersion2 - IG auth response required for LightStreamer API

type Snapshot

type Snapshot struct {
	MarketStatus              string  `json:"marketStatus"`
	NetChange                 float64 `json:"netChange"`
	PercentageChange          float64 `json:"percentageChange"`
	UpdateTime                string  `json:"updateTime"`
	DelayTime                 float64 `json:"delayTime"`
	Bid                       float64 `json:"bid"`
	Offer                     float64 `json:"offer"`
	High                      float64 `json:"high"`
	Low                       float64 `json:"low"`
	DecimalPlacesFactor       float64 `json:"decimalPlacesFactor"`
	ScalingFactor             float64 `json:"scalingFactor"`
	ControlledRiskExtraSpread float64 `json:"controlledRiskExtraSpread"`
}

Snapshot - Part of MarketsResponse

type Time

type Time time.Time

func (*Time) UnmarshalJSON

func (me *Time) UnmarshalJSON(data []byte) error

type Transaction

type Transaction struct {
	CashTransaction bool   `json:"cashTransaction"`
	CloseLevel      string `json:"closeLevel"`
	Currency        string `json:"currency"`
	Date            string `json:"date"`
	DateUTC         string `json:"dateUtc"`
	InstrumentName  string `json:"instrumentName"`
	OpenDateUtc     string `json:"openDateUtc"`
	OpenLevel       string `json:"openLevel"`
	Period          string `json:"period"`
	ProfitAndLoss   string `json:"profitAndLoss"`
	Reference       string `json:"reference"`
	Size            string `json:"size"`
	TransactionType string `json:"transactionType"`
}

Transaction - Part of HistoryTransactionResponse

type UnitValueFloat

type UnitValueFloat struct {
	Unit  string  `json:"unit"`
	Value float64 `json:"value"`
}

UnitValueFloat - Part of MarketsResponse

type Watchlist

type Watchlist struct {
	DefaultSystemWatchlist bool   `json:"defaultSystemWatchlist"`
	Deleteable             bool   `json:"deleteable"`
	Editable               bool   `json:"editable"`
	ID                     string `json:"id"`
	Name                   string `json:"name"`
}

Watchlist - Response from Watchlist endpoint

type WatchlistData

type WatchlistData struct {
	Markets []MarketData `json:"markets"`
}

WatchlistData - Response from Watchlist endpoint

type WatchlistRequest

type WatchlistRequest struct {
	Epic string `json:"epic"`
}

WatchlistRequest - For adding epic to watchlist

type WatchlistsResponse

type WatchlistsResponse struct {
	Watchlists []Watchlist
}

WatchlistsResponse - Response for getting all watchlists

type WorkingOrderData

type WorkingOrderData struct {
	CreatedDate     string  `json:"createdDate"`
	CreatedDateUTC  string  `json:"createdDateUTC"`
	CurrencyCode    string  `json:"currencyCode"`
	DealID          string  `json:"dealId"`
	Direction       string  `json:"direction"` // "BUY" or "SELL"
	DMA             bool    `json:"dma"`
	Epic            string  `json:"epic"`
	GoodTillDate    string  `json:"goodTillDate"`
	GoodTillDateISO string  `json:"goodTillDateISO"`
	GuaranteedStop  bool    `json:"guaranteedStop"`
	LimitDistance   float64 `json:"limitDistance"`
	OrderLevel      float64 `json:"orderLevel"`
	OrderSize       float64 `json:"orderSize"` // Deal size
	OrderType       string  `json:"orderType"`
	StopDistance    float64 `json:"stopDistance"`
	TimeInForce     string  `json:"timeInForce,omitempty"` // "EXECUTE_AND_ELIMINATE" or "FILL_OR_KILL"
}

WorkingOrderData - Subset of OTCWorkingOrder

type WorkingOrders

type WorkingOrders struct {
	WorkingOrders []OTCWorkingOrder `json:"workingOrders"`
}

WorkingOrders - Working orders

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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