phoenixperps

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 26 Imported by: 1 module, 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

phoenixperps (Go)

The Phoenix Perpetuals API for Go: every REST call, the account stream and market data, with retries, idempotency keys, paging and typed errors. Go 1.23 or later. Docs: https://docs.phoenixperpsfunding.com

go get github.com/phoenixperps/sdk/go
import phoenixperps "github.com/phoenixperps/sdk/go"

client, err := phoenixperps.NewClient() // PHOENIXPERPS_API_KEY from the environment
accounts, err := client.Accounts.List(ctx)
order, err := client.Orders.Create(ctx, accounts.Data[0].ID, phoenixperps.CreateOrder{
	Market: "BTC-USD",
	Side:   phoenixperps.OrderSideBuy,
	Type:   phoenixperps.CreateOrderTypeMarket,
	Size:   phoenixperps.Dec("0.01"),
})

The client

NewClient(WithAPIKey, WithEnvironment, WithBaseURL, WithStreamURLs, WithTimeout, WithMaxRetries, WithAppInfo, WithHTTPClient, WithLogger)

  • The key comes from WithAPIKey, else PHOENIXPERPS_API_KEY. Without one the client is made all the same: the public calls (Markets and Platform) work, and any other answers the API's missing_api_key.
  • The environment (live or sandbox, in any case) comes from WithEnvironment, else the key itself (ppk_live_, ppk_test_), else PHOENIXPERPS_ENVIRONMENT; a key of the other environment fails before any request.
  • WithBaseURL (else PHOENIXPERPS_BASE_URL) is the REST host; the REST address as the docs write it, with /v1, works too. The streams keep their own addresses (WithStreamURLs).
  • Every call takes a context.Context first and CallOptions last: WithIdempotencyKey, WithRequestTimeout, WithRequestMaxRetries, WithHeader, WithRawResponse(&raw) (the answer's status, headers, request id and Idempotency-Key).
  • The key never appears when the client is printed or marshalled (client.MaskedKey() shows its end).

Calls

Services follow the API: Platform, Me, Markets, Accounts, History, Margin, Positions, Orders, Fills, Exits, Strategies, Alerts, Events, WebhookEndpoints, TradingView. Prices and sizes are Decimal, a string type: exact, never a float (DecimalOf(f) writes a float in plain form). Optional fields are pointers: Dec("1"), Ptr(true). Enums are open: a value from a newer API is kept as is.

  • A call is tried again only when that is safe (a read, a call the API marks retry-safe, or one carrying its Idempotency-Key, yours included), after a network failure, a timeout, or an answer the API marks retryable (409 operation_in_progress: the same key while the first call still runs; an answer without the API's envelope: 429 or 5xx). Writes get one Idempotency-Key, the same on every attempt.
  • Retry-After (fractions of a second included) is honoured; one over 60 s is not slept: the call fails with ErrRateLimit and RetryAfter set.
  • The rate limit is kept per budget: the operation's own and the bucket the answer names (X-RateLimit-Scope: key, bulk, account_orders...) (c.RateLimit(), with its Scope). With a bucket used up, the next call that draws on it waits for the request it gives back (60 s / X-RateLimit-Limit, a minute's; or a 429's Retry-After), never for the whole window, and a call that never met that bucket does not wait at all.
  • A 304 Not Modified (your own If-None-Match header) is no error: nothing is read (a list answers a nil page), and WithRawResponse shows the 304 and its ETag.
  • client.Do(ctx, method, path, query, body, opts...) sends any route with the same key, retries and errors, and answers the answer as it came.

Lists

page, err := client.Orders.List(ctx, accountID, &phoenixperps.OrdersListParams{Status: phoenixperps.Ptr(phoenixperps.OrdersListParamsStatusWorking)})
next, err := page.GetNextPage(ctx) // nil after the last
// page.HistoryComplete (orders): false when the history reaches further back than the list covers

for fill, err := range client.Fills.ListAutoPaging(ctx, accountID, nil, phoenixperps.WithMaxItems(500)) {
	if err != nil { ... }
}

Errors

Every failure is a *phoenixperps.Error with Kind, Status, Code, Message, RequestID, Details, RetryAfter, Retryable (the API's own flag; true for a timeout or a network failure), DocURL, OrderID, IdempotencyKey and the answer's Header. errors.Is tells the family: ErrAuthentication (401), ErrPermission (403), ErrNotFound, ErrConflict (409), ErrValidation (400), ErrRuleRejected (422: the account's rules said no), ErrRateLimit, ErrServer (a 2xx that is no JSON, a proxy's page, too), ErrConnection, ErrTimeout, ErrWebhookVerification. Every code the API answers is an ErrCode* constant.

ErrTimeout is the SDK's own per-attempt timeout (WithTimeout, WithRequestTimeout). A call ended by your own context answers ctx.Err() as is (context.Canceled, context.DeadlineExceeded): its outcome is unknown, so bound a write with your own WithIdempotencyKey (or a client_order_id) and call again with a fresh context.

var e *phoenixperps.Error
if errors.As(err, &e) && e.Code == phoenixperps.ErrCodeInsufficientMargin { ... }

Streams (read only; orders go through REST)

s := client.AccountStream(ctx, phoenixperps.AccountStreamOptions{
	Risk:   true,
	OnRisk: func(accountID string, risk *phoenixperps.AccountRisk) { ... }, // each risk frame as it comes
	OnGap:  func(after string) { ... },                                     // events after this one may be missing
})
defer s.Close()
for event, err := range s.Events() { // each event once (event.Seq, event.Replayed), resumed after reconnects
	...
}

m := client.MarketStream(ctx)
_, err = m.Subscribe(ctx, "ticker", []string{"BTC-USD"}, map[string]any{"interval_ms": 250})
for frame, err := range m.Frames() { ... }
  • Both reconnect by themselves, also after three heartbeats without a frame (a connection a proxy or a sleeping laptop left half open), and after an upgrade refused with 429 or 5xx (its Retry-After); each reconnect is one line in the client's log, with its cause. Any other refusal ends the stream with the API's own error.
  • A resume the server cannot cover, and a 4008 (too far behind), are gaps: OnGap hears the last event told; read client.Events.List after it for what was missed.
  • An account the server refuses (account_not_found, too_many_accounts) ends the account stream: Next answers an ErrValidation with its code and Details (account_id, max), and Ready() is closed then too. A snapshot whose error is set (state_unavailable) is an account not read now, not a flat one: read it again by REST.
  • s.Ping asks for a pong; s.Unsubscribe(ctx, accounts) stops following accounts, after a reconnect too.
  • The market stream makes again what the server still holds: Unsubscribe needs no params (without a candle's interval it ends every interval; naming no market, every market of the channel). Made again, a subscription asks its history again: trades and candles already told can come again (a trade's id, a candle's time tell them apart). List and Ping ask the server for its list of subscriptions and a pong; Limits() are the hello's (subscriptions, symbols per subscribe, messages a second).

Helpers

  • NewMarketRules(market): RoundPrice, RoundSize, SizeForNotional, SizeForRisk(riskUSD, stopDistance), WorstPrice(side, price, slippagePct) (side buy or sell, any case; a slippage within the market's own min..max), in exact decimals with the market's own steps. What they cannot take (a string that is no decimal, another side) is an ErrValidation. A size for a notional or a risk is rounded down, even below MinSize (it may be 0): check it before you order.
  • VerifyWebhook(rawBody, header, secrets, tolerance): the WebhookPayload (the event with APIVersion, Environment and Test; a webhook.ping is a type like any other), or an ErrWebhookVerification whose Code is missing_headers, stale, bad_signature or bad_body. Pass the body exactly as received. No secret at all (none given, or only empty ones) is an ErrValidation (code missing_secret), before anything is checked: a set-up fault, never a delivery to refuse.

Examples

examples/01-accounts to 12-error-handling, the same twelve programs as in every SDK, each one in every language in the docs' cookbook (https://docs.phoenixperpsfunding.com/cookbook). From the SDK's source: go run ./examples/01-accounts.

Documentation

Overview

Package phoenixperps is the Phoenix Perpetuals API for Go: every REST call, the account stream and market data, with retries, idempotency keys, paging and typed errors. Docs: https://docs.phoenixperpsfunding.com

client, err := phoenixperps.NewClient()                // PHOENIXPERPS_API_KEY from the environment
order, err := client.Orders.Create(ctx, accountID, phoenixperps.CreateOrder{
	Market: "BTC-USD", Side: phoenixperps.OrderSideBuy, Type: phoenixperps.CreateOrderTypeMarket,
	Size: phoenixperps.Dec("0.01"),
})

Index

Constants

View Source
const (
	ErrCodeInvalidRequest           = "invalid_request"
	ErrCodeInvalidParameter         = "invalid_parameter"
	ErrCodeUnknownField             = "unknown_field"
	ErrCodeInvalidCursor            = "invalid_cursor"
	ErrCodeInvalidJSON              = "invalid_json"
	ErrCodeMissingAPIKey            = "missing_api_key"
	ErrCodeInvalidAPIKey            = "invalid_api_key"
	ErrCodeExpiredAPIKey            = "expired_api_key"
	ErrCodeRevokedAPIKey            = "revoked_api_key"
	ErrCodeInvalidToken             = "invalid_token"
	ErrCodeExpiredToken             = "expired_token"
	ErrCodeRevokedToken             = "revoked_token"
	ErrCodeWrongResource            = "wrong_resource"
	ErrCodeWrongEnvironment         = "wrong_environment"
	ErrCodeIPNotAllowed             = "ip_not_allowed"
	ErrCodeInsufficientPermission   = "insufficient_permission"
	ErrCodeAPIDisabled              = "api_disabled"
	ErrCodeInvalidSizeStep          = "invalid_size_step"
	ErrCodeInvalidPriceTick         = "invalid_price_tick"
	ErrCodePriceOutOfBand           = "price_out_of_band"
	ErrCodeStopAlreadyTriggered     = "stop_already_triggered"
	ErrCodePostOnlyWouldFill        = "post_only_would_fill"
	ErrCodeLimitInsideSpread        = "limit_inside_spread"
	ErrCodeOrderTooSmall            = "order_too_small"
	ErrCodeWorkingOrderCap          = "working_order_cap"
	ErrCodeClientOrderIDConflict    = "client_order_id_conflict"
	ErrCodeOrderNotWorking          = "order_not_working"
	ErrCodeIdempotencyKeyReused     = "idempotency_key_reused"
	ErrCodeJSONTooDeep              = "json_too_deep"
	ErrCodeOperationInProgress      = "operation_in_progress"
	ErrCodeKeyMarketNotAllowed      = "key_market_not_allowed"
	ErrCodeKeyReduceOnly            = "key_reduce_only"
	ErrCodeKeyMaxOrderNotional      = "key_max_order_notional"
	ErrCodeKeyMaxPositionNotional   = "key_max_position_notional"
	ErrCodeKeyLossStopActive        = "key_loss_stop_active"
	ErrCodeInsufficientMargin       = "insufficient_margin"
	ErrCodeExposureCapExceeded      = "exposure_cap_exceeded"
	ErrCodeReduceOnlyViolation      = "reduce_only_violation"
	ErrCodeSlippageExceeded         = "slippage_exceeded"
	ErrCodeNoPrice                  = "no_price"
	ErrCodeStaleQuote               = "stale_quote"
	ErrCodeMarketClosed             = "market_closed"
	ErrCodeMarketNotOffered         = "market_not_offered"
	ErrCodeMarketOptionHeld         = "market_option_held"
	ErrCodeWeekendClose             = "weekend_close"
	ErrCodeMarketHalted             = "market_halted"
	ErrCodePositionLiquidating      = "position_liquidating"
	ErrCodeAccountPaused            = "account_paused"
	ErrCodeAccountNotTradable       = "account_not_tradable"
	ErrCodeInsufficientBalance      = "insufficient_balance"
	ErrCodeMarginModeLocked         = "margin_mode_locked"
	ErrCodeMarginRejected           = "margin_rejected"
	ErrCodeInvalidLeverage          = "invalid_leverage"
	ErrCodeLiquidationRisk          = "liquidation_risk"
	ErrCodePositionNotIsolated      = "position_not_isolated"
	ErrCodeEngineBusy               = "engine_busy"
	ErrCodeOrderRejected            = "order_rejected"
	ErrCodeExitsChanged             = "exits_changed"
	ErrCodeExitOperationFailed      = "exit_operation_failed"
	ErrCodeExitWouldFill            = "exit_would_fill"
	ErrCodeExitsExceedPosition      = "exits_exceed_position"
	ErrCodeExitLegCap               = "exit_leg_cap"
	ErrCodeStrategyLimit            = "strategy_limit"
	ErrCodeStrategyNotActive        = "strategy_not_active"
	ErrCodeStrategyNotFound         = "strategy_not_found"
	ErrCodeClientStrategyIDConflict = "client_strategy_id_conflict"
	ErrCodeWebhookEndpointNotFound  = "webhook_endpoint_not_found"
	ErrCodeTradingviewHookNotFound  = "tradingview_hook_not_found"
	ErrCodeTradingviewAlertNotFound = "tradingview_alert_not_found"
	ErrCodeWebhookEndpointNotActive = "webhook_endpoint_not_active"
	ErrCodeDeliveryNotFound         = "delivery_not_found"
	ErrCodeEventNotFound            = "event_not_found"
	ErrCodeRungWouldFill            = "rung_would_fill"
	ErrCodeTriggerAlreadyMet        = "trigger_already_met"
	ErrCodeAlertNotFound            = "alert_not_found"
	ErrCodeAlertLimit               = "alert_limit"
	ErrCodeAlertAtPrice             = "alert_at_price"
	ErrCodeAlertNotArmed            = "alert_not_armed"
	ErrCodeStrategyTypeDisabled     = "strategy_type_disabled"
	ErrCodeAccountNotFound          = "account_not_found"
	ErrCodeMarketNotFound           = "market_not_found"
	ErrCodeOrderNotFound            = "order_not_found"
	ErrCodePositionNotFound         = "position_not_found"
	ErrCodeRouteNotFound            = "route_not_found"
	ErrCodeMethodNotAllowed         = "method_not_allowed"
	ErrCodePayloadTooLarge          = "payload_too_large"
	ErrCodeUriTooLong               = "uri_too_long"
	ErrCodeUnsupportedMediaType     = "unsupported_media_type"
	ErrCodeSandboxLimitReached      = "sandbox_limit_reached"
	ErrCodeAccountNotReady          = "account_not_ready"
	ErrCodeAccountClosed            = "account_closed"
	ErrCodeSandboxOpening           = "sandbox_opening"
	ErrCodeIdempotencyKeyRequired   = "idempotency_key_required"
	ErrCodeInvalidIdempotencyKey    = "invalid_idempotency_key"
	ErrCodeRateLimited              = "rate_limited"
	ErrCodeNotReady                 = "not_ready"
	ErrCodeStateUnavailable         = "state_unavailable"
	ErrCodeEngineUnavailable        = "engine_unavailable"
	ErrCodeLimiterUnavailable       = "limiter_unavailable"
	ErrCodeSandboxDisabled          = "sandbox_disabled"
	ErrCodeEnvironmentDisabled      = "environment_disabled"
	ErrCodeTemporarilyUnavailable   = "temporarily_unavailable"
	ErrCodeCapacity                 = "capacity"
	ErrCodeInternalError            = "internal_error"
)

The error codes the API answers (Error.Code).

View Source
const SDKVersion = "1.3.1"

SDKVersion is this SDK's version (lockstep with every other Phoenix Perpetuals SDK).

View Source
const SpecVersion = "1.1.2"

SpecVersion is the version of the API spec this SDK was generated from.

Variables

View Source
var (
	ErrAuthentication = &Error{Kind: KindAuthentication}
	ErrPermission     = &Error{Kind: KindPermission}
	ErrNotFound       = &Error{Kind: KindNotFound}
	ErrConflict       = &Error{Kind: KindConflict}
	ErrValidation     = &Error{Kind: KindValidation}
	ErrRuleRejected   = &Error{Kind: KindRuleRejected}
	ErrRateLimit      = &Error{Kind: KindRateLimit}
	ErrServer         = &Error{Kind: KindServer}
	ErrConnection     = &Error{Kind: KindConnection}
	ErrTimeout        = &Error{Kind: KindTimeout}
	ErrStreamClosed   = &Error{Kind: KindStreamClosed}

	ErrWebhookVerification = &Error{Kind: KindWebhookVerification}
)

The families, for errors.Is.

View Source
var ErrorCodes = map[string]ErrorCodeInfo{}/* 104 elements not displayed */

ErrorCodes describes every code the API answers.

Functions

func Ptr

func Ptr[T any](v T) *T

Ptr is a pointer to any value, for optional fields: Ptr(true), Ptr(TimeInForceGtc).

Types

type Account

type Account struct {
	// The account number.
	ID string `json:"id"`
	// The environment the account lives in.
	Environment PlatformEnvironment `json:"environment"`
	// Where the account is in the programme.
	Stage AccountStage `json:"stage"`
	// pending: being opened; active: trading.
	Status AccountStatus `json:"status"`
	// The product it was bought as.
	Product *string `json:"product"`
	// Its size as sold.
	Tier *string `json:"tier"`
	// The balance it started with.
	StartBalance *Decimal `json:"start_balance"`
	// The balance: closed trades and fees only.
	Balance *Decimal `json:"balance"`
	Rule    *Rule    `json:"rule"`
	// A payout may be requested now.
	PayoutEligible bool `json:"payout_eligible"`
	// Sandbox only: parked after a while unused; it wakes the moment you use it.
	Parked *bool `json:"parked,omitempty"`
	// When the account was made.
	CreatedAt *int64 `json:"created_at"`
}

Account: see the API reference.

type AccountDetail

type AccountDetail struct {
	// The account number.
	ID string `json:"id"`
	// The environment the account lives in.
	Environment PlatformEnvironment `json:"environment"`
	// Where the account is in the programme.
	Stage AccountStage `json:"stage"`
	// pending: being opened; active: trading.
	Status AccountStatus `json:"status"`
	// The product it was bought as.
	Product *string `json:"product"`
	// Its size as sold.
	Tier *string `json:"tier"`
	// The balance it started with.
	StartBalance *Decimal `json:"start_balance"`
	// The balance: closed trades and fees only.
	Balance *Decimal `json:"balance"`
	Rule    *Rule    `json:"rule"`
	// A payout may be requested now.
	PayoutEligible bool `json:"payout_eligible"`
	// Sandbox only: parked after a while unused; it wakes the moment you use it.
	Parked *bool `json:"parked,omitempty"`
	// When the account was made.
	CreatedAt *int64             `json:"created_at"`
	Risk      *AccountRiskOrNull `json:"risk"`
}

AccountDetail: see the API reference.

type AccountRisk

type AccountRisk struct {
	// When the oldest figure here was read.
	AsOf int64 `json:"as_of"`
	// Some figures are older than usual (the engine was busy).
	Stale bool `json:"stale"`
	// The daily loss limit paused trading on the account (its positions were closed): it trades again from midnight
	// New York.
	Paused bool `json:"paused"`
	// The balance.
	Balance Decimal `json:"balance"`
	// The balance plus the open P&L at the market price.
	Equity Decimal `json:"equity"`
	// The open P&L.
	UnrealizedPnL Decimal `json:"unrealized_pnl"`
	// The equity change since midnight New York, open positions included: what the daily loss rule counts.
	PnLToday Decimal `json:"pnl_today"`
	// The P&L closed today.
	RealizedToday Decimal `json:"realized_today"`
	// The fees paid today.
	FeesToday Decimal `json:"fees_today"`
	// Trades closed today.
	TradesToday int64 `json:"trades_today"`
	// The margin your positions hold.
	MarginUsed Decimal `json:"margin_used"`
	// What is left of the balance for new positions.
	MarginAvailable    *Decimal                       `json:"margin_available"`
	Exposure           AccountRiskExposure            `json:"exposure"`
	DailyLoss          *Limit                         `json:"daily_loss"`
	MaxDrawdown        *Limit                         `json:"max_drawdown"`
	ProfitTarget       *AccountRiskProfitTarget       `json:"profit_target"`
	TradingDays        AccountRiskTradingDays         `json:"trading_days"`
	NearestLiquidation *AccountRiskNearestLiquidation `json:"nearest_liquidation"`
	// When the trading day ends (midnight New York).
	TradingDayEndsAt int64 `json:"trading_day_ends_at"`
	// What needs your attention, most serious first.
	Warnings []Warning `json:"warnings"`
}

AccountRisk: see the API reference.

func (AccountRisk) MarshalJSON

func (x AccountRisk) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type AccountRiskExposure

type AccountRiskExposure struct {
	// The value of every open position.
	Gross Decimal `json:"gross"`
	// The value of the long ones.
	Long Decimal `json:"long"`
	// The value of the short ones.
	Short Decimal `json:"short"`
	// Gross exposure over equity.
	EffectiveLeverage *Decimal `json:"effective_leverage"`
	// Per market, largest first.
	Markets []AccountRiskExposureMarket `json:"markets"`
}

AccountRiskExposure: see the API reference.

func (AccountRiskExposure) MarshalJSON

func (x AccountRiskExposure) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type AccountRiskExposureMarket

type AccountRiskExposureMarket struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The value held on it.
	Notional Decimal `json:"notional"`
	// That value over equity.
	Leverage *Decimal `json:"leverage"`
	// The exposure cap of the market.
	Cap *Decimal `json:"cap"`
	// How much of the cap is used, counting your other accounts on the same rule, in percent.
	CapUsedPct *Decimal `json:"cap_used_pct"`
}

AccountRiskExposureMarket: see the API reference.

type AccountRiskNearestLiquidation

type AccountRiskNearestLiquidation struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// Its liquidation price.
	Price Decimal `json:"price"`
	// How far the price is from it, in percent.
	DistancePct Decimal `json:"distance_pct"`
}

AccountRiskNearestLiquidation: see the API reference.

type AccountRiskOrNull

type AccountRiskOrNull struct {
	// When the oldest figure here was read.
	AsOf int64 `json:"as_of"`
	// Some figures are older than usual (the engine was busy).
	Stale bool `json:"stale"`
	// The daily loss limit paused trading on the account (its positions were closed): it trades again from midnight
	// New York.
	Paused bool `json:"paused"`
	// The balance.
	Balance Decimal `json:"balance"`
	// The balance plus the open P&L at the market price.
	Equity Decimal `json:"equity"`
	// The open P&L.
	UnrealizedPnL Decimal `json:"unrealized_pnl"`
	// The equity change since midnight New York, open positions included: what the daily loss rule counts.
	PnLToday Decimal `json:"pnl_today"`
	// The P&L closed today.
	RealizedToday Decimal `json:"realized_today"`
	// The fees paid today.
	FeesToday Decimal `json:"fees_today"`
	// Trades closed today.
	TradesToday int64 `json:"trades_today"`
	// The margin your positions hold.
	MarginUsed Decimal `json:"margin_used"`
	// What is left of the balance for new positions.
	MarginAvailable    *Decimal                             `json:"margin_available"`
	Exposure           AccountRiskOrNullExposure            `json:"exposure"`
	DailyLoss          *Limit                               `json:"daily_loss"`
	MaxDrawdown        *Limit                               `json:"max_drawdown"`
	ProfitTarget       *AccountRiskOrNullProfitTarget       `json:"profit_target"`
	TradingDays        AccountRiskOrNullTradingDays         `json:"trading_days"`
	NearestLiquidation *AccountRiskOrNullNearestLiquidation `json:"nearest_liquidation"`
	// When the trading day ends (midnight New York).
	TradingDayEndsAt int64 `json:"trading_day_ends_at"`
	// What needs your attention, most serious first.
	Warnings []Warning `json:"warnings"`
}

AccountRiskOrNull: The live risk; null while the account is being opened.

func (AccountRiskOrNull) MarshalJSON

func (x AccountRiskOrNull) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type AccountRiskOrNullExposure

type AccountRiskOrNullExposure struct {
	// The value of every open position.
	Gross Decimal `json:"gross"`
	// The value of the long ones.
	Long Decimal `json:"long"`
	// The value of the short ones.
	Short Decimal `json:"short"`
	// Gross exposure over equity.
	EffectiveLeverage *Decimal `json:"effective_leverage"`
	// Per market, largest first.
	Markets []AccountRiskOrNullExposureMarket `json:"markets"`
}

AccountRiskOrNullExposure: see the API reference.

func (AccountRiskOrNullExposure) MarshalJSON

func (x AccountRiskOrNullExposure) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type AccountRiskOrNullExposureMarket

type AccountRiskOrNullExposureMarket struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The value held on it.
	Notional Decimal `json:"notional"`
	// That value over equity.
	Leverage *Decimal `json:"leverage"`
	// The exposure cap of the market.
	Cap *Decimal `json:"cap"`
	// How much of the cap is used, counting your other accounts on the same rule, in percent.
	CapUsedPct *Decimal `json:"cap_used_pct"`
}

AccountRiskOrNullExposureMarket: see the API reference.

type AccountRiskOrNullNearestLiquidation

type AccountRiskOrNullNearestLiquidation struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// Its liquidation price.
	Price Decimal `json:"price"`
	// How far the price is from it, in percent.
	DistancePct Decimal `json:"distance_pct"`
}

AccountRiskOrNullNearestLiquidation: see the API reference.

type AccountRiskOrNullProfitTarget

type AccountRiskOrNullProfitTarget struct {
	// The balance that reaches it.
	GoalBalance Decimal `json:"goal_balance"`
	// Still to make.
	Remaining Decimal `json:"remaining"`
	// How far, in percent.
	ProgressPct *Decimal `json:"progress_pct"`
	// Positions must be closed when it is reached.
	RequiresFlat bool `json:"requires_flat"`
}

AccountRiskOrNullProfitTarget: see the API reference.

type AccountRiskOrNullTradingDays

type AccountRiskOrNullTradingDays struct {
	// Days with a trade so far.
	Count *int64 `json:"count"`
	// Days the rule needs.
	Required *int64 `json:"required"`
}

AccountRiskOrNullTradingDays: see the API reference.

type AccountRiskProfitTarget

type AccountRiskProfitTarget struct {
	// The balance that reaches it.
	GoalBalance Decimal `json:"goal_balance"`
	// Still to make.
	Remaining Decimal `json:"remaining"`
	// How far, in percent.
	ProgressPct *Decimal `json:"progress_pct"`
	// Positions must be closed when it is reached.
	RequiresFlat bool `json:"requires_flat"`
}

AccountRiskProfitTarget: see the API reference.

type AccountRiskTradingDays

type AccountRiskTradingDays struct {
	// Days with a trade so far.
	Count *int64 `json:"count"`
	// Days the rule needs.
	Required *int64 `json:"required"`
}

AccountRiskTradingDays: see the API reference.

type AccountStage

type AccountStage string

AccountStage: Where the account is in the programme. Open: a value from a newer API version is kept as is.

const (
	AccountStageEvaluation AccountStage = "evaluation"
	AccountStageFunded     AccountStage = "funded"
	AccountStageSandbox    AccountStage = "sandbox"
)

type AccountStatus

type AccountStatus string

AccountStatus: pending: being opened; active: trading. Open: a value from a newer API version is kept as is.

const (
	AccountStatusPending   AccountStatus = "pending"
	AccountStatusActive    AccountStatus = "active"
	AccountStatusPassed    AccountStatus = "passed"
	AccountStatusFailed    AccountStatus = "failed"
	AccountStatusClosed    AccountStatus = "closed"
	AccountStatusSuspended AccountStatus = "suspended"
)

type AccountStream

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

AccountStream is the account stream: snapshots, then every event of the accounts, each once.

func (*AccountStream) Close

func (s *AccountStream) Close() error

Close ends the stream.

func (*AccountStream) Events

func (s *AccountStream) Events() iter.Seq2[StreamEvent, error]

Events goes over the events until the stream ends (an error that ended it is yielded once).

func (*AccountStream) LastEventID

func (s *AccountStream) LastEventID() string

LastEventID is the id of the last event told (the resume point).

func (*AccountStream) Next

func (s *AccountStream) Next(ctx context.Context) (StreamEvent, error)

Next is the next event. After Close it answers a StreamClosedError; after 4001 an AuthenticationError; after a refused subscribe a ValidationError (its code, and its Details with the account_id it names); after a refused upgrade the API's own error.

func (*AccountStream) Ping

Ping answers the server's pong ({"type": "pong", "time": ...}), asked again on the next connection when this one drops first.

func (*AccountStream) Ready

func (s *AccountStream) Ready() <-chan struct{}

Ready is closed once the first snapshots are in, or once the stream ended (Next tells why).

func (*AccountStream) Risk

func (s *AccountStream) Risk(accountID string) json.RawMessage

Risk is the last risk frame of an account (with Risk set).

func (*AccountStream) Snapshot

func (s *AccountStream) Snapshot(accountID string) json.RawMessage

Snapshot is the last snapshot frame of an account (nil before it came).

func (*AccountStream) Unsubscribe

func (s *AccountStream) Unsubscribe(ctx context.Context, accounts []string) (json.RawMessage, error)

Unsubscribe stops following accounts, after a reconnect too (the subscribe it sends names what is left). It answers the server's reply ({"type": "unsubscribed", "accounts": [...]}), or nil when the connection dropped first.

type AccountStreamOptions

type AccountStreamOptions struct {
	Accounts []string // the accounts to follow (none: every account of the key)
	Risk     bool     // live risk frames too
	Resume   string   // start after this event id
	// OnRisk hears each risk frame as it comes (with Risk set), on the stream's goroutine: return quickly.
	OnRisk func(accountID string, risk *AccountRisk)
	// OnGap hears a gap: events after this id may be missing (a resume the server could not cover, or a 4008); read
	// them with client.Events.List after it. It runs on the stream's goroutine, before the events that follow; the
	// client's log has a warning either way.
	OnGap func(after string)
}

AccountStreamOptions chooses what an AccountStream follows, and who hears its risk frames and its gaps.

type AccountsService

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

AccountsService: the accounts calls (client.Accounts).

func (*AccountsService) CreateSandbox

func (r *AccountsService) CreateSandbox(ctx context.Context, opts ...CallOption) (*Account, error)

CreateSandbox: Open a sandbox account.

func (*AccountsService) Get

func (r *AccountsService) Get(ctx context.Context, accountID string, opts ...CallOption) (*AccountDetail, error)

Get: Get an account.

func (*AccountsService) List

func (r *AccountsService) List(ctx context.Context, opts ...CallOption) (*Page[Account], error)

List: List accounts.

func (*AccountsService) Progress

func (r *AccountsService) Progress(ctx context.Context, accountID string, opts ...CallOption) (*Progress, error)

Progress: Get progress.

func (*AccountsService) Risk

func (r *AccountsService) Risk(ctx context.Context, accountID string, opts ...CallOption) (*AccountRisk, error)

Risk: Get live risk.

func (*AccountsService) TradingPolicy

func (r *AccountsService) TradingPolicy(ctx context.Context, accountID string, opts ...CallOption) (*TradingPolicy, error)

TradingPolicy: Get the trading policy.

type AlertsListParams added in v1.2.0

type AlertsListParams struct {
	// Only alerts with this status (default all).
	Status *AlertsListParamsStatus `json:"status,omitempty"`
	// Only this market.
	Market *string `json:"market,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

AlertsListParams: The query of list price alerts.

type AlertsListParamsStatus added in v1.2.0

type AlertsListParamsStatus string

AlertsListParamsStatus: one of the values below. Open: a value from a newer API version is kept as is.

const (
	AlertsListParamsStatusAll       AlertsListParamsStatus = "all"
	AlertsListParamsStatusArmed     AlertsListParamsStatus = "armed"
	AlertsListParamsStatusTriggered AlertsListParamsStatus = "triggered"
	AlertsListParamsStatusDisabled  AlertsListParamsStatus = "disabled"
)

type AlertsService added in v1.2.0

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

AlertsService: the alerts calls (client.Alerts).

func (*AlertsService) Create added in v1.2.0

func (r *AlertsService) Create(ctx context.Context, accountID string, body CreatePriceAlert, opts ...CallOption) (*PriceAlert, error)

Create: Create a price alert.

func (*AlertsService) Delete added in v1.2.0

func (r *AlertsService) Delete(ctx context.Context, accountID string, alertID string, opts ...CallOption) (*DeletedAlert, error)

Delete: Delete a price alert.

func (*AlertsService) Get added in v1.2.0

func (r *AlertsService) Get(ctx context.Context, accountID string, alertID string, opts ...CallOption) (*PriceAlert, error)

Get: Get a price alert.

func (*AlertsService) List added in v1.2.0

func (r *AlertsService) List(ctx context.Context, accountID string, params *AlertsListParams, opts ...CallOption) (*Page[PriceAlert], error)

List: List price alerts.

func (*AlertsService) ListAutoPaging added in v1.2.0

func (r *AlertsService) ListAutoPaging(ctx context.Context, accountID string, params *AlertsListParams, opts ...CallOption) iter.Seq2[PriceAlert, error]

ListAutoPaging: every item of List, page after page (WithMaxItems caps it).

func (*AlertsService) Modify added in v1.2.0

func (r *AlertsService) Modify(ctx context.Context, accountID string, alertID string, body ChangePriceAlert, opts ...CallOption) (*PriceAlert, error)

Modify: Move a price alert.

func (*AlertsService) Rearm added in v1.2.0

func (r *AlertsService) Rearm(ctx context.Context, accountID string, alertID string, opts ...CallOption) (*PriceAlert, error)

Rearm: Arm a price alert again.

type CallOption

type CallOption func(*callConfig)

CallOption configures one call.

func WithHeader

func WithHeader(k, v string) CallOption

WithHeader adds a header to the request.

func WithIdempotencyKey

func WithIdempotencyKey(k string) CallOption

WithIdempotencyKey sets the call's Idempotency-Key (else a new UUID, the same on every attempt).

func WithMaxItems

func WithMaxItems(n int) CallOption

WithMaxItems caps an AutoPaging iteration (0: every item).

func WithRawResponse

func WithRawResponse(r *RawResponse) CallOption

WithRawResponse keeps the answer of the call (its status, headers, body, request id and Idempotency-Key).

func WithRequestMaxRetries

func WithRequestMaxRetries(n int) CallOption

WithRequestMaxRetries sets how often this call is tried again when that is safe.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) CallOption

WithRequestTimeout sets the time one attempt of this call may take.

type CancelAll

type CancelAll struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market *string `json:"market,omitempty"`
}

CancelAll: Optional: only this market.

type CancelAllResult

type CancelAllResult struct {
	// The account number.
	AccountID string `json:"account_id"`
	// The market, or null for every market.
	Market *string `json:"market"`
	// How many working orders were canceled.
	Canceled int64 `json:"canceled"`
}

CancelAllResult: see the API reference.

type ChangePriceAlert added in v1.2.0

type ChangePriceAlert struct {
	// A new level; its condition is set again from the price now.
	Price *Decimal `json:"price,omitempty"`
	// A new note; null removes it.
	Note *string `json:"note,omitempty"`
	// NoteNull sends note as null (the API: null removes it); a Note set is sent instead.
	NoteNull bool `json:"-"`
}

ChangePriceAlert: What to change on an armed alert: at least one field.

func (ChangePriceAlert) MarshalJSON added in v1.3.0

func (x ChangePriceAlert) MarshalJSON() ([]byte, error)

MarshalJSON sends a field marked <Field>Null as null.

type Client

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

Client is the API. Make one with NewClient and share it: it is safe for concurrent use.

func NewClient

func NewClient(opts ...ClientOption) (*Client, error)

NewClient makes a client. A key of the other environment fails here, before any request.

func (*Client) AccountStream

func (c *Client) AccountStream(ctx context.Context, opts AccountStreamOptions) *AccountStream

AccountStream connects to the account stream; it runs until Close (or until ctx ends).

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL is the API host the calls go to.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body any, opts ...CallOption) (*RawResponse, error)

Do sends any request to the API (an operation newer than this SDK, or one made at run time) with the client's key, retries and errors. path is the API path (/v1/...). It is tried again when that is safe: a GET, a route the spec marks retry-safe, or a call with its Idempotency-Key (WithIdempotencyKey). A 2xx or 304 answer comes as it came; any other, and a 2xx that is no JSON (a proxy's page), is an *Error.

func (*Client) Environment

func (c *Client) Environment() string

Environment is live or sandbox.

func (*Client) GoString

func (c *Client) GoString() string

GoString never shows the key (%#v).

func (*Client) MarketStream

func (c *Client) MarketStream(ctx context.Context) *MarketStream

MarketStream connects to the market data stream; it runs until Close (or until ctx ends).

func (*Client) MarshalJSON

func (c *Client) MarshalJSON() ([]byte, error)

MarshalJSON never shows the key.

func (*Client) MaskedKey

func (c *Client) MaskedKey() string

MaskedKey is the key with its secret hidden (ppk_test_****abcd).

func (*Client) RateLimit

func (c *Client) RateLimit() *RateLimit

RateLimit is what the last answer said of the rate-limit window (nil before the first answer).

func (*Client) String

func (c *Client) String() string

String never shows the key.

func (*Client) UserAgent

func (c *Client) UserAgent() string

UserAgent is what every request says of the SDK.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures NewClient.

func WithAPIKey

func WithAPIKey(key string) ClientOption

WithAPIKey sets the key (else PHOENIXPERPS_API_KEY). Without one the public calls (Markets, Platform) work, and any other answers the API's missing_api_key.

func WithAppInfo

func WithAppInfo(s string) ClientOption

WithAppInfo adds your app's name and version to the User-Agent.

func WithBaseURL

func WithBaseURL(u string) ClientOption

WithBaseURL sets the API host (else PHOENIXPERPS_BASE_URL, else the environment's); a trailing /v1 is dropped.

func WithEnvironment

func WithEnvironment(env string) ClientOption

WithEnvironment sets live or sandbox, in any case (else the key's own, else PHOENIXPERPS_ENVIRONMENT).

func WithHTTPClient

func WithHTTPClient(h *http.Client) ClientOption

WithHTTPClient sets the http.Client the calls go through.

func WithLogger

func WithLogger(l *slog.Logger) ClientOption

WithLogger receives a debug line per retry and one warning per deprecated API version.

func WithMaxRetries

func WithMaxRetries(n int) ClientOption

WithMaxRetries sets how often a safe call is tried again (2).

func WithStreamURLs

func WithStreamURLs(account, market string) ClientOption

WithStreamURLs overrides the account and market stream URLs (an empty string keeps the default).

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the time one attempt may take (30 s).

type ClosePosition

type ClosePosition struct {
	// How much to close; absent: the whole position.
	Size *Decimal `json:"size,omitempty"`
	// Your own id for the close order (a partial close).
	ClientOrderID *string `json:"client_order_id,omitempty"`
}

ClosePosition: What to close.

type ClosedPosition

type ClosedPosition struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// Long or short.
	Side PositionSide `json:"side"`
	// The size closed.
	Size Decimal `json:"size"`
	// The average entry price.
	EntryPrice *Decimal `json:"entry_price"`
	// The average exit price.
	ExitPrice *Decimal `json:"exit_price"`
	// The P&L before fees.
	GrossPnL Decimal `json:"gross_pnl"`
	// The fees.
	Fees Decimal `json:"fees"`
	// The P&L after fees.
	PnL Decimal `json:"pnl"`
	// When it opened.
	OpenedAt int64 `json:"opened_at"`
	// When it was fully closed.
	ClosedAt int64 `json:"closed_at"`
	// The pieces it was closed in.
	Lots []ClosedPositionLot `json:"lots"`
}

ClosedPosition: see the API reference.

func (ClosedPosition) MarshalJSON

func (x ClosedPosition) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type ClosedPositionLot

type ClosedPositionLot struct {
	// The size.
	Size Decimal `json:"size"`
	// Entry.
	EntryPrice *Decimal `json:"entry_price"`
	// Exit.
	ExitPrice *Decimal `json:"exit_price"`
	// P&L after fees.
	PnL Decimal `json:"pnl"`
	// Fees.
	Fees Decimal `json:"fees"`
	// Opened.
	OpenedAt *int64 `json:"opened_at"`
	// Closed.
	ClosedAt int64 `json:"closed_at"`
}

ClosedPositionLot: see the API reference.

type CreateOrder

type CreateOrder struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The order's side.
	Side OrderSide `json:"side"`
	// market: now, at the best price within your worst price. limit: at your price or better. stop_market: a market
	// order once the last price reaches the stop. stop_limit: a limit once the last price reaches the stop.
	Type CreateOrderType `json:"type"`
	// The size, in the base asset: a multiple of the market's size step. Give size or notional_usd.
	Size *Decimal `json:"size,omitempty"`
	// The size as a value in USD, rounded down to the size step.
	NotionalUSD *Decimal `json:"notional_usd,omitempty"`
	// The limit price (limit and stop_limit): a multiple of the tick size.
	LimitPrice *Decimal `json:"limit_price,omitempty"`
	// The trigger price (stop_market and stop_limit).
	StopPrice *Decimal `json:"stop_price,omitempty"`
	// Market orders: the worst price you accept. Give worst_price or max_slippage_pct.
	WorstPrice *Decimal `json:"worst_price,omitempty"`
	// Market orders: how far from the best price you accept, in percent (the default and bounds are in GET
	// /v1/markets).
	MaxSlippagePct *Decimal `json:"max_slippage_pct,omitempty"`
	// It may only reduce or close your position, never open or add to one.
	ReduceOnly *bool `json:"reduce_only,omitempty"`
	// Limit orders: refused if it would fill at once.
	PostOnly *bool `json:"post_only,omitempty"`
	// gtc: until canceled. gtd: until expires_at. ioc and fok: fill now or end (a fill is always the whole order).
	// Default: ioc for market orders, gtc otherwise.
	TimeInForce *TimeInForce `json:"time_in_force,omitempty"`
	// With gtd: when it ends, from orders.gtd_min_seconds to orders.gtd_max_days ahead (GET /v1/limits).
	ExpiresAt *int64 `json:"expires_at,omitempty"`
	// Your own id for the order: unique in this environment, 1 to 64 letters, digits and . _ : -
	ClientOrderID *string     `json:"client_order_id,omitempty"`
	Exits         *OrderExits `json:"exits,omitempty"`
}

CreateOrder: A new order.

type CreateOrderType

type CreateOrderType string

CreateOrderType: market: now, at the best price within your worst price. limit: at your price or better. stop_market: a market order once the last price reaches the stop. stop_limit: a limit once the last price reaches the stop. Open: a value from a newer API version is kept as is.

const (
	CreateOrderTypeMarket     CreateOrderType = "market"
	CreateOrderTypeLimit      CreateOrderType = "limit"
	CreateOrderTypeStopMarket CreateOrderType = "stop_market"
	CreateOrderTypeStopLimit  CreateOrderType = "stop_limit"
)

type CreatePriceAlert added in v1.2.0

type CreatePriceAlert struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The level; not the price now.
	Price Decimal `json:"price"`
	// Your note (at most 280 characters).
	Note *string `json:"note,omitempty"`
}

CreatePriceAlert: A new price alert. Its condition (above or below) is set from the price now.

type CreateStrategy

type CreateStrategy struct {
	// trailing_stop: a stop-loss that follows the price. break_even: the stop-losses move to the entry once the
	// price has gone your way far enough. oco: two orders, the first fill cancels the other. twap, vwap: an order in
	// market slices over time (vwap sized by yesterday's volume over the same hours). scaled: a ladder of limits.
	// chase: a limit that follows the bid or ask. conditional: an order sent once a price is reached, on this market
	// (a buy when the price falls to trigger_price, a sell when it rises) or on another one (trigger_market).
	Type CreateStrategyType `json:"type"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The order's side.
	Side *OrderSide `json:"side,omitempty"`
	// trailing_stop: its size (absent: what the stop-losses leave of the position). twap, vwap, scaled, chase,
	// conditional: the whole size.
	Size *Decimal `json:"size,omitempty"`
	// trailing_stop: how far behind the best price (or percent).
	Distance *Decimal `json:"distance,omitempty"`
	// trailing_stop: how far behind, in percent of the best price.
	Percent *Decimal `json:"percent,omitempty"`
	// trailing_stop: start once the price reaches this (until then, initial_stop_price rests, or nothing).
	ActivationPrice *Decimal `json:"activation_price,omitempty"`
	// trailing_stop: where the stop rests until the trail moves it (absent: from the price now).
	InitialStopPrice *Decimal `json:"initial_stop_price,omitempty"`
	// trailing_stop: cancel the position's other stop-losses first.
	ReplaceStops *bool `json:"replace_stops,omitempty"`
	// break_even: how far from the entry the price must go.
	TriggerDistance *Decimal `json:"trigger_distance,omitempty"`
	// break_even: the same, in percent of the entry.
	TriggerPercent *Decimal `json:"trigger_percent,omitempty"`
	// break_even: or once the price reaches this. conditional: the level that sends the order (the trigger market's
	// price; its tick).
	TriggerPrice *Decimal `json:"trigger_price,omitempty"`
	// conditional: the market whose price is watched (absent: this market). Any market we list.
	TriggerMarket *string `json:"trigger_market,omitempty"`
	// conditional, with another trigger_market: send the order once it trades at or above trigger_price, or at or
	// below it. On this market it is set by the side and not given.
	TriggerDirection *CreateStrategyTriggerDirection `json:"trigger_direction,omitempty"`
	// conditional: the order it sends (default market).
	OrderType *CreateStrategyOrderType `json:"order_type,omitempty"`
	// conditional: the limit of its order, with order_type limit.
	LimitPrice *Decimal `json:"limit_price,omitempty"`
	// conditional: until when it waits for its price (default and longest: the gtd maximum, see GET /v1/limits). Its
	// order, once sent, stands on its own.
	ExpiresAt *int64 `json:"expires_at,omitempty"`
	// break_even: ticks beyond the entry, on the profit side. chase: ticks behind the bid (buy) or ask (sell).
	OffsetTicks *int64 `json:"offset_ticks,omitempty"`
	// oco: the two orders.
	Orders []CreateStrategyOrder `json:"orders,omitempty"`
	Exits  *OrderExits           `json:"exits,omitempty"`
	// twap, vwap: how long the schedule runs (bounds in the runner settings, see GET /v1/limits).
	DurationMinutes *int64 `json:"duration_minutes,omitempty"`
	// twap, vwap: time between slices; at most half the duration. Default: 60 (within those bounds).
	IntervalSeconds *int64 `json:"interval_seconds,omitempty"`
	// twap, vwap: vary each slice's time and size a little (the sizes still add up to size).
	Randomize *bool `json:"randomize,omitempty"`
	// twap, vwap, scaled, chase, conditional: only reduce your position (a twap ends when the position is closed).
	ReduceOnly *bool `json:"reduce_only,omitempty"`
	// twap, vwap (buy): slices wait while the price is above this. chase (buy): its cap.
	MaxPrice *Decimal `json:"max_price,omitempty"`
	// twap, vwap (sell): slices wait while the price is below this. chase (sell): its floor.
	MinPrice *Decimal `json:"min_price,omitempty"`
	// twap, vwap: each slice's slippage budget, in percent. conditional: its market order's.
	MaxSlippagePct *Decimal `json:"max_slippage_pct,omitempty"`
	// scaled: the first rung.
	StartPrice *Decimal `json:"start_price,omitempty"`
	// scaled: the last rung.
	EndPrice *Decimal `json:"end_price,omitempty"`
	// scaled: how many limits (at most the runner setting).
	Rungs *int64 `json:"rungs,omitempty"`
	// scaled: equal sizes, growing toward end_price, or shrinking.
	Distribution *CreateStrategyDistribution `json:"distribution,omitempty"`
	// scaled: each rung refused if it would fill at once.
	PostOnly *bool `json:"post_only,omitempty"`
	// scaled: one rung refused cancels the others.
	AllOrNone *bool `json:"all_or_none,omitempty"`
	// scaled: rungs through the price may fill at once (refused otherwise, rung_would_fill).
	AllowMarketable *bool `json:"allow_marketable,omitempty"`
	// chase: how long it follows the price.
	MaxMinutes *int64 `json:"max_minutes,omitempty"`
	// chase: at max_minutes, cancel it, or send what is left at the market.
	OnExpiry *CreateStrategyOnExpiry `json:"on_expiry,omitempty"`
	// chase: it may rest through the last price (it would then fill at once).
	AllowCross *bool `json:"allow_cross,omitempty"`
	// Your own id for the strategy (oco, twap, vwap, scaled, chase, conditional): unique in this environment.
	ClientStrategyID *string `json:"client_strategy_id,omitempty"`
}

CreateStrategy: A new strategy. trailing_stop and break_even act on the position's exits: the answer is that exits strategy.

type CreateStrategyDistribution

type CreateStrategyDistribution string

CreateStrategyDistribution: scaled: equal sizes, growing toward end_price, or shrinking. Open: a value from a newer API version is kept as is.

const (
	CreateStrategyDistributionFlat       CreateStrategyDistribution = "flat"
	CreateStrategyDistributionAscending  CreateStrategyDistribution = "ascending"
	CreateStrategyDistributionDescending CreateStrategyDistribution = "descending"
)

type CreateStrategyOnExpiry

type CreateStrategyOnExpiry string

CreateStrategyOnExpiry: chase: at max_minutes, cancel it, or send what is left at the market. Open: a value from a newer API version is kept as is.

const (
	CreateStrategyOnExpiryCancel CreateStrategyOnExpiry = "cancel"
	CreateStrategyOnExpiryMarket CreateStrategyOnExpiry = "market"
)

type CreateStrategyOrder

type CreateStrategyOrder struct {
	// The order's side.
	Side OrderSide `json:"side"`
	// Two orders that rest.
	Type CreateStrategyOrderType2 `json:"type"`
	// Its size.
	Size Decimal `json:"size"`
	// Its limit price.
	LimitPrice *Decimal `json:"limit_price,omitempty"`
	// Its stop price.
	StopPrice *Decimal `json:"stop_price,omitempty"`
	// Refused if it would fill at once.
	PostOnly *bool `json:"post_only,omitempty"`
	// It may only reduce your position.
	ReduceOnly *bool `json:"reduce_only,omitempty"`
}

CreateStrategyOrder: see the API reference.

type CreateStrategyOrderType

type CreateStrategyOrderType string

CreateStrategyOrderType: conditional: the order it sends (default market). Open: a value from a newer API version is kept as is.

const (
	CreateStrategyOrderTypeMarket CreateStrategyOrderType = "market"
	CreateStrategyOrderTypeLimit  CreateStrategyOrderType = "limit"
)

type CreateStrategyOrderType2 added in v1.2.0

type CreateStrategyOrderType2 string

CreateStrategyOrderType2: Two orders that rest. Open: a value from a newer API version is kept as is.

const (
	CreateStrategyOrderType2Limit      CreateStrategyOrderType2 = "limit"
	CreateStrategyOrderType2StopMarket CreateStrategyOrderType2 = "stop_market"
	CreateStrategyOrderType2StopLimit  CreateStrategyOrderType2 = "stop_limit"
)

type CreateStrategyTriggerDirection added in v1.2.0

type CreateStrategyTriggerDirection string

CreateStrategyTriggerDirection: conditional, with another trigger_market: send the order once it trades at or above trigger_price, or at or below it. On this market it is set by the side and not given. Open: a value from a newer API version is kept as is.

const (
	CreateStrategyTriggerDirectionAbove CreateStrategyTriggerDirection = "above"
	CreateStrategyTriggerDirectionBelow CreateStrategyTriggerDirection = "below"
)

type CreateStrategyType

type CreateStrategyType string

CreateStrategyType: trailing_stop: a stop-loss that follows the price. break_even: the stop-losses move to the entry once the price has gone your way far enough. oco: two orders, the first fill cancels the other. twap, vwap: an order in market slices over time (vwap sized by yesterday's volume over the same hours). scaled: a ladder of limits. chase: a limit that follows the bid or ask. conditional: an order sent once a price is reached, on this market (a buy when the price falls to trigger_price, a sell when it rises) or on another one (trigger_market). Open: a value from a newer API version is kept as is.

const (
	CreateStrategyTypeTrailingStop CreateStrategyType = "trailing_stop"
	CreateStrategyTypeBreakEven    CreateStrategyType = "break_even"
	CreateStrategyTypeOCO          CreateStrategyType = "oco"
	CreateStrategyTypeTWAP         CreateStrategyType = "twap"
	CreateStrategyTypeVWAP         CreateStrategyType = "vwap"
	CreateStrategyTypeScaled       CreateStrategyType = "scaled"
	CreateStrategyTypeChase        CreateStrategyType = "chase"
	CreateStrategyTypeConditional  CreateStrategyType = "conditional"
)

type DailyResult

type DailyResult struct {
	// The trading day (midnight to midnight New York).
	Date string `json:"date"`
	// Trades closed that day.
	Trades int64 `json:"trades"`
	// Their P&L before fees.
	GrossPnL Decimal `json:"gross_pnl"`
	// Their fees.
	Fees Decimal `json:"fees"`
	// Their P&L after fees.
	PnL Decimal `json:"pnl"`
	// Paid out that day.
	Withdrawn Decimal `json:"withdrawn"`
	// The balance at the day's end.
	BalanceEnd *Decimal `json:"balance_end"`
}

DailyResult: see the API reference.

type Decimal

type Decimal string

Decimal is a price, a size or an amount exactly as the API writes it: a decimal string ("62000.5"), never a float. It reads a JSON number too, and goes out as a string.

func Dec

func Dec(s string) *Decimal

Dec is a pointer to a Decimal, for optional fields: Dec("62000").

func DecimalOf

func DecimalOf(f float64) Decimal

DecimalOf writes a float in plain decimal form (the shortest that reads back the same, never an exponent).

func RoundTo

func RoundTo(x, step Decimal, mode RoundMode) (Decimal, error)

RoundTo is x as a multiple of step, as the decimal string the API takes.

func (Decimal) Rat

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

Rat is the exact value (false when the string is not a decimal).

func (Decimal) String

func (d Decimal) String() string

String is the decimal as written.

func (*Decimal) UnmarshalJSON

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

UnmarshalJSON takes a string or a number.

type DeletedAlert added in v1.2.0

type DeletedAlert struct {
	// The alert.
	ID string `json:"id"`
	// It was deleted.
	Deleted bool `json:"deleted"`
}

DeletedAlert: see the API reference.

type DeletedEndpoint

type DeletedEndpoint struct {
	// The endpoint.
	ID string `json:"id"`
	// It was deleted.
	Deleted bool `json:"deleted"`
}

DeletedEndpoint: see the API reference.

type DeletedHook

type DeletedHook struct {
	// The link.
	ID string `json:"id"`
	// It was revoked: its address answers 404 from now on.
	Deleted bool `json:"deleted"`
}

DeletedHook: see the API reference.

type EquityHistory

type EquityHistory struct {
	// One point per closed trade, or per trading day.
	Resolution Resolution `json:"resolution"`
	// Oldest first; the first point is the opening balance.
	Points []EquityHistoryPoint `json:"points"`
	Live   EquityHistoryLive    `json:"live"`
}

EquityHistory: see the API reference.

func (EquityHistory) MarshalJSON

func (x EquityHistory) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type EquityHistoryLive

type EquityHistoryLive struct {
	// When the live figures were read.
	Time *int64 `json:"time"`
	// The balance now.
	Balance Decimal `json:"balance"`
	// The equity now.
	Equity Decimal `json:"equity"`
}

EquityHistoryLive: see the API reference.

type EquityHistoryPoint

type EquityHistoryPoint struct {
	// When.
	Time int64 `json:"time"`
	// The trading day (New York), with resolution day.
	Date *string `json:"date,omitempty"`
	// The balance then.
	Balance Decimal `json:"balance"`
}

EquityHistoryPoint: see the API reference.

type Error

type Error struct {
	Kind           Kind
	Status         int
	Code           string
	Message        string
	Type           string
	RequestID      string
	Details        json.RawMessage
	RetryAfter     time.Duration
	Retryable      bool
	DocURL         string
	OrderID        string
	IdempotencyKey string
	Header         http.Header
	Err            error
}

Error is every failure of a call: the API's code and message, the HTTP status, the request id, the details, the Retry-After, whether it may be tried again (the API's own retryable; without its envelope, by the status; true for a timeout or a network failure), its doc page, the order it is about, the call's Idempotency-Key and the answer's headers. errors.Is(err, ErrRateLimit) tells the family.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches a sentinel of the same family (ErrRateLimit...) or an Error with the same Kind and Code.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCodeInfo

type ErrorCodeInfo struct {
	Type      string
	Status    int
	Retryable bool
}

ErrorCodeInfo is what the spec says of an error code.

type ErrorEnvelope

type ErrorEnvelope struct {
	Error ErrorEnvelopeError `json:"error"`
}

ErrorEnvelope: Every error has this shape.

type ErrorEnvelopeError

type ErrorEnvelopeError struct {
	// The family of the error; it decides the HTTP status.
	Type ErrorEnvelopeErrorType `json:"type"`
	// The error code: match on this.
	Code string `json:"code"`
	// A sentence for people. It may change; never match on it.
	Message string `json:"message"`
	// The id of the request; give it to support.
	RequestID string `json:"request_id"`
	// Whether the same request may succeed later.
	Retryable bool `json:"retryable"`
	// Where this code is explained.
	DocURL string `json:"doc_url"`
	// More about the problem: the fields at fault, a limit, where to go.
	Details json.RawMessage `json:"details,omitempty"`
	// The order the error is about (an order the engine refused is kept, with this id).
	OrderID *string `json:"order_id,omitempty"`
}

ErrorEnvelopeError: see the API reference.

type ErrorEnvelopeErrorType

type ErrorEnvelopeErrorType string

ErrorEnvelopeErrorType: The family of the error; it decides the HTTP status. Open: a value from a newer API version is kept as is.

const (
	ErrorEnvelopeErrorTypeInvalidRequest ErrorEnvelopeErrorType = "invalid_request"
	ErrorEnvelopeErrorTypeAuthentication ErrorEnvelopeErrorType = "authentication"
	ErrorEnvelopeErrorTypePermission     ErrorEnvelopeErrorType = "permission"
	ErrorEnvelopeErrorTypeNotFound       ErrorEnvelopeErrorType = "not_found"
	ErrorEnvelopeErrorTypeMethod         ErrorEnvelopeErrorType = "method"
	ErrorEnvelopeErrorTypeConflict       ErrorEnvelopeErrorType = "conflict"
	ErrorEnvelopeErrorTypePayload        ErrorEnvelopeErrorType = "payload"
	ErrorEnvelopeErrorTypeRuleRejection  ErrorEnvelopeErrorType = "rule_rejection"
	ErrorEnvelopeErrorTypeKeyLimit       ErrorEnvelopeErrorType = "key_limit"
	ErrorEnvelopeErrorTypeRateLimit      ErrorEnvelopeErrorType = "rate_limit"
	ErrorEnvelopeErrorTypeServer         ErrorEnvelopeErrorType = "server"
	ErrorEnvelopeErrorTypeEngine         ErrorEnvelopeErrorType = "engine"
)

type Event

type Event struct {
	// The event; pass it as after (GET /v1/events) or resume (the stream) to continue from it.
	ID string `json:"id"`
	// What happened (GET /v1/webhook-event-types says what each type means).
	Type EventType `json:"type"`
	// The account number.
	AccountID string `json:"account_id"`
	// When it happened.
	Time int64 `json:"time"`
	// Where it came from: an order placed through this API or by an AI assistant (the MCP server), one placed on a
	// trading platform, the engine itself (positions), a strategy of this API, or a TradingView alert.
	Source EventSource `json:"source"`
	// order or fill (the objects REST answers), with changes or close_reason when they apply. A position.* event
	// carries position { market, side, size, average_price } as the engine reported it, and previous_size: read GET
	// .../positions/{market} for its margin, P&L and liquidation.
	Data map[string]any `json:"data"`
}

Event: see the API reference.

type EventSource

type EventSource string

EventSource: Where it came from: an order placed through this API or by an AI assistant (the MCP server), one placed on a trading platform, the engine itself (positions), a strategy of this API, or a TradingView alert. Open: a value from a newer API version is kept as is.

const (
	EventSourceAPI         EventSource = "api"
	EventSourceMcp         EventSource = "mcp"
	EventSourcePlatform    EventSource = "platform"
	EventSourceEngine      EventSource = "engine"
	EventSourceStrategy    EventSource = "strategy"
	EventSourceTradingview EventSource = "tradingview"
)

type EventType

type EventType string

EventType: What happened (GET /v1/webhook-event-types says what each type means). Open: a value from a newer API version is kept as is.

const (
	EventTypeOrderCreated             EventType = "order.created"
	EventTypeOrderEdited              EventType = "order.edited"
	EventTypeOrderFilled              EventType = "order.filled"
	EventTypeOrderCanceled            EventType = "order.canceled"
	EventTypeOrderRejected            EventType = "order.rejected"
	EventTypeOrderExpired             EventType = "order.expired"
	EventTypeFillCreated              EventType = "fill.created"
	EventTypePositionOpened           EventType = "position.opened"
	EventTypePositionChanged          EventType = "position.changed"
	EventTypePositionClosed           EventType = "position.closed"
	EventTypeStrategyCreated          EventType = "strategy.created"
	EventTypeStrategyLegPlaced        EventType = "strategy.leg_placed"
	EventTypeStrategyLegModified      EventType = "strategy.leg_modified"
	EventTypeStrategyLegFilled        EventType = "strategy.leg_filled"
	EventTypeStrategyLegCanceled      EventType = "strategy.leg_canceled"
	EventTypeStrategyLegRejected      EventType = "strategy.leg_rejected"
	EventTypeStrategyOrphanRepaired   EventType = "strategy.orphan_repaired"
	EventTypeStrategySlice            EventType = "strategy.slice"
	EventTypeStrategyTriggered        EventType = "strategy.triggered"
	EventTypeStrategyEnded            EventType = "strategy.ended"
	EventTypeTradingviewAlertExecuted EventType = "tradingview.alert_executed"
	EventTypeTradingviewAlertRefused  EventType = "tradingview.alert_refused"
	EventTypeAccountUpdated           EventType = "account.updated"
	EventTypeAccountPassed            EventType = "account.passed"
	EventTypeAccountFailed            EventType = "account.failed"
	EventTypeAccountPayoutEligible    EventType = "account.payout_eligible"
	EventTypeAccountDisabled          EventType = "account.disabled"
	EventTypeAccountRemoved           EventType = "account.removed"
	EventTypeKeyLossStop              EventType = "key.loss_stop"
	EventTypeKeyExpiring              EventType = "key.expiring"
	EventTypeSystemRestarted          EventType = "system.restarted"
	EventTypeRiskWarning              EventType = "risk.warning"
	EventTypeRiskCleared              EventType = "risk.cleared"
	EventTypeAlertTriggered           EventType = "alert.triggered"
)

type EventsListParams

type EventsListParams struct {
	// Only this account.
	AccountID *string `json:"account_id,omitempty"`
	// The id of the last event you have: the ones after it, oldest first. Absent: from the oldest kept.
	After *string `json:"after,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
}

EventsListParams: The query of list events.

type EventsService

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

EventsService: the events calls (client.Events).

func (*EventsService) Get

func (r *EventsService) Get(ctx context.Context, eventID string, opts ...CallOption) (*Event, error)

Get: Get an event.

func (*EventsService) List

func (r *EventsService) List(ctx context.Context, params *EventsListParams, opts ...CallOption) (*Page[Event], error)

List: List events.

func (*EventsService) ListAutoPaging

func (r *EventsService) ListAutoPaging(ctx context.Context, params *EventsListParams, opts ...CallOption) iter.Seq2[Event, error]

ListAutoPaging: every item of List, page after page (WithMaxItems caps it).

type ExitLeg

type ExitLeg struct {
	// The working order.
	OrderID string `json:"order_id"`
	// The order's type.
	Type OrderType `json:"type"`
	// Its trigger or limit price.
	Price *Decimal `json:"price"`
	// Its size.
	Size *Decimal `json:"size"`
}

ExitLeg: see the API reference.

type Exits

type Exits struct {
	// The account number.
	AccountID string `json:"account_id"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The strategy that keeps these exits (type exits); null when there are none.
	StrategyID *string `json:"strategy_id"`
	// The open position; null when flat.
	Position *ExitsPosition `json:"position"`
	// The take-profit legs: together at most the position.
	TakeProfit []ExitsLeg `json:"take_profit"`
	// The stop-loss legs: together at most the position.
	StopLoss []ExitsLeg `json:"stop_loss"`
	// The legs grow with the position, keeping their share of it (rounded down to the size step).
	ResizeWithPosition bool `json:"resize_with_position"`
}

Exits: see the API reference.

func (Exits) MarshalJSON

func (x Exits) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type ExitsBatch

type ExitsBatch struct {
	// The position you saw: { side, size }, or null.
	ExpectedPosition *ExitsBatchExpectedPosition `json:"expected_position"`
	// Every leg you saw (an empty list when there were none): if anything differs now, nothing is done and the
	// answer is 409 exits_changed with the state now.
	ExpectedExits []ExitsBatchExpectedExit `json:"expected_exits"`
	// Applied in this order: cancels, changes, then new legs (stop-losses first). An engine refusal stops the batch:
	// 422 exit_operation_failed says what each operation did.
	Operations []ExitsBatchOperation `json:"operations"`
	// The legs grow with the position (default true).
	ResizeWithPosition *bool `json:"resize_with_position,omitempty"`
}

ExitsBatch: The take-profit and stop-loss legs of a position, changed together.

func (ExitsBatch) MarshalJSON

func (x ExitsBatch) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type ExitsBatchExpectedExit

type ExitsBatchExpectedExit struct {
	// A leg.
	ID string `json:"id"`
	// Its size.
	Size Decimal `json:"size"`
	// Its price; null for a stop-loss that waits (as GET exits shows it).
	Price *Decimal `json:"price"`
}

ExitsBatchExpectedExit: see the API reference.

type ExitsBatchExpectedPosition

type ExitsBatchExpectedPosition struct {
	// Long or short.
	Side PositionSide `json:"side"`
	// Its size.
	Size Decimal `json:"size"`
}

ExitsBatchExpectedPosition: The position you saw: { side, size }, or null.

type ExitsBatchOperation

type ExitsBatchOperation struct {
	// What to do.
	Op ExitsBatchOperationOp `json:"op"`
	// modify, cancel: the leg.
	ID *string `json:"id,omitempty"`
	// place: the group of the new leg.
	Group *ExitsLegGroup `json:"group,omitempty"`
	// place: limit for a take-profit (the default); stop_market (the default) or stop_limit for a stop-loss.
	Type *CreateStrategyOrderType2 `json:"type,omitempty"`
	// The take-profit price, or the stop price.
	Price *Decimal `json:"price,omitempty"`
	// The limit of a stop_limit leg.
	LimitPrice *Decimal `json:"limit_price,omitempty"`
	// The size; absent on a place: what the group leaves of the position.
	Size *Decimal `json:"size,omitempty"`
	// A stop-loss that follows the price: { distance } (a price difference) or { percent }, with activation_price to
	// start only once the price reaches it. Without a price and an activation price it starts from the price now.
	// null removes it.
	Trail *ExitsBatchOperationTrail `json:"trail,omitempty"`
	// Move the stop-loss to the entry price (plus offset_ticks) once the price has gone your way by
	// trigger_distance, trigger_percent or to trigger_price. Without a price, the stop is placed only then. null
	// removes it.
	BreakEven *ExitsBatchOperationBreakEven `json:"break_even,omitempty"`
	// modify: the settings to remove from a stop-loss (the same as sending them null).
	Clear []ExitsBatchOperationClear `json:"clear,omitempty"`
	// TrailNull sends trail as null (the API: null removes it); a Trail set is sent instead.
	TrailNull bool `json:"-"`
	// BreakEvenNull sends break_even as null (the API: null removes it); a BreakEven set is sent instead.
	BreakEvenNull bool `json:"-"`
}

ExitsBatchOperation: see the API reference.

func (ExitsBatchOperation) MarshalJSON added in v1.3.1

func (x ExitsBatchOperation) MarshalJSON() ([]byte, error)

MarshalJSON sends a field marked <Field>Null as null.

type ExitsBatchOperationBreakEven

type ExitsBatchOperationBreakEven struct {
	// How far from the entry.
	TriggerDistance *Decimal `json:"trigger_distance,omitempty"`
	// How far from the entry, in percent.
	TriggerPercent *Decimal `json:"trigger_percent,omitempty"`
	// Or this price.
	TriggerPrice *Decimal `json:"trigger_price,omitempty"`
	// Ticks beyond the entry, on the profit side.
	OffsetTicks *int64 `json:"offset_ticks,omitempty"`
}

ExitsBatchOperationBreakEven: Move the stop-loss to the entry price (plus offset_ticks) once the price has gone your way by trigger_distance, trigger_percent or to trigger_price. Without a price, the stop is placed only then. null removes it.

type ExitsBatchOperationClear

type ExitsBatchOperationClear string

ExitsBatchOperationClear: one of the values below. Open: a value from a newer API version is kept as is.

const (
	ExitsBatchOperationClearTrail     ExitsBatchOperationClear = "trail"
	ExitsBatchOperationClearBreakEven ExitsBatchOperationClear = "break_even"
)

type ExitsBatchOperationOp

type ExitsBatchOperationOp string

ExitsBatchOperationOp: What to do. Open: a value from a newer API version is kept as is.

const (
	ExitsBatchOperationOpPlace  ExitsBatchOperationOp = "place"
	ExitsBatchOperationOpModify ExitsBatchOperationOp = "modify"
	ExitsBatchOperationOpCancel ExitsBatchOperationOp = "cancel"
)

type ExitsBatchOperationTrail

type ExitsBatchOperationTrail struct {
	// How far behind the best price.
	Distance *Decimal `json:"distance,omitempty"`
	// How far behind, in percent of the best price.
	Percent *Decimal `json:"percent,omitempty"`
	// Start once the price reaches this.
	ActivationPrice *Decimal `json:"activation_price,omitempty"`
}

ExitsBatchOperationTrail: A stop-loss that follows the price: { distance } (a price difference) or { percent }, with activation_price to start only once the price reaches it. Without a price and an activation price it starts from the price now. null removes it.

type ExitsLeg

type ExitsLeg struct {
	// The leg: an order of this API, also listed under the account's orders.
	ID string `json:"id"`
	// take_profit: a limit on the profit side. stop_loss: a stop on the loss side.
	Group ExitsLegGroup `json:"group"`
	// take_profit legs are limits; stop_loss legs are stop_market or stop_limit.
	Type CreateStrategyOrderType2 `json:"type"`
	// The order's status; waiting: a stop-loss not placed yet (it waits for its activation price or its break-even).
	Status ExitsLegStatus `json:"status"`
	// Its size.
	Size Decimal `json:"size"`
	// The take-profit price, or the stop price.
	Price *Decimal `json:"price"`
	// The limit of a stop_limit leg.
	LimitPrice *Decimal `json:"limit_price"`
	// A trailing stop-loss: how it follows the price.
	Trail *ExitsLegTrail `json:"trail"`
	// A stop-loss moved to the entry price once the price has gone your way far enough.
	BreakEven *ExitsLegBreakEven `json:"break_even"`
}

ExitsLeg: see the API reference.

type ExitsLegBreakEven

type ExitsLegBreakEven struct {
	// How far from the entry the price must go (or null: another trigger).
	TriggerDistance *Decimal `json:"trigger_distance"`
	// The same, in percent of the entry.
	TriggerPercent *Decimal `json:"trigger_percent"`
	// Or once the price reaches this.
	TriggerPrice *Decimal `json:"trigger_price"`
	// Ticks beyond the entry, on the profit side.
	OffsetTicks int64 `json:"offset_ticks"`
	// The stop-loss was moved to the entry already.
	Done bool `json:"done"`
}

ExitsLegBreakEven: A stop-loss moved to the entry price once the price has gone your way far enough.

type ExitsLegGroup

type ExitsLegGroup string

ExitsLegGroup: take_profit: a limit on the profit side. stop_loss: a stop on the loss side. Open: a value from a newer API version is kept as is.

const (
	ExitsLegGroupTakeProfit ExitsLegGroup = "take_profit"
	ExitsLegGroupStopLoss   ExitsLegGroup = "stop_loss"
)

type ExitsLegStatus

type ExitsLegStatus string

ExitsLegStatus: The order's status; waiting: a stop-loss not placed yet (it waits for its activation price or its break-even). Open: a value from a newer API version is kept as is.

const (
	ExitsLegStatusPending     ExitsLegStatus = "pending"
	ExitsLegStatusWorking     ExitsLegStatus = "working"
	ExitsLegStatusFilled      ExitsLegStatus = "filled"
	ExitsLegStatusCanceled    ExitsLegStatus = "canceled"
	ExitsLegStatusRejected    ExitsLegStatus = "rejected"
	ExitsLegStatusExpired     ExitsLegStatus = "expired"
	ExitsLegStatusUnconfirmed ExitsLegStatus = "unconfirmed"
	ExitsLegStatusWaiting     ExitsLegStatus = "waiting"
)

type ExitsLegTrail

type ExitsLegTrail struct {
	// How far behind the best price (or null: percent).
	Distance *Decimal `json:"distance"`
	// How far behind, in percent of the best price (or null: distance).
	Percent *Decimal `json:"percent"`
	// It starts once the price reaches this; null: from the start.
	ActivationPrice *Decimal `json:"activation_price"`
	// It follows the price now (its activation price was reached, or it had none).
	Active bool `json:"active"`
	// The best price since it started, which the stop follows.
	BestPrice *Decimal `json:"best_price"`
}

ExitsLegTrail: A trailing stop-loss: how it follows the price.

type ExitsPosition

type ExitsPosition struct {
	// Long or short.
	Side PositionSide `json:"side"`
	// Its size.
	Size Decimal `json:"size"`
}

ExitsPosition: The open position; null when flat.

type ExitsService

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

ExitsService: the exits calls (client.Exits).

func (*ExitsService) Get

func (r *ExitsService) Get(ctx context.Context, accountID string, market string, opts ...CallOption) (*Exits, error)

Get: Get a position's exits.

func (*ExitsService) Set

func (r *ExitsService) Set(ctx context.Context, accountID string, market string, body ExitsBatch, opts ...CallOption) (*Exits, error)

Set: Change a position's exits.

type Fill

type Fill struct {
	// The fill.
	ID string `json:"id"`
	// Its order.
	OrderID string `json:"order_id"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The side; null for an order placed elsewhere before the API saw it.
	Side *OrderSide `json:"side"`
	// The size filled.
	Size Decimal `json:"size"`
	// The fill price.
	Price Decimal `json:"price"`
	// Its fee.
	Fee *Decimal `json:"fee"`
	// A liquidation filled it.
	Liquidation bool `json:"liquidation"`
	// When it filled.
	Time int64 `json:"time"`
}

Fill: see the API reference.

type FillsListParams

type FillsListParams struct {
	// Only this market.
	Market *string `json:"market,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

FillsListParams: The query of list fills.

type FillsService

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

FillsService: the fills calls (client.Fills).

func (*FillsService) List

func (r *FillsService) List(ctx context.Context, accountID string, params *FillsListParams, opts ...CallOption) (*Page[Fill], error)

List: List fills.

func (*FillsService) ListAutoPaging

func (r *FillsService) ListAutoPaging(ctx context.Context, accountID string, params *FillsListParams, opts ...CallOption) iter.Seq2[Fill, error]

ListAutoPaging: every item of List, page after page (WithMaxItems caps it).

type FlattenResult

type FlattenResult struct {
	// The account number.
	AccountID string `json:"account_id"`
	// How many working orders were canceled.
	OrdersCanceled int64 `json:"orders_canceled"`
	// The orders that closed the positions.
	Closes []Order `json:"closes"`
}

FlattenResult: see the API reference.

func (FlattenResult) MarshalJSON

func (x FlattenResult) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type HistoryEquityParams

type HistoryEquityParams struct {
	// One point per closed trade, or per trading day.
	Resolution *Resolution `json:"resolution,omitempty"`
}

HistoryEquityParams: The query of get the equity curve.

type HistoryService

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

HistoryService: the history calls (client.History).

func (*HistoryService) Daily

func (r *HistoryService) Daily(ctx context.Context, accountID string, opts ...CallOption) (*Page[DailyResult], error)

Daily: List daily results.

func (*HistoryService) Equity

func (r *HistoryService) Equity(ctx context.Context, accountID string, params *HistoryEquityParams, opts ...CallOption) (*EquityHistory, error)

Equity: Get the equity curve.

type Kind

type Kind string

Kind is an error's family (docs/BEHAVIOUR.md "Answers"), the same classes as every other Phoenix Perpetuals SDK.

const (
	KindAuthentication Kind = "AuthenticationError" // 401: the key is missing, wrong, revoked, expired or of the other environment
	KindPermission     Kind = "PermissionError"     // 403: the key may not do this
	KindNotFound       Kind = "NotFoundError"       // 404
	KindConflict       Kind = "ConflictError"       // 409
	KindValidation     Kind = "ValidationError"     // other 4xx: the request is not right
	KindRuleRejected   Kind = "RuleRejectedError"   // 422: the account's rules or the key's controls said no
	KindRateLimit      Kind = "RateLimitError"      // 429
	KindServer         Kind = "ServerError"         // 5xx
	KindConnection     Kind = "ConnectionError"     // no answer: the network failed
	KindTimeout        Kind = "TimeoutError"        // no answer in time
	KindStreamClosed   Kind = "StreamClosedError"   // a stream ended for good
	// a webhook delivery that did not verify: missing_headers, stale, bad_signature or bad_body
	KindWebhookVerification Kind = "WebhookVerificationError"
)

type Limit

type Limit struct {
	// The limit, in USD.
	Limit *Decimal `json:"limit,omitempty"`
	// The equity at which it is breached.
	Floor *Decimal `json:"floor,omitempty"`
	// How much more the account may lose before it.
	Room *Decimal `json:"room,omitempty"`
	// How much of it is used, in percent.
	UsedPct *Decimal `json:"used_pct,omitempty"`
	// Daily loss only: when it resets (midnight New York).
	ResetsAt *int64 `json:"resets_at,omitempty"`
	// Daily loss only: what happens when it is reached.
	OnBreach *OnBreach `json:"on_breach,omitempty"`
	// Daily loss only: the day's start is estimated (the engine does not publish it).
	Estimated *bool `json:"estimated,omitempty"`
	// Max drawdown only: how the reference moves.
	Mode *RuleMaxDrawdownMode `json:"mode,omitempty"`
	// Max drawdown only: the engine may hold a higher floor than shown (it follows equity highs).
	AtLeast *bool `json:"at_least,omitempty"`
	// The rule no longer applies this limit (its cut-off was reached).
	Lifted bool `json:"lifted"`
}

Limit: A loss limit and the room left to it.

type LimitStanding

type LimitStanding struct {
	// The limit, in USD.
	Limit *Decimal `json:"limit,omitempty"`
	// The equity at which it is breached.
	Floor *Decimal `json:"floor,omitempty"`
	// How much more the account may lose before it.
	Room *Decimal `json:"room,omitempty"`
	// How much of it is used, in percent.
	UsedPct *Decimal `json:"used_pct,omitempty"`
	// Daily loss only: when it resets (midnight New York).
	ResetsAt *int64 `json:"resets_at,omitempty"`
	// Daily loss only: what happens when it is reached.
	OnBreach *OnBreach `json:"on_breach,omitempty"`
	// Daily loss only: the day's start is estimated (the engine does not publish it).
	Estimated *bool `json:"estimated,omitempty"`
	// Max drawdown only: how the reference moves.
	Mode *RuleMaxDrawdownMode `json:"mode,omitempty"`
	// Max drawdown only: the engine may hold a higher floor than shown (it follows equity highs).
	AtLeast *bool `json:"at_least,omitempty"`
	// The rule no longer applies this limit (its cut-off was reached).
	Lifted bool `json:"lifted"`
	// Where it stands.
	Status LimitStandingStatus `json:"status"`
}

LimitStanding: see the API reference.

type LimitStandingStatus

type LimitStandingStatus string

LimitStandingStatus: Where it stands. Open: a value from a newer API version is kept as is.

const (
	LimitStandingStatusOk       LimitStandingStatus = "ok"
	LimitStandingStatusWarning  LimitStandingStatus = "warning"
	LimitStandingStatusCritical LimitStandingStatus = "critical"
	LimitStandingStatusBreached LimitStandingStatus = "breached"
)

type Limits

type Limits struct {
	// The environment of the host you called.
	Environment PlatformEnvironment `json:"environment"`
	// The request budgets. A request takes from every budget it belongs to.
	Rate       LimitsRate       `json:"rate"`
	Keys       LimitsKeys       `json:"keys"`
	Orders     LimitsOrders     `json:"orders"`
	Sandbox    *LimitsSandbox   `json:"sandbox,omitempty"`
	Strategies LimitsStrategies `json:"strategies"`
	Alerts     LimitsAlerts     `json:"alerts"`
	// The largest request body.
	BodyMaxBytes int64           `json:"body_max_bytes"`
	PageLimit    LimitsPageLimit `json:"page_limit"`
}

Limits: see the API reference.

type LimitsAlerts added in v1.2.0

type LimitsAlerts struct {
	// Price alerts armed at once on one account.
	ArmedPerAccount int64 `json:"armed_per_account"`
	// Price alerts armed at once across your accounts.
	ArmedPerCustomer int64 `json:"armed_per_customer"`
	// How long an alert that fired (or was disabled) stays listed, in days.
	KeptDays int64 `json:"kept_days"`
}

LimitsAlerts: see the API reference.

type LimitsKeys

type LimitsKeys struct {
	// Keys you may hold in each environment.
	PerEnvironment int64 `json:"per_environment"`
	// Addresses in a key's allowlist.
	IPAllowlistMax int64 `json:"ip_allowlist_max"`
	// The longest a key may live, in days.
	ExpiryMaxDays int64 `json:"expiry_max_days"`
}

LimitsKeys: see the API reference.

type LimitsOrders

type LimitsOrders struct {
	// Working orders an account may hold.
	MaxWorkingPerAccount int64 `json:"max_working_per_account"`
	// Working orders across your accounts.
	MaxWorkingPerCustomer int64 `json:"max_working_per_customer"`
	// New orders a minute on one account.
	NewPerMinAccount int64 `json:"new_per_min_account"`
	// New orders a day on one account.
	NewPerDayAccount int64 `json:"new_per_day_account"`
	// How far from the market price a priced order may be, in percent.
	PriceBandPct Decimal `json:"price_band_pct"`
	// The oldest price an order is checked against, in seconds.
	QuoteMaxAgeS int64 `json:"quote_max_age_s"`
	// The oldest unchanged price of a quiet market an order is checked against, while the price feed lives (other
	// markets move), in seconds.
	QuoteMaxAgeSlowS int64 `json:"quote_max_age_slow_s"`
	// The nearest a gtd order may expire, in seconds from now.
	GtdMinSeconds int64 `json:"gtd_min_seconds"`
	// The farthest, in days from now.
	GtdMaxDays int64 `json:"gtd_max_days"`
	// The least time between two orders that can open a position on one account, in ms: the engine takes one about
	// this often, so the next waits its turn (reduce-only orders and cancels never wait). A call that would wait
	// past its reply time is refused 429 rate_limited, scope order_spacing.
	OpenSpacingMs int64 `json:"open_spacing_ms"`
}

LimitsOrders: see the API reference.

type LimitsPageLimit

type LimitsPageLimit struct {
	// Items a page holds by default.
	Default int64 `json:"default"`
	// The most a page may hold.
	Max int64 `json:"max"`
}

LimitsPageLimit: see the API reference.

type LimitsRate

type LimitsRate struct {
	PublicPerIP     LimitsRatePublicPerIp     `json:"public_per_ip"`
	PerIP           LimitsRatePerIp           `json:"per_ip"`
	PerKeyRead      LimitsRatePerKeyRead      `json:"per_key_read"`
	PerKeyTrade     LimitsRatePerKeyTrade     `json:"per_key_trade"`
	PerAccountTrade LimitsRatePerAccountTrade `json:"per_account_trade"`
	PerCustomer     LimitsRatePerCustomer     `json:"per_customer"`
	Bulk            LimitsRateBulk            `json:"bulk"`
	WhatIf          LimitsRateWhatIf          `json:"what_if"`
}

LimitsRate: The request budgets. A request takes from every budget it belongs to.

type LimitsRateBulk

type LimitsRateBulk struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRateBulk: see the API reference.

type LimitsRatePerAccountTrade

type LimitsRatePerAccountTrade struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRatePerAccountTrade: see the API reference.

type LimitsRatePerCustomer

type LimitsRatePerCustomer struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRatePerCustomer: see the API reference.

type LimitsRatePerIp

type LimitsRatePerIp struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRatePerIp: see the API reference.

type LimitsRatePerKeyRead

type LimitsRatePerKeyRead struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRatePerKeyRead: see the API reference.

type LimitsRatePerKeyTrade

type LimitsRatePerKeyTrade struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRatePerKeyTrade: see the API reference.

type LimitsRatePublicPerIp

type LimitsRatePublicPerIp struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRatePublicPerIp: see the API reference.

type LimitsRateWhatIf

type LimitsRateWhatIf struct {
	// Requests a minute.
	PerMin int64 `json:"per_min"`
	// Requests at once.
	Burst int64 `json:"burst"`
}

LimitsRateWhatIf: see the API reference.

type LimitsSandbox

type LimitsSandbox struct {
	// Sandbox accounts you may open, ever.
	AccountsForLife int64 `json:"accounts_for_life"`
	// The balance a sandbox account starts with.
	StartBalance Decimal `json:"start_balance"`
	// Hours without use before a sandbox account is parked.
	ParkedAfterHours int64 `json:"parked_after_hours"`
}

LimitsSandbox: see the API reference.

type LimitsStrategies

type LimitsStrategies struct {
	// Running strategies an account may hold.
	PerAccount int64 `json:"per_account"`
	// Of those, programs (oco, twap, vwap, scaled, chase, conditional).
	ProgramsPerAccount int64 `json:"programs_per_account"`
	// Working orders of strategies on one account.
	LegsPerAccount int64 `json:"legs_per_account"`
	// Running strategies across your accounts.
	PerCustomer int64 `json:"per_customer"`
	// Take-profit legs on one position.
	TakeProfitsPerPosition int64 `json:"take_profits_per_position"`
	// Stop-loss legs on one position.
	StopLossesPerPosition int64 `json:"stop_losses_per_position"`
	// The shortest twap or vwap, in minutes.
	TWAPMinMinutes int64 `json:"twap_min_minutes"`
	// The longest twap or vwap, in minutes.
	TWAPMaxMinutes int64 `json:"twap_max_minutes"`
	// The shortest time between slices, in seconds.
	SliceMinSeconds int64 `json:"slice_min_seconds"`
	// The most limits in a scaled ladder.
	ScaledMaxRungs int64 `json:"scaled_max_rungs"`
	// Whether chase strategies may start.
	ChaseEnabled bool `json:"chase_enabled"`
	// The longest a chase may run, in minutes.
	ChaseMaxMinutes int64 `json:"chase_max_minutes"`
}

LimitsStrategies: see the API reference.

type MarginMode

type MarginMode string

MarginMode: Isolated: each position holds its own margin. Cross: positions share the balance. Open: a value from a newer API version is kept as is.

const (
	MarginModeIsolated MarginMode = "isolated"
	MarginModeCross    MarginMode = "cross"
)

type MarginService

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

MarginService: the margin calls (client.Margin).

func (*MarginService) List

func (r *MarginService) List(ctx context.Context, accountID string, opts ...CallOption) (*Page[MarginSetting], error)

List: List margin settings.

func (*MarginService) Set

func (r *MarginService) Set(ctx context.Context, accountID string, market string, body MarginSettingInput, opts ...CallOption) (*MarginSettingResult, error)

Set: Set leverage and margin mode.

type MarginSetting

type MarginSetting struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The leverage new positions on this market get.
	Leverage int64 `json:"leverage"`
	// Isolated: each position holds its own margin. Cross: positions share the balance.
	MarginMode MarginMode `json:"margin_mode"`
	// The highest this account may use on the market (its trading rule's). null: the market is not available on this
	// account.
	MaxLeverage *int64 `json:"max_leverage"`
	// Where it comes from: the open position, your saved setting, or the market default.
	Source MarginSettingSource `json:"source"`
	// A position or a working order on the market: the mode cannot change now.
	Locked bool `json:"locked"`
}

MarginSetting: see the API reference.

type MarginSettingInput

type MarginSettingInput struct {
	// isolated: the position has its own margin. cross: positions share the account's balance.
	MarginMode MarginMode `json:"margin_mode"`
	// A whole number from 1 to the market's max_leverage.
	Leverage int64 `json:"leverage"`
}

MarginSettingInput: The market's setting. The mode cannot change while a position or a working order is open on the market.

type MarginSettingResult

type MarginSettingResult struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The margin mode.
	MarginMode MarginMode `json:"margin_mode"`
	// The leverage.
	Leverage int64 `json:"leverage"`
}

