exness

package module
v0.1.0-alpha.7 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Exness Go

Unofficial, read-only Go SDK for the public Exness Trading API (contract 1.0.2). Alpha v0.1.0-alpha.7; not verified against a live account. Go 1.26+. WebSocket transport uses coder/websocket (v1.8.15); REST and signing use the standard library.

Supports signed Gateway discovery, account details, instrument names and conditions, trading snapshot, API limits, paginated orders/deals history, candle history and existing operation status. All nine read-only REST operations in the pinned contract are covered, plus discovery, live WebSocket ticks, transactions and account/instrument/HMR events. Trading mutations remain future work.

Installation

In your Go module:

go get github.com/angru/exness-go@v0.1.0-alpha.7

Go records the explicit prerelease version in your module. For local development, clone the repository and optionally use a replace directive pointing to your checkout.

import (
    "context"
    "os"
    exness "github.com/angru/exness-go"
)

credentials, err := exness.NewCredentials(
    os.Getenv("EXN_API_KEY"), os.Getenv("EXN_PRIVATE_KEY"),
)
if err != nil { return err }
client, err := exness.NewClient(exness.Config{
    Credentials: credentials,
    AccountID: os.Getenv("EXN_ACCOUNT_ID"),
    DiscoveryURL: os.Getenv("EXN_DISCOVERY_BASE_URL"),
})
if err != nil { return err }
defer client.Close()
account, err := client.GetAccount(context.Background())

This fragment belongs inside a function returning error. A complete runnable example is go run ./examples/read-account. Configure the same four EXN_* variables as the Python SDK. EXN_PRIVATE_KEY is the Exness 128-character hex key or full unencrypted Ed25519 PKCS#8 PEM. The discovery URL must come from the DNS widget in Key Management. Only HTTPS origins are accepted; signed redirects are never followed. API keys need Trading read access.

History

start := time.Now().UTC().Add(-time.Hour)
query := exness.DealHistoryQuery{
    HistoryQuery: exness.HistoryQuery{From: &start, Limit: 100},
    DealType: exness.DealBalance,
}
for item, err := range client.IterDealsHistory(ctx, query) {
    if err != nil { return err }
    fmt.Println(item.Deal.DealID)
}

Use GetOrdersHistory / GetDealsHistory for individual pages. Cursor requests accept only Cursor and Limit. Iterators drop initial filters automatically, preserve opaque tokens and stop on repeated/inconsistent cursors. Breaking the loop prevents the next page request. Earlier rows may have been yielded before an error. Choose a time window within the current GetLimits history constraints.

Candles, conditions and operation status

conditions, err := client.GetInstrumentConditions(ctx, "EURUSD")
if err != nil { return err }
fmt.Println(conditions.PointDigits, conditions.VolumeStep)

count := 10
candles, err := client.GetCandleHistory(ctx, exness.CandleQuery{
    Instrument: "EURUSD", Timeframe: exness.TimeframeM1, From: start,
    Count: &count, PriceType: exness.PriceBoth,
})
if err != nil { return err }
for _, candle := range candles.Candles {
    fmt.Println(candle.Time, candle.Bid, candle.Ask)
}

// Read an operation ID you already have. This does not submit a trade.
operation, err := client.GetOperationStatus(ctx, "789")
if err != nil { return err }
fmt.Println(operation.Status, operation.IsTerminal())

Candles require From and exactly one of To (exclusive) or a nonzero Count. Negative counts are valid. Empty PriceType defaults to bid; ask and both are also supported. Timeframes: S1, S5, S15, M1, M3, M5, M10, M15, M30, H1, H2, H4, D1, W1, MN. Current count/range caps come from GetLimits and are enforced by the server; the method makes no hidden limits request and does not split, sort or retry.

Candle OHLC and volume are JSON doubles, exposed as *float64 to distinguish zero from missing data. Bid/ask-only responses use flat OHLC; both-side responses use nested Bid and Ask. The upstream oneOf is ambiguous because both branches have only optional fields and allow extra fields. The SDK preserves both shapes; Python contract tests document the defect and validate a request-selected branch without modifying the vendored YAML. See the contract notes.

Conditions retain exact Decimal volume, swap and commission fields. Optional settings remain nil. Operation status is read once without polling; pending, confirmed, rejected and failed are recognized. IsTerminal means processing ended, not success. Rejection/failure codes remain model fields; HTTP failures return APIError. Run go run ./examples/read-market for a complete example with optional EXN_INSTRUMENT and EXN_OPERATION_ID environment inputs.

Data and error semantics

  • String-encoded money, prices and volumes use Decimal, retaining the exact wire string. String() returns it; Rat() converts to math/big.Rat for exact arithmetic. Numbers, scientific notation, NaN and null are rejected in required decimal fields. Optional decimals use pointers and accept null. An unset Decimal is not a numeric zero; construct values with NewDecimal.
  • Time values use time.Time. History request times are sent in UTC. Optional fields use pointers to distinguish absent values from zero values.
  • encoding/json checks field types; the client also checks essential required data such as account identity, balances and history entities. This is not a full runtime JSON Schema validator. Unlike Python's Pydantic models, unknown response fields are discarded and unknown instrument/trading enum strings are retained. Operation states are checked against pending/confirmed/rejected/failed. Request filter enums are validated before network calls. Dot-only instrument path names are rejected to prevent URL normalization; operation IDs use uint64 syntax and numeric identity comparison, allowing leading zeros.
  • All requests take a context.Context. Default total REST timeout: 15 seconds; override with Config.Timeout. REST responses are limited to 16 MiB. Tick streams have a separate handshake timeout and message limit, described below.
  • Client supports concurrent calls and serializes cached discovery. Explicit Discover(ctx, true) refreshes the host. Callers waiting for discovery honor their own context; cached reads can continue while an explicit refresh runs. Close does not wait for discovery, closes idle connections and prevents new operations. In-flight REST calls can finish; active WebSocket streams are canceled, including their discovery and reconnect waits. Custom transports must be safe for concurrent use. Environment proxies are ignored by the default transport.
  • REST calls have no SDK retry loop; HTTP errors including 429 are returned directly. The Go HTTP transport may recover stale pooled connections for safe GETs.
  • Use errors.As for *APIError, *ProtocolError, *TransportError. APIError exposes status, optional numeric code/message and raw Retry-After. Error strings do not echo credentials or raw response bodies. ErrorMessage and an unwrapped transport cause may contain untrusted details; do not log them indiscriminately. errors.Is(err, context.Canceled) works through transport errors.

