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
- type APIError
- type AccountBalance
- type AccountSnapshot
- type AccountType
- type Balance
- type BalanceHistory
- type BalanceHistoryParams
- type BalanceSnapshot
- type BankIdentifier
- type BankTransferTransactionDetails
- type Candle
- type CardTransactionDetails
- type CashCounterparty
- type CashPagination
- type CashTransaction
- type CashTransactionsPage
- type CashTransactionsParams
- type Client
- func (c *Client) AggregatedBalances(ctx context.Context) (Balance, error)
- func (c *Client) Balance(ctx context.Context) (Balance, error)
- func (c *Client) BalanceHistory(ctx context.Context, params BalanceHistoryParams) (BalanceHistory, error)
- func (c *Client) BalancesByType(ctx context.Context, accountType AccountType) (Balance, error)
- func (c *Client) CancelCloseOrder(ctx context.Context, orderID int64) (string, error)
- func (c *Client) CancelOrder(ctx context.Context, orderID int64) (string, error)
- func (c *Client) Candles(ctx context.Context, instrumentID int, interval Interval, count int) ([]Candle, error)
- func (c *Client) CashTransactions(ctx context.Context, accountID string, params CashTransactionsParams) (CashTransactionsPage, error)
- func (c *Client) CloseOrderInfo(ctx context.Context, orderID int64) (OrderLookup, error)
- func (c *Client) ClosePosition(ctx context.Context, positionID int64, instrumentID int, ...) (ClosePositionResult, error)
- func (c *Client) ClosingPrices(ctx context.Context) ([]InstrumentClosingPrices, error)
- func (c *Client) CreateOrder(ctx context.Context, req OrderRequest) (OrderResult, error)
- func (c *Client) Exchanges(ctx context.Context) ([]Exchange, error)
- func (c *Client) Identity(ctx context.Context) (Identity, error)
- func (c *Client) InstrumentDisplayData(ctx context.Context, ids []int) ([]InstrumentDisplayData, error)
- func (c *Client) InstrumentTypes(ctx context.Context) ([]InstrumentType, error)
- func (c *Client) ModifyPositionSLTP(ctx context.Context, positionID int64, stopLossRate, takeProfitRate *float64) (PositionEditResult, error)
- func (c *Client) OrderInfo(ctx context.Context, orderID int64) (OrderLookup, error)
- func (c *Client) OrderInfoByReference(ctx context.Context, referenceID string) (OrderLookup, error)
- func (c *Client) PortfolioBreakdown(ctx context.Context) (ClientPortfolio, error)
- func (c *Client) PortfolioSummary(ctx context.Context) (ClientPortfolio, error)
- func (c *Client) Rates(ctx context.Context, ids []int) ([]Rate, error)
- func (c *Client) ResolveInstrument(ctx context.Context, symbol string) (Instrument, error)
- func (c *Client) SearchInstruments(ctx context.Context, symbol string) ([]Instrument, error)
- func (c *Client) TradingCostEstimate(ctx context.Context, req OrderRequest) (CostEstimate, error)
- func (c *Client) TradingEligibility(ctx context.Context, instrumentID int) (InstrumentEligibility, error)
- func (c *Client) TradingHistory(ctx context.Context, params TradeHistoryParams) ([]ClosedTrade, error)
- type ClientPortfolio
- type CloseOrderReceipt
- type ClosePositionResult
- type ClosedTrade
- type ClosingPriceSet
- type CostEstimate
- type EquityDetails
- type Exchange
- type Identity
- type Instrument
- type InstrumentClosingPrices
- type InstrumentDisplayData
- type InstrumentEligibility
- type InstrumentImage
- type InstrumentType
- type InternalTransferTransactionDetails
- type Interval
- type LeverageConfig
- type Mirror
- type Option
- type OrderAsset
- type OrderForClose
- type OrderForOpen
- type OrderLookup
- type OrderRequest
- type OrderResult
- type OrderStatus
- type PendingOrder
- type PeriodClose
- type Position
- type PositionEditResult
- type PositionExecution
- type PositionOpeningData
- type PositionPnL
- type Rate
- type TradeCost
- type TradeHistoryParams
Constants ¶
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
BalancesByType returns the current balance of the accounts of one type, for example AccountTypeTrading.
GET /api/v1/balances/{accountType}
func (*Client) CancelCloseOrder ¶
CancelCloseOrder cancels a pending close order (DELETE /api/v1/trading/execution/{demo/}market-close-orders/{orderId}) and returns the tracking token.
func (*Client) CancelOrder ¶
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 ¶
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) 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 ¶
OrderInfo looks an order up by its id (GET /api/v2/trading/info/{demo/}orders:lookup?orderId=).
func (*Client) OrderInfoByReference ¶
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 ¶
Rates fetches real-time bid/ask rates for the given instrument ids. At least one id is required.
func (*Client) ResolveInstrument ¶
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 ¶
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 ¶
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 ¶
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.