etoro

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 12 Imported by: 0

README

etoro-go

A dependency-free Go client for the eToro Public API at public-api.etoro.com: market data (instrument search, candles, real-time rates, reference data), balances, identity, cash-account transactions, and trading (orders, positions, portfolio, history) against either the demo or the real account.

Authentication

Every request carries three headers: x-api-key, x-user-key, and an x-request-id the client generates as a fresh UUID v4 per call. The key pair is issued in the eToro API portal. Credentials are caller-supplied at construction — the package never reads environment variables, never logs key material, and sends it only in request headers, never in URLs or error messages. Keeping the keys in the environment and binding them at startup is the recommended pattern:

c := etoro.New(os.Getenv("ETORO_API_KEY"), os.Getenv("ETORO_USER_KEY"))

A client targets the demo (paper-trading) account by default. Demo and real share one host and differ only by a path segment on the trading routes; market-data, balances, identity, and cash endpoints are identical in both modes:

demo := etoro.New(apiKey, userKey)               // demo trading (default)
real := etoro.New(apiKey, userKey, etoro.Real()) // real-money trading

Identity(ctx) (GET /api/v1/me) verifies the pair and reports the OAuth scopes it was granted — a 403 elsewhere means the pair lacks that endpoint's scope.

Market data: search → candles

ctx := context.Background()
c := etoro.New(os.Getenv("ETORO_API_KEY"), os.Getenv("ETORO_USER_KEY"))

// Search matches internalSymbolFull by containment, so "AAPL" also returns
// "AAPL.24-7" and "AAPL.EUR". ResolveInstrument narrows to the exact symbol.
inst, err := c.ResolveInstrument(ctx, "AAPL")
if err != nil {
    log.Fatal(err)
}

candles, err := c.Candles(ctx, inst.InstrumentID, etoro.IntervalOneDay, 250)
if err != nil {
    log.Fatal(err)
}
for _, bar := range candles { // oldest first
    fmt.Println(bar.FromDate.Format("2006-01-02"), bar.Open, bar.High, bar.Low, bar.Close, bar.Volume)
}

Two candle-endpoint behaviours worth knowing, both verified against the live API:

  • Depth is capped at 1000 bars, and the window always ends at the most recent bar. There are no from/to parameters and no way to page further back in time; requesting more than 1000 is silently clamped by the server (the client clamps to 1000 up front for a predictable request). 1000 dailies reach back about four years — for deeper history use a coarser interval (IntervalOneWeek at full depth covers roughly 19 years).
  • An unknown instrument id is not an HTTP error. The API answers 200 with "candles": null. The client detects this and returns an error naming the instrument instead of an empty slice.

Balance

bal, err := c.Balance(ctx) // GET /api/v1/balances
if err != nil {
    log.Fatal(err)
}
fmt.Printf("total %.2f %s\n", bal.TotalBalance, bal.DisplayCurrency)
for _, acc := range bal.Balances {
    fmt.Printf("  %s (%s): %.2f %s\n", acc.AccountID, acc.AccountType, acc.Balance, acc.Currency)
}

AggregatedBalances adds zero-balance accounts and per-account equity details (buying power, used margin, crypto holdings); BalancesByType filters to one account type; BalanceHistory returns daily snapshots for up to 365 days within the last 12 months.

Trading

Consult TradingEligibility for an instrument's valid leverage values, sizing mode, and SL/TP bounds, and TradingCostEstimate to price an order without placing it. Order submission validates client-side first (see OrderRequest), and the x-request-id sent with the order doubles as its idempotency key: it is echoed back as referenceId, surfaced as OrderResult.RequestID, and accepted by OrderInfoByReference to recover an order's status even when the response was lost.

This places an order. With a client constructed via etoro.Real() the code below trades real money on the real account. Run it against the default demo mode until you have verified the behaviour end to end.

amount := 50.0
res, err := c.CreateOrder(ctx, etoro.OrderRequest{
    Action:         etoro.ActionOpen,
    Transaction:    etoro.TransactionBuy,
    Symbol:         "AAPL",
    OrderType:      etoro.OrderTypeMarket,
    SettlementType: etoro.SettlementCFD,
    Leverage:       1,
    Amount:         &amount, // USD; exactly one of Amount, Units, Contracts
})
if err != nil {
    log.Fatal(err)
}

// Execution is asynchronous: poll until filled to learn the position ids.
info, err := c.OrderInfo(ctx, res.OrderID)
if err != nil {
    log.Fatal(err)
}
if info.Status.ID == etoro.OrderStatusFilled {
    for _, p := range info.PositionExecutions {
        fmt.Println("opened position", p.PositionID)
    }
}

The rest of the trading surface: CancelOrder, ClosePosition (full or partial), CancelCloseOrder, ModifyPositionSLTP, PortfolioSummary (with live per-position P&L), PortfolioBreakdown (same portfolio, no valuations), CloseOrderInfo, and TradingHistory.

Backtest data source

The nested module github.com/florinel-chis/etoro-go/backtestsource adapts the client to the gobacktest engine's source.Source:

import (
    etoro "github.com/florinel-chis/etoro-go"
    etorobs "github.com/florinel-chis/etoro-go/backtestsource"
    "github.com/florinel-chis/gobacktest/source"
)

src := etorobs.New(etoro.New(apiKey, userKey))
data, err := src.Fetch(ctx, "AAPL", start, end, source.D1)

Symbols resolve to instrument ids once per source (ids are immutable, so the cache never goes stale) and candles are fetched natively. The candle endpoint serves only the most recent window of at most 1000 bars per interval — about 4 years of daily bars, or an instrument's full history on weekly bars. When a requested window reaches deeper than that, Fetch returns an error naming the earliest available bar instead of silently truncating; instruments whose whole history fits (young listings) are returned from their first bar. Bars follow the family-wide [start, end) contract, and the newest, still-forming session is dropped rather than reported as final OHLCV.

Rate limits and errors

Endpoints are rate-limited in pools (market data 120/60s shared across the group; trading execution 20/60s shared per mode; costs and eligibility 20/60s each; balances, identity, and cash draw from the shared default 60/60s quota). The server reports the quota in ratelimit-* response headers. On a 429 the client retries exactly once, honoring Retry-After when present (2s otherwise) and reusing the same x-request-id, since that id is the operation's idempotency key. Any 2xx status is success; every other status is returned as an *APIError carrying the HTTP status and the API's error message — never request headers or key material.

Tests

All tests are hermetic (httptest servers with fixtures shaped like live responses); go test ./... needs no network or credentials.

License

MIT

Documentation

Overview

Package etoro is a dependency-free Go client for the eToro Public API at public-api.etoro.com: market data (instrument search, candles, real-time rates, reference data), balances, identity, cash-account transactions, and trading (orders, portfolio, positions, history) against either the demo or the real account.