Development

gofmt -l .
go vet ./...
go test -race -cover ./...
go build ./...

CI checks formatting, vet, race-enabled tests and build on Go 1.26 and 1.27. Native fuzz targets cover exact decimal arithmetic/JSON, key parsing, HTTPS origins, cursor encoding/signing and pagination termination. Seeds run with ordinary tests; CI also fuzzes each target for five seconds on Go 1.27. To explore longer locally:

go test -run '^$' -fuzz '^FuzzDecimal$' -fuzztime 1m -parallel 2 .

Tests use synthetic keys, mocked RoundTrippers and loopback HTTPS servers with test certificates. No Exness account or external service is required, but local socket binding must be allowed. Real connections exercise cancellation (including queued discovery), header/body deadlines, truncated responses, redirect refusal, signature verification, connection reuse and idle-connection closure. JSON fixtures are copied from the Python SDK and must be kept in sync. signing-vector.json was independently signed by OpenSSL and is checked byte-for-byte by both SDKs. Python tests validate response fixtures against the pinned OpenAPI snapshot; Go tests consume the same fixtures independently.

Contract sources

Retrieved 2026-11-19 (Asia/Nicosia):

For contract maintenance, use the shared checker from a separate Python SDK checkout:

cd /path/to/exness-python
uv sync --locked
uv run python -m tools.check_contract
# Offline candidate review:
uv run python -m tools.check_contract --candidate /path/to/candidate.yaml

It reports operations, parameters and model changes without updating the snapshot. Exit codes: 0 unchanged, 1 review required, 2 check failed. The Python repository also provides a manually triggered Contract review workflow with downloadable JSON reports and candidate YAML. See the maintenance instructions. This is development tooling, not a Go dependency. Review shared-schema changes in both SDKs, keep synthetic fixtures aligned, and update the provenance hash here only after explicitly adopting a reviewed snapshot. Structural differences are not automatically classified as breaking or compatible.

This is not an official Exness product or a MetaTrader wrapper.

Live ticks

for event, err := range client.StreamTicks(ctx, []string{"EURUSD"}, exness.TickStreamOptions{
    MaxReconnects: 3, // Opt in; the default is no reconnects.
}) {
    if err != nil { return err }
    if event.Gap != nil {
        fmt.Printf("possible tick loss; reconnect %d in %s\n",
            event.Gap.ReconnectAttempt, event.Gap.Delay)
        continue
    }
    if event.Tick.Bid != nil {
        fmt.Println(*event.Tick.Instrument, *event.Tick.Bid)
    }
}

Run go run ./examples/read-ticks with the same four EXN_* variables and optional EXN_INSTRUMENT (default EURUSD). Ctrl-C cancels the stream. The SDK discovers the account host, signs the exact WebSocket GET path and subscribes with a fresh request ID on every connection. Instrument lists are copied when StreamTicks is called; validation and networking are lazy, beginning when the iterator is consumed.

Tick follows the pinned WSTick schema: instrument is required by the SDK and must belong to the subscription; bid, ask and timestamp are optional. Prices are JSON doubles (*float64), as with candle OHLC, rather than string decimals. Tick, subscription and error fixtures are shared with Python. Unknown fields are ignored. A terminal failure yields one error and ends iteration; earlier ticks remain valid.

  • Reconnects are disabled by default. MaxReconnects accepts 0–1000 and applies across the whole iteration, including successful connections. It never resets when a tick arrives. Backoff starts at one second and doubles up to 30 seconds; customize ReconnectDelay and MaxReconnectDelay to positive durations.
  • A Gap is yielded before every retry delay. It contains the attempt, delay and optional close code (nil when no connection was established). It signals possible loss, not a count of missed ticks. There is no replay, sorting or deduplication. Reconnects resubscribe using cached discovery; no hidden host refresh.
  • Network failures and close codes 1001, 1006, 1011 and 1012 may reconnect within the budget. A normal 1000 close ends successfully. Other close codes, protocol errors, subscription errors, TLS validation errors and all HTTP handshake failures (including 429 and 503) are terminal. Discovery failures are not retried.
  • OpenTimeout defaults to 15 seconds and applies only to each handshake. The caller context bounds the stream lifetime. There is no tick inactivity timeout. Pings run every 20 seconds with a 20-second pong deadline.
  • Reading is driven by iteration, with transport backpressure and no SDK tick queue. Keep the loop responsive: pong processing also needs reads, so a stalled consumer may lose its connection. This differs from Python's bounded background frame queue.
  • MaxMessageBytes defaults to 64 KiB and accepts 1 byte through 16 MiB, applying to incoming messages and the outgoing subscription. Oversized incoming messages end with StreamClosed{Code: 1009}. An oversized subscription fails before dialing.
  • Breaking iteration, canceling the context or calling Client.Close releases the socket promptly. Local cleanup closes the socket without waiting for a peer close handshake. Cancellation is inspectable with errors.Is(err, context.Canceled). Closing the client also releases sockets while consumer code is paused; it cannot interrupt that consumer's own code.
  • Use errors.As for *StreamClosed, *WebSocketAPIError, *APIError, *ProtocolError and *TransportError. Close reasons and subscription error text are excluded from error strings. Do not indiscriminately log underlying causes or server-provided error fields.