MarginSettingResult: see the API reference.

type MarginSettingSource

type MarginSettingSource string

MarginSettingSource: Where it comes from: the open position, your saved setting, or the market default. Open: a value from a newer API version is kept as is.

const (
	MarginSettingSourcePosition MarginSettingSource = "position"
	MarginSettingSourceSaved    MarginSettingSource = "saved"
	MarginSettingSourceDefault  MarginSettingSource = "default"
)

type Market

type Market struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The market's name; for a currency, the pair its price is quoted in (JPY-USD: USD/JPY, yen per dollar).
	Name string `json:"name"`
	// Whether the market trades now.
	Status MarketStatus `json:"status"`
	// The venue it trades on: its prices and fills are that venue's. Null for a currency on FX hours.
	Venue *string `json:"venue"`
	// When it trades: around the clock, its underlying market's sessions (Standard Market Hours, closed on
	// weekends), or FX hours.
	TradingHours TradingHours `json:"trading_hours"`
	// For an option (the same asset on another venue, or on Standard Market Hours): its market. Null for a market.
	OptionOf *string `json:"option_of"`
	// The ways this asset can be traded, the market first, then its options: an account holds one of them at a time
	// (market_option_held). Null when there is only the market.
	Options []MarketOption `json:"options"`
	// Prices are multiples of this.
	TickSize Decimal `json:"tick_size"`
	// Sizes are multiples of this, in the base asset.
	SizeStep Decimal `json:"size_step"`
	// The smallest order size (the size step). An order must also be worth at least min_notional.
	MinSize Decimal `json:"min_size"`
	// The smallest order value in USD: an order worth less is refused order_too_small.
	MinNotional *Decimal `json:"min_notional"`
	// The highest leverage on this market.
	MaxLeverage int64 `json:"max_leverage"`
	// The fee on each fill, in percent of its value.
	FeeRatePct Decimal `json:"fee_rate_pct"`
	// The most you may hold on this market across your accounts on the same rule, in USD.
	ExposureCap *Decimal `json:"exposure_cap"`
	// How far from the price a market order may fill, in percent.
	MaxSlippagePct *MarketMaxSlippagePct `json:"max_slippage_pct"`
}