Every request carries the three headers the API requires: x-api-key, x-user-key, and an x-request-id that the client generates as a fresh UUID v4 per call. For order submission the x-request-id doubles as the idempotency key and is echoed back by the API as referenceId, so methods that place orders surface the id they sent.

Demo and real trading share one host; they differ only in a path segment. A Client targets the demo account unless constructed with the Real option. Market-data, balances, identity, and cash endpoints are not mode-specific.

Credentials are caller-supplied at construction; the package never reads environment variables, never logs key material, and sends it only in request headers — never in URLs or error messages.

Index

Constants

View Source
const (
	ActionOpen  = "open"
	ActionClose = "close"

	TransactionBuy        = "buy"
	TransactionSell       = "sell"
	TransactionSellShort  = "sellShort"
	TransactionBuyToCover = "buyToCover"

	OrderTypeMarket          = "mkt"
	OrderTypeMarketIfTouched = "mit"

	SettlementCFD         = "cfd"
	SettlementReal        = "real"
	SettlementRealFutures = "realFutures"
	SettlementMarginTrade = "marginTrade"

	StopLossFixed    = "fixed"
	StopLossTrailing = "trailing"
)

Order request enums. The API accepts these exact lowercase strings.

View Source
const (
	OrderStatusReceived                = 1
	OrderStatusPlaced                  = 2
	OrderStatusFilled                  = 3
	OrderStatusRejected                = 4
	OrderStatusPartiallyFilled         = 5
	OrderStatusPendingCancel           = 6
	OrderStatusCanceled                = 7
	OrderStatusExpired                 = 8
	OrderStatusCanceledPartiallyFilled = 9
	OrderStatusRejectedPartiallyFilled = 10
)

Order status ids as reported by OrderStatus.ID.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Status  int    // HTTP status code
	Message string // best-effort message from the response body
}

APIError is a non-2xx response from the API. Message is taken from the API's JSON error envelope when one is present; it never contains request headers or key material.

func (*APIError) Error

func (e *APIError) Error() string

type AccountBalance

type AccountBalance struct {
	AccountID       string         `json:"accountId"`
	AccountType     AccountType    `json:"accountType"`
	SubType         string         `json:"subType"`
	Balance         float64        `json:"balance"` // in the account's native currency
	Currency        string         `json:"currency"`
	DisplayBalance  float64        `json:"displayBalance"`
	DisplayCurrency string         `json:"displayCurrency"`
	ExchangeRate    float64        `json:"exchangeRate"`
	EquityDetails   *EquityDetails `json:"equityDetails"` // only when requested with expand=equityDetails
}

AccountBalance is one account's balance within a Balance response.

type AccountSnapshot

type AccountSnapshot struct {
	AccountID             string      `json:"accountId"`
	AccountType           AccountType `json:"accountType"`
	Currency              string      `json:"currency"`
	Cash                  float64     `json:"cash"`
	InvestedAmount        float64     `json:"investedAmount"`
	Pnl                   float64     `json:"pnl"`
	Total                 float64     `json:"total"`
	USDRate               float64     `json:"usdRate"`
	DisplayCash           float64     `json:"displayCash"`
	DisplayInvestedAmount float64     `json:"displayInvestedAmount"`
	DisplayPnl            float64     `json:"displayPnl"`
	DisplayTotal          float64     `json:"displayTotal"`
	ExchangeRate          float64     `json:"exchangeRate"`
}

AccountSnapshot is one account's state within a BalanceSnapshot.

type AccountType

type AccountType string

AccountType identifies an account category in balance requests, used both as a path segment and as an accountTypes query filter.

const (
	AccountTypeTrading   AccountType = "Trading"
	AccountTypeCash      AccountType = "Cash"
	AccountTypeOptions   AccountType = "Options"
	AccountTypeCrypto    AccountType = "Crypto"
	AccountTypeMoneyFarm AccountType = "MoneyFarm"
	AccountTypeSpaceship AccountType = "Spaceship"
)

Account types accepted by the balance endpoints.

func (*AccountType) UnmarshalJSON

func (a *AccountType) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts both the named form documented for request parameters ("Trading", "Cash", ...) and the bare numeric code the live service has been observed to return in balance payloads (for example 1 for the trading account). Numeric codes are kept as their decimal string.

type Balance

type Balance struct {
	GCID            int64            `json:"gcid"`
	TotalBalance    float64          `json:"totalBalance"`
	DisplayCurrency string           `json:"displayCurrency"`
	Balances        []AccountBalance `json:"balances"`
}

Balance is the current-balance response shared by the balance endpoints: the total across the returned accounts plus a per-account breakdown.

type BalanceHistory

type BalanceHistory struct {
	GCID            int64             `json:"gcid"`
	DisplayCurrency string            `json:"displayCurrency"`
	FromDate        string            `json:"fromDate"` // YYYY-MM-DD
	ToDate          string            `json:"toDate"`   // YYYY-MM-DD
	Snapshots       []BalanceSnapshot `json:"snapshots"`
}

BalanceHistory is a series of daily balance snapshots.

type BalanceHistoryParams

type BalanceHistoryParams struct {
	AccountTypes    []AccountType // optional filter; empty = all types
	DisplayCurrency string        // optional ISO 4217 code; empty = USD
	FromDate        time.Time     // optional; sent as YYYY-MM-DD
	ToDate          time.Time     // optional; sent as YYYY-MM-DD
}

BalanceHistoryParams filters a BalanceHistory request. The zero value requests the server default: all account types over the last 30 days, in USD. History is limited to the last 12 months and a range may span at most 365 days; the server responds 404 when no data exists for the range.

type BalanceSnapshot

type BalanceSnapshot struct {
	Date                       string            `json:"date"`
	TotalCurrencyISO           string            `json:"totalCurrencyIso"`
	TotalCash                  float64           `json:"totalCash"`
	TotalInvestedAmount        float64           `json:"totalInvestedAmount"`
	TotalPnl                   float64           `json:"totalPnl"`
	TotalBalance               float64           `json:"totalBalance"`
	DisplayTotalCash           float64           `json:"displayTotalCash"`
	DisplayTotalInvestedAmount float64           `json:"displayTotalInvestedAmount"`
	DisplayTotalPnl            float64           `json:"displayTotalPnl"`
	DisplayTotalBalance        float64           `json:"displayTotalBalance"`
	TotalExchangeRate          float64           `json:"totalExchangeRate"`
	AccountSnapshots           []AccountSnapshot `json:"accountSnapshots"`
}

BalanceSnapshot is the account-wide state on one day.

type BankIdentifier

type BankIdentifier struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

BankIdentifier is one named identifier of a counterparty bank account, for example an IBAN or a sort code.

type BankTransferTransactionDetails