Redirects and compression are disabled; signed headers are never forwarded across redirects. The default transport ignores environment proxies. Config.Transport is shared by REST and WebSocket requests; custom transports must support an HTTP/1.1 upgrade with a writable response body (as http.Transport does). TLS settings come from that transport. Live Exness interoperability remains unverified; tests use local TLS servers for signatures, subscriptions, reconnection, cancellation, ping/pong, slow consumers, message limits, certificate validation and handshake deadlines.

See ROADMAP.md for planned work without a live account. SDK code is available under the MIT license. The public RFC 8032 test key is attributed in THIRD_PARTY_NOTICES.md.

Trading events

for event, err := range client.StreamTrading(ctx, exness.TradingStreamOptions{MaxReconnects: 3}) {
    if err != nil { return err }
    switch {
    case event.Gap != nil:
        fmt.Println("State is stale; waiting for a fresh snapshot")
    case event.Snapshot != nil:
        fmt.Println("New baseline", len(event.Snapshot.Positions))
    case event.Transaction != nil:
        fmt.Println("Changed positions", len(event.Transaction.Payload.Positions))
    }
}

Run go run ./examples/read-trading with the same four EXN_* variables. TradingStreamEvent contains exactly one Snapshot, Transaction or Gap when there is no error. TradingStreamOptions and TradingStreamGap alias their tick counterparts. Breaking iteration or canceling the context releases the connection.

The transactions subscription sends a full trading_state_snapshot, followed by transaction_event deltas. The SDK requires a valid snapshot before yielding any transaction on every connection, including after reconnect. A transaction received before that boundary is a terminal protocol error. Repeated snapshots are accepted as replacement baselines. Each subscription uses a fresh request ID.

Recovery belongs to the caller's application state:

  1. On a gap, mark the previous cache stale immediately; on termination (including normal close), it is no longer live either.
  2. Replace cached active orders, open positions and account state with the next snapshot. Do not merge a new baseline into stale state.
  3. Apply subsequent transaction payloads as changed entities, not full lists. Retain an open position after a partial close; remove closed positions and terminal orders from an active-state view. Missing entities are not deletions.
  4. Use order/deal history separately if missed historical changes matter. Snapshots cannot reconstruct missed transactions. There is no resume token, replay or exactly-once guarantee; the SDK does not merge, deduplicate or poll implicitly.

status is optional: success, rejected and failed are supported. Rejected or failed operations with empty payloads are still data events, even when they contain error_message; subscription errors instead raise/return WebSocketAPIError. An absent status is not inferred as success. operation_id can be absent for balance or system changes. Monetary values remain exact decimals; transaction account state also requires leverage. Server error fields are untrusted data.

Transport behavior is shared with ticks: reconnects are opt-in and lifetime-bounded, gaps precede retries, HTTP/TLS/protocol failures are terminal, and cancellation and client closure release sockets. The default message cap is 64 KiB, including the initial snapshot; explicitly increase it up to 16 MiB for larger accounts. There is no snapshot-arrival timeout beyond the caller's stream deadline and heartbeat. Other server subscriptions are documented below. Live Exness interoperability has not been verified.

Account, instrument and HMR events

for event, err := range client.StreamHMR(ctx, []string{"EURUSD"}, exness.ServerStreamOptions{
    MaxReconnects: 3,
}) {
    if err != nil { return err }
    switch {
    case event.Gap != nil:
        fmt.Println("HMR state is stale")
    case event.Snapshot != nil:
        fmt.Println("Replace baseline", len(event.Snapshot.Periods))
    case event.Update != nil:
        fmt.Println("Changes", event.Update.UpsertedPeriods, event.Update.RemovedPeriodIDs)
    }
}

StreamAccountState(ctx, options) yields AccountStateStreamEvent with either AccountState or Gap. StreamInstruments(ctx, names, options) yields InstrumentStreamEvent with either Instrument or Gap. StreamHMR yields HmrStreamEvent with exactly one Snapshot, Update or Gap on success. ServerStreamOptions and ServerStreamGap alias the tick equivalents. Break or cancel the context to close a stream. Run an example with the four EXN_* variables already configured:

EXN_STREAM=account_state go run ./examples/read-events
EXN_STREAM=instruments EXN_INSTRUMENTS=all go run ./examples/read-events
EXN_STREAM=hmr EXN_INSTRUMENTS=EURUSD,XAUUSD go run ./examples/read-events

Each call opens a dedicated /ws/events connection with one subscription and a fresh request ID. Multiple concurrent calls consume multiple server connections; check GetLimits / get_limits when choosing concurrency. These methods do not multiplex subscriptions or change instrument lists mid-connection. Close the iterator to unsubscribe by closing its connection; open a new stream to change selection. Reconnects reuse the copied selection and the existing signed transport. Options and gap types alias their tick equivalents; retries remain disabled by default, bounded when enabled, and preceded by visible gaps. Message/queue limits, heartbeat, redirect refusal and cancellation rules are unchanged.