Market: see the API reference.

type MarketFrame

type MarketFrame struct {
	Type     string          `json:"type"`
	Symbol   string          `json:"symbol"`
	Interval string          `json:"interval,omitempty"`
	Data     json.RawMessage `json:"data"`
	Raw      json.RawMessage `json:"-"`
}

MarketFrame is one frame of the market stream: its type (the channel: ticker, book, trades, candles, stats, status; or snapshot_end), its symbol, its interval (candles), its data, and the frame as it came.

type MarketMaxSlippagePct

type MarketMaxSlippagePct struct {
	// The slippage bound a market order gets when it names none.
	Default *Decimal `json:"default"`
	// The tightest bound an order may ask.
	Min *Decimal `json:"min"`
	// The widest bound an order may ask.
	Max *Decimal `json:"max"`
}

MarketMaxSlippagePct: How far from the price a market order may fill, in percent.

type MarketOption added in v1.1.0

type MarketOption struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// Its venue.
	Venue *string `json:"venue"`
	// When it trades.
	TradingHours TradingHours `json:"trading_hours"`
}

MarketOption: see the API reference.

type MarketRules

type MarketRules struct {
	Market   string
	TickSize Decimal
	SizeStep Decimal
	MinSize  Decimal
	Slippage *MarketMaxSlippagePct
}