type BankTransferTransactionDetails struct {
	BankIdentifier   []BankIdentifier `json:"bankIdentifier"`
	Description      string           `json:"description"`
	PaymentReference string           `json:"paymentReference"`
}

BankTransferTransactionDetails is set on bank-transfer transactions.

type Candle

type Candle struct {
	InstrumentID int       `json:"instrumentID"`
	FromDate     time.Time `json:"fromDate"`
	Open         float64   `json:"open"`
	High         float64   `json:"high"`
	Low          float64   `json:"low"`
	Close        float64   `json:"close"`
	Volume       float64   `json:"volume"`
}

Candle is one OHLCV bar. FromDate is the start of the candle period.

type CardTransactionDetails

type CardTransactionDetails struct {
	CardID              string `json:"cardId"`
	MerchantName        string `json:"merchantName"`
	Country             string `json:"country"`
	AuthorizationStatus string `json:"authorizationStatus"`
}

CardTransactionDetails is set on card transactions.

type CashCounterparty

type CashCounterparty struct {
	Name string `json:"name"`
	Type string `json:"type"` // merchant, bank_account, internal_account, unknown
}

CashCounterparty is the other party of a cash transaction.

type CashPagination

type CashPagination struct {
	PageSize      int    `json:"pageSize"`
	NextPageToken string `json:"nextPageToken"` // empty on the last page
	HasNext       bool   `json:"hasNext"`
}

CashPagination is the cursor state of a CashTransactionsPage. Feed NextPageToken into the next request's CashTransactionsParams.PageToken while HasNext is true.

type CashTransaction

type CashTransaction struct {
	ID                                 string                              `json:"id"`
	AccountID                          string                              `json:"accountId"`
	TransactionType                    string                              `json:"transactionType"`    // card, internalTransfer, bankTransfer, balanceAdjustment
	TransactionSubtype                 string                              `json:"transactionSubtype"` // cardPayment, transferReceived, refund, fee, ...
	Direction                          string                              `json:"direction"`          // debit or credit
	Status                             string                              `json:"status"`             // failed, authorized, settled, rejected, returned, expired, unknown
	Amount                             string                              `json:"amount"`             // decimal string
	Currency                           string                              `json:"currency"`           // ISO 4217
	OriginalAmount                     string                              `json:"originalAmount"`
	OriginalCurrency                   string                              `json:"originalCurrency"`
	ConversionRate                     string                              `json:"conversionRate"`
	PostedAt                           time.Time                           `json:"postedAt"`
	Counterparty                       CashCounterparty                    `json:"counterparty"`
	CardTransactionDetails             *CardTransactionDetails             `json:"cardTransactionDetails"`
	BankTransferTransactionDetails     *BankTransferTransactionDetails     `json:"bankTransferTransactionDetails"`
	InternalTransferTransactionDetails *InternalTransferTransactionDetails `json:"internalTransferTransactionDetails"`
}

CashTransaction is one movement on a cash account. Monetary amounts are decimal strings as sent by the API, preserving exact precision.

type CashTransactionsPage

type CashTransactionsPage struct {
	Results    []CashTransaction `json:"results"`
	Pagination CashPagination    `json:"pagination"`
}

CashTransactionsPage is one page of a cash account's transactions.

type CashTransactionsParams

type CashTransactionsParams struct {
	PageSize  int    // optional; server default 50, max 500
	PageToken string // opaque cursor from a previous page's Pagination.NextPageToken
}

CashTransactionsParams selects a page of cash-account transactions. The zero value requests the first page at the server default size (50).

type Client

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

Client is an eToro Public API client. Create with New. The zero value is not usable.

func New

func New(apiKey, userKey string, opts ...Option) *Client

New returns a Client for public-api.etoro.com authenticated with the given API key and user key, sent as the x-api-key and x-user-key headers on every request. Trading endpoints target the demo account unless the Real option is given.

func (*Client) AggregatedBalances

func (c *Client) AggregatedBalances(ctx context.Context) (Balance, error)

AggregatedBalances returns the current balance of every account, including zero-balance accounts, with per-account equity details expanded.

GET /api/v1/balances?expand=equityDetails&includeZeroBalances=true

func (*Client) Balance

func (c *Client) Balance(ctx context.Context) (Balance, error)

Balance returns the current balance of the accounts that hold a non-zero balance, in the default display currency (USD).

GET /api/v1/balances

func (*Client) BalanceHistory

func (c *Client) BalanceHistory(ctx context.Context, params BalanceHistoryParams) (BalanceHistory, error)

BalanceHistory returns daily balance snapshots for the range selected by params, across all account types.

GET /api/v1/balances/history

func (*Client) BalancesByType

func (c *Client) BalancesByType(ctx context.Context, accountType AccountType) (Balance, error)

BalancesByType returns the current balance of the accounts of one type, for example AccountTypeTrading.

GET /api/v1/balances/{accountType}

func (*Client) CancelCloseOrder

func (c *Client) CancelCloseOrder(ctx context.Context, orderID int64) (string, error)

CancelCloseOrder cancels a pending close order (DELETE /api/v1/trading/execution/{demo/}market-close-orders/{orderId}) and returns the tracking token.

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, orderID int64) (string, error)

CancelOrder cancels a pending order (DELETE /api/v2/trading/execution/{demo/}orders/{orderId}) and returns the tracking token. Cancelling an already closed or cancelled order is idempotent; an executed order can no longer be cancelled.

func (*Client) Candles

func (c *Client) Candles(ctx context.Context, instrumentID int, interval Interval, count int) ([]Candle, error)

Candles fetches up to count candles for an instrument, oldest first. count is clamped to the 1..1000 range the endpoint supports. The window always ends at the most recent bar (which may be a still-forming session); there is no way to page further back in time — use a coarser interval for deeper history.

For an unknown instrument id the API answers 200 with a null candle list rather than an error status, so a missing series is reported here as an error naming the instrument.

func (*Client) CashTransactions

func (c *Client) CashTransactions(ctx context.Context, accountID string, params CashTransactionsParams) (CashTransactionsPage, error)

CashTransactions returns one page of transactions for a cash account. The accountID must be the cash account's id (a UUID) as reported by the balance endpoints, not the numeric trading account id.

GET /api/v1/money/accounts/cash/{accountId}/transactions

func (*Client) CloseOrderInfo

func (c *Client) CloseOrderInfo(ctx context.Context, orderID int64) (OrderLookup, error)

CloseOrderInfo looks a close order up by its id (GET /api/v1/trading/info/{demo|real}/close-orders/{orderId}). The PositionsToClose and PositionExecutions fields report what was closed.

func (*Client) ClosePosition

func (c *Client) ClosePosition(ctx context.Context, positionID int64, instrumentID int, unitsToDeduct *float64) (ClosePositionResult, error)