Subscription Events Initial state and recovery
account_state AccountStateEvent No initial snapshot. Each event is a fresh floating-state observation; a gap makes the prior observation stale until the next event.
instruments InstrumentEvent, action new, upd, del No initial snapshot. new/upd contain full conditions; del removes the instrument from a cache. Missed changes or deletions require explicit reconciliation.
hmr HmrSnapshot, HmrUpdate A fresh snapshot is mandatory before updates on every connection. Every snapshot, even empty, replaces the entire baseline.

Instrument subscriptions require a nonempty explicit list or exactly ["all"]. HMR requires explicit instruments and rejects all. Duplicate or malformed names fail before networking; account availability is checked by the server, without a hidden REST lookup. Unsubscribed instrument events and unknown/wrong event kinds are terminal protocol errors. Lists are copied when constructing the iterator.

An account-state event contains exact balance, equity and used-margin values. It is an observation, not a transaction history or a substitute for transactions. The SDK does not assume a fixed delivery interval or generate synthetic values. For instrument caches, treat a gap or termination as loss of continuity. Explicitly refresh the available instrument list and conditions through REST when needed; that REST fetch and concurrent WebSocket delivery are not an atomic snapshot. The SDK does not silently merge a REST result with events or mark the entire cache current merely because one instrument received an update.

HMR arrays live at the event top level, without payload or event_time. Snapshots contain periods; updates contain upserted_periods and removed_period_ids, both required even when empty. Applications maintain their own map keyed by period_id: replace it on a snapshot, upsert changed periods and remove the listed IDs on updates. Removing an unknown ID is harmless. A gap or termination invalidates the baseline; the SDK refuses an update before the new snapshot. It yields data without automatic merging, sorting, replay or deduplication.

A period preserves the server's complete instruments list (not filtered locally) and string leverage. regular schedule strings use calendar dates, while periodic strings use weekly schedules such as Mon, 13:00:00. Both are preserved verbatim; no timezone, recurrence calculation or "active now" flag is inferred. All synthetic fixtures are shared across SDKs and checked against the pinned OpenAPI. Live Exness interoperability remains unverified.

Reviewed alpha API

Prefer StreamOptions and StreamGap for all five stream types. Existing TickStream*, TradingStream* and ServerStream* aliases remain supported. API_REVIEW.md maps the full Python/Go surface and records model, error, lifecycle and timeout differences. RELEASE.md contains the alpha release notes, installation instructions and publication procedure.

Documentation

Overview

Package exness provides an unofficial read-only Exness Trading API client.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode   int
	Code         *int
	ErrorMessage *string
	RetryAfter   string
}

APIError reports an unsuccessful REST response or WebSocket handshake. ErrorMessage is untrusted server text.

func (*APIError) Error

func (e *APIError) Error() string

type APILimits

type APILimits struct {
	Rest      RestLimits      `json:"rest"`
	WebSocket WebSocketLimits `json:"websocket"`
}

type AccountDetails

type AccountDetails struct {
	AccountID   string           `json:"account_id"`
	CreateDate  time.Time        `json:"create_date"`
	AccountName *string          `json:"account_name,omitempty"`
	Settings    *AccountSettings `json:"settings,omitempty"`
}

type AccountSettings

type AccountSettings struct {
	Currency        string   `json:"currency"`
	Leverage        string   `json:"leverage"`
	AccountStatus   string   `json:"account_status"`
	TradeMode       string   `json:"trade_mode"`
	ExecutionMode   string   `json:"execution_mode"`
	MarginCallLevel *Decimal `json:"margin_call_level,omitempty"`
	StopoutLevel    *Decimal `json:"stopout_level,omitempty"`
}

type AccountState

type AccountState struct {
	Balance    Decimal `json:"balance"`
	Equity     Decimal `json:"equity"`
	UsedMargin Decimal `json:"used_margin"`
}

type AccountStateEvent

type AccountStateEvent struct {
	EventType string              `json:"event_type"`
	EventTime time.Time           `json:"event_time"`
	Payload   AccountStatePayload `json:"payload"`
}

type AccountStatePayload

type AccountStatePayload struct {
	AccountState AccountState `json:"account_state"`
}

type AccountStateStreamEvent

type AccountStateStreamEvent struct {
	AccountState *AccountStateEvent
	Gap          *ServerStreamGap
}

Successful stream events contain exactly one data field or Gap.

type Candle

type Candle struct {
	CandleSide
	Time   *time.Time  `json:"time,omitempty"`
	Volume *float64    `json:"volume,omitempty"`
	Bid    *CandleSide `json:"bid,omitempty"`
	Ask    *CandleSide `json:"ask,omitempty"`
}

Candle preserves flat bid/ask or nested both-side data without guessing a discriminator.

type CandleHistory

type CandleHistory struct {
	Candles []Candle `json:"candles"`
}

type CandlePriceType

type CandlePriceType string
const (
	PriceBid  CandlePriceType = "bid"
	PriceAsk  CandlePriceType = "ask"
	PriceBoth CandlePriceType = "both"
)

type CandleQuery

type CandleQuery struct {
	Instrument string
	Timeframe  CandleTimeframe
	From       time.Time
	To         *time.Time
	Count      *int            // Must be nonzero; negative counts are valid. Exactly one of To or Count.
	PriceType  CandlePriceType // Empty selects bid.
}

type CandleSide

type CandleSide struct {
	Open  *float64 `json:"open,omitempty"`
	High  *float64 `json:"high,omitempty"`
	Low   *float64 `json:"low,omitempty"`
	Close *float64 `json:"close,omitempty"`
}