MarketRules rounds prices and sizes the way a market takes them.

func NewMarketRules

func NewMarketRules(m *Market) *MarketRules

NewMarketRules reads the rules of a market (client.Markets.Get).

func (*MarketRules) RoundPrice

func (r *MarketRules) RoundPrice(price Decimal, mode RoundMode) (Decimal, error)

RoundPrice is price as a multiple of the tick size.

func (*MarketRules) RoundSize

func (r *MarketRules) RoundSize(size Decimal) (Decimal, error)

RoundSize is size down to the size step.

func (*MarketRules) SizeForNotional

func (r *MarketRules) SizeForNotional(usd, price Decimal) (Decimal, error)

SizeForNotional is the size worth usd at price, down to the step.

func (*MarketRules) SizeForRisk

func (r *MarketRules) SizeForRisk(riskUSD, stopDistance Decimal) (Decimal, error)

SizeForRisk is the size that loses riskUSD over stopDistance, down to the step.

func (*MarketRules) WorstPrice

func (r *MarketRules) WorstPrice(side string, price Decimal, slippagePct *Decimal) (Decimal, error)

WorstPrice is the worst price a market order of side ("buy" or "sell", in any case; anything else is an error) accepts at price, slippagePct away (nil: the market's default; outside its min..max, an error), rounded outward to the tick.

type MarketStats

type MarketStats struct {
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The last trade.
	Last *Decimal `json:"last"`
	// The change over 24 hours.
	Change24h *Decimal `json:"change_24h"`
	// That change in percent.
	Change24hPct *Decimal `json:"change_24h_pct"`
	// The highest in 24 hours.
	High24h *Decimal `json:"high_24h"`
	// The lowest in 24 hours.
	Low24h *Decimal `json:"low_24h"`
	// The size traded in 24 hours, in the base asset.
	Volume24h *Decimal `json:"volume_24h"`
	// The value traded in 24 hours, in USD.
	NotionalVolume24h *Decimal `json:"notional_volume_24h"`
	// The market's open interest: the size held open in positions, in the base asset.
	OpenInterest *Decimal `json:"open_interest"`
	// That open interest in USD, at the last price.
	NotionalOpenInterest *Decimal `json:"notional_open_interest"`
}

MarketStats: A market's 24-hour figures and open interest. A figure not known yet is null.

type MarketStatus

type MarketStatus string

MarketStatus: Whether the market trades now. Open: a value from a newer API version is kept as is.

const (
	MarketStatusOpen   MarketStatus = "open"
	MarketStatusHalted MarketStatus = "halted"
	MarketStatusClosed MarketStatus = "closed"
)

type MarketStream

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

MarketStream is the market data stream.

func (*MarketStream) Close

func (m *MarketStream) Close() error

Close ends the stream.

func (*MarketStream) Frames

func (m *MarketStream) Frames() iter.Seq2[MarketFrame, error]

Frames goes over the market data frames until the stream ends (an error that ended it is yielded once): ticker, book, trades, candles, stats and status; snapshot_end, which marks where a subscription's first frames end, only through Next (Q63).

func (*MarketStream) Limits

func (m *MarketStream) Limits() json.RawMessage

Limits are the per-connection limits the hello announced: {"subscriptions", "symbols_per_subscribe", "messages_per_s"} (nil before it).

func (*MarketStream) List

func (m *MarketStream) List(ctx context.Context) (json.RawMessage, error)

List is the server's list of this connection's subscriptions ({"type": "list", "subscriptions": [...]}).

func (*MarketStream) Next

func (m *MarketStream) Next(ctx context.Context) (MarketFrame, error)

Next is the next frame. After Close it answers a StreamClosedError.

func (*MarketStream) Ping

func (m *MarketStream) Ping(ctx context.Context) (json.RawMessage, error)

Ping answers the server's pong ({"type": "pong", "time": ...}).

func (*MarketStream) Subscribe

func (m *MarketStream) Subscribe(ctx context.Context, channel string, symbols []string, params map[string]any) (json.RawMessage, error)

Subscribe follows symbols on a channel (ticker, book, trades, candles, stats, status) with its params; it answers the server's reply (the symbols taken and the ones it refused).

func (*MarketStream) Unsubscribe

func (m *MarketStream) Unsubscribe(ctx context.Context, channel string, symbols []string, params map[string]any) (json.RawMessage, error)

Unsubscribe stops following symbols on a channel (none: every one), whatever params they were subscribed with (candles: those of params' interval; without one, every interval).

type MarketsService

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

MarketsService: the markets calls (client.Markets).

func (*MarketsService) Get

func (r *MarketsService) Get(ctx context.Context, market string, opts ...CallOption) (*Market, error)

Get: Get a market.

func (*MarketsService) List

func (r *MarketsService) List(ctx context.Context, opts ...CallOption) (*Page[Market], error)

List: List markets.

func (*MarketsService) Stats

func (r *MarketsService) Stats(ctx context.Context, opts ...CallOption) (*Page[MarketStats], error)

Stats: List market stats.

type Me

type Me struct {
	Credential MeCredential `json:"credential"`
	// The accounts it reaches.
	Accounts []string `json:"accounts"`
	// all: every account of the environment, new ones too. selected: only those listed.
	AccountScope MeAccountScope `json:"account_scope"`
	// The limits you set on the key.
	Controls MeControls `json:"controls"`
	Budgets  MeBudgets  `json:"budgets"`
	// Through the MCP server (an AI assistant): how its trades are confirmed and its budget. Null for any other
	// call.
	Assistant *MeAssistant `json:"assistant"`
}

Me: see the API reference.

func (Me) MarshalJSON

func (x Me) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type MeAccountScope

type MeAccountScope string

MeAccountScope: all: every account of the environment, new ones too. selected: only those listed. Open: a value from a newer API version is kept as is.

const (
	MeAccountScopeAll      MeAccountScope = "all"
	MeAccountScopeSelected MeAccountScope = "selected"
)

type MeAssistant

type MeAssistant struct {
	// Each trade is shown first and placed only when repeated with its confirmation (preview, then confirm).
	ConfirmTrades bool `json:"confirm_trades"`
	// How long a preview's confirmation holds, in seconds.
	ConfirmSeconds int64 `json:"confirm_seconds"`
	// The AI assistant's own budget, on top of the others.
	Budget MeAssistantBudget `json:"budget"`
}

MeAssistant: Through the MCP server (an AI assistant): how its trades are confirmed and its budget. Null for any other call.

type MeAssistantBudget

type MeAssistantBudget struct {
	// Reads a minute.
	ReadsPerMin int64 `json:"reads_per_min"`
	// Trading calls a minute.
	WritesPerMin int64 `json:"writes_per_min"`
	// Trading calls an hour.
	WritesPerHour int64 `json:"writes_per_hour"`
}

MeAssistantBudget: The AI assistant's own budget, on top of the others.

type MeBudgets

type MeBudgets struct {
	// Reads a minute for this key.
	ReadPerMin int64 `json:"read_per_min"`
	// Trading calls a minute for this key.
	TradePerMin int64 `json:"trade_per_min"`
}

MeBudgets: see the API reference.

type MeControls

type MeControls struct {
	// The markets the key may trade; empty: every market.
	Markets []string `json:"markets"`
	// The key may only reduce positions.
	ReduceOnly bool `json:"reduce_only"`
	// The largest order the key may place, in USD.
	MaxOrderUSD *Decimal `json:"max_order_usd"`
	// The largest position the key may hold, in USD.
	MaxPositionUSD *Decimal `json:"max_position_usd"`
	// The loss in a trading day at which the key stops trading the account.
	DailyLossUSD *Decimal `json:"daily_loss_usd"`
}

MeControls: The limits you set on the key.

func (MeControls) MarshalJSON

func (x MeControls) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type MeCredential

type MeCredential struct {
	// What you called with: an API key, or an app you signed in to.
	Kind MeCredentialKind `json:"kind"`
	// The key's id (the part after ppk_test_ or ppk_live_), or the app access's id.
	ID string `json:"id"`
	// Its name (an app: the app's name).
	Name string `json:"name"`
	// Its environment.
	Environment PlatformEnvironment `json:"environment"`
	// read: look only. trade: also place and cancel.
	Access MeCredentialAccess `json:"access"`
	// When it expires; null: never.
	ExpiresAt *int64 `json:"expires_at"`
	// When it was made.
	CreatedAt *int64 `json:"created_at"`
}

MeCredential: see the API reference.

type MeCredentialAccess

type MeCredentialAccess string

MeCredentialAccess: read: look only. trade: also place and cancel. Open: a value from a newer API version is kept as is.

const (
	MeCredentialAccessRead  MeCredentialAccess = "read"
	MeCredentialAccessTrade MeCredentialAccess = "trade"
)

type MeCredentialKind

type MeCredentialKind string

MeCredentialKind: What you called with: an API key, or an app you signed in to. Open: a value from a newer API version is kept as is.

const (
	MeCredentialKindKey MeCredentialKind = "key"
	MeCredentialKindApp MeCredentialKind = "app"
)

type MeService

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

MeService: the me calls (client.Me).

func (*MeService) Get

func (r *MeService) Get(ctx context.Context, opts ...CallOption) (*Me, error)

Get: Get your key.

type ModifyOrder

type ModifyOrder struct {
	// The new size.
	Size *Decimal `json:"size,omitempty"`
	// The new limit price.
	LimitPrice *Decimal `json:"limit_price,omitempty"`
	// The new trigger price.
	StopPrice *Decimal `json:"stop_price,omitempty"`
}

ModifyOrder: What to change: at least one field. The order keeps its place in the engine (changed in place, never canceled and placed again).

type OnBreach

type OnBreach string

OnBreach: What happens when it is reached. Open: a value from a newer API version is kept as is.

const (
	OnBreachFailAccount     OnBreach = "fail_account"
	OnBreachFlatten         OnBreach = "flatten"
	OnBreachFlattenAndPause OnBreach = "flatten_and_pause"
)

type Order

type Order struct {
	// The order.
	ID string `json:"id"`
	// Your own id for it, when it was placed through the API.
	ClientOrderID *string `json:"client_order_id"`
	// The account number.
	AccountID string `json:"account_id"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The order's side; null for an order placed elsewhere before the API saw it.
	Side *OrderSide `json:"side"`
	// The order's type.
	Type *OrderType `json:"type"`
	// unconfirmed: the engine has not confirmed its last state yet.
	Status OrderStatus `json:"status"`
	// The size, in the base asset.
	Size *Decimal `json:"size"`
	// How much filled.
	FilledSize *Decimal `json:"filled_size"`
	// Its limit price.
	LimitPrice *Decimal `json:"limit_price"`
	// Its trigger price.
	StopPrice *Decimal `json:"stop_price"`
	// The average fill price.
	AverageFillPrice *Decimal `json:"average_fill_price"`
	// The fee its fill paid.
	Fee *Decimal `json:"fee"`
	// It may only reduce a position; null when not known (placed elsewhere).
	ReduceOnly *bool `json:"reduce_only"`
	// How long it rests.
	TimeInForce TimeInForce `json:"time_in_force"`
	// A gtd order: when it expires (it ends expired then); null otherwise.
	ExpiresAt *int64 `json:"expires_at"`
	// It may only rest, never fill at once; null when not known (placed elsewhere).
	PostOnly *bool `json:"post_only"`
	// Where it was placed: this API, an AI assistant (the MCP server), a trading platform, a strategy, a TradingView
	// alert, or the system (a liquidation).
	Source OrderSource `json:"source"`
	// The strategy that placed it (source strategy).
	StrategyID *string `json:"strategy_id"`
	// Exits attached to it (orders placed through the API).
	Exits map[string]any `json:"exits"`
	// Why it was canceled.
	CancelReason *OrderCancelReason `json:"cancel_reason"`
	Reject       *OrderReject       `json:"reject"`
	// When it was placed.
	CreatedAt *int64 `json:"created_at"`
	// When it filled.
	FilledAt *int64 `json:"filled_at"`
	// When it was canceled.
	CanceledAt *int64 `json:"canceled_at"`
	// Its latest change.
	UpdatedAt *int64 `json:"updated_at,omitempty"`
}

Order: see the API reference.

type OrderCancelReason

type OrderCancelReason string

OrderCancelReason: Why it was canceled. Open: a value from a newer API version is kept as is.

const (
	OrderCancelReasonUser             OrderCancelReason = "user"
	OrderCancelReasonCancelAll        OrderCancelReason = "cancel_all"
	OrderCancelReasonFlatten          OrderCancelReason = "flatten"
	OrderCancelReasonCloseAll         OrderCancelReason = "close_all"
	OrderCancelReasonPositionClosed   OrderCancelReason = "position_closed"
	OrderCancelReasonPositionReversed OrderCancelReason = "position_reversed"
	OrderCancelReasonCloseAssist      OrderCancelReason = "close_assist"
	OrderCancelReasonOCO              OrderCancelReason = "oco"
	OrderCancelReasonReplaced         OrderCancelReason = "replaced"
	OrderCancelReasonStrategy         OrderCancelReason = "strategy"
	OrderCancelReasonKeyLossStop      OrderCancelReason = "key_loss_stop"
	OrderCancelReasonRiskRule         OrderCancelReason = "risk_rule"
	OrderCancelReasonSystemRestart    OrderCancelReason = "system_restart"
	OrderCancelReasonExternal         OrderCancelReason = "external"
)

type OrderExits

type OrderExits struct {
	// Limit orders on the profit side, each at price, or at distance or percent from the fill.
	TakeProfit []OrderExitsTakeProfit `json:"take_profit,omitempty"`
	// A stop on the loss side, at price, or at distance or percent from the fill; it may trail and move to
	// break-even (as in a position's exits).
	StopLoss *OrderExitsStopLoss `json:"stop_loss,omitempty"`
	// StopLossNull sends stop_loss as null (the API: null removes it); a StopLoss set is sent instead.
	StopLossNull bool `json:"-"`
}

OrderExits: Exits placed when the order fills: the stop-loss for the filled size first, then the take-profits. From then on they are the position's exits. An empty object removes them.

func (OrderExits) MarshalJSON added in v1.3.0

func (x OrderExits) MarshalJSON() ([]byte, error)

MarshalJSON sends a field marked <Field>Null as null.

type OrderExitsStopLoss

type OrderExitsStopLoss struct {
	// An exact price.
	Price *Decimal `json:"price,omitempty"`
	// A price difference from the fill price.
	Distance *Decimal `json:"distance,omitempty"`
	// A percent of the fill price.
	Percent *Decimal `json:"percent,omitempty"`
	// The stop's type (default stop_market).
	Type *OrderExitsStopLossType `json:"type,omitempty"`
	// stop_limit: how many ticks past the stop its limit sits.
	LimitOffsetTicks *int64 `json:"limit_offset_ticks,omitempty"`
	// As a position's exits take it: { distance } or { percent }, with activation_price to start only once the price
	// reaches it.
	Trail *OrderExitsStopLossTrail `json:"trail,omitempty"`
	// As a position's exits take it: one of trigger_distance, trigger_percent, trigger_price, and offset_ticks.
	BreakEven *OrderExitsStopLossBreakEven `json:"break_even,omitempty"`
}

OrderExitsStopLoss: A stop on the loss side, at price, or at distance or percent from the fill; it may trail and move to break-even (as in a position's exits).

type OrderExitsStopLossBreakEven

type OrderExitsStopLossBreakEven struct {
	// How far from the entry.
	TriggerDistance *Decimal `json:"trigger_distance,omitempty"`
	// How far from the entry, in percent.
	TriggerPercent *Decimal `json:"trigger_percent,omitempty"`
	// Or this price.
	TriggerPrice *Decimal `json:"trigger_price,omitempty"`
	// Ticks beyond the entry, on the profit side.
	OffsetTicks *int64 `json:"offset_ticks,omitempty"`
}

OrderExitsStopLossBreakEven: As a position's exits take it: one of trigger_distance, trigger_percent, trigger_price, and offset_ticks.

type OrderExitsStopLossTrail

type OrderExitsStopLossTrail struct {
	// How far behind the best price.
	Distance *Decimal `json:"distance,omitempty"`
	// How far behind, in percent of the best price.
	Percent *Decimal `json:"percent,omitempty"`
	// Start once the price reaches this.
	ActivationPrice *Decimal `json:"activation_price,omitempty"`
}

OrderExitsStopLossTrail: As a position's exits take it: { distance } or { percent }, with activation_price to start only once the price reaches it.

type OrderExitsStopLossType

type OrderExitsStopLossType string

OrderExitsStopLossType: The stop's type (default stop_market). Open: a value from a newer API version is kept as is.

const (
	OrderExitsStopLossTypeStopMarket OrderExitsStopLossType = "stop_market"
	OrderExitsStopLossTypeStopLimit  OrderExitsStopLossType = "stop_limit"
)

type OrderExitsTakeProfit

type OrderExitsTakeProfit struct {
	// An exact price.
	Price *Decimal `json:"price,omitempty"`
	// A price difference from the fill price.
	Distance *Decimal `json:"distance,omitempty"`
	// A percent of the fill price.
	Percent *Decimal `json:"percent,omitempty"`
	// Its share of the filled size, in percent (absent: the take-profits split it evenly).
	SizePct *Decimal `json:"size_pct,omitempty"`
}

OrderExitsTakeProfit: see the API reference.

type OrderReject

type OrderReject struct {
	// The error code.
	Code string `json:"code"`
	// What happened.
	Message *string `json:"message"`
}

OrderReject: see the API reference.

type OrderSide

type OrderSide string

OrderSide: The order's side; null for an order placed elsewhere before the API saw it. Open: a value from a newer API version is kept as is.

const (
	OrderSideBuy  OrderSide = "buy"
	OrderSideSell OrderSide = "sell"
)

type OrderSource

type OrderSource string

OrderSource: Where it was placed: this API, an AI assistant (the MCP server), a trading platform, a strategy, a TradingView alert, or the system (a liquidation). Open: a value from a newer API version is kept as is.

const (
	OrderSourceAPI         OrderSource = "api"
	OrderSourceMcp         OrderSource = "mcp"
	OrderSourcePlatform    OrderSource = "platform"
	OrderSourceStrategy    OrderSource = "strategy"
	OrderSourceTradingview OrderSource = "tradingview"
	OrderSourceSystem      OrderSource = "system"
)

type OrderStatus

type OrderStatus string

OrderStatus: unconfirmed: the engine has not confirmed its last state yet. Open: a value from a newer API version is kept as is.

const (
	OrderStatusPending     OrderStatus = "pending"
	OrderStatusWorking     OrderStatus = "working"
	OrderStatusFilled      OrderStatus = "filled"
	OrderStatusCanceled    OrderStatus = "canceled"
	OrderStatusRejected    OrderStatus = "rejected"
	OrderStatusExpired     OrderStatus = "expired"
	OrderStatusUnconfirmed OrderStatus = "unconfirmed"
)

type OrderType

type OrderType string

OrderType: The order's type. Open: a value from a newer API version is kept as is.

const (
	OrderTypeMarket     OrderType = "market"
	OrderTypeLimit      OrderType = "limit"
	OrderTypeStopMarket OrderType = "stop_market"
	OrderTypeStopLimit  OrderType = "stop_limit"
	OrderTypeTakeMarket OrderType = "take_market"
	OrderTypeTakeLimit  OrderType = "take_limit"
)

type OrdersListParams

type OrdersListParams struct {
	// working: the complete set of working orders. history: past orders. all: both.
	Status *OrdersListParamsStatus `json:"status,omitempty"`
	// Only this market.
	Market *string `json:"market,omitempty"`
	// The order you placed through the API with this id.
	ClientOrderID *string `json:"client_order_id,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

OrdersListParams: The query of list orders.

type OrdersListParamsStatus

type OrdersListParamsStatus string

OrdersListParamsStatus: one of the values below. Open: a value from a newer API version is kept as is.

const (
	OrdersListParamsStatusAll     OrdersListParamsStatus = "all"
	OrdersListParamsStatusWorking OrdersListParamsStatus = "working"
	OrdersListParamsStatusHistory OrdersListParamsStatus = "history"
)

type OrdersService

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

OrdersService: the orders calls (client.Orders).

func (*OrdersService) Cancel

func (r *OrdersService) Cancel(ctx context.Context, accountID string, orderID string, opts ...CallOption) (*Order, error)

Cancel: Cancel an order.

func (*OrdersService) CancelAll

func (r *OrdersService) CancelAll(ctx context.Context, accountID string, body CancelAll, opts ...CallOption) (*CancelAllResult, error)

CancelAll: Cancel all orders.

func (*OrdersService) Create

func (r *OrdersService) Create(ctx context.Context, accountID string, body CreateOrder, opts ...CallOption) (*Order, error)

Create: Place an order.

func (*OrdersService) Get

func (r *OrdersService) Get(ctx context.Context, accountID string, orderID string, opts ...CallOption) (*Order, error)

Get: Get an order.

func (*OrdersService) List

func (r *OrdersService) List(ctx context.Context, accountID string, params *OrdersListParams, opts ...CallOption) (*Page[Order], error)

List: List orders.

func (*OrdersService) ListAutoPaging

func (r *OrdersService) ListAutoPaging(ctx context.Context, accountID string, params *OrdersListParams, opts ...CallOption) iter.Seq2[Order, error]

ListAutoPaging: every item of List, page after page (WithMaxItems caps it).

func (*OrdersService) Modify

func (r *OrdersService) Modify(ctx context.Context, accountID string, orderID string, body ModifyOrder, opts ...CallOption) (*Order, error)

Modify: Change an order.

func (*OrdersService) Preview

func (r *OrdersService) Preview(ctx context.Context, accountID string, body CreateOrder, opts ...CallOption) (*WhatIf, error)

Preview: Preview an order.

func (*OrdersService) SetExits

func (r *OrdersService) SetExits(ctx context.Context, accountID string, orderID string, body OrderExits, opts ...CallOption) (*Order, error)

SetExits: Attach exits to an order.

type Page

type Page[T any] struct {
	Data       []T     `json:"data"`
	HasMore    bool    `json:"has_more"`
	NextCursor *string `json:"next_cursor"`
	AsOf       *int64  `json:"as_of"`
	// HistoryComplete is false when the history reaches further back than the list covers (the orders list; nil on
	// the others).
	HistoryComplete *bool `json:"history_complete"`
	// Stale is true when some figures of an account list are older than usual (the trading servers were busy: at most
	// a minute, then the call is 503 state_unavailable); nil on the lists that never say.
	Stale *bool `json:"stale"`
	// Raw is the answer the page came in.
	Raw *RawResponse `json:"-"`
	// contains filtered or unexported fields
}

Page is one page of a list: its items, whether more follow, and the cursor to them.

func (*Page[T]) GetNextPage

func (p *Page[T]) GetNextPage(ctx context.Context) (*Page[T], error)

GetNextPage is the next page, or nil after the last.

type Platform

type Platform struct {
	// The environment of the host you called.
	Environment PlatformEnvironment `json:"environment"`
	// The version of this API.
	Version string `json:"version"`
	// The time on the server.
	ServerTime int64 `json:"server_time"`
	// The documentation.
	DocsURL string `json:"docs_url"`
	// This API as OpenAPI 3.1.
	SpecURL string         `json:"spec_url"`
	Status  PlatformStatus `json:"status"`
}

Platform: see the API reference.

type PlatformEnvironment

type PlatformEnvironment string

PlatformEnvironment: The environment of the host you called. Open: a value from a newer API version is kept as is.

const (
	PlatformEnvironmentLive    PlatformEnvironment = "live"
	PlatformEnvironmentSandbox PlatformEnvironment = "sandbox"
)

type PlatformService

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

PlatformService: the platform calls (client.Platform).

func (*PlatformService) Info

func (r *PlatformService) Info(ctx context.Context, opts ...CallOption) (*Platform, error)

Info: Get the API.

func (*PlatformService) Limits

func (r *PlatformService) Limits(ctx context.Context, opts ...CallOption) (*Limits, error)

Limits: Get the limits.

func (*PlatformService) RestrictedCountries added in v1.2.0

func (r *PlatformService) RestrictedCountries(ctx context.Context, opts ...CallOption) (*Page[RestrictedCountry], error)

RestrictedCountries: List restricted countries.

func (*PlatformService) Spec

func (r *PlatformService) Spec(ctx context.Context, opts ...CallOption) (map[string]any, error)

Spec: Get the OpenAPI document.

func (*PlatformService) Status

func (r *PlatformService) Status(ctx context.Context, opts ...CallOption) (*Status, error)

Status: Get the status.

type PlatformStatus

type PlatformStatus struct {
	// Whether the trading engine is reachable.
	Engine PlatformStatusEngine `json:"engine"`
	// When the trading engine last started.
	EngineStartedAt *int64 `json:"engine_started_at"`
	// Whether the market-data stream is live, with every price feed.
	MarketData PlatformStatusMarketData `json:"market_data"`
	// Whether outbound webhooks are being delivered.
	Webhooks PlatformStatusWebhooks `json:"webhooks"`
}

PlatformStatus: see the API reference.

type PlatformStatusEngine

type PlatformStatusEngine string

PlatformStatusEngine: Whether the trading engine is reachable. Open: a value from a newer API version is kept as is.

const (
	PlatformStatusEngineUp   PlatformStatusEngine = "up"
	PlatformStatusEngineDown PlatformStatusEngine = "down"
)

type PlatformStatusMarketData

type PlatformStatusMarketData string

PlatformStatusMarketData: Whether the market-data stream is live, with every price feed. Open: a value from a newer API version is kept as is.

const (
	PlatformStatusMarketDataUp   PlatformStatusMarketData = "up"
	PlatformStatusMarketDataDown PlatformStatusMarketData = "down"
)

type PlatformStatusWebhooks

type PlatformStatusWebhooks string

PlatformStatusWebhooks: Whether outbound webhooks are being delivered. Open: a value from a newer API version is kept as is.

const (
	PlatformStatusWebhooksUp   PlatformStatusWebhooks = "up"
	PlatformStatusWebhooksDown PlatformStatusWebhooks = "down"
)

type Position

type Position struct {
	// This position, while it stays open on the same side.
	ID string `json:"id"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// Long or short.
	Side PositionSide `json:"side"`
	// The size, in the base asset.
	Size Decimal `json:"size"`
	// The average entry price.
	EntryPrice *Decimal `json:"entry_price"`
	// The market price it is valued at.
	MarkPrice *Decimal `json:"mark_price"`
	// Its value at that price.
	Notional *Decimal `json:"notional"`
	// Its open P&L.
	UnrealizedPnL *Decimal `json:"unrealized_pnl"`
	// Its leverage.
	Leverage int64 `json:"leverage"`
	// Its margin mode.
	MarginMode MarginMode `json:"margin_mode"`
	// The margin it took at entry.
	InitialMargin *Decimal `json:"initial_margin"`
	// Margin you added to it.
	AddedMargin *Decimal `json:"added_margin"`
	// What it holds of the balance.
	Margin       *Decimal             `json:"margin"`
	Liquidation  *PositionLiquidation `json:"liquidation"`
	BreachPrices PositionBreachPrices `json:"breach_prices"`
	Exits        PositionExits        `json:"exits"`
	// At least one stop loss rests on it.
	Protected bool `json:"protected"`
	// When it opened.
	OpenedAt *int64 `json:"opened_at"`
}

Position: see the API reference.

type PositionBreachPrices

type PositionBreachPrices struct {
	// The price at which this position alone would breach the daily loss limit.
	DailyLoss *Decimal `json:"daily_loss"`
	// The price at which it alone would breach the max drawdown.
	MaxDrawdown *Decimal `json:"max_drawdown"`
}

PositionBreachPrices: see the API reference.

type PositionExits

type PositionExits struct {
	// Limit orders on the closing side.
	TakeProfit []ExitLeg `json:"take_profit"`
	// Stop orders on the closing side.
	StopLoss []ExitLeg `json:"stop_loss"`
}

PositionExits: see the API reference.

func (PositionExits) MarshalJSON

func (x PositionExits) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type PositionLiquidation

type PositionLiquidation struct {
	// The price at which it is liquidated; null when there is none or it depends on several positions.
	Price *Decimal `json:"price"`
	// How far the market price is from it, in percent.
	DistancePct *Decimal `json:"distance_pct"`
	// Cross margin on several markets: no single price, every one of them moves it.
	AccountWide bool `json:"account_wide"`
}

PositionLiquidation: see the API reference.

type PositionSide

type PositionSide string

PositionSide: Long or short. Open: a value from a newer API version is kept as is.

const (
	PositionSideLong  PositionSide = "long"
	PositionSideShort PositionSide = "short"
)

type PositionsListClosedParams

type PositionsListClosedParams struct {
	// Only this market.
	Market *string `json:"market,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

PositionsListClosedParams: The query of list closed positions.

type PositionsListParams

type PositionsListParams struct {
	// Only this market.
	Market *string `json:"market,omitempty"`
}

PositionsListParams: The query of list open positions.

type PositionsService

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

PositionsService: the positions calls (client.Positions).

func (*PositionsService) Close

func (r *PositionsService) Close(ctx context.Context, accountID string, market string, body ClosePosition, opts ...CallOption) (*Order, error)

Close: Close a position.

func (*PositionsService) Flatten

func (r *PositionsService) Flatten(ctx context.Context, accountID string, opts ...CallOption) (*FlattenResult, error)

Flatten: Flatten the account.

func (*PositionsService) Get

func (r *PositionsService) Get(ctx context.Context, accountID string, market string, opts ...CallOption) (*Position, error)

Get: Get an open position.

func (*PositionsService) List

func (r *PositionsService) List(ctx context.Context, accountID string, params *PositionsListParams, opts ...CallOption) (*Page[Position], error)

List: List open positions.

func (*PositionsService) ListClosed

func (r *PositionsService) ListClosed(ctx context.Context, accountID string, params *PositionsListClosedParams, opts ...CallOption) (*Page[ClosedPosition], error)

ListClosed: List closed positions.

func (*PositionsService) ListClosedAutoPaging

func (r *PositionsService) ListClosedAutoPaging(ctx context.Context, accountID string, params *PositionsListClosedParams, opts ...CallOption) iter.Seq2[ClosedPosition, error]

ListClosedAutoPaging: every item of ListClosed, page after page (WithMaxItems caps it).

type PriceAlert added in v1.2.0

type PriceAlert struct {
	// The alert.
	ID string `json:"id"`
	// The account number.
	AccountID string `json:"account_id"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// Its level.
	Price Decimal `json:"price"`
	// above: it fires once the price reaches the level from below; below: from above. Set from the price when the
	// level was set.
	Condition PriceAlertCondition `json:"condition"`
	// Your note, sent with it.
	Note *string `json:"note"`
	// armed: it waits for its level. triggered: it fired (rearm arms it again). disabled: its account or market went
	// away before it fired.
	Status PriceAlertStatus `json:"status"`
	// The price it watches: the market's last trade (the middle of the book until there is one), the price trailing
	// stops follow.
	PriceSource PriceAlertPriceSource `json:"price_source"`
	// The price it fired at.
	TriggerPrice *Decimal `json:"trigger_price"`
	// When it fired.
	TriggeredAt *int64 `json:"triggered_at"`
	// Why it was disabled.
	DisabledReason *PriceAlertDisabledReason `json:"disabled_reason"`
	// When it was set.
	CreatedAt int64 `json:"created_at"`
	// Its latest change.
	UpdatedAt int64 `json:"updated_at"`
}

PriceAlert: A level on a market, told once when the price reaches it (alert.triggered: the account stream, webhooks, GET /v1/events). It never places or changes an order.

type PriceAlertCondition added in v1.2.0

type PriceAlertCondition string

PriceAlertCondition: above: it fires once the price reaches the level from below; below: from above. Set from the price when the level was set. Open: a value from a newer API version is kept as is.

const (
	PriceAlertConditionAbove PriceAlertCondition = "above"
	PriceAlertConditionBelow PriceAlertCondition = "below"
)

type PriceAlertDisabledReason added in v1.2.0

type PriceAlertDisabledReason string

PriceAlertDisabledReason: Why it was disabled. Open: a value from a newer API version is kept as is.

const (
	PriceAlertDisabledReasonAccountRemoved PriceAlertDisabledReason = "account_removed"
	PriceAlertDisabledReasonMarketRemoved  PriceAlertDisabledReason = "market_removed"
)

type PriceAlertPriceSource added in v1.2.0

type PriceAlertPriceSource string

PriceAlertPriceSource: The price it watches: the market's last trade (the middle of the book until there is one), the price trailing stops follow. Open: a value from a newer API version is kept as is.

const (
	PriceAlertPriceSourceLast PriceAlertPriceSource = "last"
)

type PriceAlertStatus added in v1.2.0

type PriceAlertStatus string

PriceAlertStatus: armed: it waits for its level. triggered: it fired (rearm arms it again). disabled: its account or market went away before it fired. Open: a value from a newer API version is kept as is.

const (
	PriceAlertStatusArmed     PriceAlertStatus = "armed"
	PriceAlertStatusTriggered PriceAlertStatus = "triggered"
	PriceAlertStatusDisabled  PriceAlertStatus = "disabled"
)

type Progress

type Progress struct {
	// Where the account is in the programme.
	Stage      AccountStage       `json:"stage"`
	Objectives ProgressObjectives `json:"objectives"`
	Limits     ProgressLimits     `json:"limits"`
	Payout     *ProgressPayout    `json:"payout"`
	// When the oldest figure here was read.
	AsOf int64 `json:"as_of"`
}

Progress: see the API reference.

type ProgressLimits

type ProgressLimits struct {
	DailyLoss   *LimitStanding `json:"daily_loss"`
	MaxDrawdown *LimitStanding `json:"max_drawdown"`
}

ProgressLimits: see the API reference.

type ProgressObjectives

type ProgressObjectives struct {
	ProfitTarget    *ProgressObjectivesProfitTarget    `json:"profit_target"`
	MinTradingDays  *ProgressObjectivesMinTradingDays  `json:"min_trading_days"`
	MinCalendarDays *ProgressObjectivesMinCalendarDays `json:"min_calendar_days"`
}

ProgressObjectives: see the API reference.

type ProgressObjectivesMinCalendarDays

type ProgressObjectivesMinCalendarDays struct {
	// Calendar days the rule needs.
	Required int64 `json:"required"`
	// Calendar days so far.
	Count int64 `json:"count"`
	// Whether it is reached.
	Status ProgressObjectivesProfitTargetStatus `json:"status"`
}

ProgressObjectivesMinCalendarDays: see the API reference.

type ProgressObjectivesMinTradingDays

type ProgressObjectivesMinTradingDays struct {
	// Days the rule needs.
	Required int64 `json:"required"`
	// Days with a trade so far.
	Count *int64 `json:"count"`
	// Whether it is reached.
	Status ProgressObjectivesProfitTargetStatus `json:"status"`
}

ProgressObjectivesMinTradingDays: see the API reference.

type ProgressObjectivesProfitTarget

type ProgressObjectivesProfitTarget struct {
	// The balance that reaches it.
	GoalBalance Decimal `json:"goal_balance"`
	// Still to make.
	Remaining Decimal `json:"remaining"`
	// How far, in percent.
	ProgressPct *Decimal `json:"progress_pct"`
	// Positions must be closed when it is reached.
	RequiresFlat bool `json:"requires_flat"`
	// Whether it is reached.
	Status ProgressObjectivesProfitTargetStatus `json:"status"`
}

ProgressObjectivesProfitTarget: see the API reference.

type ProgressObjectivesProfitTargetStatus

type ProgressObjectivesProfitTargetStatus string

ProgressObjectivesProfitTargetStatus: Whether it is reached. Open: a value from a newer API version is kept as is.

const (
	ProgressObjectivesProfitTargetStatusOpen ProgressObjectivesProfitTargetStatus = "open"
	ProgressObjectivesProfitTargetStatusMet  ProgressObjectivesProfitTargetStatus = "met"
)

type ProgressPayout

type ProgressPayout struct {
	// A payout may be requested now.
	Eligible bool `json:"eligible"`
	// What may be paid out.
	Available Decimal `json:"available"`
	// The smallest payout.
	MinPayout *Decimal `json:"min_payout"`
	// Paid out so far.
	PaidOut Decimal `json:"paid_out"`
}

ProgressPayout: see the API reference.

type RateLimit

type RateLimit struct {
	Limit     int
	Remaining int
	ResetAt   time.Time // when the window is full again
	Scope     string    // the bucket that answered (X-RateLimit-Scope: key, bulk, account_orders...), "" when none
	// contains filtered or unexported fields
}

RateLimit is what the last answer said of the rate-limit window.

type RawResponse

type RawResponse struct {
	StatusCode     int
	Header         http.Header
	Body           []byte
	RequestID      string
	IdempotencyKey string
}

RawResponse is the answer of a call as it came.

type Resolution

type Resolution string

Resolution: One point per closed trade, or per trading day. Open: a value from a newer API version is kept as is.

const (
	ResolutionTrade Resolution = "trade"
	ResolutionDay   Resolution = "day"
)

type RestrictedCountry added in v1.2.0

type RestrictedCountry struct {
	// The country, ISO 3166-1 alpha-2.
	Code string `json:"code"`
	// Its name in English.
	Name string `json:"name"`
}

RestrictedCountry: see the API reference.

type RoundMode

type RoundMode int

RoundMode is how a value meets a step.

const (
	RoundNearest RoundMode = iota // the nearest multiple; a tie goes away from zero
	RoundDown                     // the multiple at or below
	RoundUp                       // the multiple at or above
)

type Rule

type Rule struct {
	// The balance the account started with.
	StartBalance Decimal           `json:"start_balance"`
	DailyLoss    *RuleDailyLoss    `json:"daily_loss"`
	MaxDrawdown  *RuleMaxDrawdown  `json:"max_drawdown"`
	WeeklyLoss   *RuleWeeklyLoss   `json:"weekly_loss"`
	ProfitTarget *RuleProfitTarget `json:"profit_target"`
	// Days with a trade the account needs.
	MinTradingDays *int64 `json:"min_trading_days"`
	// Calendar days the account needs.
	MinCalendarDays *int64           `json:"min_calendar_days"`
	Consistency     *RuleConsistency `json:"consistency"`
	// Positions may stay open overnight.
	OvernightHolding bool `json:"overnight_holding"`
	// Positions may stay open over the weekend.
	WeekendHolding bool `json:"weekend_holding"`
	// Days without a trade after which the account fails.
	InactivityDays *int64 `json:"inactivity_days"`
}

Rule: The account's rule, as the trading engine enforces it.

type RuleConsistency

type RuleConsistency struct {
	// The most one day may bring, in USD.
	Amount *Decimal `json:"amount"`
	// The most one day may bring, in percent of the total.
	Pct *Decimal `json:"pct"`
}

RuleConsistency: see the API reference.

type RuleDailyLoss

type RuleDailyLoss struct {
	// The most the account may lose in a trading day, in USD.
	Amount *Decimal `json:"amount"`
	// The same limit in percent of its basis.
	Pct *Decimal `json:"pct"`
	// What the day's loss is measured from.
	Basis RuleDailyLossBasis `json:"basis"`
	// What happens when it is reached.
	OnBreach OnBreach `json:"on_breach"`
}

RuleDailyLoss: see the API reference.

type RuleDailyLossBasis

type RuleDailyLossBasis string

RuleDailyLossBasis: What the day's loss is measured from. Open: a value from a newer API version is kept as is.

const (
	RuleDailyLossBasisPeakBalance     RuleDailyLossBasis = "peak_balance"
	RuleDailyLossBasisStartBalance    RuleDailyLossBasis = "start_balance"
	RuleDailyLossBasisPeakEquity      RuleDailyLossBasis = "peak_equity"
	RuleDailyLossBasisDayStartBalance RuleDailyLossBasis = "day_start_balance"
	RuleDailyLossBasisDayStartEquity  RuleDailyLossBasis = "day_start_equity"
)

type RuleMaxDrawdown

type RuleMaxDrawdown struct {
	// The most the account may fall from its reference, in USD.
	Amount *Decimal `json:"amount"`
	// The same limit in percent.
	Pct *Decimal `json:"pct"`
	// How the reference moves: end_of_day and end_of_trade follow the highest balance, static stays at the start,
	// intraday_equity follows the highest equity.
	Mode RuleMaxDrawdownMode `json:"mode"`
}

RuleMaxDrawdown: see the API reference.

type RuleMaxDrawdownMode

type RuleMaxDrawdownMode string

RuleMaxDrawdownMode: How the reference moves: end_of_day and end_of_trade follow the highest balance, static stays at the start, intraday_equity follows the highest equity. Open: a value from a newer API version is kept as is.

const (
	RuleMaxDrawdownModeEndOfDay       RuleMaxDrawdownMode = "end_of_day"
	RuleMaxDrawdownModeEndOfTrade     RuleMaxDrawdownMode = "end_of_trade"
	RuleMaxDrawdownModeStatic         RuleMaxDrawdownMode = "static"
	RuleMaxDrawdownModeIntradayEquity RuleMaxDrawdownMode = "intraday_equity"
)

type RuleProfitTarget

type RuleProfitTarget struct {
	// The profit to reach, in USD.
	Amount *Decimal `json:"amount"`
	// The same target in percent.
	Pct *Decimal `json:"pct"`
	// Positions must be closed when it is reached.
	RequiresFlat bool `json:"requires_flat"`
}

RuleProfitTarget: see the API reference.

type RuleWeeklyLoss

type RuleWeeklyLoss struct {
	// The most the account may lose in a week, in USD.
	Amount *Decimal `json:"amount"`
	// The same limit in percent.
	Pct *Decimal `json:"pct"`
}

RuleWeeklyLoss: see the API reference.

type Status

type Status struct {
	// The environment of the host you called.
	Environment PlatformEnvironment `json:"environment"`
	// Whether this environment takes requests.
	API         StatusApi         `json:"api"`
	Engine      StatusEngine      `json:"engine"`
	AccountData StatusAccountData `json:"account_data"`
	MarketData  StatusMarketData  `json:"market_data"`
	Features    StatusFeatures    `json:"features"`
	// The time on the server.
	ServerTime int64 `json:"server_time"`
}

Status: see the API reference.

type StatusAccountData

type StatusAccountData struct {
	// When your keys and accounts were last confirmed with the website.
	SyncedAt *int64 `json:"synced_at"`
	// Account figures over the last minute: degraded when more than 5% of them were older than usual (stale) or
	// could not be read (state_unavailable).
	State StatusAccountDataState `json:"state"`
}

StatusAccountData: see the API reference.

type StatusAccountDataState added in v1.3.0

type StatusAccountDataState string

StatusAccountDataState: Account figures over the last minute: degraded when more than 5% of them were older than usual (stale) or could not be read (state_unavailable). Open: a value from a newer API version is kept as is.

const (
	StatusAccountDataStateOperational StatusAccountDataState = "operational"
	StatusAccountDataStateDegraded    StatusAccountDataState = "degraded"
)

type StatusApi

type StatusApi string

StatusApi: Whether this environment takes requests. Open: a value from a newer API version is kept as is.

const (
	StatusApiOperational StatusApi = "operational"
	StatusApiDisabled    StatusApi = "disabled"
)

type StatusEngine

type StatusEngine struct {
	// Whether the API is connected to the trading engine.
	Connected bool `json:"connected"`
	// When the trading engine last started.
	StartedAt *int64 `json:"started_at"`
	// Closes, flattens, cancel-alls and margin changes over the last minute: degraded when the engine was too busy
	// to take one (engine_busy).
	Writes StatusEngineWrites `json:"writes"`
}

StatusEngine: see the API reference.

type StatusEngineWrites added in v1.3.0

type StatusEngineWrites string

StatusEngineWrites: Closes, flattens, cancel-alls and margin changes over the last minute: degraded when the engine was too busy to take one (engine_busy). Open: a value from a newer API version is kept as is.

const (
	StatusEngineWritesOperational StatusEngineWrites = "operational"
	StatusEngineWritesDegraded    StatusEngineWrites = "degraded"
)

type StatusFeatures

type StatusFeatures struct {
	// The account stream.
	Stream bool `json:"stream"`
	// Market data.
	MarketData bool `json:"market_data"`
	// Webhooks.
	Webhooks bool `json:"webhooks"`
	// TradingView alerts.
	Tradingview bool `json:"tradingview"`
	// AI assistants (MCP).
	Mcp bool `json:"mcp"`
}

StatusFeatures: see the API reference.

type StatusMarketData

type StatusMarketData struct {
	// Whether the market-data stream is live, with every price feed.
	Live bool `json:"live"`
	// When that was last checked.
	CheckedAt *int64 `json:"checked_at"`
}

StatusMarketData: see the API reference.

type StrategiesListParams

type StrategiesListParams struct {
	// active: waiting or working. ended: completed, canceled or ended. all: both.
	Status *StrategiesListParamsStatus `json:"status,omitempty"`
	// Only this market.
	Market *string `json:"market,omitempty"`
	// The strategy you created with this id.
	ClientStrategyID *string `json:"client_strategy_id,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

StrategiesListParams: The query of list strategies.

type StrategiesListParamsStatus

type StrategiesListParamsStatus string

StrategiesListParamsStatus: one of the values below. Open: a value from a newer API version is kept as is.

const (
	StrategiesListParamsStatusAll    StrategiesListParamsStatus = "all"
	StrategiesListParamsStatusActive StrategiesListParamsStatus = "active"
	StrategiesListParamsStatusEnded  StrategiesListParamsStatus = "ended"
)

type StrategiesService

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

StrategiesService: the strategies calls (client.Strategies).

func (*StrategiesService) Cancel

func (r *StrategiesService) Cancel(ctx context.Context, accountID string, strategyID string, opts ...CallOption) (*Strategy, error)

Cancel: Cancel a strategy.

func (*StrategiesService) Create

func (r *StrategiesService) Create(ctx context.Context, accountID string, body CreateStrategy, opts ...CallOption) (*Strategy, error)

Create: Create a strategy.

func (*StrategiesService) Get

func (r *StrategiesService) Get(ctx context.Context, accountID string, strategyID string, opts ...CallOption) (*Strategy, error)

Get: Get a strategy.

func (*StrategiesService) List

func (r *StrategiesService) List(ctx context.Context, accountID string, params *StrategiesListParams, opts ...CallOption) (*Page[Strategy], error)

List: List strategies.

func (*StrategiesService) ListAutoPaging

func (r *StrategiesService) ListAutoPaging(ctx context.Context, accountID string, params *StrategiesListParams, opts ...CallOption) iter.Seq2[Strategy, error]

ListAutoPaging: every item of List, page after page (WithMaxItems caps it).

type Strategy

type Strategy struct {
	// The strategy.
	ID string `json:"id"`
	// Your own id for it.
	ClientStrategyID *string `json:"client_strategy_id"`
	// The account number.
	AccountID string `json:"account_id"`
	// exits: a position's take-profit and stop-loss legs. bracket: an order with exits once it fills. oco: two
	// orders, the first fill cancels the other. twap, vwap: an order in slices over time. scaled: a ladder of
	// limits. chase: a limit that follows the price. conditional: an order sent once a price is reached.
	Type StrategyType `json:"type"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The side of its orders (exits: the closing side).
	Side *OrderSide `json:"side"`
	// waiting: armed, nothing placed yet. working: running. completed: done as asked. canceled: you ended it. ended:
	// it stopped for end_reason.
	Status StrategyStatus `json:"status"`
	// Why it stopped.
	EndReason *StrategyEndReason `json:"end_reason"`
	// What it was created with.
	Params map[string]any `json:"params"`
	// How far it is (by type).
	Progress map[string]any `json:"progress"`
	// Every order it placed, oldest first.
	Orders []Order `json:"orders"`
	// When it was created.
	CreatedAt int64 `json:"created_at"`
	// Its latest change.
	UpdatedAt int64 `json:"updated_at"`
	// When it stopped.
	EndedAt *int64 `json:"ended_at"`
}

Strategy: see the API reference.

func (Strategy) MarshalJSON

func (x Strategy) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type StrategyEndReason

type StrategyEndReason string

StrategyEndReason: Why it stopped. Open: a value from a newer API version is kept as is.

const (
	StrategyEndReasonTakeProfit       StrategyEndReason = "take_profit"
	StrategyEndReasonStopLoss         StrategyEndReason = "stop_loss"
	StrategyEndReasonFilled           StrategyEndReason = "filled"
	StrategyEndReasonPositionClosed   StrategyEndReason = "position_closed"
	StrategyEndReasonPositionReversed StrategyEndReason = "position_reversed"
	StrategyEndReasonCanceledByUser   StrategyEndReason = "canceled_by_user"
	StrategyEndReasonExternal         StrategyEndReason = "external"
	StrategyEndReasonKeyRevoked       StrategyEndReason = "key_revoked"
	StrategyEndReasonAccountClosed    StrategyEndReason = "account_closed"
	StrategyEndReasonEngineRestart    StrategyEndReason = "engine_restart"
	StrategyEndReasonChildRejected    StrategyEndReason = "child_rejected"
	StrategyEndReasonPriceBound       StrategyEndReason = "price_bound"
	StrategyEndReasonExpired          StrategyEndReason = "expired"
)

type StrategyStatus

type StrategyStatus string

StrategyStatus: waiting: armed, nothing placed yet. working: running. completed: done as asked. canceled: you ended it. ended: it stopped for end_reason. Open: a value from a newer API version is kept as is.

const (
	StrategyStatusWaiting   StrategyStatus = "waiting"
	StrategyStatusWorking   StrategyStatus = "working"
	StrategyStatusCompleted StrategyStatus = "completed"
	StrategyStatusCanceled  StrategyStatus = "canceled"
	StrategyStatusEnded     StrategyStatus = "ended"
)

type StrategyType

type StrategyType string

StrategyType: exits: a position's take-profit and stop-loss legs. bracket: an order with exits once it fills. oco: two orders, the first fill cancels the other. twap, vwap: an order in slices over time. scaled: a ladder of limits. chase: a limit that follows the price. conditional: an order sent once a price is reached. Open: a value from a newer API version is kept as is.

const (
	StrategyTypeExits       StrategyType = "exits"
	StrategyTypeBracket     StrategyType = "bracket"
	StrategyTypeOCO         StrategyType = "oco"
	StrategyTypeTWAP        StrategyType = "twap"
	StrategyTypeVWAP        StrategyType = "vwap"
	StrategyTypeScaled      StrategyType = "scaled"
	StrategyTypeChase       StrategyType = "chase"
	StrategyTypeConditional StrategyType = "conditional"
)

type StreamEvent

type StreamEvent struct {
	Event
	Seq      int64 `json:"seq"`
	Replayed bool  `json:"replayed,omitempty"`
}

StreamEvent is an event as the account stream told it: the event, the frame's seq (this connection's count, without a gap) and replayed (sent again after a resume).

type TimeInForce

type TimeInForce string

TimeInForce: How long it rests. Open: a value from a newer API version is kept as is.

const (
	TimeInForceGtc TimeInForce = "gtc"
	TimeInForceGtd TimeInForce = "gtd"
	TimeInForceIoc TimeInForce = "ioc"
	TimeInForceFok TimeInForce = "fok"
)

type TradingHours added in v1.1.0

type TradingHours string

TradingHours: When it trades: around the clock, its underlying market's sessions (Standard Market Hours, closed on weekends), or FX hours. Open: a value from a newer API version is kept as is.

const (
	TradingHoursN24_7    TradingHours = "24/7"
	TradingHoursStandard TradingHours = "standard"
	TradingHoursFx       TradingHours = "fx"
)

type TradingPolicy

type TradingPolicy struct {
	Rule        *Rule                    `json:"rule"`
	TradingDay  TradingPolicyTradingDay  `json:"trading_day"`
	SlippagePct TradingPolicySlippagePct `json:"slippage_pct"`
	Margin      TradingPolicyMargin      `json:"margin"`
	Orders      TradingPolicyOrders      `json:"orders"`
	// The limits you set on the key.
	Controls TradingPolicyControls `json:"controls"`
	Budgets  TradingPolicyBudgets  `json:"budgets"`
	// When the oldest figure here was read.
	AsOf int64 `json:"as_of"`
}

TradingPolicy: see the API reference.

type TradingPolicyBudgets

type TradingPolicyBudgets struct {
	// Reads a minute for this key.
	ReadPerMin int64 `json:"read_per_min"`
	// Trading calls a minute for this key.
	TradePerMin int64 `json:"trade_per_min"`
}

TradingPolicyBudgets: see the API reference.

type TradingPolicyControls

type TradingPolicyControls struct {
	// The markets the key may trade; empty: every market.
	Markets []string `json:"markets"`
	// The key may only reduce positions.
	ReduceOnly bool `json:"reduce_only"`
	// The largest order the key may place, in USD.
	MaxOrderUSD *Decimal `json:"max_order_usd"`
	// The largest position the key may hold, in USD.
	MaxPositionUSD *Decimal `json:"max_position_usd"`
	// The loss in a trading day at which the key stops trading the account.
	DailyLossUSD *Decimal `json:"daily_loss_usd"`
}

TradingPolicyControls: The limits you set on the key.

func (TradingPolicyControls) MarshalJSON

func (x TradingPolicyControls) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type TradingPolicyMargin

type TradingPolicyMargin struct {
	// The margin mode of a market you never set.
	DefaultMode TradingPolicyMarginDefaultMode `json:"default_mode"`
	// The share of a position's margin kept as maintenance, in percent.
	MaintenanceMarginPct *Decimal `json:"maintenance_margin_pct"`
}

TradingPolicyMargin: see the API reference.

type TradingPolicyMarginDefaultMode

type TradingPolicyMarginDefaultMode string

TradingPolicyMarginDefaultMode: The margin mode of a market you never set. Open: a value from a newer API version is kept as is.

const (
	TradingPolicyMarginDefaultModeIsolated TradingPolicyMarginDefaultMode = "isolated"
	TradingPolicyMarginDefaultModeCross    TradingPolicyMarginDefaultMode = "cross"
)

type TradingPolicyOrders

type TradingPolicyOrders struct {
	// Working orders the account may hold.
	MaxWorkingPerAccount int64 `json:"max_working_per_account"`
	// New orders a minute.
	NewPerMinAccount int64 `json:"new_per_min_account"`
	// How far from the market price a priced order may be, in percent.
	PriceBandPct Decimal `json:"price_band_pct"`
	// The oldest price an order is checked against, in seconds.
	QuoteMaxAgeS int64 `json:"quote_max_age_s"`
	// The oldest unchanged price of a quiet market an order is checked against, while the price feed lives (other
	// markets move), in seconds.
	QuoteMaxAgeSlowS int64 `json:"quote_max_age_slow_s"`
}

TradingPolicyOrders: see the API reference.

type TradingPolicySlippagePct

type TradingPolicySlippagePct struct {
	// The bound a market order gets when it names none, in percent.
	Default *Decimal `json:"default"`
	// The tightest it may ask.
	Min *Decimal `json:"min"`
	// The widest it may ask.
	Max *Decimal `json:"max"`
}

TradingPolicySlippagePct: see the API reference.

type TradingPolicyTradingDay

type TradingPolicyTradingDay struct {
	// The trading day runs midnight to midnight in this zone.
	Timezone string `json:"timezone"`
	// When this one ends.
	EndsAt int64 `json:"ends_at"`
}

TradingPolicyTradingDay: see the API reference.

type TradingViewAlert

type TradingViewAlert struct {
	// The alert.
	ID string `json:"id"`
	// Its link.
	HookID string `json:"hook_id"`
	// The account number.
	AccountID string `json:"account_id"`
	// What it did.
	Status TradingViewAlertStatus `json:"status"`
	// Why it placed nothing (or not all): a reason code.
	Reason *string `json:"reason"`
	// That reason in words.
	ReasonText *string `json:"reason_text"`
	// How the message was read: universal, pickmytrade, traderspost, pineconnector, text.
	Format *string `json:"format"`
	// The market it named.
	Market *string `json:"market"`
	// Its action.
	Action *string `json:"action"`
	// The message as kept (credentials masked).
	Message *string `json:"message"`
	// The sender's address, its end masked.
	Sender *string `json:"sender"`
	// What it was to do: { legs } or { skip } or { refuse }.
	Plan map[string]any `json:"plan"`
	// What each leg did.
	Results []map[string]any `json:"results"`
	// More about a refusal.
	Details map[string]any `json:"details"`
	// The alert this one repeats.
	DuplicateOf *string `json:"duplicate_of"`
	// Refusals folded into this row (rate limits).
	RepeatCount int64 `json:"repeat_count"`
	// When it came.
	ReceivedAt int64 `json:"received_at"`
	// When it was done.
	FinishedAt *int64 `json:"finished_at"`
}

TradingViewAlert: see the API reference.

func (TradingViewAlert) MarshalJSON

func (x TradingViewAlert) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type TradingViewAlertStatus

type TradingViewAlertStatus string

TradingViewAlertStatus: What it did. Open: a value from a newer API version is kept as is.

const (
	TradingViewAlertStatusProcessing  TradingViewAlertStatus = "processing"
	TradingViewAlertStatusPlaced      TradingViewAlertStatus = "placed"
	TradingViewAlertStatusPartial     TradingViewAlertStatus = "partial"
	TradingViewAlertStatusDryRun      TradingViewAlertStatus = "dry_run"
	TradingViewAlertStatusDuplicate   TradingViewAlertStatus = "duplicate"
	TradingViewAlertStatusSkipped     TradingViewAlertStatus = "skipped"
	TradingViewAlertStatusRefused     TradingViewAlertStatus = "refused"
	TradingViewAlertStatusFailed      TradingViewAlertStatus = "failed"
	TradingViewAlertStatusRateLimited TradingViewAlertStatus = "rate_limited"
)

type TradingViewHook

type TradingViewHook struct {
	// The link.
	ID string `json:"id"`
	// Its name.
	Name string `json:"name"`
	// The account number.
	AccountID string `json:"account_id"`
	// Its environment.
	Environment PlatformEnvironment `json:"environment"`
	// paused: alerts are refused (link_paused).
	Status TradingViewHookStatus `json:"status"`
	// The markets it may trade; empty: every market.
	Markets []string `json:"markets"`
	// It may only reduce positions.
	ReduceOnly bool `json:"reduce_only"`
	// Its largest order, in USD.
	MaxOrderUSD *Decimal `json:"max_order_usd"`
	// Its largest position, in USD.
	MaxPositionUSD *Decimal `json:"max_position_usd"`
	// Its daily loss stop: no new position once today's loss reaches it.
	DailyLossUSD *Decimal              `json:"daily_loss_usd"`
	Sizing       TradingViewHookSizing `json:"sizing"`
	// signal: an opposite alert reverses, a repeat is skipped. add: a repeat adds. target: the strategy's position
	// size is followed.
	PositionMode TradingViewHookPositionMode `json:"position_mode"`
}

TradingViewHook: see the API reference.

func (TradingViewHook) MarshalJSON

func (x TradingViewHook) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type TradingViewHookPositionMode

type TradingViewHookPositionMode string

TradingViewHookPositionMode: signal: an opposite alert reverses, a repeat is skipped. add: a repeat adds. target: the strategy's position size is followed. Open: a value from a newer API version is kept as is.

const (
	TradingViewHookPositionModeSignal TradingViewHookPositionMode = "signal"
	TradingViewHookPositionModeAdd    TradingViewHookPositionMode = "add"
	TradingViewHookPositionModeTarget TradingViewHookPositionMode = "target"
)

type TradingViewHookSizing

type TradingViewHookSizing struct {
	// from_alert: the size the alert gives. qty, usd, pct_balance: the link's own.
	Mode TradingViewHookSizingMode `json:"mode"`
	// The link's size, in its mode's unit.
	Value *Decimal `json:"value"`
}

TradingViewHookSizing: see the API reference.

type TradingViewHookSizingMode

type TradingViewHookSizingMode string

TradingViewHookSizingMode: from_alert: the size the alert gives. qty, usd, pct_balance: the link's own. Open: a value from a newer API version is kept as is.

const (
	TradingViewHookSizingModeFromAlert  TradingViewHookSizingMode = "from_alert"
	TradingViewHookSizingModeQty        TradingViewHookSizingMode = "qty"
	TradingViewHookSizingModeUSD        TradingViewHookSizingMode = "usd"
	TradingViewHookSizingModePctBalance TradingViewHookSizingMode = "pct_balance"
)

type TradingViewHookStatus

type TradingViewHookStatus string

TradingViewHookStatus: paused: alerts are refused (link_paused). Open: a value from a newer API version is kept as is.

const (
	TradingViewHookStatusActive TradingViewHookStatus = "active"
	TradingViewHookStatusPaused TradingViewHookStatus = "paused"
)

type TradingViewParse

type TradingViewParse struct {
	// It reads, and names a market we offer.
	Ok bool `json:"ok"`
	// Why not, when it does not.
	Code *string `json:"code"`
	// The field at fault.
	Field *string `json:"field"`
	// What went wrong.
	Message *string `json:"message"`
	// The message as read: action, side, sizes, prices, exits.
	Signal map[string]any `json:"signal"`
	// The market it names (ALL for every market).
	Market *string `json:"market"`
	// The market meant, when the ticker names one we offer only scaled.
	Suggestion *string `json:"suggestion"`
	// With hook_id: what the alert would do now ({ legs } / { skip } / { refuse }).
	Plan map[string]any `json:"plan"`
}

TradingViewParse: see the API reference.

type TradingViewParseInput

type TradingViewParseInput struct {
	// The alert's message, as TradingView would send it.
	Message string `json:"message"`
	// A link: the plan is then worked out on its account and settings, as of now.
	HookID *string `json:"hook_id,omitempty"`
}

TradingViewParseInput: A message to read, sent nowhere.

type TradingViewService

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

TradingViewService: the tradingview calls (client.TradingView).

func (*TradingViewService) DeleteHook

func (r *TradingViewService) DeleteHook(ctx context.Context, hookID string, opts ...CallOption) (*DeletedHook, error)

DeleteHook: Revoke a TradingView link.

func (*TradingViewService) DisableHook

func (r *TradingViewService) DisableHook(ctx context.Context, hookID string, opts ...CallOption) (*TradingViewHook, error)

DisableHook: Pause a TradingView link.

func (*TradingViewService) EnableHook

func (r *TradingViewService) EnableHook(ctx context.Context, hookID string, opts ...CallOption) (*TradingViewHook, error)

EnableHook: Resume a TradingView link.

func (*TradingViewService) GetAlert

func (r *TradingViewService) GetAlert(ctx context.Context, hookID string, alertID string, opts ...CallOption) (*TradingViewAlert, error)

GetAlert: Get an alert.

func (*TradingViewService) GetHook

func (r *TradingViewService) GetHook(ctx context.Context, hookID string, opts ...CallOption) (*TradingViewHook, error)

GetHook: Get a TradingView link.

func (*TradingViewService) ListAlerts

func (r *TradingViewService) ListAlerts(ctx context.Context, hookID string, params *TradingviewListAlertsParams, opts ...CallOption) (*Page[TradingViewAlert], error)

ListAlerts: List a link's alerts.

func (*TradingViewService) ListAlertsAutoPaging

func (r *TradingViewService) ListAlertsAutoPaging(ctx context.Context, hookID string, params *TradingviewListAlertsParams, opts ...CallOption) iter.Seq2[TradingViewAlert, error]

ListAlertsAutoPaging: every item of ListAlerts, page after page (WithMaxItems caps it).

func (*TradingViewService) ListHooks

func (r *TradingViewService) ListHooks(ctx context.Context, opts ...CallOption) (*Page[TradingViewHook], error)

ListHooks: List TradingView links.

func (*TradingViewService) Parse

Parse: Read an alert message.

type TradingviewListAlertsParams

type TradingviewListAlertsParams struct {
	// Only alerts with this status.
	Status *string `json:"status,omitempty"`
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

TradingviewListAlertsParams: The query of list a link's alerts.

type Warning

type Warning struct {
	// What it is about.
	Code WarningCode `json:"code"`
	// How serious.
	Level WarningLevel `json:"level"`
	// The market it is about.
	Market *string `json:"market,omitempty"`
	// The figure behind it, in percent.
	Value *Decimal `json:"value,omitempty"`
}

Warning: see the API reference.

type WarningCode

type WarningCode string

WarningCode: What it is about. Open: a value from a newer API version is kept as is.

const (
	WarningCodeDailyLossUsed        WarningCode = "daily_loss_used"
	WarningCodeMaxDrawdownUsed      WarningCode = "max_drawdown_used"
	WarningCodeLiquidationNear      WarningCode = "liquidation_near"
	WarningCodeNoStopLoss           WarningCode = "no_stop_loss"
	WarningCodeMarginUsed           WarningCode = "margin_used"
	WarningCodeOrderWithoutPosition WarningCode = "order_without_position"
)

type WarningLevel

type WarningLevel string

WarningLevel: How serious. Open: a value from a newer API version is kept as is.

const (
	WarningLevelInfo     WarningLevel = "info"
	WarningLevelWarning  WarningLevel = "warning"
	WarningLevelCritical WarningLevel = "critical"
)

type WebhookDelivery

type WebhookDelivery struct {
	// The delivery.
	ID string `json:"id"`
	// Its endpoint.
	EndpointID string `json:"endpoint_id"`
	// The event sent (the same id when it is sent again).
	EventID string `json:"event_id"`
	// The event's type.
	EventType string `json:"event_type"`
	// Its account.
	AccountID *string `json:"account_id"`
	// A test.
	Test bool `json:"test"`
	// pending: waiting for its next try. failed: every try failed. canceled: the endpoint was disabled or deleted.
	Status WebhookDeliveryStatus `json:"status"`
	// Every try, oldest first.
	Attempts []WebhookDeliveryAttempt `json:"attempts"`
	// When it is tried again.
	NextAttemptAt *int64 `json:"next_attempt_at"`
	// When it was queued.
	CreatedAt int64 `json:"created_at"`
	// When your endpoint took it.
	DeliveredAt *int64 `json:"delivered_at"`
}

WebhookDelivery: see the API reference.

func (WebhookDelivery) MarshalJSON

func (x WebhookDelivery) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type WebhookDeliveryAttempt

type WebhookDeliveryAttempt struct {
	// Which try.
	Attempt int64 `json:"attempt"`
	// When.
	At int64 `json:"at"`
	// What your endpoint answered; null when it could not be reached.
	HTTPStatus *int64 `json:"http_status"`
	// Why it failed, when it did (timeout, redirect, private_address, http_500, ...).
	Error *string `json:"error"`
	// How long it took.
	DurationMs *int64 `json:"duration_ms"`
	// The start of the answer (up to 512 bytes).
	Response *string `json:"response"`
}

WebhookDeliveryAttempt: see the API reference.

type WebhookDeliveryStatus

type WebhookDeliveryStatus string

WebhookDeliveryStatus: pending: waiting for its next try. failed: every try failed. canceled: the endpoint was disabled or deleted. Open: a value from a newer API version is kept as is.

const (
	WebhookDeliveryStatusPending    WebhookDeliveryStatus = "pending"
	WebhookDeliveryStatusDelivering WebhookDeliveryStatus = "delivering"
	WebhookDeliveryStatusDelivered  WebhookDeliveryStatus = "delivered"
	WebhookDeliveryStatusFailed     WebhookDeliveryStatus = "failed"
	WebhookDeliveryStatusCanceled   WebhookDeliveryStatus = "canceled"
)

type WebhookEndpoint

type WebhookEndpoint struct {
	// The endpoint.
	ID string `json:"id"`
	// Its address: the host and the start of the path (never whole: chat addresses carry tokens).
	URL *string `json:"url"`
	// json: the signed event. discord, slack, telegram: a chat message.
	Format WebhookEndpointFormat `json:"format"`
	// The groups it receives (see GET /v1/webhook-event-types).
	Events []WebhookEndpointEvent `json:"events"`
	// disabled: we stopped after failures in a row; turn it on again from your dashboard.
	Status WebhookEndpointStatus `json:"status"`
	// The version its events are written in.
	APIVersion string `json:"api_version"`
	// Its environment: it receives that environment's events only.
	Environment PlatformEnvironment `json:"environment"`
}

WebhookEndpoint: see the API reference.

func (WebhookEndpoint) MarshalJSON

func (x WebhookEndpoint) MarshalJSON() ([]byte, error)

MarshalJSON sends a required list left nil as [], never null.

type WebhookEndpointEvent

type WebhookEndpointEvent string

WebhookEndpointEvent: A group of events. Open: a value from a newer API version is kept as is.

const (
	WebhookEndpointEventOrders    WebhookEndpointEvent = "orders"
	WebhookEndpointEventPositions WebhookEndpointEvent = "positions"
	WebhookEndpointEventAccount   WebhookEndpointEvent = "account"
	WebhookEndpointEventRisk      WebhookEndpointEvent = "risk"
	WebhookEndpointEventAlerts    WebhookEndpointEvent = "alerts"
)

type WebhookEndpointFormat

type WebhookEndpointFormat string

WebhookEndpointFormat: json: the signed event. discord, slack, telegram: a chat message. Open: a value from a newer API version is kept as is.

const (
	WebhookEndpointFormatJSON     WebhookEndpointFormat = "json"
	WebhookEndpointFormatDiscord  WebhookEndpointFormat = "discord"
	WebhookEndpointFormatSlack    WebhookEndpointFormat = "slack"
	WebhookEndpointFormatTelegram WebhookEndpointFormat = "telegram"
)

type WebhookEndpointStatus

type WebhookEndpointStatus string

WebhookEndpointStatus: disabled: we stopped after failures in a row; turn it on again from your dashboard. Open: a value from a newer API version is kept as is.

const (
	WebhookEndpointStatusActive   WebhookEndpointStatus = "active"
	WebhookEndpointStatusPaused   WebhookEndpointStatus = "paused"
	WebhookEndpointStatusDisabled WebhookEndpointStatus = "disabled"
)

type WebhookEndpointsListDeliveriesParams

type WebhookEndpointsListDeliveriesParams struct {
	// Page size.
	Limit *int64 `json:"limit,omitempty"`
	// next_cursor from the previous page, with the same filters.
	Cursor *string `json:"cursor,omitempty"`
}

WebhookEndpointsListDeliveriesParams: The query of list deliveries.

type WebhookEndpointsService

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

WebhookEndpointsService: the webhookEndpoints calls (client.WebhookEndpoints).

func (*WebhookEndpointsService) Delete

func (r *WebhookEndpointsService) Delete(ctx context.Context, endpointID string, opts ...CallOption) (*DeletedEndpoint, error)

Delete: Delete an endpoint.

func (*WebhookEndpointsService) Disable

func (r *WebhookEndpointsService) Disable(ctx context.Context, endpointID string, opts ...CallOption) (*WebhookEndpoint, error)

Disable: Pause an endpoint.

func (*WebhookEndpointsService) Enable

func (r *WebhookEndpointsService) Enable(ctx context.Context, endpointID string, opts ...CallOption) (*WebhookEndpoint, error)

Enable: Resume an endpoint.

func (*WebhookEndpointsService) EventTypes

func (r *WebhookEndpointsService) EventTypes(ctx context.Context, opts ...CallOption) (*Page[WebhookEventType], error)

EventTypes: List event types.

func (*WebhookEndpointsService) Get

func (r *WebhookEndpointsService) Get(ctx context.Context, endpointID string, opts ...CallOption) (*WebhookEndpoint, error)

Get: Get a webhook endpoint.

func (*WebhookEndpointsService) GetDelivery

func (r *WebhookEndpointsService) GetDelivery(ctx context.Context, endpointID string, deliveryID string, opts ...CallOption) (*WebhookDelivery, error)

GetDelivery: Get a delivery.

func (*WebhookEndpointsService) List

List: List webhook endpoints.

func (*WebhookEndpointsService) ListDeliveries

ListDeliveries: List deliveries.

func (*WebhookEndpointsService) ListDeliveriesAutoPaging

func (r *WebhookEndpointsService) ListDeliveriesAutoPaging(ctx context.Context, endpointID string, params *WebhookEndpointsListDeliveriesParams, opts ...CallOption) iter.Seq2[WebhookDelivery, error]

ListDeliveriesAutoPaging: every item of ListDeliveries, page after page (WithMaxItems caps it).

func (*WebhookEndpointsService) ResendDelivery

func (r *WebhookEndpointsService) ResendDelivery(ctx context.Context, endpointID string, deliveryID string, opts ...CallOption) (*WebhookDelivery, error)

ResendDelivery: Send a delivery again.

func (*WebhookEndpointsService) Test

func (r *WebhookEndpointsService) Test(ctx context.Context, endpointID string, opts ...CallOption) (*WebhookDelivery, error)

Test: Send a test.

type WebhookError deprecated

type WebhookError = Error

WebhookError is the error VerifyWebhook answers (KindWebhookVerification, its Code one of missing_headers, stale, bad_signature, bad_body).

Deprecated: it is Error; use errors.Is(err, ErrWebhookVerification).

type WebhookEventType

type WebhookEventType struct {
	// The type.
	Type string `json:"type"`
	// The group that receives it; null: every endpoint (the test).
	Group *WebhookEventTypeGroup `json:"group"`
	// What it means.
	Description string `json:"description"`
}

WebhookEventType: see the API reference.

type WebhookEventTypeGroup

type WebhookEventTypeGroup string

WebhookEventTypeGroup: The group that receives it; null: every endpoint (the test). Open: a value from a newer API version is kept as is.

const (
	WebhookEventTypeGroupOrders    WebhookEventTypeGroup = "orders"
	WebhookEventTypeGroupPositions WebhookEventTypeGroup = "positions"
	WebhookEventTypeGroupAccount   WebhookEventTypeGroup = "account"
	WebhookEventTypeGroupRisk      WebhookEventTypeGroup = "risk"
	WebhookEventTypeGroupAlerts    WebhookEventTypeGroup = "alerts"
)

type WebhookPayload

type WebhookPayload struct {
	// The event; pass it as after (GET /v1/events) or resume (the stream) to continue from it.
	ID string `json:"id"`
	// What happened; webhook.ping is a test.
	Type WebhookPayloadType `json:"type"`
	// The account number (none on webhook.ping).
	AccountID *string `json:"account_id,omitempty"`
	// When it happened.
	Time int64 `json:"time"`
	// Where it came from: an order placed through this API or by an AI assistant (the MCP server), one placed on a
	// trading platform, the engine itself (positions), a strategy of this API, or a TradingView alert.
	Source EventSource `json:"source"`
	// order or fill (the objects REST answers), with changes or close_reason when they apply. A position.* event
	// carries position { market, side, size, average_price } as the engine reported it, and previous_size: read GET
	// .../positions/{market} for its margin, P&L and liquidation.
	Data map[string]any `json:"data"`
	// The API version the endpoint receives.
	APIVersion string `json:"api_version"`
	// The environment of the endpoint and the account.
	Environment PlatformEnvironment `json:"environment"`
	// A test (webhook.ping) or a delivery resent as one.
	Test *bool `json:"test,omitempty"`
}

WebhookPayload: What a json webhook endpoint receives: the event as GET /v1/events shows it, with the endpoint's API version and environment.

func VerifyWebhook

func VerifyWebhook(raw []byte, header http.Header, secrets []string, tolerance time.Duration) (*WebhookPayload, error)

VerifyWebhook is a delivery once its signature and time check out: the WebhookPayload (the event, with the endpoint's api_version and environment, and test on a webhook.ping or a delivery resent as one). raw is the body exactly as received; secrets are the endpoint's (two during a rotation). A delivery that does not verify is an ErrWebhookVerification (Code: missing_headers, stale, bad_signature or bad_body).

func VerifyWebhookAt

func VerifyWebhookAt(raw []byte, header http.Header, secrets []string, tolerance time.Duration, now time.Time) (*WebhookPayload, error)

VerifyWebhookAt is VerifyWebhook at a given time.

func VerifyWebhookPayload deprecated

func VerifyWebhookPayload(raw []byte, header http.Header, secrets []string, tolerance time.Duration) (*WebhookPayload, error)

VerifyWebhookPayload is VerifyWebhook.

Deprecated: VerifyWebhook answers the WebhookPayload.

type WebhookPayloadType

type WebhookPayloadType string

WebhookPayloadType: What happened; webhook.ping is a test. Open: a value from a newer API version is kept as is.

const (
	WebhookPayloadTypeOrderCreated             WebhookPayloadType = "order.created"
	WebhookPayloadTypeOrderEdited              WebhookPayloadType = "order.edited"
	WebhookPayloadTypeOrderFilled              WebhookPayloadType = "order.filled"
	WebhookPayloadTypeOrderCanceled            WebhookPayloadType = "order.canceled"
	WebhookPayloadTypeOrderRejected            WebhookPayloadType = "order.rejected"
	WebhookPayloadTypeOrderExpired             WebhookPayloadType = "order.expired"
	WebhookPayloadTypeFillCreated              WebhookPayloadType = "fill.created"
	WebhookPayloadTypePositionOpened           WebhookPayloadType = "position.opened"
	WebhookPayloadTypePositionChanged          WebhookPayloadType = "position.changed"
	WebhookPayloadTypePositionClosed           WebhookPayloadType = "position.closed"
	WebhookPayloadTypeStrategyCreated          WebhookPayloadType = "strategy.created"
	WebhookPayloadTypeStrategyLegPlaced        WebhookPayloadType = "strategy.leg_placed"
	WebhookPayloadTypeStrategyLegModified      WebhookPayloadType = "strategy.leg_modified"
	WebhookPayloadTypeStrategyLegFilled        WebhookPayloadType = "strategy.leg_filled"
	WebhookPayloadTypeStrategyLegCanceled      WebhookPayloadType = "strategy.leg_canceled"
	WebhookPayloadTypeStrategyLegRejected      WebhookPayloadType = "strategy.leg_rejected"
	WebhookPayloadTypeStrategyOrphanRepaired   WebhookPayloadType = "strategy.orphan_repaired"
	WebhookPayloadTypeStrategySlice            WebhookPayloadType = "strategy.slice"
	WebhookPayloadTypeStrategyTriggered        WebhookPayloadType = "strategy.triggered"
	WebhookPayloadTypeStrategyEnded            WebhookPayloadType = "strategy.ended"
	WebhookPayloadTypeTradingviewAlertExecuted WebhookPayloadType = "tradingview.alert_executed"
	WebhookPayloadTypeTradingviewAlertRefused  WebhookPayloadType = "tradingview.alert_refused"
	WebhookPayloadTypeAccountUpdated           WebhookPayloadType = "account.updated"
	WebhookPayloadTypeAccountPassed            WebhookPayloadType = "account.passed"
	WebhookPayloadTypeAccountFailed            WebhookPayloadType = "account.failed"
	WebhookPayloadTypeAccountPayoutEligible    WebhookPayloadType = "account.payout_eligible"
	WebhookPayloadTypeAccountDisabled          WebhookPayloadType = "account.disabled"
	WebhookPayloadTypeAccountRemoved           WebhookPayloadType = "account.removed"
	WebhookPayloadTypeKeyLossStop              WebhookPayloadType = "key.loss_stop"
	WebhookPayloadTypeKeyExpiring              WebhookPayloadType = "key.expiring"
	WebhookPayloadTypeSystemRestarted          WebhookPayloadType = "system.restarted"
	WebhookPayloadTypeRiskWarning              WebhookPayloadType = "risk.warning"
	WebhookPayloadTypeRiskCleared              WebhookPayloadType = "risk.cleared"
	WebhookPayloadTypeAlertTriggered           WebhookPayloadType = "alert.triggered"
	WebhookPayloadTypeWebhookPing              WebhookPayloadType = "webhook.ping"
)

type WhatIf

type WhatIf struct {
	// What the order would do now: fill at once, rest, or be refused (reject says why).
	Result WhatIfResult  `json:"result"`
	Reject *WhatIfReject `json:"reject"`
	// A market id: the asset and USD; an option adds its venue or hours after a dot.
	Market string `json:"market"`
	// The order's side.
	Side OrderSide `json:"side"`
	// The order's type.
	Type CreateOrderType `json:"type"`
	// Its size (after a notional_usd is rounded to the size step).
	Size      *Decimal         `json:"size"`
	Execution *WhatIfExecution `json:"execution"`
	// Its value in USD.
	Notional *Decimal `json:"notional"`
	// The fee its fill would pay.
	Fee           *Decimal             `json:"fee"`
	Margin        *WhatIfMargin        `json:"margin"`
	PositionAfter *WhatIfPositionAfter `json:"position_after"`
	Exposure      *WhatIfExposure      `json:"exposure"`
}

WhatIf: see the API reference.

type WhatIfExecution

type WhatIfExecution struct {
	// It would fill at once.
	Marketable bool `json:"marketable"`
	// The price it would fill at (at once) or rest at.
	ExpectedPrice Decimal `json:"expected_price"`
	// A market order's worst price.
	WorstPrice *Decimal `json:"worst_price"`
}

WhatIfExecution: see the API reference.

type WhatIfExposure

type WhatIfExposure struct {
	// The market's exposure cap across your accounts of this product.
	Cap Decimal `json:"cap"`
	// Your open value on the market now.
	OpenBefore Decimal `json:"open_before"`
	// What would remain under the cap.
	RoomAfter Decimal `json:"room_after"`
}

WhatIfExposure: see the API reference.

type WhatIfMargin

type WhatIfMargin struct {
	// The margin mode the position would use.
	Mode WhatIfMarginMode `json:"mode"`
	// The leverage it would use.
	Leverage int64 `json:"leverage"`
	// The margin the order needs.
	Required Decimal `json:"required"`
	// The margin available now.
	AvailableBefore *Decimal `json:"available_before"`
	// What would remain available.
	AvailableAfter *Decimal `json:"available_after"`
}

WhatIfMargin: see the API reference.

type WhatIfMarginMode

type WhatIfMarginMode string

WhatIfMarginMode: The margin mode the position would use. Open: a value from a newer API version is kept as is.

const (
	WhatIfMarginModeIsolated WhatIfMarginMode = "isolated"
	WhatIfMarginModeCross    WhatIfMarginMode = "cross"
)

type WhatIfPositionAfter

type WhatIfPositionAfter struct {
	// The position's size after the fill.
	Size Decimal `json:"size"`
	// Its side; null when flat.
	Side *PositionSide `json:"side"`
	// Its average price.
	AveragePrice *Decimal `json:"average_price"`
}

WhatIfPositionAfter: see the API reference.

type WhatIfReject

type WhatIfReject struct {
	// The error code it would get.
	Code string `json:"code"`
	// What it means.
	Message *string `json:"message"`
	// More about it.
	Details json.RawMessage `json:"details,omitempty"`
}

WhatIfReject: see the API reference.

type WhatIfResult

type WhatIfResult string

WhatIfResult: What the order would do now: fill at once, rest, or be refused (reject says why). Open: a value from a newer API version is kept as is.

const (
	WhatIfResultWouldFill   WhatIfResult = "would_fill"
	WhatIfResultWouldRest   WhatIfResult = "would_rest"
	WhatIfResultWouldReject WhatIfResult = "would_reject"
)

Directories

Path Synopsis
examples
01-accounts command
01: who you are (the key, its access and limits) and your accounts.
01: who you are (the key, its access and limits) and your accounts.
02-markets command
02: the markets and their rules, then a quote (bid, ask, last) from the market stream.
02: the markets and their rules, then a quote (bid, ask, last) from the market stream.
03-market-stream command
03: live market data: prices for two markets and the trades of one, until 20 frames came.
03: live market data: prices for two markets and the trades of one, until 20 frames came.
04-place-cancel-limit command
04: a limit order far from the market, found again by your own id, then canceled.
04: a limit order far from the market, found again by your own id, then canceled.
05-market-with-brackets command
05: a market order with its exits: a take profit 1% away and a stop loss 0.5% away, placed by the API the moment it fills and kept on its servers.
05: a market order with its exits: a take profit 1% away and a stop loss 0.5% away, placed by the API the moment it fills and kept on its servers.
06-trailing-breakeven command
06: a position whose stop loss trails the price by 0.5% and moves to break-even once the price has gone 0.5% your way, all on the API's servers.
06: a position whose stop loss trails the price by 0.5% and moves to break-even once the price has gone 0.5% your way, all on the API's servers.
07-what-if command
07: what an order would do now, without placing it: fill or rest, the price, the fee, the margin, the position after.
07: what an order would do now, without placing it: fill or rest, the price, the fee, the margin, the position after.
08-account-stream-mirror command
08: a live copy of your accounts' positions and working orders: the snapshot first, then every event applied once.
08: a live copy of your accounts' positions and working orders: the snapshot first, then every event applied once.
09-history command
09: an account's history: the equity curve by day, the result of each trading day, closed positions and fills.
09: an account's history: the equity curve by day, the result of each trading day, closed positions and fills.
10-candles-to-csv command
10: the last 100 closed one-minute candles of a market and the one forming (final false), written to candles.csv.
10: the last 100 closed one-minute candles of a market and the one forming (final false), written to candles.csv.
11-webhook-receiver command
11: receive webhooks: every delivery is checked (its signature and its time) before it is trusted.
11: receive webhooks: every delivery is checked (its signature and its time) before it is trusted.
12-error-handling command
12: what failures look like: each has a family (errors.Is), the API's code, the request id to quote to support, and details.
12: what failures look like: each has a family (errors.Is), the API's code, the request id to quote to support, and details.

Jump to

Keyboard shortcuts

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