ClosePosition places a market order to close a position (POST /api/v1/trading/execution/{demo/}market-close-orders/positions/{positionId}). instrumentID must be the position's instrument. A nil unitsToDeduct closes the whole position; a value closes that many units.

func (*Client) ClosingPrices

func (c *Client) ClosingPrices(ctx context.Context) ([]InstrumentClosingPrices, error)

ClosingPrices fetches the latest official closing prices for all instruments in one call. The endpoint takes no parameters.

func (*Client) CreateOrder

func (c *Client) CreateOrder(ctx context.Context, req OrderRequest) (OrderResult, error)

CreateOrder submits an order (POST /api/v2/trading/execution/{demo/}orders). The request is validated client-side first; see OrderRequest for the rules. Poll OrderInfo (or OrderInfoByReference with the returned RequestID) until the status reaches OrderStatusFilled to learn the resulting position ids.

func (*Client) Exchanges

func (c *Client) Exchanges(ctx context.Context) ([]Exchange, error)

Exchanges lists all exchanges.

func (*Client) Identity

func (c *Client) Identity(ctx context.Context) (Identity, error)

Identity returns the authenticated user's profile.

GET /api/v1/me

func (*Client) InstrumentDisplayData

func (c *Client) InstrumentDisplayData(ctx context.Context, ids []int) ([]InstrumentDisplayData, error)

InstrumentDisplayData fetches display metadata for the given instrument ids. With no ids the API returns data for all instruments.

func (*Client) InstrumentTypes

func (c *Client) InstrumentTypes(ctx context.Context) ([]InstrumentType, error)

InstrumentTypes lists all instrument types.

func (*Client) ModifyPositionSLTP

func (c *Client) ModifyPositionSLTP(ctx context.Context, positionID int64, stopLossRate, takeProfitRate *float64) (PositionEditResult, error)

ModifyPositionSLTP edits a position's stop loss and/or take profit (PATCH /api/v2/trading/{demo/}positions/{positionId}). Rates are absolute; a nil pointer leaves that side unchanged, and at least one of the two must be set. The edit is asynchronous: a 202 acknowledgement is returned, not the updated position.

func (*Client) OrderInfo

func (c *Client) OrderInfo(ctx context.Context, orderID int64) (OrderLookup, error)

OrderInfo looks an order up by its id (GET /api/v2/trading/info/{demo/}orders:lookup?orderId=).

func (*Client) OrderInfoByReference

func (c *Client) OrderInfoByReference(ctx context.Context, referenceID string) (OrderLookup, error)

OrderInfoByReference looks an order up by the x-request-id it was submitted with (GET /api/v2/trading/info/{demo/}orders:lookup?referenceId=). This recovers an order's status when the CreateOrder response was lost: pass the RequestID from OrderResult.

func (*Client) PortfolioBreakdown

func (c *Client) PortfolioBreakdown(ctx context.Context) (ClientPortfolio, error)

PortfolioBreakdown returns the portfolio without valuations (GET /api/v1/trading/info/{demo/}portfolio) — the same positions, orders, and mirrors as PortfolioSummary, but cheaper and with no per-position or account-level unrealized P&L.

func (*Client) PortfolioSummary

func (c *Client) PortfolioSummary(ctx context.Context) (ClientPortfolio, error)

PortfolioSummary returns the portfolio with live valuations (GET /api/v1/trading/info/{demo|real}/pnl): every position carries an UnrealizedPnL and the account-level UnrealizedPnL and AccountCurrencyID are set.

func (*Client) Rates

func (c *Client) Rates(ctx context.Context, ids []int) ([]Rate, error)

Rates fetches real-time bid/ask rates for the given instrument ids. At least one id is required.

func (*Client) ResolveInstrument

func (c *Client) ResolveInstrument(ctx context.Context, symbol string) (Instrument, error)

ResolveInstrument resolves symbol to a single instrument by exact, case-insensitive match on internalSymbolFull among the search results. When no result matches exactly, or more than one does, the error lists the candidate symbols the search returned.

func (*Client) SearchInstruments

func (c *Client) SearchInstruments(ctx context.Context, symbol string) ([]Instrument, error)

SearchInstruments looks up instruments whose internalSymbolFull matches symbol. The API matches by containment, not equality: searching "AAPL" also returns variants such as "AAPL.24-7" and "AAPL.EUR". Use ResolveInstrument for an exact-symbol resolution.

func (*Client) TradingCostEstimate

func (c *Client) TradingCostEstimate(ctx context.Context, req OrderRequest) (CostEstimate, error)

TradingCostEstimate prices an order without placing it (POST /api/v2/trading/info/{demo/}costs). The request takes the same shape and client-side validation as CreateOrder.

func (*Client) TradingEligibility

func (c *Client) TradingEligibility(ctx context.Context, instrumentID int) (InstrumentEligibility, error)

TradingEligibility returns the trading configuration for one instrument (POST /api/v2/trading/info/{demo/}eligibility). Consult it before ordering: it carries the valid leverage values, sizing mode, fractional support, and SL/TP bounds. An unknown instrument id is an error.

func (*Client) TradingHistory

func (c *Client) TradingHistory(ctx context.Context, params TradeHistoryParams) ([]ClosedTrade, error)