CandleSide uses JSON doubles per the market-data contract, not trading Decimal strings.

type CandleTimeframe

type CandleTimeframe string
const (
	TimeframeS1  CandleTimeframe = "S1"
	TimeframeS5  CandleTimeframe = "S5"
	TimeframeS15 CandleTimeframe = "S15"
	TimeframeM1  CandleTimeframe = "M1"
	TimeframeM3  CandleTimeframe = "M3"
	TimeframeM5  CandleTimeframe = "M5"
	TimeframeM10 CandleTimeframe = "M10"
	TimeframeM15 CandleTimeframe = "M15"
	TimeframeM30 CandleTimeframe = "M30"
	TimeframeH1  CandleTimeframe = "H1"
	TimeframeH2  CandleTimeframe = "H2"
	TimeframeH4  CandleTimeframe = "H4"
	TimeframeD1  CandleTimeframe = "D1"
	TimeframeW1  CandleTimeframe = "W1"
	TimeframeMN  CandleTimeframe = "MN"
)

type Client

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

Client is safe for concurrent use. Close prevents new operations and cancels active streams; in-flight REST calls may finish.

func NewClient

func NewClient(config Config) (*Client, error)

func (*Client) Close

func (c *Client) Close()

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, refresh bool) (string, error)

Discover resolves the account host once. Set refresh after an account migration.

func (*Client) GetAccount

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

func (*Client) GetCandleHistory

func (c *Client) GetCandleHistory(ctx context.Context, query CandleQuery) (*CandleHistory, error)

GetCandleHistory performs one request. Dynamic candle caps are enforced by the server.

func (*Client) GetDealsHistory

func (c *Client) GetDealsHistory(ctx context.Context, query DealHistoryQuery) (*HistoryPage[DealHistoryItem], error)

func (*Client) GetInstrumentConditions

func (c *Client) GetInstrumentConditions(ctx context.Context, instrument string) (*InstrumentConditions, error)

func (*Client) GetInstruments

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

func (*Client) GetLimits

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

func (*Client) GetOperationStatus

func (c *Client) GetOperationStatus(ctx context.Context, operationID string) (*OperationStatus, error)

GetOperationStatus reads an existing operation once. Rejected/failed are returned as data.

func (*Client) GetOrdersHistory

func (c *Client) GetOrdersHistory(ctx context.Context, query OrderHistoryQuery) (*HistoryPage[OrderHistoryItem], error)

func (*Client) GetSnapshot

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

func (*Client) IterDealsHistory

func (c *Client) IterDealsHistory(ctx context.Context, query DealHistoryQuery) iter.Seq2[DealHistoryItem, error]

IterDealsHistory lazily yields rows and at most one error, then stops.

func (*Client) IterOrdersHistory

func (c *Client) IterOrdersHistory(ctx context.Context, query OrderHistoryQuery) iter.Seq2[OrderHistoryItem, error]

IterOrdersHistory lazily yields rows and at most one error, then stops.

func (*Client) StreamAccountState

func (c *Client) StreamAccountState(ctx context.Context, options ServerStreamOptions) iter.Seq2[AccountStateStreamEvent, error]

StreamAccountState yields periodic floating state without an initial snapshot. A gap invalidates the last observation; a later event is a new observation only.

func (*Client) StreamHMR

func (c *Client) StreamHMR(ctx context.Context, instruments []string, options ServerStreamOptions) iter.Seq2[HmrStreamEvent, error]

StreamHMR requires explicit instruments (no "all") and a fresh snapshot before updates on every connection. Replace cached periods on every snapshot, even empty.

func (*Client) StreamInstruments

func (c *Client) StreamInstruments(ctx context.Context, instruments []string, options ServerStreamOptions) iter.Seq2[InstrumentStreamEvent, error]

StreamInstruments accepts explicit names or exactly ["all"]. No initial snapshot is promised. Lists are copied; callers reconcile stale caches after gaps.

func (*Client) StreamTicks

func (c *Client) StreamTicks(ctx context.Context, instruments []string, options TickStreamOptions) iter.Seq2[TickStreamEvent, error]

StreamTicks lazily yields live ticks and explicit gap events. Break or cancel ctx to release the connection. No background tick queue, sorting or deduplication is performed. The instrument list is copied; each iteration gets a fresh budget.

func (*Client) StreamTrading

func (c *Client) StreamTrading(ctx context.Context, options TradingStreamOptions) iter.Seq2[TradingStreamEvent, error]

StreamTrading subscribes to transactions. A snapshot is required before any transaction on every connection. It does not merge deltas, replay or deduplicate.

type ClosedOrderState

type ClosedOrderState string
const (
	OrderFilled    ClosedOrderState = "filled"
	OrderCancelled ClosedOrderState = "cancelled"
	OrderRejected  ClosedOrderState = "rejected"
)

type CommissionSettings

type CommissionSettings struct {
	CommissionType  *string `json:"commission_type,omitempty"`
	CommissionValue *Money  `json:"commission_value,omitempty"`
}

type Config

type Config struct {
	Credentials  *Credentials
	AccountID    string
	DiscoveryURL string
	Timeout      time.Duration     // REST timeout; zero selects 15 seconds. WebSockets use StreamOptions.OpenTimeout.
	Transport    http.RoundTripper // Optional; Close closes its idle connections.
}

type Credentials

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

Credentials holds signing material. Its formatting methods redact both fields.

func NewCredentials

func NewCredentials(apiKey, privateKey string) (*Credentials, error)