TradingHistory returns ONE PAGE of closed trades since params.MinDate (GET /api/v1/trading/info/trade/{demo/}history). The endpoint is paged: a single call never returns more than one page (the server's default page size when Page/PageSize are unset), so a period with more trades than one page holds must be walked by incrementing params.Page until a call returns fewer than params.PageSize trades (or none).

type ClientPortfolio

type ClientPortfolio struct {
	Positions         []Position      `json:"positions"`
	Credit            float64         `json:"credit"`
	Mirrors           []Mirror        `json:"mirrors"`
	Orders            []PendingOrder  `json:"orders"`
	OrdersForOpen     []OrderForOpen  `json:"ordersForOpen"`
	OrdersForClose    []OrderForClose `json:"ordersForClose"`
	BonusCredit       float64         `json:"bonusCredit"`
	UnrealizedPnL     float64         `json:"unrealizedPnL"`
	AccountCurrencyID int             `json:"accountCurrencyId"` // 1 = USD
}

ClientPortfolio is the account's positions, pending orders, mirrors, and cash. Credit is the available trading balance in USD before deducting pending orders. UnrealizedPnL and AccountCurrencyID are populated by PortfolioSummary only.

type CloseOrderReceipt

type CloseOrderReceipt struct {
	PositionID    int64     `json:"positionID"`
	InstrumentID  int       `json:"instrumentID"`
	UnitsToDeduct float64   `json:"unitsToDeduct"`
	OrderID       int64     `json:"orderID"`
	OrderType     int       `json:"orderType"`
	StatusID      int       `json:"statusID"`
	CID           int64     `json:"CID"`
	OpenDateTime  time.Time `json:"openDateTime"`
	LastUpdate    time.Time `json:"lastUpdate"`
}

CloseOrderReceipt describes the close order created by ClosePosition.

type ClosePositionResult

type ClosePositionResult struct {
	OrderForClose CloseOrderReceipt `json:"orderForClose"`
	Token         string            `json:"token"`
}

ClosePositionResult is the acknowledgement returned by ClosePosition.

type ClosedTrade

type ClosedTrade struct {
	NetProfit         float64   `json:"netProfit"`
	CloseRate         float64   `json:"closeRate"`
	CloseTimestamp    time.Time `json:"closeTimestamp"`
	PositionID        int64     `json:"positionId"`
	InstrumentID      int       `json:"instrumentId"`
	IsBuy             bool      `json:"isBuy"`
	Leverage          int       `json:"leverage"`
	OpenRate          float64   `json:"openRate"`
	OpenTimestamp     time.Time `json:"openTimestamp"`
	StopLossRate      float64   `json:"stopLossRate"`
	TakeProfitRate    float64   `json:"takeProfitRate"`
	TrailingStopLoss  bool      `json:"trailingStopLoss"`
	OrderID           int64     `json:"orderId"`
	SocialTradeID     int64     `json:"socialTradeId"`
	ParentPositionID  int64     `json:"parentPositionId"`
	Investment        float64   `json:"investment"`
	InitialInvestment float64   `json:"initialInvestment"`
	Fees              float64   `json:"fees"`
	Units             float64   `json:"units"`
}

ClosedTrade is one closed trade from the trading history.

type ClosingPriceSet

type ClosingPriceSet struct {
	Daily   PeriodClose `json:"daily"`
	Weekly  PeriodClose `json:"weekly"`
	Monthly PeriodClose `json:"monthly"`
}

ClosingPriceSet groups the previous daily, weekly, and monthly closes of one instrument.

type CostEstimate

type CostEstimate struct {
	InstrumentID int         `json:"instrumentId"`
	Symbol       string      `json:"symbol"`
	Costs        []TradeCost `json:"costs"`
	LastUpdated  time.Time   `json:"lastUpdated"`
}

CostEstimate is the what-if cost breakdown of an order.

type EquityDetails

type EquityDetails struct {
	Available              *float64 `json:"available"`  // buying power (Trading/Options/MoneyFarm/Cash)
	FrozenCash             *float64 `json:"frozenCash"` // Trading
	CurrentPNL             *float64 `json:"currentPNL"` // Trading
	TotalUsedMargin        *float64 `json:"totalUsedMargin"`
	CryptoID               *int     `json:"cryptoId"`
	Balance                *float64 `json:"balance"`
	TotalBalance           *float64 `json:"totalBalance"`
	SpendableBalance       *float64 `json:"spendableBalance"`
	BalanceInFiat          *float64 `json:"balanceInFiat"`
	TotalBalanceInFiat     *float64 `json:"totalBalanceInFiat"`
	SpendableBalanceInFiat *float64 `json:"spendableBalanceInFiat"`
	FiatConversionCurrency string   `json:"fiatConversionCurrency"`
	OrderIndex             *int     `json:"orderIndex"`
}

EquityDetails carries provider-specific equity figures for an account. Every field is nullable and which ones are populated depends on the account type (trading accounts fill the margin fields, crypto accounts the crypto ones).

type Exchange

type Exchange struct {
	ExchangeID          int    `json:"exchangeID"`
	ExchangeDescription string `json:"exchangeDescription"`
}

Exchange is one trading venue known to the platform.

type Identity

type Identity struct {
	GCID        int64    `json:"gcid"`    // global customer id
	RealCID     int64    `json:"realCid"` // real-account customer id
	DemoCID     int64    `json:"demoCid"` // demo-account customer id
	Username    string   `json:"username"`
	FirstName   string   `json:"firstName"`
	MiddleName  string   `json:"middleName"`
	LastName    string   `json:"lastName"`
	PlayerLevel int      `json:"playerLevel"` // 1 Bronze, 2 Platinum, 3 Gold, 4 Internal, 5 Silver, 6 PlatinumPlus, 7 Diamond
	Gender      int      `json:"gender"`      // 0 unknown, 1 male, 2 female
	Language    int      `json:"language"`    // 1 English, 2 German, ...
	DateOfBirth string   `json:"dateOfBirth"`
	AvatarURL   string   `json:"avatarUrl"`
	Scopes      []string `json:"scopes"` // OAuth scopes granted to this credential pair
}

Identity is the authenticated user's profile, including the customer ids of the real and demo accounts and the OAuth scopes granted to the credential pair. Fetch it once to verify credentials and discover what the keys are allowed to do.

type Instrument

type Instrument struct {
	InstrumentID        int     `json:"instrumentId"`
	InternalSymbolFull  string  `json:"internalSymbolFull"`
	DisplayName         string  `json:"displayname"`
	InstrumentTypeID    int     `json:"instrumentTypeID"`
	ExchangeID          int     `json:"exchangeID"`
	IsCurrentlyTradable bool    `json:"isCurrentlyTradable"`
	IsDelisted          bool    `json:"isDelisted"`
	CurrentRate         float64 `json:"currentRate"`
}

Instrument is one item from instrument search. InstrumentID is immutable (it survives ticker changes and rebrands), so it is safe to cache.

type InstrumentClosingPrices

type InstrumentClosingPrices struct {
	InstrumentID         int             `json:"instrumentId"`
	OfficialClosingPrice float64         `json:"officialClosingPrice"`
	ClosingPrices        ClosingPriceSet `json:"closingPrices"`
}

InstrumentClosingPrices is the closing-price record of one instrument.

type InstrumentDisplayData

type InstrumentDisplayData struct {
	InstrumentID          int               `json:"instrumentID"`
	InstrumentDisplayName string            `json:"instrumentDisplayName"`
	InstrumentTypeID      int               `json:"instrumentTypeID"`
	ExchangeID            int               `json:"exchangeID"`
	SymbolFull            string            `json:"symbolFull"`
	StocksIndustryID      int               `json:"stocksIndustryId"`
	PriceSource           string            `json:"priceSource"`
	HasExpirationDate     bool              `json:"hasExpirationDate"`
	IsInternalInstrument  bool              `json:"isInternalInstrument"`
	Images                []InstrumentImage `json:"images"`
}

InstrumentDisplayData is descriptive metadata for one instrument. IsInternalInstrument true means the instrument is restricted from public use.

type InstrumentEligibility

type InstrumentEligibility struct {
	InstrumentID                  int              `json:"instrumentId"`
	Symbol                        string           `json:"symbol"`
	MinPositionExposure           float64          `json:"minPositionExposure"`
	MaxUnitsPerOrder              float64          `json:"maxUnitsPerOrder"`
	AllowOpenPosition             bool             `json:"allowOpenPosition"`
	AllowClosePosition            bool             `json:"allowClosePosition"`
	AllowPartialClosePosition     bool             `json:"allowPartialClosePosition"`
	AllowMitOrders                bool             `json:"allowMitOrders"`
	AllowEntryOrders              bool             `json:"allowEntryOrders"`
	AllowExitOrders               bool             `json:"allowExitOrders"`
	AllowTrailingStopLoss         bool             `json:"allowTrailingStopLoss"`
	RequiresW8Ben                 *bool            `json:"requiresW8Ben"`
	UnitsQuantityType             string           `json:"unitsQuantityType"` // whole or fractional
	OrderFillBehaviorType         string           `json:"orderFillBehaviorType"`
	AllowedOrderQuantityType      string           `json:"allowedOrderQuantityType"`
	TradeUnitType                 string           `json:"tradeUnitType"`
	InitialMarginInAssetCurrency  *float64         `json:"initialMarginInAssetCurrency"`
	StopLossMarginInAssetCurrency *float64         `json:"stopLossMarginInAssetCurrency"`
	AdditionalBufferPercent       *float64         `json:"additionalBufferPercent"`
	LeverageConfigs               []LeverageConfig `json:"leverageConfigs"`
}

InstrumentEligibility is an instrument's trading configuration: what order types it allows, how it is sized, and the valid leverage values per settlement type and direction.

type InstrumentImage

type InstrumentImage struct {
	InstrumentID    int    `json:"instrumentID"`
	Width           int    `json:"width"`
	Height          int    `json:"height"`
	URI             string `json:"uri"`
	BackgroundColor string `json:"backgroundColor"`
	TextColor       string `json:"textColor"`
}

InstrumentImage is one logo rendition for an instrument.

type InstrumentType

type InstrumentType struct {
	InstrumentTypeID          int    `json:"instrumentTypeID"`
	InstrumentTypeDescription string `json:"instrumentTypeDescription"`
}

InstrumentType is one asset class (stocks, crypto, ...).

type InternalTransferTransactionDetails

type InternalTransferTransactionDetails struct {
	TransferID string `json:"transferId"`
}

InternalTransferTransactionDetails is set on transfers between eToro accounts.

type Interval

type Interval string

Interval is a candle period for Candles. The API accepts exactly these nine values.

const (
	IntervalOneMinute      Interval = "OneMinute"
	IntervalFiveMinutes    Interval = "FiveMinutes"
	IntervalTenMinutes     Interval = "TenMinutes"
	IntervalFifteenMinutes Interval = "FifteenMinutes"
	IntervalThirtyMinutes  Interval = "ThirtyMinutes"
	IntervalOneHour        Interval = "OneHour"
	IntervalFourHours      Interval = "FourHours"
	IntervalOneDay         Interval = "OneDay"
	IntervalOneWeek        Interval = "OneWeek"
)

Candle intervals accepted by the candles endpoint.

type LeverageConfig

type LeverageConfig struct {
	SettlementType              string  `json:"settlementType"`
	Direction                   string  `json:"direction"` // long or short
	LeverageValues              []int   `json:"leverageValues"`
	IsPotential                 bool    `json:"isPotential"`
	MinPositionAmount           float64 `json:"minPositionAmount"`
	AllowEditStopLoss           bool    `json:"allowEditStopLoss"`
	MinStopLossPercentage       float64 `json:"minStopLossPercentage"`
	MaxStopLossPercentage       float64 `json:"maxStopLossPercentage"`
	DefaultStopLossPercentage   float64 `json:"defaultStopLossPercentage"`
	AllowEditTakeProfit         bool    `json:"allowEditTakeProfit"`
	MinTakeProfitPercentage     float64 `json:"minTakeProfitPercentage"`
	MaxTakeProfitPercentage     float64 `json:"maxTakeProfitPercentage"`
	DefaultTakeProfitPercentage float64 `json:"defaultTakeProfitPercentage"`
	AllowStopLossTakeProfit     bool    `json:"allowStopLossTakeProfit"`
}

LeverageConfig is one settlement-type/direction combination an instrument can be traded with.

type Mirror

type Mirror struct {
	MirrorID                 int             `json:"mirrorID"`
	CID                      int64           `json:"CID"`
	ParentCID                int64           `json:"parentCID"`
	ParentUsername           string          `json:"parentUsername"`
	StopLossPercentage       float64         `json:"stopLossPercentage"`
	StopLossAmount           float64         `json:"stopLossAmount"`
	IsPaused                 bool            `json:"isPaused"`
	CopyExistingPositions    bool            `json:"copyExistingPositions"`
	AvailableAmount          float64         `json:"availableAmount"`
	InitialInvestment        float64         `json:"initialInvestment"`
	DepositSummary           float64         `json:"depositSummary"`
	WithdrawalSummary        float64         `json:"withdrawalSummary"`
	Positions                []Position      `json:"positions"`
	ClosedPositionsNetProfit float64         `json:"closedPositionsNetProfit"`
	StartedCopyDate          time.Time       `json:"startedCopyDate"`
	PendingForClosure        bool            `json:"pendingForClosure"`
	MirrorStatusID           int             `json:"mirrorStatusID"` // 0 active, 1 paused, 2 pending closure, 3 in alignment
	OrdersForOpen            []OrderForOpen  `json:"ordersForOpen"`
	OrdersForClose           []OrderForClose `json:"ordersForClose"`
}

Mirror is a copy-trading relationship and the positions held under it.

type Option

type Option func(*Client)

Option configures a Client.

func Demo

func Demo() Option

Demo targets the demo (paper-trading) account for trading endpoints. This is the default.

func Real

func Real() Option

Real targets the real account for trading endpoints. Market-data, balances, identity, and cash endpoints are identical in both modes.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient replaces the default HTTP client (30s timeout).

type OrderAsset

type OrderAsset struct {
	Symbol         string `json:"symbol"`
	InstrumentID   int    `json:"instrumentId"`
	Currency       string `json:"currency"`
	SettlementType string `json:"settlementType"`
	Leverage       int    `json:"leverage"`
	Side           string `json:"side"` // long or short
}

OrderAsset identifies the instrument an order trades.

type OrderForClose

type OrderForClose struct {
	OrderID       int64     `json:"orderId"`
	OrderType     int       `json:"orderType"`
	StatusID      int       `json:"statusId"`
	CID           int64     `json:"cid"`
	OpenDateTime  time.Time `json:"openDateTime"`
	LastUpdate    time.Time `json:"lastUpdate"`
	InstrumentID  int       `json:"instrumentId"`
	UnitsToDeduct float64   `json:"unitsToDeduct"`
	LotsToDeduct  float64   `json:"lotsToDeduct"`
	PositionID    int64     `json:"positionId"`
}

OrderForClose is a pending market order to close a position.

type OrderForOpen

type OrderForOpen struct {
	OrderID            int64     `json:"orderId"`
	OrderType          int       `json:"orderType"`
	StatusID           int       `json:"statusId"`
	CID                int64     `json:"cid"`
	OpenDateTime       time.Time `json:"openDateTime"`
	LastUpdate         time.Time `json:"lastUpdate"`
	InstrumentID       int       `json:"instrumentId"`
	Amount             float64   `json:"amount"`
	AmountInUnits      float64   `json:"amountInUnits"`
	IsBuy              bool      `json:"isBuy"`
	Leverage           int       `json:"leverage"`
	StopLossRate       float64   `json:"stopLossRate"`
	TakeProfitRate     float64   `json:"takeProfitRate"`
	IsTslEnabled       bool      `json:"isTslEnabled"`
	MirrorID           int       `json:"mirrorId"`
	FrozenAmount       float64   `json:"frozenAmount"`
	TotalExternalCosts float64   `json:"totalExternalCosts"`
	IsNoTakeProfit     bool      `json:"isNoTakeProfit"`
	IsNoStopLoss       bool      `json:"isNoStopLoss"`
	LotCount           float64   `json:"lotCount"`
}

OrderForOpen is a pending market order to open a position.

type OrderLookup

type OrderLookup struct {
	AccountID            int64               `json:"accountId"`
	GCID                 int64               `json:"gcid"`
	PortfolioID          int                 `json:"portfolioId"`
	OrderID              int64               `json:"orderId"`
	Action               string              `json:"action"`
	Transaction          string              `json:"transaction"`
	Type                 string              `json:"type"` // mkt or mit
	EtoroOrderTypeID     int                 `json:"etoroOrderTypeId"`
	Status               OrderStatus         `json:"status"`
	Asset                OrderAsset          `json:"asset"`
	OrderCurrency        string              `json:"orderCurrency"`
	RequestedAmount      *float64            `json:"requestedAmount"`
	RequestedUnits       *float64            `json:"requestedUnits"`
	RequestedContracts   *float64            `json:"requestedContracts"`
	FrozenAmount         *float64            `json:"frozenAmount"`
	RequestedTriggerRate *float64            `json:"requestedTriggerRate"`
	OpenStopLossRate     *float64            `json:"openStopLossRate"`
	OpenTakeProfitRate   *float64            `json:"openTakeProfitRate"`
	StopLossType         string              `json:"stopLossType"`
	TotalCosts           float64             `json:"totalCosts"`
	PositionsToClose     []int64             `json:"positionsToClose"`
	PositionExecutions   []PositionExecution `json:"positionExecutions"`
	RequestTime          time.Time           `json:"requestTime"`
	LastUpdate           time.Time           `json:"lastUpdate"`
	OpenActionType       string              `json:"openActionType"`
	RequestType          string              `json:"requestType"` // byAmount, byUnits, or byContracts
}

OrderLookup is the full status of an order or close order.

type OrderRequest

type OrderRequest struct {
	Action           string   `json:"action"`
	Transaction      string   `json:"transaction"`
	Symbol           string   `json:"symbol,omitempty"`
	InstrumentID     int      `json:"instrumentId,omitempty"`
	SettlementType   string   `json:"settlementType,omitempty"`
	OrderType        string   `json:"orderType,omitempty"`
	TriggerRate      *float64 `json:"triggerRate,omitempty"`
	Leverage         int      `json:"leverage,omitempty"`
	Amount           *float64 `json:"amount,omitempty"`
	Units            *float64 `json:"units,omitempty"`
	Contracts        *float64 `json:"contracts,omitempty"`
	OrderCurrency    string   `json:"orderCurrency,omitempty"`
	StopLossRate     *float64 `json:"stopLossRate,omitempty"`
	TakeProfitRate   *float64 `json:"takeProfitRate,omitempty"`
	StopLossType     string   `json:"stopLossType,omitempty"`
	AdditionalMargin *float64 `json:"additionalMargin,omitempty"`
	PositionIDs      []int64  `json:"positionIds,omitempty"`
}

OrderRequest describes an order for CreateOrder and TradingCostEstimate.

Action and Transaction are always required. For open orders exactly one of Symbol or InstrumentID identifies the asset, exactly one of Amount, Units, or Contracts sizes the order, and SettlementType, Leverage, and OrderType are required by the API. OrderType is "mkt" (market) or "mit" (market-if-touched, which additionally needs TriggerRate). Close orders identify what to close through PositionIDs instead.

StopLossRate and TakeProfitRate are absolute rates, not distances.

type OrderResult

type OrderResult struct {
	Token       string `json:"token"`       // tracking token
	OrderID     int64  `json:"orderId"`     // assigned order id
	ReferenceID string `json:"referenceId"` // echo of the x-request-id header

	// RequestID is the x-request-id this client sent with the order. It is
	// the order's idempotency key and matches ReferenceID on success; use it
	// with OrderInfoByReference to recover an order's status even when the
	// response was lost. It is populated on decode failures too.
	RequestID string `json:"-"`
}

OrderResult is the acknowledgement returned by CreateOrder.

type OrderStatus

type OrderStatus struct {
	ID           int    `json:"id"` // one of the OrderStatus* constants
	Name         string `json:"name"`
	ErrorCode    int    `json:"errorCode"` // 0 means no error
	ErrorMessage string `json:"errorMessage"`
}

OrderStatus is the state of an order in an OrderLookup.

type PendingOrder

type PendingOrder struct {
	OrderID        int64     `json:"orderId"`
	CID            int64     `json:"cid"`
	OpenDateTime   time.Time `json:"openDateTime"`
	InstrumentID   int       `json:"instrumentId"`
	IsBuy          bool      `json:"isBuy"`
	TakeProfitRate float64   `json:"takeProfitRate"`
	StopLossRate   float64   `json:"stopLossRate"`
	Rate           float64   `json:"rate"` // trigger rate
	Amount         float64   `json:"amount"`
	Leverage       int       `json:"leverage"`
	Units          float64   `json:"units"`
	IsTslEnabled   bool      `json:"isTslEnabled"`
	IsNoTakeProfit bool      `json:"isNoTakeProfit"`
	IsNoStopLoss   bool      `json:"isNoStopLoss"`
}

PendingOrder is a pending market-if-touched order (the portfolio's orders array). Units > 0 means the order was sized by units, not amount.

type PeriodClose

type PeriodClose struct {
	Price float64   `json:"price"`
	Date  time.Time `json:"date"`
}

PeriodClose is the closing price of one period. The API marks "no data" with the sentinel pair Price -1 and the zero date 0001-01-01; use HasData to test for it.

func (PeriodClose) HasData

func (p PeriodClose) HasData() bool

HasData reports whether the period carries a real closing price rather than the API's -1 / 0001-01-01 no-data sentinel.

type Position

type Position struct {
	PositionID             int64        `json:"positionID"`
	CID                    int64        `json:"CID"`
	OpenDateTime           time.Time    `json:"openDateTime"`
	OpenRate               float64      `json:"openRate"`
	InstrumentID           int          `json:"instrumentID"`
	MirrorID               int          `json:"mirrorID"`
	ParentPositionID       int64        `json:"parentPositionID"`
	IsBuy                  bool         `json:"isBuy"`
	TakeProfitRate         float64      `json:"takeProfitRate"`
	StopLossRate           float64      `json:"stopLossRate"`
	Amount                 float64      `json:"amount"` // USD margin incl. collateral
	Leverage               float64      `json:"leverage"`
	OrderID                int64        `json:"orderID"`
	OrderType              int          `json:"orderType"`
	Units                  float64      `json:"units"`
	TotalFees              float64      `json:"totalFees"` // negative = refund
	InitialAmountInDollars float64      `json:"initialAmountInDollars"`
	IsTslEnabled           bool         `json:"isTslEnabled"`
	StopLossVersion        int          `json:"stopLossVersion"`
	RedeemStatusID         int          `json:"redeemStatusID"`
	InitialUnits           float64      `json:"initialUnits"`
	IsPartiallyAltered     bool         `json:"isPartiallyAltered"`
	UnitsBaseValueDollars  float64      `json:"unitsBaseValueDollars"`
	OpenPositionActionType int          `json:"openPositionActionType"`
	SettlementTypeID       int          `json:"settlementTypeID"`
	IsDetached             bool         `json:"isDetached"`
	OpenConversionRate     float64      `json:"openConversionRate"`
	PnLVersion             int          `json:"pnlVersion"`
	TotalExternalFees      float64      `json:"totalExternalFees"`
	TotalExternalTaxes     float64      `json:"totalExternalTaxes"`
	IsNoTakeProfit         bool         `json:"isNoTakeProfit"`
	IsNoStopLoss           bool         `json:"isNoStopLoss"`
	LotCount               float64      `json:"lotCount"`
	UnrealizedPnL          *PositionPnL `json:"unrealizedPnL,omitempty"`
}

Position is an open position. MirrorID is 0 for manually opened positions and non-zero for copy-trading positions. Note the inverted IsNoTakeProfit/IsNoStopLoss flags: false means the level is set. UnrealizedPnL is populated by PortfolioSummary only; PortfolioBreakdown leaves it nil.

type PositionEditResult

type PositionEditResult struct {
	OperationID string `json:"operationId"`
	PositionID  int64  `json:"positionId"`
	ReferenceID string `json:"referenceId"` // echo of the x-request-id header
}

PositionEditResult is the asynchronous acknowledgement returned by ModifyPositionSLTP (HTTP 202).

type PositionExecution

type PositionExecution struct {
	PositionID                     int64               `json:"positionId"`
	State                          string              `json:"state"` // open or closed
	InvestedAmountCurrency         float64             `json:"investedAmountCurrency"`
	InitialExposureAccountCurrency float64             `json:"initialExposureAccountCurrency"`
	InitialExposureAssetCurrency   float64             `json:"initialExposureAssetCurrency"`
	AddedFunds                     float64             `json:"addedFunds"`
	MarginAccountCurrency          float64             `json:"marginAccountCurrency"`
	MarginAssetCurrency            float64             `json:"marginAssetCurrency"`
	RemainingUnits                 float64             `json:"remainingUnits"`
	RemainingContracts             *float64            `json:"remainingContracts"`
	StopLossRate                   *float64            `json:"stopLossRate"`
	TakeProfitRate                 *float64            `json:"takeProfitRate"`
	OpeningData                    PositionOpeningData `json:"openingData"`
}

PositionExecution is a position created or affected by an order.

type PositionOpeningData

type PositionOpeningData struct {
	OpenTime          time.Time `json:"openTime"`
	OrderID           int64     `json:"orderId"`
	ExecutionTime     time.Time `json:"executionTime"`
	Units             *float64  `json:"units"`
	Contracts         *float64  `json:"contracts"`
	AvgPrice          float64   `json:"avgPrice"`
	AvgConversionRate float64   `json:"avgConversionRate"`
	MarketSpread      float64   `json:"marketSpread"`
	Markup            float64   `json:"markup"`
	PriceID           int64     `json:"priceId"`
	Fees              float64   `json:"fees"`
	Taxes             float64   `json:"taxes"`
}

PositionOpeningData records how a position produced by an order was opened.

type PositionPnL

type PositionPnL struct {
	PnL                       float64   `json:"pnL"`
	PnLAssetCurrency          float64   `json:"pnlAssetCurrency"`
	ExposureInAccountCurrency float64   `json:"exposureInAccountCurrency"`
	ExposureInAssetCurrency   float64   `json:"exposureInAssetCurrency"`
	MarginInAccountCurrency   float64   `json:"marginInAccountCurrency"`
	MarginInAssetCurrency     float64   `json:"marginInAssetCurrency"`
	MarginCurrencyID          int       `json:"marginCurrencyId"`
	AssetCurrencyID           int       `json:"assetCurrencyId"`
	CloseRate                 float64   `json:"closeRate"`
	CloseConversionRate       float64   `json:"closeConversionRate"`
	Timestamp                 time.Time `json:"timestamp"`
}

PositionPnL is the live valuation attached to positions by the pnl endpoint. PnL is in the account currency.

type Rate

type Rate struct {
	InstrumentID      int       `json:"instrumentID"`
	Ask               float64   `json:"ask"`
	Bid               float64   `json:"bid"`
	LastExecution     float64   `json:"lastExecution"`
	ConversionRateAsk float64   `json:"conversionRateAsk"`
	ConversionRateBid float64   `json:"conversionRateBid"`
	Date              time.Time `json:"date"`
	PriceRateID       int       `json:"priceRateID"`
}

Rate is a real-time price for one instrument. Ask is the buy price, Bid the sell price. The conversion rates translate the instrument currency to USD.

type TradeCost

type TradeCost struct {
	CostType string  `json:"costType"` // markup, marketSpread, transactionFee, overnightFee, overWeekendFee, or sdrt
	Amount   float64 `json:"amount"`
	Currency string  `json:"currency"`
}

TradeCost is one cost component of a hypothetical order.

type TradeHistoryParams

type TradeHistoryParams struct {
	MinDate  time.Time
	Page     int
	PageSize int
}

TradeHistoryParams selects the closed trades TradingHistory returns. MinDate is required (the start of the period); Page and PageSize are sent only when positive.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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