NewCredentials accepts an Exness 128-character hex key or unencrypted PKCS#8 PEM.

func (Credentials) GoString

func (Credentials) GoString() string

func (Credentials) String

func (Credentials) String() string

type Deal

type Deal struct {
	DealID     string        `json:"deal_id"`
	Type       DealType      `json:"type"`
	CreateTime time.Time     `json:"create_time"`
	OrderID    *string       `json:"order_id,omitempty"`
	PositionID *string       `json:"position_id,omitempty"`
	Direction  *string       `json:"direction,omitempty"`
	Instrument *string       `json:"instrument,omitempty"`
	Volume     *Decimal      `json:"volume,omitempty"`
	Price      *Decimal      `json:"price,omitempty"`
	Profit     *ProfitAmount `json:"profit,omitempty"`
	Commission *Decimal      `json:"commission,omitempty"`
}

type DealHistoryItem

type DealHistoryItem struct {
	EventTime time.Time `json:"event_time"`
	Deal      Deal      `json:"deal"`
}

type DealHistoryQuery

type DealHistoryQuery struct {
	HistoryQuery
	DealType DealType
}

type DealType

type DealType string
const (
	DealOpen             DealType = "open"
	DealClose            DealType = "close"
	DealBalance          DealType = "balance"
	DealNullCompensation DealType = "null_compensation"
	DealSwapFee          DealType = "swap_fee"
	DealAdminFee         DealType = "admin_fee"
	DealDividend         DealType = "dividend"
	DealExnessDollar     DealType = "exness_dollar"
)

type Decimal

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

Decimal preserves the API's exact decimal string. Use Rat for exact arithmetic. The zero value is unset, not a numeric zero. Construct with NewDecimal.

func NewDecimal

func NewDecimal(value string) (Decimal, error)

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

func (Decimal) Rat

func (d Decimal) Rat() (*big.Rat, error)

func (Decimal) String

func (d Decimal) String() string

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(data []byte) error

type HistoryPage

type HistoryPage[T any] struct {
	Items      []T           `json:"items"`
	NextCursor *string       `json:"next_cursor,omitempty"`
	HasMore    *bool         `json:"has_more,omitempty"`
	Range      *HistoryRange `json:"range,omitempty"`
}

type HistoryQuery

type HistoryQuery struct {
	From       *time.Time
	To         *time.Time
	Cursor     *string
	Limit      int // Zero selects 100. Otherwise 1..200.
	Instrument string
}

type HistoryRange

type HistoryRange struct {
	From *time.Time `json:"from,omitempty"`
	To   *time.Time `json:"to,omitempty"`
}

type HmrPeriod

type HmrPeriod struct {
	PeriodID    string   `json:"period_id"`
	EventType   string   `json:"event_type"` // regular or periodic.
	Instruments []string `json:"instruments"`
	Leverage    string   `json:"leverage"`
	StartTime   string   `json:"start_time"`
	EndTime     string   `json:"end_time"`
}

HmrPeriod preserves server schedule strings, including weekly schedules. No timezone, recurrence expansion or active-now calculation is inferred.

type HmrSnapshot

type HmrSnapshot struct {
	EventType string      `json:"event_type"`
	Periods   []HmrPeriod `json:"periods"`
}

type HmrStreamEvent

type HmrStreamEvent struct {
	Snapshot *HmrSnapshot
	Update   *HmrUpdate
	Gap      *ServerStreamGap
}

type HmrUpdate

type HmrUpdate struct {
	EventType        string      `json:"event_type"`
	UpsertedPeriods  []HmrPeriod `json:"upserted_periods"`
	RemovedPeriodIDs []string    `json:"removed_period_ids"`
}

type InstrumentConditions

type InstrumentConditions struct {
	Instrument         string              `json:"instrument"`
	Description        *string             `json:"description,omitempty"`
	InternationalName  *string             `json:"international_name,omitempty"`
	Category           *string             `json:"category,omitempty"`
	BaseCurrency       *string             `json:"base_currency,omitempty"`
	QuoteCurrency      *string             `json:"quote_currency,omitempty"`
	MarginCurrency     *string             `json:"margin_currency,omitempty"`
	PointDigits        *int32              `json:"point_digits,omitempty"`
	CalcMode           *string             `json:"calc_mode,omitempty"`
	ExecMode           *string             `json:"exec_mode,omitempty"`
	MarginPercent      *Decimal            `json:"margin_percent,omitempty"`
	ContractSize       *Decimal            `json:"contract_size,omitempty"`
	VolumeMin          *Decimal            `json:"volume_min,omitempty"`
	VolumeMax          *Decimal            `json:"volume_max,omitempty"`
	VolumeStep         *Decimal            `json:"volume_step,omitempty"`
	SwapLong           *Decimal            `json:"swap_long,omitempty"`
	SwapShort          *Decimal            `json:"swap_short,omitempty"`
	SwapMultipliers    []SwapMultiplier    `json:"swap_multipliers,omitempty"`
	TradeMode          *string             `json:"trade_mode,omitempty"`
	OrderTypes         []string            `json:"order_types,omitempty"`
	FillingModes       []string            `json:"filling_modes,omitempty"`
	TradeSessions      []InstrumentSession `json:"trade_sessions,omitempty"`
	CommissionSettings *CommissionSettings `json:"commission_settings,omitempty"`
}

type InstrumentEvent

type InstrumentEvent struct {
	EventType string               `json:"event_type"`
	EventTime time.Time            `json:"event_time"`
	Action    string               `json:"action"` // new, upd or del; payload contains full conditions.
	Payload   InstrumentConditions `json:"payload"`
}

type InstrumentSession

type InstrumentSession struct {
	TradeMode     *string `json:"trade_mode,omitempty"`
	WeekStartTime *string `json:"week_start_time,omitempty"`
	WeekEndTime   *string `json:"week_end_time,omitempty"`
}

type InstrumentStreamEvent

type InstrumentStreamEvent struct {
	Instrument *InstrumentEvent
	Gap        *ServerStreamGap
}

type Instruments

type Instruments struct {
	Instruments []string `json:"instruments"`
}

type Limits

type Limits struct {
	Limits APILimits `json:"limits"`
}

type Money

type Money struct {
	Amount   *Decimal `json:"amount,omitempty"`
	Currency *string  `json:"currency,omitempty"`
}

type OperationState

type OperationState string
const (
	OperationPending   OperationState = "pending"
	OperationConfirmed OperationState = "confirmed"
	OperationRejected  OperationState = "rejected"
	OperationFailed    OperationState = "failed"
)

type OperationStatus

type OperationStatus struct {
	OperationID     string         `json:"operation_id"`
	Status          OperationState `json:"status"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	ClientRequestID *string        `json:"client_request_id,omitempty"`
	ErrorCode       *int32         `json:"error_code,omitempty"`
	ErrorMessage    *string        `json:"error_message,omitempty"`
}

func (OperationStatus) IsTerminal

func (s OperationStatus) IsTerminal() bool

IsTerminal is true for confirmed, rejected or failed; it does not mean success.

type Order

type Order struct {
	OrderID         string     `json:"order_id"`
	OrderType       string     `json:"order_type"`
	State           string     `json:"state"`
	CreateTime      time.Time  `json:"create_time"`
	PositionID      *string    `json:"position_id,omitempty"`
	Direction       *string    `json:"direction,omitempty"`
	Instrument      *string    `json:"instrument,omitempty"`
	Price           *Decimal   `json:"price,omitempty"`
	StopLossPrice   *Decimal   `json:"stop_loss_price,omitempty"`
	TakeProfitPrice *Decimal   `json:"take_profit_price,omitempty"`
	UpdateTime      *time.Time `json:"update_time,omitempty"`
	Volume          *Decimal   `json:"volume,omitempty"`
	Reason          *string    `json:"reason,omitempty"`
}

type OrderHistoryItem

type OrderHistoryItem struct {
	EventTime time.Time `json:"event_time"`
	Order     Order     `json:"order"`
}

type OrderHistoryQuery

type OrderHistoryQuery struct {
	HistoryQuery
	OrderState ClosedOrderState
}

type Position

type Position struct {
	PositionID    string     `json:"position_id"`
	Direction     string     `json:"direction"`
	Instrument    string     `json:"instrument"`
	State         string     `json:"state"`
	CreateTime    time.Time  `json:"create_time"`
	Volume        Decimal    `json:"volume"`
	InitialVolume *Decimal   `json:"initial_volume,omitempty"`
	OpenPrice     *Decimal   `json:"open_price,omitempty"`
	MarginRate    *Decimal   `json:"margin_rate,omitempty"`
	Commission    *Decimal   `json:"commission,omitempty"`
	Swap          *Decimal   `json:"swap,omitempty"`
	RolloverTime  *time.Time `json:"rollover_time,omitempty"`
}

type ProfitAmount

type ProfitAmount struct {
	Amount   *Decimal `json:"amount,omitempty"`
	Currency *string  `json:"currency,omitempty"`
}

type ProtocolError

type ProtocolError struct{ Message string }

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

type RateLimit

type RateLimit struct {
	Limit         int `json:"limit"`
	WindowSeconds int `json:"window_seconds"`
}

type RequestLimits

type RequestLimits struct {
	MaxCandlesPerRequest            *int    `json:"max_candles_per_request,omitempty"`
	MaxCandlesPerRequestDescription *string `json:"max_candles_per_request_description,omitempty"`
	HistoryRangeDays                *int    `json:"history_range_days,omitempty"`
	HistoryAgeDays                  *int    `json:"history_age_days,omitempty"`
}

type RestLimits

type RestLimits struct {
	GlobalAccountRate RateLimit          `json:"global_account_rate"`
	Methods           []RestMethodLimits `json:"methods"`
}

type RestMethodLimits

type RestMethodLimits struct {
	APIOperationID string         `json:"api_operation_id"`
	HTTPMethod     string         `json:"http_method"`
	Path           string         `json:"path"`
	RateLimit      RateLimit      `json:"rate_limit"`
	Limits         *RequestLimits `json:"limits,omitempty"`
}

type ServerStreamGap

type ServerStreamGap = TickStreamGap

type ServerStreamOptions

type ServerStreamOptions = TickStreamOptions

ServerStreamOptions and ServerStreamGap share the existing WebSocket policy.

type StreamClosed

type StreamClosed struct{ Code int }

StreamClosed reports a terminal remote close code or local message-size limit. Arbitrary server close reason text is deliberately omitted.

func (*StreamClosed) Error

func (e *StreamClosed) Error() string

type StreamGap

type StreamGap = TickStreamGap

StreamGap signals a possible loss of continuity in any WebSocket subscription.

type StreamOptions

type StreamOptions = TickStreamOptions

StreamOptions is the neutral name for all WebSocket subscription options. TickStreamOptions, TradingStreamOptions and ServerStreamOptions remain compatible.

type StrikeLimits

type StrikeLimits struct {
	RefillAmount int `json:"refill_amount"`
	Threshold    int `json:"threshold"`
	PeriodMS     int `json:"period_ms"`
}

type SwapMultiplier

type SwapMultiplier struct {
	Day        *string `json:"day,omitempty"`
	Multiplier *int32  `json:"multiplier,omitempty"`
}

type Tick

type Tick struct {
	Instrument *string    `json:"instrument,omitempty"`
	Bid        *float64   `json:"bid,omitempty"`
	Ask        *float64   `json:"ask,omitempty"`
	Timestamp  *time.Time `json:"timestamp,omitempty"`
}

Tick contains market-data doubles, not monetary Decimal values. Optional fields remain nil. StreamTicks checks Instrument against its subscription.

type TickStreamEvent

type TickStreamEvent struct {
	Tick *Tick
	Gap  *TickStreamGap
}

TickStreamEvent contains exactly one Tick or Gap when yielded without an error.

type TickStreamGap

type TickStreamGap struct {
	ReconnectAttempt int
	Delay            time.Duration
	CloseCode        *int // Nil if a connection couldn't be established.
}

TickStreamGap signals possible loss; the server cannot replay or count missed ticks.

type TickStreamOptions

type TickStreamOptions struct {
	MaxReconnects     int
	ReconnectDelay    time.Duration // Default 1 second.
	MaxReconnectDelay time.Duration // Default 30 seconds.
	OpenTimeout       time.Duration // Default 15 seconds, handshake only.
	MaxMessageBytes   int64         // Default 64 KiB; maximum 16 MiB.
}

TickStreamOptions controls one iteration's lifetime reconnect budget. Zero values select defaults, except MaxReconnects, whose zero disables reconnection.

type TokenBucketLimit

type TokenBucketLimit struct {
	Limit         int     `json:"limit"`
	WindowSeconds float64 `json:"window_seconds"`
	Burst         int     `json:"burst"`
}

type TradingSnapshot

type TradingSnapshot struct {
	AccountState AccountState `json:"account_state"`
	Orders       []Order      `json:"orders"`
	Positions    []Position   `json:"positions"`
}

type TradingStreamEvent

type TradingStreamEvent struct {
	Snapshot    *TradingSnapshot
	Transaction *TransactionEvent
	Gap         *TradingStreamGap
}

TradingStreamEvent contains exactly one snapshot, transaction or gap on success. Replace cached state on Snapshot; invalidate it on Gap and at stream termination.

type TradingStreamGap

type TradingStreamGap = TickStreamGap

TradingStreamGap invalidates cached trading state; wait for a new snapshot.

type TradingStreamOptions

type TradingStreamOptions = TickStreamOptions

TradingStreamOptions shares the tick transport's bounded reconnect policy.

type TransactionAccountState

type TransactionAccountState struct {
	AccountState
	Leverage string `json:"leverage"`
}

TransactionAccountState includes leverage, required by transaction payloads.

type TransactionEvent

type TransactionEvent struct {
	EventType       string             `json:"event_type"`
	Payload         TransactionPayload `json:"payload"`
	OperationID     *string            `json:"operation_id,omitempty"`
	ClientRequestID *string            `json:"client_request_id,omitempty"`
	Status          *string            `json:"status,omitempty"`
	ErrorCode       *int               `json:"error_code,omitempty"`
	ErrorMessage    *string            `json:"error_message,omitempty"`
	EventTime       *time.Time         `json:"event_time,omitempty"`
}

TransactionEvent includes successful changes and rejected/failed results. ErrorMessage is untrusted server data. OperationID may be absent, e.g. deposits.

type TransactionPayload

type TransactionPayload struct {
	Orders       []Order                  `json:"orders,omitempty"`
	Positions    []Position               `json:"positions,omitempty"`
	Deals        []Deal                   `json:"deals,omitempty"`
	AccountState *TransactionAccountState `json:"account_state,omitempty"`
}

TransactionPayload holds changed entities, never a complete account snapshot.

type TransportError

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

TransportError keeps a sanitized message, while supporting errors.Is/As for its cause.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type WebSocketAPIError

type WebSocketAPIError struct {
	RequestID    string
	Code         int
	ErrorMessage string
}

WebSocketAPIError reports a subscription rejection. ErrorMessage is untrusted.

func (*WebSocketAPIError) Error

func (e *WebSocketAPIError) Error() string

type WebSocketAccountLimits

type WebSocketAccountLimits struct {
	MaxActiveConnections   int              `json:"max_active_connections"`
	MaxInboundMessageBytes int              `json:"max_inbound_message_bytes"`
	ConnectionRate         TokenBucketLimit `json:"connection_rate"`
	InboundMessageRate     TokenBucketLimit `json:"inbound_message_rate"`
	Strikes                StrikeLimits     `json:"strikes"`
}

type WebSocketEndpointLimits

type WebSocketEndpointLimits struct {
	APIOperationID            string                      `json:"api_operation_id"`
	HTTPMethod                string                      `json:"http_method"`
	Path                      string                      `json:"path"`
	ConnectionRate            TokenBucketLimit            `json:"connection_rate"`
	InboundMessageRate        TokenBucketLimit            `json:"inbound_message_rate"`
	SubscriptionOperationRate map[string]TokenBucketLimit `json:"subscription_operation_rate"`
}

type WebSocketLimits

type WebSocketLimits struct {
	GlobalAccountLimits WebSocketAccountLimits    `json:"global_account_limits"`
	Endpoints           []WebSocketEndpointLimits `json:"endpoints"`
}

Directories

Path Synopsis
examples
read-account command
read-events command
read-market command
read-ticks command
read-trading command

Jump to

Keyboard shortcuts

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