grvt

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 33 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

grvt (Go SDK, preview)

Preview. This SDK is still being stabilised. Its API can change in any 0.x release, so pin an exact version. It becomes stable at 1.0.0.

The Go SDK for Grvt: REST, WebSocket streams, WebSocket order entry, EIP-712 signing and login in one package. It mirrors the Python and Rust SDKs in sdk/languages/python and sdk/languages/rust: same operations, same behaviour. Everything that grows with the API (models, enums, error codes, RPC/stream methods, sign functions) is generated from sdk/contract/contract.json by sdk/generator/golang into *_gen.go files; the hand-written runtime stays the same size however many APIs exist.

It is its own Go module (github.com/gravity-technologies/grvt-sdk-go), outside the platform module. The required Go version is in go.mod. During preview, we intentionally use the latest Go release for both development and consumers (currently Go 1.27.4). This is a support policy, not a claim that the SDK needs a specific new standard-library feature. We may raise this requirement in a 0.x release.

Quickstart

Use the canonical quickstart and download its Go example. The example reads public testnet data by default. Add --trade to place, observe, and cancel one testnet order. Trading requires GRVT_API_KEY, GRVT_PRIVATE_KEY, and GRVT_SUB_ACCOUNT_ID. An order can fill before cancellation. The example uses current instrument limits and stops after bounded observation attempts.

From this SDK's directory, run:

go run ./examples/quickstart

Every RPC is a method directly on the client, client.<Method>(ctx, *Request) (*Response, error), and every stream is client.<Method>Stream(ctx, *Selector) (*Subscription[Feed], error). Names are the contract's method_name in Go style (create_order -> client.CreateOrder, the trade stream -> client.TradeStream). The contract's namespace is only a docs category and never appears in your code. Model types keep the contract names (models.ApiCreateOrderRequest) and their JSON tags are the wire field names. Required fields are checked before anything is signed or sent.

Errors are distinct types for errors.As: *grvt.APIError (Code, Message, Status, RPC, Retryable), *grvt.RateLimitError (also matches *APIError with code 1006), *grvt.TransportError, *grvt.OrderStateUnknownError (ClientOrderID, ClientOrderIDs), *grvt.StreamOverflowError, *grvt.SigningError, *grvt.ConfigError, *grvt.DecodeError, *grvt.FrameTooLargeError, and grvt.ErrClosed. Error code constants are grvt.Code<Name> (grvt.CodeSignatureExpired).

Generated source

The public source repo includes the generated code and shared test fixtures. For development in the platform monorepo, run make sdk-gen-go from its root before building this SDK. Generated source comes from the Grvt API contract. Send proposed changes to the Grvt maintainers so they can update the monorepo.

Layout

api_gen.go              GENERATED: Client, New, one Client method per RPC/stream
specs_gen.go            GENERATED: RPCSpec / StreamSpec values (RPCs, Streams)
signing_gen.go          GENERATED: EIP-712 types, message builders, Sign<Id> functions
errors_gen.go           GENERATED: Code<Name> constants and the error table
api_gen_test.go         GENERATED: every RPC and stream is reachable through the client
models/models_gen.go    GENERATED: one struct per wire type
models/enums_gen.go     GENERATED: one string type per enum, known values, signing codes
models/wire.go          Uint64s (lists of 64-bit ints as JSON strings)
runtime.go              Runtime: Call, Subscribe, signing hooks, session rotation, metadata cache access
ws.go, subscription.go  one managed socket per gateway; Subscription
protocol.go             sans-IO state: request table, sequencer, backoff (unit-tested)
rest.go, auth.go        REST calls with read retries; api-key login, cookie + X-Grvt-Account-Id
eip712.go, signer.go    EIP-712 domain + typed data; Signer + PrivateKeySigner (external signers are verified)
eip712_encode.go        helpers for the generated encoders (zero-allocation hashing)
signing.go              wire transforms (MessageBuilder), metadata cache
config.go, env.go       Config, OrderTransport, Encoding, Environment, specs; Ptr / Deref
hooks.go, log.go        BeforeSend / OnEvent; GRVT_LOG with redaction
errors.go, clock.go     error types; clock, nonces, client order ids
RUNTIME_API.md          the contract between generator (sdk/generator/golang) and runtime
*_test.go               signing cases, protocol, fake-gateway WS/REST, contract coverage, testnet smoke
examples/quickstart     runnable example

Run the tests

go test ./...                                              # everything offline
go test -race ./...
GRVT_SMOKE=1 go test -run TestSmokeTestnet -v .            # read-only, unauthenticated testnet check (full and lite)
GRVT_TEST_ENCODING=lite go test .                          # every fake-gateway test with a lite client
go test -run '^$' -bench 'Decode|Route|Sign|Encode|Lite' -benchmem .   # hot paths, full vs lite

How the main pieces behave

Same as Python and Rust:

  • Order transport is per client: OrderTransportREST (default) or OrderTransportWS. Writes are never retried. If a write may have reached the exchange but no answer came back (timeout, socket drop, cancelled context), the call returns *OrderStateUnknownError with the client order id; look the order up (Order.GetOrder with ClientOrderID), don't resend.
  • Encoding is per client: EncodingLite (default) or EncodingFull, the gateways' short field names, for both REST and WebSocket (order book frames are about a quarter smaller on testnet). Only the wire changes: models, errors and signing are the same, and login stays full. Lite WebSockets use MarketDataWS / TradingWS with /ws/full swapped for /ws/lite; set MarketDataWSLite / TradingWSLite on a custom Environment only when its URLs don't end in /ws/full.
  • Reads are tried up to 3 times in all, with full-jitter backoff, on retryable errors (code 1006, a code the contract marks retryable, HTTP 502/503/504, transport errors).
  • Signing: CreateOrder fills client_order_id and the signature; signing loads instrument and currency metadata once (cached). Over-precise decimals are a *SigningError, never rounded. Signed calls work on a copy, so your request is not changed.
  • Order checks: before signing, each leg is checked against its instrument's tick, size step, min_size and min_notional. A miss returns *OrderOutOfBoundsError with the nearest valid values; nothing is sent and nothing is rounded. If the exchange still rejects an order for these limits, the instrument's cached metadata is dropped so the next order refetches it. Config.CheckOrders: grvt.Ptr(false) turns the check off and leaves the limits to the exchange.
  • Streams use global sequence numbers. The snapshot frame has sequence_number 0, and the first update's prev_sequence_number is at or below the subscribe reply's latest_sequence_number. The first frame after a (re)subscribe reply is accepted when its prev_sequence_number is 0 or not greater than the latest sequence number known then (testnet sends the old sequence number there). After that, prev_sequence_number must equal the last sequence number seen; otherwise it is a gap: the runtime re-subscribes the same selector and drops frames until the new snapshot. No snapshot within 5s -> reconnect. On reconnect every subscription is re-sent.
  • Backpressure: the read loop never waits for a consumer; each subscription has a bounded queue. Only snapshot streams (every frame complete, *.s) drop the oldest frame when the consumer falls behind. Every other stream (deltas, events, private) returns *StreamOverflowError and re-syncs.
  • Session: api-key login on edge gives the gravity cookie and X-Grvt-Account-Id; both go on REST calls and the WS handshake. The client re-logs in at 80% of the cookie lifetime and sockets reconnect with the new cookie.
  • Hooks: Config.BeforeSend(*OutgoingCall) runs before signing and may edit call.Params (the typed request) in place. Config.OnEvent(Event) gets connect, disconnect, reconnect, subscribe, gap, retry, frame, session_rotated and error events; it runs on the read goroutine and must not block.
  • Logging: log/slog. GRVT_LOG=debug logs to stderr unless Config.Logger is set. Cookie, api key, private keys and r/s are redacted.

Library choices

need library why
WebSocket github.com/coder/websocket v1.8.15 context-aware, concurrent writes, small; already in the platform module
secp256k1 github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 RFC 6979, low-s, compact recoverable signatures; what go-ethereum uses
keccak golang.org/x/crypto/sha3 v0.58.0 NewLegacyKeccak256
decimals math/big + string scaling exact; no decimal library needed for "scale by 10^n and reject over-precision"
HTTP, JSON, logs net/http, encoding/json, log/slog standard library; replies and frames decode with generated one-pass decoders (internal/wirejson) that keep encoding/json's rules

Draft notes (shortcuts and TODOs)

  • Optional fields: strings and enums use "" for absent; every other scalar is a pointer (nil = absent) so false and 0 can be sent. Use grvt.Ptr(...). Optional struct fields are pointers. Required fields use native values. Decoding rejects missing required keys, while nullable arrays accept null. Signed calls use Input models for SDK-filled fields. Only contract-declared partial streams use Partial payloads.
  • 64-bit ints use encoding/json's ,string option: they are sent as strings and must arrive as strings (Rust also accepts numbers and hex). Lists of them (models.Uint64s) accept both.
  • Exact values: decimal fields use models.Decimal. ParseDecimal validates text; Rat() returns an exact big.Rat for arithmetic. Use MustParseDecimal only for known constants. Timestamps use native time.Time; the generated JSON codec preserves Unix nanoseconds and rejects values outside the wire range.
  • Re-subscribe quirk: the first delta after a subscribe ack may carry a prev_sequence_number from before that ack (seen on testnet after a re-subscribe on the same socket). The sequencer accepts any prev at or below latest_sequence_number for that first delta only; a prev past it is still a gap. Python and Rust use the same first-frame rule.
  • Flat names must be unique: methods are not grouped by namespace, so the generator fails if two calls (or two streams) in different namespaces share a method_name.
  • Session rotation on WS is simplified (break-before-make, as in Python and Rust): after a re-login a socket waits for no writes in flight, then reconnects with the new cookie.
  • Frame-size check exists but is off (Environment.WSMaxFrameBytes is 0 for named environments); when set, an oversized frame is *FrameTooLargeError and nothing is sent. REST fallback is a TODO.
  • Book deltas are never conflated. The local OrderBook helper merges levels. Queue overflow invalidates continuity. See rebuild a book after a gap.
  • Private-stream resume is not possible until the server supports it; callers backfill via REST.
  • Read/write access is explicit in the contract. Unclassified calls stop generation; only reads can retry.
  • Signing scope matches Python and Rust: Order / OrderWithBuilderFee (also each order of BulkOrders, signed on its own), Transfer V1-V3, Withdrawal V1-V2, WalletLogin. Algo orders, vault and session keys are not bound in the contract.
  • Authentication belongs to the session runtime. Set Config.APIKey on the client to log in. Raw edge login routes are not generated client methods; wallet session login is not supported.
  • Client order ids use the wall clock (TimeCounterClientOrderID), not Config.Clock.
  • Config.HTTPClient is also used for the WebSocket handshake, so do not set Timeout on it.
  • No Bazel BUILD files; the module's own go.mod keeps it out of the platform build.

Timeouts

Config.CallTimeout defaults to 30 seconds for the whole RPC, including authentication, metadata, signing, retries, and the response. An earlier deadline on the caller's context takes precedence. Config.HTTPAttemptTimeout caps each HTTP attempt at 10 seconds by default, within the remaining total limit. Replace the old RequestTimeout setting with HTTPAttemptTimeout.

Uncertain orders and stream gaps

Use the recovery helpers and gap ranges to look up uncertain orders and detect lost stream continuity. A missing order stays unknown. The helpers never resend an order.

Pagination

Use Pages to follow cursors without fetching ahead. Pass an empty starting cursor for the first page. Keep filters fixed in the callback.

fetch := func(ctx context.Context, cursor string) (*models.ApiTradeHistoryResponse, error) {
    return client.TradeHistory(ctx, &models.ApiTradeHistoryRequest{
        Instrument: "BTC_USDT_Perp", Cursor: cursor,
    })
}
for page, err := range grvt.Pages(ctx, fetch, "") {
    if err != nil { return err }
    for _, trade := range page.Result { fmt.Println(trade) }
}

An empty page can still have a next cursor. Breaking the loop stops further calls; the context cancels a fetch. A repeated cursor returns PaginationCycleError. Fetch errors pass through without extra retries. Cursors do not guarantee a stable snapshot while records change.

Default sub-account

Set Config.SubAccountID to fill omitted request and stream account IDs. Zero leaves the client default unset. A zero account in a request or selector means omitted; an OrderInput uses nil for omitted. Explicit nonzero IDs take precedence. Bulk orders first inherit the request account, then the client default. Transfer source and destination IDs stay explicit. Defaults are applied to copies before signing. Without a default, calls that need an account still require one.

Recovery helpers

The SDK exposes lookup-only order resolution, history backfill with unproven continuity, and explicit cancellation-countdown refresh. Session rotation reports that authenticated WebSockets must reconnect. See the recovery recipes, including rebuilding a local order book, before restoring trading after a gap.

Documentation

Overview

Package grvt is the Go SDK for Grvt: REST, WebSocket streams, WebSocket order entry, EIP-712 signing and login in one package. Everything that grows with the API (models, enums, error codes, RPC and stream methods, sign functions) is generated from sdk/contract/contract.json into *_gen.go files and package models; the hand-written runtime stays the same size however many APIs exist. See README.md and RUNTIME_API.md.

Index

Constants

View Source
const (
	CookieName    = "gravity"
	AccountHeader = "X-Grvt-Account-Id"
	LoginPath     = "/auth/api_key/login"
)
View Source
const (
	// CodeUnauthorized is 1000 (HTTP 401): You need to authenticate prior to using this functionality
	CodeUnauthorized = 1000
	// CodeForbidden is 1001 (HTTP 403): You are not authorized to access this functionality
	CodeForbidden = 1001
	// CodeInternalServer is 1002 (HTTP 500): Internal Server Error
	CodeInternalServer = 1002
	// CodeInvalidRequest is 1003 (HTTP 400): Request could not be processed due to malformed syntax
	CodeInvalidRequest = 1003
	// CodeNotFound is 1004 (HTTP 404): Data Not Found
	CodeNotFound = 1004
	// CodeUnknownErr is 1005 (HTTP 500): Unknown Error
	CodeUnknownErr = 1005
	// CodeRateLimit is 1006 (HTTP 429): You have surpassed the allocated rate limit for your tier
	CodeRateLimit = 1006
	// CodeUnsupportedCurrency is 1007 (HTTP 404): The currency you are requesting for is not currently supported
	CodeUnsupportedCurrency = 1007
	// CodeIPNotWhitelisted is 1008 (HTTP 401): Your IP has not been whitelisted for access
	CodeIPNotWhitelisted = 1008
	// CodeAPIEndpointTemporarilyDeactivated is 1009 (HTTP 503): We are temporarily deactivating this API endpoint, please try again later
	CodeAPIEndpointTemporarilyDeactivated = 1009
	// CodeInvalidTierOrder is 1010 (HTTP 400): Invalid tier order
	CodeInvalidTierOrder = 1010
	// CodeVisibilityRestricted is 1011 (HTTP 403): This API is restricted based on the client type
	CodeVisibilityRestricted = 1011
	// CodeInvalidSignatureChainID is 1012 (HTTP 400): Invalid signature chain ID
	CodeInvalidSignatureChainID = 1012
	// CodeSpotFeeRebateNotSupported is 1013 (HTTP 400): Spot fee rebate is not supported
	CodeSpotFeeRebateNotSupported = 1013
	// CodeGatewayTimeout is 1014 (HTTP 504): Upstream data service timed out, please try again
	CodeGatewayTimeout = 1014
	// CodeServiceUnavailable is 1015 (HTTP 503): Upstream data service is temporarily unavailable, please try again
	CodeServiceUnavailable = 1015
	// CodeStreamNotFound is 1100 (HTTP 400): Stream not supported on this gateway
	CodeStreamNotFound = 1100
	// CodeInvalidFeedFormat is 1101 (HTTP 400): Feed Format must be in the format of @
	CodeInvalidFeedFormat = 1101
	// CodePrimarySelectorParts is 1102 (HTTP 400): Wrong number of primary selectors
	CodePrimarySelectorParts = 1102
	// CodeSecondarySelectorParts is 1103 (HTTP 400): Wrong number of secondary selectors
	CodeSecondarySelectorParts = 1103
	// CodeDuplicatePrimarySelector is 1104 (HTTP 400): Attempted to subscribe to same primary selector twice, in same request
	CodeDuplicatePrimarySelector = 1104
	// CodeInvalidSubscribeParams is 1105 (HTTP 400): Subscribe params are invalid
	CodeInvalidSubscribeParams = 1105
	// CodeInvalidUnsubscribeParams is 1106 (HTTP 400): Unsubscribe params are invalid
	CodeInvalidUnsubscribeParams = 1106
	// CodeInvalidJSONRPCVersion is 1107 (HTTP 400): JSON RPC version must be 2.0
	CodeInvalidJSONRPCVersion = 1107
	// CodeRPCMethodNotFound is 1200 (HTTP 404): RPC method not found
	CodeRPCMethodNotFound = 1200
	// CodeJSONRPCIDExceedsUint32 is 1300 (HTTP 400): JSON RPC ID exceeds uint32
	CodeJSONRPCIDExceedsUint32 = 1300
	// CodeNoTradePermission is 1400 (HTTP 403): Signer does not have trade permission
	CodeNoTradePermission = 1400
	// CodeMainAccIDInvalid is 1500 (HTTP 400): Request must contain a valid main account ID
	CodeMainAccIDInvalid = 1500
	// CodeSignerUnauthorized is 2000 (HTTP 403): Signature is from an unauthorized signer
	CodeSignerUnauthorized = 2000
	// CodeSignatureExpired is 2001 (HTTP 403): Signature has expired
	CodeSignatureExpired = 2001
	// CodeSignatureDoesNotMatchPayload is 2002 (HTTP 403): Signature does not match payload
	CodeSignatureDoesNotMatchPayload = 2002
	// CodeOrderSubAccountDoesNotMatchLoggedInUser is 2003 (HTTP 403): Order sub account does not match logged in user
	CodeOrderSubAccountDoesNotMatchLoggedInUser = 2003
	// CodeSessionKeySignerExpired is 2004 (HTTP 403): Signature is from an expired session key
	CodeSessionKeySignerExpired = 2004
	// CodeSignatureInvalidV is 2005 (HTTP 403): Signature V must be 27/28
	CodeSignatureInvalidV = 2005
	// CodeSignatureInvalidRSLength is 2006 (HTTP 403): Signature R/S must have exactly 64 characters long without 0x prefix
	// Note: The message is misleading: send r and s as "0x" + 64 hex characters. Without 0x the server reads them as 0 and the signature fails to verify.
	CodeSignatureInvalidRSLength = 2006
	// CodeSignatureSIsNotCurveLowerHalf is 2007 (HTTP 403): Signature S must be in the lower half of the curve
	CodeSignatureSIsNotCurveLowerHalf = 2007
	// CodeSignatureExpirationTooLong is 2008 (HTTP 403): Signature exceeds maximum allowed duration.
	CodeSignatureExpirationTooLong = 2008
	// CodeOrderIDShouldBeEmpty is 2010 (HTTP 400): Order ID should be empty when creating an order
	CodeOrderIDShouldBeEmpty = 2010
	// CodeClientOrderIDShouldBeSupplied is 2011 (HTTP 400): Client Order ID should be supplied when creating an order
	CodeClientOrderIDShouldBeSupplied = 2011
	// CodeClientOrderIDOverlaps is 2012 (HTTP 400): Client Order ID overlaps with existing active order
	CodeClientOrderIDOverlaps = 2012
	// CodeClientOrderIDRepeats is 2013 (HTTP 400): Client Order ID repeats with the last order
	CodeClientOrderIDRepeats = 2013
	// CodeMarketOrderWithLimitPrice is 2020 (HTTP 400): Market Order must always be supplied without a limit price
	CodeMarketOrderWithLimitPrice = 2020
	// CodeLimitOrderWithoutLimitPrice is 2021 (HTTP 400): Limit Order must always be supplied with a limit price
	CodeLimitOrderWithoutLimitPrice = 2021
	// CodeInvalidTimeInForceOrderbook is 2030 (HTTP 400): Orderbook Orders must have a TimeInForce of GTT/IOC/FOK
	CodeInvalidTimeInForceOrderbook = 2030
	// CodeInvalidTimeInForceRFQ is 2031 (HTTP 400): RFQ Orders must have a TimeInForce of GTT/AON/IOC/FOK
	CodeInvalidTimeInForceRFQ = 2031
	// CodePostOnlyWhenTakerOrder is 2032 (HTTP 400): Post Only can only be set to true for GTT/AON orders
	CodePostOnlyWhenTakerOrder = 2032
	// CodeLegsEmpty is 2040 (HTTP 400): Order must contain at least one leg
	CodeLegsEmpty = 2040
	// CodeLegsNotSorted is 2041 (HTTP 400): Order Legs must be sorted by Derivative.Instrument/Underlying/BaseCurrency/Expiration/StrikePrice
	CodeLegsNotSorted = 2041
	// CodeLegsMultipleOrderbook is 2042 (HTTP 400): Orderbook Orders must contain only one leg
	CodeLegsMultipleOrderbook = 2042
	// CodeNonEmptyState is 2050 (HTTP 400): Order state must be empty upon creation
	CodeNonEmptyState = 2050
	// CodeExecutionMetadataShouldBeEmpty is 2051 (HTTP 400): Order execution metadata must be empty upon creation
	CodeExecutionMetadataShouldBeEmpty = 2051
	// CodeInactiveDerivative is 2060 (HTTP 400): Order Legs contain one or more inactive derivative
	CodeInactiveDerivative = 2060
	// CodeInstrumentNotSupported is 2061 (HTTP 400): Unsupported Instrument Requested
	CodeInstrumentNotSupported = 2061
	// CodeNumContractsUnderMinSize is 2062 (HTTP 400): Order size smaller than min size
	CodeNumContractsUnderMinSize = 2062
	// CodeNumContractsUnderMinBlockSize is 2063 (HTTP 400): Order size smaller than min block size in block trade venue
	CodeNumContractsUnderMinBlockSize = 2063
	// CodeInvalidLimitPriceTick is 2064 (HTTP 400): Invalid limit price tick
	CodeInvalidLimitPriceTick = 2064
	// CodeInvalidContractGrainSize is 2065 (HTTP 400): Order size too granular
	CodeInvalidContractGrainSize = 2065
	// CodeNotionalBelowMinimum is 2066 (HTTP 400): Order below minimum notional. Please try again with a higher price or size.
	CodeNotionalBelowMinimum = 2066
	// CodePositionClosingNotionalBelowMinimum is 2067 (HTTP 400): Order below minimum notional. Please try reducing your position again with a higher price or size.
	CodePositionClosingNotionalBelowMinimum = 2067
	// CodeLiquidationOrderNotSupported is 2070 (HTTP 400): Liquidation Order is not supported
	CodeLiquidationOrderNotSupported = 2070
	// CodeInsufficientMargin is 2080 (HTTP 400): Insufficient margin to create order
	CodeInsufficientMargin = 2080
	// CodeMaximumPositionSizeExceeded is 2081 (HTTP 400): Order Fill would result in exceeding maximum position size
	CodeMaximumPositionSizeExceeded = 2081
	// CodeFailedPreOrderCheck is 2082 (HTTP 400): Pre-order check failed
	CodeFailedPreOrderCheck = 2082
	// CodeMaximumLeverageConfigPositionSizeExceeded is 2083 (HTTP 400): Order Fill would result in exceeding maximum position size under current configurable leverage tier
	CodeMaximumLeverageConfigPositionSizeExceeded = 2083
	// CodeFailedPostOrderCheck is 2084 (HTTP 400): Post-order check failed
	CodeFailedPostOrderCheck = 2084
	// CodeMaxOpenOrdersExceeded is 2090 (HTTP 429): Max open orders exceeded
	CodeMaxOpenOrdersExceeded = 2090
	// CodeSessionOrderReduceOnlyRequired is 2091 (HTTP 403): As a precaution, only position-reducing (`reduce_only` as true) orders are currently allowed on your account. Please contact support so we...
	CodeSessionOrderReduceOnlyRequired = 2091
	// CodeInvalidInitialLeverage is 2100 (HTTP 400): Invalid initial leverage
	CodeInvalidInitialLeverage = 2100
	// CodeVaultsCannotConfigureLeverage is 2101 (HTTP 400): Vaults cannot configure leverage
	CodeVaultsCannotConfigureLeverage = 2101
	// CodeMarginTypeChangeFailedHasOpenPosition is 2102 (HTTP 400): Margin type change failed, has open position for this instrument
	CodeMarginTypeChangeFailedHasOpenPosition = 2102
	// CodeMarginTypeChangeFailedHasOpenOrders is 2103 (HTTP 400): Margin type change failed, has open orders for this instrument
	CodeMarginTypeChangeFailedHasOpenOrders = 2103
	// CodeMarginTypeNotSupported is 2104 (HTTP 400): Margin type not supported
	CodeMarginTypeNotSupported = 2104
	// CodeMarginTypeChangeFailed is 2105 (HTTP 400): Margin type change failed
	CodeMarginTypeChangeFailed = 2105
	// CodeNewLeverageBelowMinimum is 2107 (HTTP 400): Attempted to set leverage below minimum
	CodeNewLeverageBelowMinimum = 2107
	// CodeNewLeverageAboveMaximum is 2108 (HTTP 400): Attempted to set leverage above maximum
	CodeNewLeverageAboveMaximum = 2108
	// CodeInvalidTriggerBy is 2110 (HTTP 400): Invalid trigger by
	CodeInvalidTriggerBy = 2110
	// CodeUnsupportedTriggerBy is 2111 (HTTP 400): Unsupported trigger by
	CodeUnsupportedTriggerBy = 2111
	// CodeInvalidTriggerOrder is 2112 (HTTP 400): Invalid trigger order
	CodeInvalidTriggerOrder = 2112
	// CodeEmptyTriggerPrice is 2113 (HTTP 400): Trigger price must be non-zero
	CodeEmptyTriggerPrice = 2113
	// CodeInvalidPTPSLReduceOnly is 2114 (HTTP 400): Invalid position linked TPSL orders, position linked TPSL must be a reduce-only order
	CodeInvalidPTPSLReduceOnly = 2114
	// CodeInvalidPTPSLSize is 2115 (HTTP 400): Invalid position linked TPSL orders, position linked TPSL must not have smaller size than the position
	CodeInvalidPTPSLSize = 2115
	// CodePTPSLOrderAlreadyExists is 2116 (HTTP 400): Position linked TPSL order for this asset already exists
	CodePTPSLOrderAlreadyExists = 2116
	// CodePTPSLMustBeFromWebOrMobile is 2117 (HTTP 400): Position linked TPSL orders must be created from web or mobile clients
	CodePTPSLMustBeFromWebOrMobile = 2117
	// CodeInvalidTriggerPriceTick is 2118 (HTTP 400): Invalid trigger price tick
	CodeInvalidTriggerPriceTick = 2118
	// CodeRPIOrderNotSupported is 2120 (HTTP 400): RPI orders are not supported yet
	CodeRPIOrderNotSupported = 2120
	// CodeRPIOrderMustBeLimit is 2121 (HTTP 400): RPI order must be a limit order
	CodeRPIOrderMustBeLimit = 2121
	// CodeRPIOrderMustBePostOnly is 2122 (HTTP 400): RPI order must be post-only
	CodeRPIOrderMustBePostOnly = 2122
	// CodeRPIOrderMustBeFromApiSource is 2123 (HTTP 400): RPI order must be from API source
	CodeRPIOrderMustBeFromApiSource = 2123
	// CodeECNOrderNotSupported is 2130 (HTTP 400): ECN orders are not supported yet
	CodeECNOrderNotSupported = 2130
	// CodeECNOrderMustBeGTT is 2131 (HTTP 400): ECN order must be a GTT order
	CodeECNOrderMustBeGTT = 2131
	// CodeECNOrderMustBeLimit is 2132 (HTTP 400): ECN order must be a limit order
	CodeECNOrderMustBeLimit = 2132
	// CodeECNOrderMustBePostOnly is 2133 (HTTP 400): ECN order must be post-only
	CodeECNOrderMustBePostOnly = 2133
	// CodeECNOrderMustBeFromApiSource is 2134 (HTTP 400): ECN order must be from API source
	CodeECNOrderMustBeFromApiSource = 2134
	// CodeECNOrderMustNotBeReduceOnly is 2135 (HTTP 400): ECN order must not be a reduce-only order
	CodeECNOrderMustNotBeReduceOnly = 2135
	// CodeECNOrderMustNotBeConditional is 2136 (HTTP 400): ECN order must not be a conditional order
	CodeECNOrderMustNotBeConditional = 2136
	// CodeRfqSubAccountDoesNotMatchLoggedInUser is 2141 (HTTP 403): RFQ sub account does not match logged in user
	CodeRfqSubAccountDoesNotMatchLoggedInUser = 2141
	// CodeRfqInstrumentNotStablePerp is 2142 (HTTP 400): RFQ instrument must be a stable perpetual
	CodeRfqInstrumentNotStablePerp = 2142
	// CodeRfqSizeBelowMinimum is 2143 (HTTP 400): RFQ size is below the instrument minimum size
	CodeRfqSizeBelowMinimum = 2143
	// CodeRfqSizeAboveMaximum is 2144 (HTTP 400): RFQ size exceeds the instrument maximum position size
	CodeRfqSizeAboveMaximum = 2144
	// CodeRfqInvalidExpiry is 2145 (HTTP 400): RFQ expiry is invalid
	CodeRfqInvalidExpiry = 2145
	// CodeRfqAlreadyExistsForAsset is 2146 (HTTP 400): An open RFQ already exists for this sub account and instrument
	CodeRfqAlreadyExistsForAsset = 2146
	// CodeStablePerpRequiresMultiAssetMode is 2147 (HTTP 400): stable perp orders require a multi-asset-mode sub-account
	CodeStablePerpRequiresMultiAssetMode = 2147
	// CodeVaultCannotTrade is 2148 (HTTP 400): a vault whose investment currency is not its quote currency cannot trade
	CodeVaultCannotTrade = 2148
	// CodeNoOrdersProvided is 2220 (HTTP 400): No orders provided
	CodeNoOrdersProvided = 2220
	// CodeNotTPSLOrder is 2222 (HTTP 400): Order is not a TPSL order
	CodeNotTPSLOrder = 2222
	// CodeUnsupportedBulkOrders is 2223 (HTTP 400): Unsupported bulk orders type
	CodeUnsupportedBulkOrders = 2223
	// CodeInvalidOCO is 2224 (HTTP 400): Invalid OCO orders
	CodeInvalidOCO = 2224
	// CodeInvalidOCOInvalidLeg is 2225 (HTTP 400): OCO orders have invalid legs
	CodeInvalidOCOInvalidLeg = 2225
	// CodeInvalidOCOMismatchedLegs is 2226 (HTTP 400): OCO order take profit and stop loss legs must share the same instrument, size and direction
	CodeInvalidOCOMismatchedLegs = 2226
	// CodeInvalidOSO is 2227 (HTTP 400): Invalid OSO orders
	CodeInvalidOSO = 2227
	// CodeInvalidOSOInvalidLeg is 2228 (HTTP 400): OSO orders have invalid legs
	CodeInvalidOSOInvalidLeg = 2228
	// CodeInvalidOSOMismatchedLegs is 2229 (HTTP 400): OSO orders must share the same instrument and size, with main order direction opposite to TPSL orders
	CodeInvalidOSOMismatchedLegs = 2229
	// CodeInvalidOSOTriggerPrice is 2230 (HTTP 400): OSO orders has invalid trigger price
	CodeInvalidOSOTriggerPrice = 2230
	// CodeInvalidPTPSL is 2231 (HTTP 400): Invalid position linked TPSL orders
	CodeInvalidPTPSL = 2231
	// CodeInvalidPTPSLOrderLinkage is 2232 (HTTP 400): Invalid position linked TPSL orders, position linked TPSL must not have order linkage
	CodeInvalidPTPSLOrderLinkage = 2232
	// CodeBothOrderIDAndClientOrderIDProvided is 2233 (HTTP 400): Both order ID and client order ID cannot be provided
	CodeBothOrderIDAndClientOrderIDProvided = 2233
	// CodeInvalidBulkOrdersAssetMismatch is 2234 (HTTP 400): Bulk create orders must have the same instrument
	CodeInvalidBulkOrdersAssetMismatch = 2234
	// CodeBulkOrdersMaxCountExceeded is 2235 (HTTP 400): Bulk orders count exceeds the maximum allowed
	CodeBulkOrdersMaxCountExceeded = 2235
	// CodeBulkOrdersNotSupportTriggerOrder is 2236 (HTTP 400): Bulk orders does not support trigger order
	CodeBulkOrdersNotSupportTriggerOrder = 2236
	// CodeBulkOrdersNotFromApiSource is 2237 (HTTP 400): Bulk orders must be from API source
	CodeBulkOrdersNotFromApiSource = 2237
	// CodeSplitTPSLMustNotBePositionLinkedTPSL is 2238 (HTTP 400): Split TPSL orders must not be position-linked TPSL
	CodeSplitTPSLMustNotBePositionLinkedTPSL = 2238
	// CodeSplitTPSLMustBeReduceOnly is 2239 (HTTP 400): Split TPSL orders must be reduce-only
	CodeSplitTPSLMustBeReduceOnly = 2239
	// CodeSplitTPSLCreatesMustNotContainNonSplit is 2240 (HTTP 400): If creating split TPSL orders, can only specify split TPSL orders in the creation array
	CodeSplitTPSLCreatesMustNotContainNonSplit = 2240
	// CodeSplitTPSLCreatesExceedsSetSize is 2241 (HTTP 400): Split TPSL order count exceeds maximum allowed set size
	CodeSplitTPSLCreatesExceedsSetSize = 2241
	// CodeSplitTPSLNotSupported is 2242 (HTTP 400): Split TPSL functionality not supported; you may be using a deprecated API, or this functionality is temporarily disabled
	CodeSplitTPSLNotSupported = 2242
	// CodeSplitTPSLSetAlreadyExists is 2243 (HTTP 400): Split TPSL set already exists for this asset. Please modify the existing set of split TPSL orders.
	CodeSplitTPSLSetAlreadyExists = 2243
	// CodeCreatingSplitTPSLWithoutExistingPosition is 2244 (HTTP 400): Split TPSL creation only allowed for instruments with already-existing positions.
	CodeCreatingSplitTPSLWithoutExistingPosition = 2244
	// CodeCreatingSplitTPSLExceedingPositionSize is 2245 (HTTP 400): Split TPSL creation exceeds position size.
	CodeCreatingSplitTPSLExceedingPositionSize = 2245
	// CodeModifyingSplitTPSLMismatchedCancels is 2246 (HTTP 400): Split TPSL modification requires all existing split TPSL orders to be cancelled
	CodeModifyingSplitTPSLMismatchedCancels = 2246
	// CodeCancelTTLDisabled is 2300 (HTTP 400): Order cancel time-to-live settings currently disabled.
	CodeCancelTTLDisabled = 2300
	// CodeCancelTTLMaxExceeded is 2301 (HTTP 400): Order cancel time-to-live exceeds maximum allowed value.
	CodeCancelTTLMaxExceeded = 2301
	// CodeReduceOnlyOrderWithNoPosition is 2400 (HTTP 400): Reduce only order with no position
	CodeReduceOnlyOrderWithNoPosition = 2400
	// CodeReduceOnlyOrderIncreaseSize is 2401 (HTTP 400): Reduce only order must not increase position size
	CodeReduceOnlyOrderIncreaseSize = 2401
	// CodeReduceOnlyOrderSizeExceeded is 2402 (HTTP 400): Reduce only order size exceeds maximum allowed value
	CodeReduceOnlyOrderSizeExceeded = 2402
	// CodeReplaceOrderNumOrdersMismatch is 2413 (HTTP 400): Replace order failed, number of orders provided does not match the number of orders to replace
	CodeReplaceOrderNumOrdersMismatch = 2413
	// CodeSpotOrderNotSupported is 2450 (HTTP 400): Spot order is not supported
	CodeSpotOrderNotSupported = 2450
	// CodeSpotOrderReduceOnlyNotSupported is 2451 (HTTP 400): Spot order must not be a reduce-only order
	CodeSpotOrderReduceOnlyNotSupported = 2451
	// CodeSpotOrderTPSLNotSupported is 2452 (HTTP 400): Spot order must not be a TPSL order
	CodeSpotOrderTPSLNotSupported = 2452
	// CodeSpotTradingBlockedDuringSocializedLoss is 2453 (HTTP 400): Spot trading is blocked during socialized loss
	CodeSpotTradingBlockedDuringSocializedLoss = 2453
	// CodeInvalidInstrument is 3000 (HTTP 400): Instrument is invalid
	CodeInvalidInstrument = 3000
	// CodeMMConfigNotFound is 3004 (HTTP 500): Instrument does not have a valid maintenance margin configuration
	CodeMMConfigNotFound = 3004
	// CodeAssetUnderlyingBalDecConfigNotFound is 3005 (HTTP 500): Instrument's underlying currency does not have a valid balance decimal configuration
	CodeAssetUnderlyingBalDecConfigNotFound = 3005
	// CodeAssetQuoteBalDecConfigNotFound is 3006 (HTTP 500): Instrument's quote currency does not have a valid balance decimal configuration
	CodeAssetQuoteBalDecConfigNotFound = 3006
	// CodeNotApplicableForSpotInstrument is 3007 (HTTP 400): API is not applicable for spot instruments
	CodeNotApplicableForSpotInstrument = 3007
	// CodeInvalidFundingAggregationTypeForStablePerp is 3008 (HTTP 400): Funding rate aggregation type is not applicable for stable perp instruments
	CodeInvalidFundingAggregationTypeForStablePerp = 3008
	// CodeInvalidLimit is 3011 (HTTP 400): Limit exceeds min or max value
	CodeInvalidLimit = 3011
	// CodeInvalidCursor is 3012 (HTTP 400): Cursor is invalid
	CodeInvalidCursor = 3012
	// CodeExactLimitNotSupported is 3013 (HTTP 400): Exact limit value is not supported
	CodeExactLimitNotSupported = 3013
	// CodeInvalidSubAccountID is 3020 (HTTP 400): Sub account ID must be an uint64 integer
	CodeInvalidSubAccountID = 3020
	// CodeInvalidOrderID is 3021 (HTTP 400): Either order ID or client order ID must be supplied
	CodeInvalidOrderID = 3021
	// CodeInvalidFeedRate is 3030 (HTTP 400): Feed rate is invalid
	CodeInvalidFeedRate = 3030
	// CodeInvalidDepth is 3031 (HTTP 400): Depth is invalid
	CodeInvalidDepth = 3031
	// CodeInvalidCandlestickInterval is 3040 (HTTP 400): Candlestick interval is invalid
	CodeInvalidCandlestickInterval = 3040
	// CodeInvalidCandlestickType is 3041 (HTTP 400): Candlestick type is invalid
	CodeInvalidCandlestickType = 3041
	// CodeInvalidCandlestickTypeForSpot is 3042 (HTTP 400): Candlestick type is not applicable for spot instruments
	CodeInvalidCandlestickTypeForSpot = 3042
	// CodeInvalidCandlestickTypeForStablePerp is 3043 (HTTP 400): Candlestick type not supported for this instrument
	CodeInvalidCandlestickTypeForStablePerp = 3043
	// CodeInsufficientBalanceToTransfer is 4000 (HTTP 400): Insufficient balance to complete transfer
	CodeInsufficientBalanceToTransfer = 4000
	// CodeTransferFailedReasonUnrefined is 4002 (HTTP 400): Transfer failed with an unrefined failure reason, please report to GRVT
	CodeTransferFailedReasonUnrefined = 4002
	// CodeBothTransferWalletTypeMustBeProvided is 4004 (HTTP 400): Both transfer wallet types must be provided
	CodeBothTransferWalletTypeMustBeProvided = 4004
	// CodeInvalidWalletTypeForFundingAccount is 4005 (HTTP 400): Invalid wallet type for funding account
	CodeInvalidWalletTypeForFundingAccount = 4005
	// CodeInvalidWalletTypeForSubAccount is 4006 (HTTP 400): Invalid wallet type for sub account
	CodeInvalidWalletTypeForSubAccount = 4006
	// CodeDuplicatedTransfer is 4007 (HTTP 400): Transfer failed because signature is an exact duplicate of another recently-observed transfer.
	CodeDuplicatedTransfer = 4007
	// CodeCurrencyNotAllowedInWallet is 4008 (HTTP 400): Currency is not allowed in the target wallet type
	CodeCurrencyNotAllowedInWallet = 4008
	// CodeUnspecifiedTransferType is 4009 (HTTP 400): Please specify the transfer type
	CodeUnspecifiedTransferType = 4009
	// CodeWithdrawalWalletNotSupported is 4010 (HTTP 400): This wallet is not supported. Please try another wallet.
	CodeWithdrawalWalletNotSupported = 4010
	// CodeCVRZeroNotAllowedInFuturesWallet is 4011 (HTTP 400): This currency cannot be used as collateral in a multi-asset margin futures wallet.
	CodeCVRZeroNotAllowedInFuturesWallet = 4011
	// CodeCollateralLimitExceeded is 4012 (HTTP 400): Transfer would push your holdings of this currency above the per-user collateral limit.
	CodeCollateralLimitExceeded = 4012
	// CodeCurrencyTransferNotAllowed is 4014 (HTTP 400): This currency has been disabled for transfers and withdrawals.
	CodeCurrencyTransferNotAllowed = 4014
	// CodeNoTransferPermission is 4015 (HTTP 403): Signer does not have transfer permission
	CodeNoTransferPermission = 4015
	// CodeTransferWithdrawalBlocked is 4016 (HTTP 403): As a precaution, funds movements on your account are temporarily unavailable. Please contact support so we can help complete the necessary...
	CodeTransferWithdrawalBlocked = 4016
	// CodeGrvtExternalTransferNotAllowed is 4018 (HTTP 400): $GRVT is disabled for external transfer
	CodeGrvtExternalTransferNotAllowed = 4018
	// CodeWithdrawalWalletUnderReview is 4019 (HTTP 400): Your wallet has been put under review. Please reach out to kyc@grvt.io for any questions.
	CodeWithdrawalWalletUnderReview = 4019
	// CodeCurrencyNotEnabledAsCollateral is 4020 (HTTP 400): This currency is not enabled as collateral for the destination sub account. Enable it in your collateral preferences first.
	CodeCurrencyNotEnabledAsCollateral = 4020
	// CodeInsufficientFundingVaultShares is 4021 (HTTP 400): The funding account has fewer vault shares than requested, after reserving any pending redemption.
	CodeInsufficientFundingVaultShares = 4021
	// CodeInsufficientTradingVaultShares is 4022 (HTTP 400): The trading account has fewer vault shares than requested.
	CodeInsufficientTradingVaultShares = 4022
	// CodeVaultShareTransferRoute is 4023 (HTTP 400): Vault shares move only between your own funding account and your own multi-asset trading accounts.
	CodeVaultShareTransferRoute = 4023
	// CodeInvalidTransferMetadata is 5000 (HTTP 400): Transfer Metadata does not match the expected structure.
	CodeInvalidTransferMetadata = 5000
	// CodeInvalidTransferProvider is 5001 (HTTP 400): Transfer Provider does not match the expected provider.
	CodeInvalidTransferProvider = 5001
	// CodeInvalidDirection is 5002 (HTTP 400): Direction of the transfer does not match the expected direction.
	CodeInvalidDirection = 5002
	// CodeInvalidEndpoint is 5003 (HTTP 400): Endpoint account ID is invalid.
	CodeInvalidEndpoint = 5003
	// CodeFundingAccountDoesntExist is 5004 (HTTP 400): Funding account does not exist in our system.
	CodeFundingAccountDoesntExist = 5004
	// CodeInvalidChainID is 5005 (HTTP 400): Invalid ChainID for the transfer request.
	CodeInvalidChainID = 5005
	// CodeLongCancelOnDisconnectCountdown is 6000 (HTTP 400): Countdown time is bigger than 300s supported
	CodeLongCancelOnDisconnectCountdown = 6000
	// CodeDeriskMMRatioOutOfRange is 6100 (HTTP 400): Derisk MM Ratio is out of range
	CodeDeriskMMRatioOutOfRange = 6100
	// CodeInvalidVaultID is 7000 (HTTP 400): Vault ID provided is invalid and does not belong to any vault
	CodeInvalidVaultID = 7000
	// CodeInsufficientVaultLPToken is 7001 (HTTP 400): Vault does not have sufficient LP token balance
	CodeInsufficientVaultLPToken = 7001
	// CodeOngoingRedemption is 7002 (HTTP 400): User has an ongoing redemption
	CodeOngoingRedemption = 7002
	// CodeVaultNotActive is 7003 (HTTP 400): This vault has been delisted/closed.
	CodeVaultNotActive = 7003
	// CodeInvestmentExceedsCap is 7004 (HTTP 400): This investment would cause the vault to exceed its valuation cap.
	CodeInvestmentExceedsCap = 7004
	// CodeBurningMoreVaultTokensThanOwned is 7005 (HTTP 400): You are attempting to burn more vault tokens than you own.
	CodeBurningMoreVaultTokensThanOwned = 7005
	// CodeBurningTokenWhileActiveRedemption is 7006 (HTTP 400): You are attempting to burn vault tokens whilst having an active redemption request.
	CodeBurningTokenWhileActiveRedemption = 7006
	// CodeInvestorNotVaultLP is 7007 (HTTP 400): The investor is not an LP for this vault.
	CodeInvestorNotVaultLP = 7007
	// CodeOnlyAllowedToRedeemInVaultInvestmentCurrency is 7008 (HTTP 400): Vault redemption requests may only be submitted in the vault's investment currency.
	CodeOnlyAllowedToRedeemInVaultInvestmentCurrency = 7008
	// CodeInsufficientInvestorTokenBalanceForRedemption is 7009 (HTTP 400): Vault Investor does not have enough LP tokens to redeem.
	CodeInsufficientInvestorTokenBalanceForRedemption = 7009
	// CodeInvalidVaultInvestorID is 7012 (HTTP 400): Vault investor ID provided is invalid.
	CodeInvalidVaultInvestorID = 7012
	// CodeCrossExchangeVaultNotSupported is 7013 (HTTP 400): Cross-exchange vaults not supported
	CodeCrossExchangeVaultNotSupported = 7013
	// CodeOnlyAllowedToInvestInVaultInvestmentCurrency is 7014 (HTTP 400): Only allowed to invest in vault's investment currency
	CodeOnlyAllowedToInvestInVaultInvestmentCurrency = 7014
	// CodeVaultLpTokensLocked is 7015 (HTTP 400): Some of these vault shares are still within the vault's minimum investment period and cannot be redeemed yet.
	CodeVaultLpTokensLocked = 7015
	// CodeVaultConversionRateNotAllowed is 7017 (HTTP 400): The exchange rate is not allowed: it must be exactly 1 when both currencies are the same, and at most the current conversion rate otherwise.
	CodeVaultConversionRateNotAllowed = 7017
	// CodeVaultInvalidInvestSource is 7018 (HTTP 400): Invalid invest source: use the funding account with the funding wallet, or a spot or futures wallet of one of your own trading accounts...
	CodeVaultInvalidInvestSource = 7018
	// CodeVaultConversionPriceStale is 7019 (HTTP 400): A price this conversion needs is stale or not available yet. Please try again later.
	CodeVaultConversionPriceStale = 7019
	// CodeVaultConversionZeroOutput is 7027 (HTTP 400): The conversion would pay out nothing: the exchange rate or the amount is too small.
	CodeVaultConversionZeroOutput = 7027
	// CodeVaultInvestAlreadyExecuted is 7028 (HTTP 400): This signed vault investment has already been executed. Sign a new one to invest again.
	CodeVaultInvestAlreadyExecuted = 7028
	// CodeVaultInvestSourceNeedsSpotTransfers is 7035 (HTTP 400): Spot transfers are not enabled, so only the funding account or the futures wallet of a trading account, in USDT, can pay this investment.
	CodeVaultInvestSourceNeedsSpotTransfers = 7035
	// CodeUnknownTransactionType is 7100 (HTTP 500): Unknown transaction type
	CodeUnknownTransactionType = 7100
	// CodeTransferAccountNotFound is 7101 (HTTP 400): Transfer account not found
	CodeTransferAccountNotFound = 7101
	// CodeTransferSubAccountNotFound is 7102 (HTTP 400): Transfer sub-account not found
	CodeTransferSubAccountNotFound = 7102
	// CodeChargedTradingFeeBelowConfigMinimum is 7103 (HTTP 500): Charged trading fee below the config minimum
	CodeChargedTradingFeeBelowConfigMinimum = 7103
	// CodeTransferSubAccountNotUnderAccount is 7104 (HTTP 400): Transfer sub-account doesn't belong to the transfer main account
	CodeTransferSubAccountNotUnderAccount = 7104
	// CodeTransferBetweenSubAccOfDifferentAccount is 7105 (HTTP 400): Transfer between subaccounts of different accounts
	CodeTransferBetweenSubAccOfDifferentAccount = 7105
	// CodeDelistCreateOrderBlocked is 7303 (HTTP 400): Order creations have been blocked for this delisted asset.
	CodeDelistCreateOrderBlocked = 7303
	// CodeDelistPositionOpenBlocked is 7304 (HTTP 400): Only position-reducing orders (`reduce_only` as true) allowed for this asset right now.
	CodeDelistPositionOpenBlocked = 7304
	// CodeMaintenanceCreateOrderBlocked is 7306 (HTTP 400): Order creation is temporarily blocked during the corporate action / maintenance window
	CodeMaintenanceCreateOrderBlocked = 7306
	// CodeAddMarginFailed is 7450 (HTTP 400): Add margin failed
	CodeAddMarginFailed = 7450
	// CodeAddMarginToEmptyPosition is 7451 (HTTP 400): Add margin to empty position
	CodeAddMarginToEmptyPosition = 7451
	// CodeAddMarginToNonIsolatedPosition is 7452 (HTTP 400): Add margin to non isolated position
	CodeAddMarginToNonIsolatedPosition = 7452
	// CodeMaxAddableAmountExceeded is 7453 (HTTP 400): Max addable amount exceeded
	CodeMaxAddableAmountExceeded = 7453
	// CodeMaxRemovableAmountExceeded is 7454 (HTTP 400): Max removable amount exceeded
	CodeMaxRemovableAmountExceeded = 7454
	// CodeNotIsolatedMarginPosition is 7455 (HTTP 400): Not isolated margin position
	CodeNotIsolatedMarginPosition = 7455
	// CodeBuilderFeeNegative is 7501 (HTTP 400): Builder Fee can't be negative.
	CodeBuilderFeeNegative = 7501
	// CodeBuilderNotAuthorized is 7504 (HTTP 400): Builder is not authorized for the specified user.
	CodeBuilderNotAuthorized = 7504
	// CodeBuilderFeeExceedsAuthorizationLimit is 7505 (HTTP 400): Builder Fee exceeds authorized limit.
	CodeBuilderFeeExceedsAuthorizationLimit = 7505
	// CodeBuilderMissing is 7506 (HTTP 400): Builder Account is missing but builder fee is provided.
	CodeBuilderMissing = 7506
	// CodeSlippageFeatureDisabled is 7600 (HTTP 400): Order slippage protection is not enabled.
	CodeSlippageFeatureDisabled = 7600
	// CodeSlippageRequiresIOCLimitOrder is 7601 (HTTP 400): Slippage protection is only supported on IOC limit orders.
	CodeSlippageRequiresIOCLimitOrder = 7601
	// CodeSlippageBelowMinimum is 7602 (HTTP 400): Slippage is below the minimum allowed value.
	CodeSlippageBelowMinimum = 7602
	// CodeSlippageExceedsPriceProtectionBand is 7603 (HTTP 400): Slippage exceeds the asset's price protection band.
	CodeSlippageExceedsPriceProtectionBand = 7603
	// CodeSfpIndicativeNotQualifiedMaker is 7701 (HTTP 403): You are not a qualified market maker or designated market maker for this instrument.
	CodeSfpIndicativeNotQualifiedMaker = 7701
	// CodeSfpOrderNotSupported is 7704 (HTTP 400): Stable Funding Perpetual orders are not yet supported.
	CodeSfpOrderNotSupported = 7704
	// CodeSfpInstrumentMismatch is 7705 (HTTP 400): The order's instrument does not match the referenced RFQ's instrument.
	CodeSfpInstrumentMismatch = 7705
	// CodeSfpPrivateQuoteNotSupported is 7706 (HTTP 400): Private maker quotes are not yet supported.
	CodeSfpPrivateQuoteNotSupported = 7706
	// CodeSfpRfqNotLive is 7707 (HTTP 400): The referenced RFQ is not open.
	CodeSfpRfqNotLive = 7707
	// CodeSfpRfqAlreadyHasTakerOrder is 7708 (HTTP 400): The referenced RFQ already has a taker order.
	CodeSfpRfqAlreadyHasTakerOrder = 7708
	// CodeSfpTakerInvalidTimeInForce is 7709 (HTTP 400): Invalid time in force for a Stable Funding Perpetual taker order.
	CodeSfpTakerInvalidTimeInForce = 7709
	// CodeSfpMarketOrderNotAllowed is 7711 (HTTP 400): Market orders are not allowed for Stable Funding Perpetual taker orders; a market-order slippage bound must be set.
	CodeSfpMarketOrderNotAllowed = 7711
	// CodeRfqIDNotAllowedForNonSFP is 7712 (HTTP 400): Non-Stable-Funding-Perpetual orders must always be supplied without rfq_id.
	CodeRfqIDNotAllowedForNonSFP = 7712
	// CodeUsdcCollateralDisabled is 7723 (HTTP 400): USDC must be enabled as collateral on this sub account to trade USDC-quoted instruments.
	CodeUsdcCollateralDisabled = 7723
	// CodeSfpPostOnlyNotAllowedForRetail is 7724 (HTTP 400): Post-only orders are not allowed on Stable Funding Perpetuals.
	CodeSfpPostOnlyNotAllowedForRetail = 7724
	// CodeSfpEndpointNotSupported is 7725 (HTTP 403): This endpoint is not supported for stable funding.
	CodeSfpEndpointNotSupported = 7725
	// CodeSfpMarketClosed is 7726 (HTTP 400): The Stable Funding Perpetual market is closed.
	CodeSfpMarketClosed = 7726
	// CodeCurrencyNotConvertible is 7801 (HTTP 400): This currency is not enabled for stable coin convert.
	CodeCurrencyNotConvertible = 7801
	// CodePriceOutOfConvertBand is 7802 (HTTP 400): The index price of one of the currencies is outside the permitted convert band. Please try again later.
	CodePriceOutOfConvertBand = 7802
	// CodeMissingIndexPrice is 7803 (HTTP 400): An index price required for this conversion is unavailable. Please try again later.
	CodeMissingIndexPrice = 7803
	// CodeInexactConversion is 7805 (HTTP 400): This amount cannot be converted exactly between the two currencies’ decimals. Please adjust the amount.
	CodeInexactConversion = 7805
	// CodeNegativeBalance is 7811 (HTTP 400): This conversion would leave a negative balance.
	CodeNegativeBalance = 7811
	// CodeValueOverflow is 7812 (HTTP 400): The convert amount is too large to be represented. Please use a smaller amount.
	CodeValueOverflow = 7812
	// CodeTradingCouponNotTransferable is 7901 (HTTP 400): Trading coupons move only by an adjustment or a liquidation.
	CodeTradingCouponNotTransferable = 7901
)

Error codes from the contract. Compare with APIError.Code:

var apiErr *grvt.APIError
if errors.As(err, &apiErr) && apiErr.Code == grvt.CodeSignatureExpired { ... }
View Source
const (
	// SignatureTTL is the default expiration for gateway signatures, in ns (server cap: 30 days).
	SignatureTTL int64 = 24 * 3600 * 1_000_000_000
	// LoginSignatureTTL is the wallet-login expiration, in ns (the server allows at most 5 minutes).
	LoginSignatureTTL int64 = 4 * 60 * 1_000_000_000
)
View Source
const (
	// ConnectTimeout bounds one connect (login + handshake).
	ConnectTimeout = 10 * time.Second
	// Heartbeat is the client ping interval. The server pings every 5s too.
	Heartbeat = 10 * time.Second
	// IdleTimeout: no frame at all for this long means the connection is dead.
	IdleTimeout = 30 * time.Second
	// ResyncTimeout: no snapshot this long after a gap re-subscribe means reconnect.
	ResyncTimeout = behavior.ResyncTimeout
)
View Source
const BaseDecimals = -1

BaseDecimals marks a field scaled by the instrument's base_decimals in OrderChecks.Scales.

View Source
const ContractVersion = "0.1.0"

ContractVersion is the contract version this code was generated from. The module's own version is its independent git tag (vX.Y.Z) in github.com/gravity-technologies/grvt-sdk-go.

View Source
const (

	// LiteWSPath is the lite WebSocket path; the full one is /ws/full.
	LiteWSPath = "/ws/lite"
)

Lite names outside the models, from the contract: the JSON-RPC envelope (JSONRPCRequest, JSONRPCResponse, Error), the routing fields every stream frame shares, and the HTTP error body (transport.lite.http_error_body).

View Source
const RateLimitCode = behavior.RateLimitCode

RateLimitCode is the rate-limit error code. Always retryable for reads.

View Source
const ReadAttempts = behavior.ReadAttempts

ReadAttempts is how many times a read is tried in all.

Variables

View Source
var (
	RPCEdgeAPIKeyLogin = RPCSpec{Method: "auth/api_key/login", Gateway: GatewayEdge, Path: "/auth/api_key/login", Auth: false}
	RPCEdgeWalletLogin = RPCSpec{Method: "auth/wallet/login", Gateway: GatewayEdge, Path: "/auth/wallet/login", Auth: false}
)

Edge (login) routes.

View Source
var (
	RPCAccountAggregatedAccountSummary         = RPCSpec{Method: "v1/aggregated_account_summary", Gateway: GatewayTrading, Path: "/full/v1/aggregated_account_summary", LitePath: "/lite/v1/aggregated_account_summary", Auth: true, Write: false, OrderEntry: false}
	RPCAccountFundingAccountSummary            = RPCSpec{Method: "v1/funding_account_summary", Gateway: GatewayTrading, Path: "/full/v1/funding_account_summary", LitePath: "/lite/v1/funding_account_summary", Auth: true, Write: false, OrderEntry: false}
	RPCAccountGetSubAccounts                   = RPCSpec{Method: "v1/get_sub_accounts", Gateway: GatewayTrading, Path: "/full/v1/get_sub_accounts", LitePath: "/lite/v1/get_sub_accounts", Auth: true, Write: false, OrderEntry: false}
	RPCAccountSpotAccountSummary               = RPCSpec{Method: "v1/spot_account_summary", Gateway: GatewayTrading, Path: "/full/v1/spot_account_summary", LitePath: "/lite/v1/spot_account_summary", Auth: true, Write: false, OrderEntry: false}
	RPCAccountSubAccountSummary                = RPCSpec{Method: "v1/account_summary", Gateway: GatewayTrading, Path: "/full/v1/account_summary", LitePath: "/lite/v1/account_summary", Auth: true, Write: false, OrderEntry: false}
	RPCAlgoOrderAlgoOrderHistory               = RPCSpec{Method: "v1/algo_order_history", Gateway: GatewayTrading, Path: "/full/v1/algo_order_history", LitePath: "/lite/v1/algo_order_history", Auth: true, Write: false, OrderEntry: false}
	RPCAlgoOrderAlgoSubOrderHistory            = RPCSpec{Method: "v1/algo_sub_order_history", Gateway: GatewayTrading, Path: "/full/v1/algo_sub_order_history", LitePath: "/lite/v1/algo_sub_order_history", Auth: true, Write: false, OrderEntry: false}
	RPCAlgoOrderCancelAlgoOrder                = RPCSpec{Method: "v1/cancel_algo_order", Gateway: GatewayTrading, Path: "/full/v1/cancel_algo_order", LitePath: "/lite/v1/cancel_algo_order", Auth: true, Write: true, OrderEntry: false}
	RPCAlgoOrderCreateAlgoOrder                = RPCSpec{Method: "v1/create_algo_order", Gateway: GatewayTrading, Path: "/full/v1/create_algo_order", LitePath: "/lite/v1/create_algo_order", Auth: true, Write: true, OrderEntry: false}
	RPCAlgoOrderGetAlgoOrder                   = RPCSpec{Method: "v1/get_algo_order", Gateway: GatewayTrading, Path: "/full/v1/get_algo_order", LitePath: "/lite/v1/get_algo_order", Auth: true, Write: false, OrderEntry: false}
	RPCAlgoOrderOpenAlgoOrders                 = RPCSpec{Method: "v1/open_algo_orders", Gateway: GatewayTrading, Path: "/full/v1/open_algo_orders", LitePath: "/lite/v1/open_algo_orders", Auth: true, Write: false, OrderEntry: false}
	RPCBuilderGetAuthorizedBuilders            = RPCSpec{Method: "v1/get_authorized_builders", Gateway: GatewayTrading, Path: "/full/v1/get_authorized_builders", LitePath: "/lite/v1/get_authorized_builders", Auth: true, Write: false, OrderEntry: false}
	RPCCandlestickCandlestick                  = RPCSpec{Method: "v1/kline", Gateway: GatewayMarketData, Path: "/full/v1/kline", LitePath: "/lite/v1/kline", Auth: false, Write: false, OrderEntry: false}
	RPCDeriskMmRatioSetDeriskMmRatio           = RPCSpec{Method: "v1/set_derisk_mm_ratio", Gateway: GatewayTrading, Path: "/full/v1/set_derisk_mm_ratio", LitePath: "/lite/v1/set_derisk_mm_ratio", Auth: true, Write: true, OrderEntry: false}
	RPCExecutionBuilderFillHistory             = RPCSpec{Method: "v1/builder_fill_history", Gateway: GatewayTrading, Path: "/full/v1/builder_fill_history", LitePath: "/lite/v1/builder_fill_history", Auth: true, Write: false, OrderEntry: false}
	RPCExecutionFillHistory                    = RPCSpec{Method: "v1/fill_history", Gateway: GatewayTrading, Path: "/full/v1/fill_history", LitePath: "/lite/v1/fill_history", Auth: true, Write: false, OrderEntry: false}
	RPCExecutionFundingPaymentHistory          = RPCSpec{Method: "v1/funding_payment_history", Gateway: GatewayTrading, Path: "/full/v1/funding_payment_history", LitePath: "/lite/v1/funding_payment_history", Auth: true, Write: false, OrderEntry: false}
	RPCExecutionInterestPaymentHistory         = RPCSpec{Method: "v1/interest_payment_history", Gateway: GatewayTrading, Path: "/full/v1/interest_payment_history", LitePath: "/lite/v1/interest_payment_history", Auth: true, Write: false, OrderEntry: false}
	RPCInitialLeverageGetAllInitialLeverage    = RPCSpec{Method: "v1/get_all_initial_leverage", Gateway: GatewayTrading, Path: "/full/v1/get_all_initial_leverage", LitePath: "/lite/v1/get_all_initial_leverage", Auth: true, Write: false, OrderEntry: false}
	RPCInitialLeverageSetInitialLeverage       = RPCSpec{Method: "v1/set_initial_leverage", Gateway: GatewayTrading, Path: "/full/v1/set_initial_leverage", LitePath: "/lite/v1/set_initial_leverage", Auth: true, Write: true, OrderEntry: false}
	RPCInstrumentGetAllCollateralAssetInfo     = RPCSpec{Method: "v1/get_all_collateral_asset_info", Gateway: GatewayMarketData, Path: "/full/v1/get_all_collateral_asset_info", LitePath: "/lite/v1/get_all_collateral_asset_info", Auth: false, Write: false, OrderEntry: false}
	RPCInstrumentGetAllInstruments             = RPCSpec{Method: "v1/all_instruments", Gateway: GatewayMarketData, Path: "/full/v1/all_instruments", LitePath: "/lite/v1/all_instruments", Auth: false, Write: false, OrderEntry: false}
	RPCInstrumentGetCurrency                   = RPCSpec{Method: "v1/currency", Gateway: GatewayMarketData, Path: "/full/v1/currency", LitePath: "/lite/v1/currency", Auth: false, Write: false, OrderEntry: false}
	RPCInstrumentGetFilteredInstruments        = RPCSpec{Method: "v1/instruments", Gateway: GatewayMarketData, Path: "/full/v1/instruments", LitePath: "/lite/v1/instruments", Auth: false, Write: false, OrderEntry: false}
	RPCInstrumentGetInstrument                 = RPCSpec{Method: "v1/instrument", Gateway: GatewayMarketData, Path: "/full/v1/instrument", LitePath: "/lite/v1/instrument", Auth: false, Write: false, OrderEntry: false}
	RPCInstrumentGetMarginRules                = RPCSpec{Method: "v1/margin_rules", Gateway: GatewayMarketData, Path: "/full/v1/margin_rules", LitePath: "/lite/v1/margin_rules", Auth: false, Write: false, OrderEntry: false}
	RPCInstrumentGetSupportedAssets            = RPCSpec{Method: "v1/supported_assets", Gateway: GatewayMarketData, Path: "/full/v1/supported_assets", LitePath: "/lite/v1/supported_assets", Auth: false, Write: false, OrderEntry: false}
	RPCOrderBulkOrders                         = RPCSpec{Method: "v2/bulk_orders", Gateway: GatewayTrading, Path: "/full/v2/bulk_orders", LitePath: "/lite/v2/bulk_orders", Auth: true, Write: true, OrderEntry: true, RefreshMetadataOn: []int{2062, 2064, 2065, 2066, 2067}}
	RPCOrderCancelAllOrders                    = RPCSpec{Method: "v1/cancel_all_orders", Gateway: GatewayTrading, Path: "/full/v1/cancel_all_orders", LitePath: "/lite/v1/cancel_all_orders", Auth: true, Write: true, OrderEntry: true}
	RPCOrderCancelOnDisconnect                 = RPCSpec{Method: "v1/cancel_on_disconnect", Gateway: GatewayTrading, Path: "/full/v1/cancel_on_disconnect", LitePath: "/lite/v1/cancel_on_disconnect", Auth: true, Write: true, OrderEntry: true}
	RPCOrderCancelOrder                        = RPCSpec{Method: "v1/cancel_order", Gateway: GatewayTrading, Path: "/full/v1/cancel_order", LitePath: "/lite/v1/cancel_order", Auth: true, Write: true, OrderEntry: true}
	RPCOrderCreateOrder                        = RPCSpec{Method: "v1/create_order", Gateway: GatewayTrading, Path: "/full/v1/create_order", LitePath: "/lite/v1/create_order", Auth: true, Write: true, OrderEntry: true, RefreshMetadataOn: []int{2062, 2064, 2065, 2066, 2067}}
	RPCOrderGetOrder                           = RPCSpec{Method: "v1/order", Gateway: GatewayTrading, Path: "/full/v1/order", LitePath: "/lite/v1/order", Auth: true, Write: false, OrderEntry: false}
	RPCOrderOpenOrders                         = RPCSpec{Method: "v1/open_orders", Gateway: GatewayTrading, Path: "/full/v1/open_orders", LitePath: "/lite/v1/open_orders", Auth: true, Write: false, OrderEntry: false}
	RPCOrderOrderHistory                       = RPCSpec{Method: "v1/order_history", Gateway: GatewayTrading, Path: "/full/v1/order_history", LitePath: "/lite/v1/order_history", Auth: true, Write: false, OrderEntry: false}
	RPCOrderbookOrderbookLevels                = RPCSpec{Method: "v1/book", Gateway: GatewayMarketData, Path: "/full/v1/book", LitePath: "/lite/v1/book", Auth: false, Write: false, OrderEntry: false}
	RPCPositionAddPositionMargin               = RPCSpec{Method: "v1/add_position_margin", Gateway: GatewayTrading, Path: "/full/v1/add_position_margin", LitePath: "/lite/v1/add_position_margin", Auth: true, Write: true, OrderEntry: false}
	RPCPositionGetPositionMarginLimits         = RPCSpec{Method: "v1/get_position_margin_limits", Gateway: GatewayTrading, Path: "/full/v1/get_position_margin_limits", LitePath: "/lite/v1/get_position_margin_limits", Auth: true, Write: false, OrderEntry: false}
	RPCPositionPositionHistory                 = RPCSpec{Method: "v1/position_history", Gateway: GatewayTrading, Path: "/full/v1/position_history", LitePath: "/lite/v1/position_history", Auth: true, Write: false, OrderEntry: false}
	RPCPositionPositions                       = RPCSpec{Method: "v1/positions", Gateway: GatewayTrading, Path: "/full/v1/positions", LitePath: "/lite/v1/positions", Auth: true, Write: false, OrderEntry: false}
	RPCPositionSetPositionConfig               = RPCSpec{Method: "v1/set_position_config", Gateway: GatewayTrading, Path: "/full/v1/set_position_config", LitePath: "/lite/v1/set_position_config", Auth: true, Write: true, OrderEntry: false}
	RPCRfqCancelRfq                            = RPCSpec{Method: "v1/cancel_rfq", Gateway: GatewayTrading, Path: "/full/v1/cancel_rfq", LitePath: "/lite/v1/cancel_rfq", Auth: true, Write: true, OrderEntry: false}
	RPCRfqCreateRfq                            = RPCSpec{Method: "v1/create_rfq", Gateway: GatewayTrading, Path: "/full/v1/create_rfq", LitePath: "/lite/v1/create_rfq", Auth: true, Write: true, OrderEntry: false}
	RPCSettlementFundingRate                   = RPCSpec{Method: "v1/funding", Gateway: GatewayMarketData, Path: "/full/v1/funding", LitePath: "/lite/v1/funding", Auth: false, Write: false, OrderEntry: false}
	RPCSfpTradingScheduleGetSfpTradingSchedule = RPCSpec{Method: "v1/sfp_trading_schedule", Gateway: GatewayMarketData, Path: "/full/v1/sfp_trading_schedule", LitePath: "/lite/v1/sfp_trading_schedule", Auth: false, Write: false, OrderEntry: false}
	RPCSubAccountGetCollateralPreference       = RPCSpec{Method: "v1/get_collateral_preference", Gateway: GatewayTrading, Path: "/full/v1/get_collateral_preference", LitePath: "/lite/v1/get_collateral_preference", Auth: true, Write: false, OrderEntry: false}
	RPCTickerMiniTicker                        = RPCSpec{Method: "v1/mini", Gateway: GatewayMarketData, Path: "/full/v1/mini", LitePath: "/lite/v1/mini", Auth: false, Write: false, OrderEntry: false}
	RPCTickerTicker                            = RPCSpec{Method: "v1/ticker", Gateway: GatewayMarketData, Path: "/full/v1/ticker", LitePath: "/lite/v1/ticker", Auth: false, Write: false, OrderEntry: false}
	RPCTradeTrade                              = RPCSpec{Method: "v1/trade", Gateway: GatewayMarketData, Path: "/full/v1/trade", LitePath: "/lite/v1/trade", Auth: false, Write: false, OrderEntry: false}
	RPCTradeTradeHistory                       = RPCSpec{Method: "v1/trade_history", Gateway: GatewayMarketData, Path: "/full/v1/trade_history", LitePath: "/lite/v1/trade_history", Auth: false, Write: false, OrderEntry: false}
	RPCTransferDepositHistory                  = RPCSpec{Method: "v1/deposit_history", Gateway: GatewayTrading, Path: "/full/v1/deposit_history", LitePath: "/lite/v1/deposit_history", Auth: true, Write: false, OrderEntry: false}
	RPCTransferGetWithdrawalFee                = RPCSpec{Method: "v1/withdrawal_fee", Gateway: GatewayTrading, Path: "/full/v1/withdrawal_fee", LitePath: "/lite/v1/withdrawal_fee", Auth: true, Write: false, OrderEntry: false}
	RPCTransferTransfer                        = RPCSpec{Method: "v1/transfer", Gateway: GatewayTrading, Path: "/full/v1/transfer", LitePath: "/lite/v1/transfer", Auth: true, Write: true, OrderEntry: false}
	RPCTransferTransferHistory                 = RPCSpec{Method: "v1/transfer_history", Gateway: GatewayTrading, Path: "/full/v1/transfer_history", LitePath: "/lite/v1/transfer_history", Auth: true, Write: false, OrderEntry: false}
	RPCTransferWithdrawal                      = RPCSpec{Method: "v1/withdrawal", Gateway: GatewayTrading, Path: "/full/v1/withdrawal", LitePath: "/lite/v1/withdrawal", Auth: true, Write: true, OrderEntry: false}
	RPCTransferWithdrawalHistory               = RPCSpec{Method: "v1/withdrawal_history", Gateway: GatewayTrading, Path: "/full/v1/withdrawal_history", LitePath: "/lite/v1/withdrawal_history", Auth: true, Write: false, OrderEntry: false}
	RPCVaultVaultBurnTokens                    = RPCSpec{Method: "v1/vault_burn_tokens", Gateway: GatewayTrading, Path: "/full/v1/vault_burn_tokens", LitePath: "/lite/v1/vault_burn_tokens", Auth: true, Write: true, OrderEntry: false}
	RPCVaultVaultConversionRate                = RPCSpec{Method: "v1/vault_conversion_rate", Gateway: GatewayTrading, Path: "/full/v1/vault_conversion_rate", LitePath: "/lite/v1/vault_conversion_rate", Auth: true, Write: false, OrderEntry: false}
	RPCVaultVaultInvest                        = RPCSpec{Method: "v2/vault_invest", Gateway: GatewayTrading, Path: "/full/v2/vault_invest", LitePath: "/lite/v2/vault_invest", Auth: true, Write: true, OrderEntry: false}
	RPCVaultVaultInvestorSummary               = RPCSpec{Method: "v1/vault_investor_summary", Gateway: GatewayTrading, Path: "/full/v1/vault_investor_summary", LitePath: "/lite/v1/vault_investor_summary", Auth: true, Write: false, OrderEntry: false}
	RPCVaultVaultManagerInvestmentHistory      = RPCSpec{Method: "v1/vault_manager_investor_history", Gateway: GatewayTrading, Path: "/full/v1/vault_manager_investor_history", LitePath: "/lite/v1/vault_manager_investor_history", Auth: true, Write: false, OrderEntry: false}
	RPCVaultVaultRedeem                        = RPCSpec{Method: "v2/vault_redeem", Gateway: GatewayTrading, Path: "/full/v2/vault_redeem", LitePath: "/lite/v2/vault_redeem", Auth: true, Write: true, OrderEntry: false}
	RPCVaultVaultRedeemCancel                  = RPCSpec{Method: "v1/vault_redeem_cancel", Gateway: GatewayTrading, Path: "/full/v1/vault_redeem_cancel", LitePath: "/lite/v1/vault_redeem_cancel", Auth: true, Write: true, OrderEntry: false}
	RPCVaultVaultRedemptionQueue               = RPCSpec{Method: "v1/vault_view_redemption_queue", Gateway: GatewayTrading, Path: "/full/v1/vault_view_redemption_queue", LitePath: "/lite/v1/vault_view_redemption_queue", Auth: true, Write: false, OrderEntry: false}
)

Gateway RPCs.

View Source
var (
	StreamAlgoOrderAlgoOrder      = StreamSpec{Stream: "v1.algo.order", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamCandlestickCandlestick  = StreamSpec{Stream: "v1.candle", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: false, Conflate: false}
	StreamExecutionFill           = StreamSpec{Stream: "v1.fill", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamExecutionPositions      = StreamSpec{Stream: "v1.position", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamOrderCancelStatus       = StreamSpec{Stream: "v1.cancel", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamOrderOrder              = StreamSpec{Stream: "v1.order", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamOrderOrderState         = StreamSpec{Stream: "v1.state", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamOrderbookOrderbookDelta = StreamSpec{Stream: "v1.book.d", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: false, Conflate: false}
	StreamOrderbookOrderbookSnap  = StreamSpec{Stream: "v1.book.s", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: true, Conflate: true}
	StreamRfqRfqQuote             = StreamSpec{Stream: "v1.quote", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamTickerMiniTickerDelta   = StreamSpec{Stream: "v1.mini.d", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: false, Conflate: false}
	StreamTickerMiniTickerSnap    = StreamSpec{Stream: "v1.mini.s", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: true, Conflate: true}
	StreamTickerTickerDelta       = StreamSpec{Stream: "v1.ticker.d", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: false, Conflate: false}
	StreamTickerTickerSnap        = StreamSpec{Stream: "v1.ticker.s", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: true, Conflate: true}
	StreamTradeTrade              = StreamSpec{Stream: "v1.trade", Gateway: GatewayMarketData, Auth: false, SnapshotFeed: false, Conflate: false}
	StreamTransferDeposit         = StreamSpec{Stream: "v1.deposit", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamTransferTransfer        = StreamSpec{Stream: "v1.transfer", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
	StreamTransferWithdrawal      = StreamSpec{Stream: "v1.withdrawal", Gateway: GatewayTrading, Auth: true, SnapshotFeed: false, Conflate: false}
)

Streams. Snapshot channels may drop old items when the consumer is slow; others never drop.

View Source
var ErrClosed = errors.New("grvt: client closed")

ErrClosed is returned after Client.Close.

View Source
var RPCs = []*RPCSpec{&RPCEdgeAPIKeyLogin, &RPCEdgeWalletLogin, &RPCAccountAggregatedAccountSummary, &RPCAccountFundingAccountSummary, &RPCAccountGetSubAccounts, &RPCAccountSpotAccountSummary, &RPCAccountSubAccountSummary, &RPCAlgoOrderAlgoOrderHistory, &RPCAlgoOrderAlgoSubOrderHistory, &RPCAlgoOrderCancelAlgoOrder, &RPCAlgoOrderCreateAlgoOrder, &RPCAlgoOrderGetAlgoOrder, &RPCAlgoOrderOpenAlgoOrders, &RPCBuilderGetAuthorizedBuilders, &RPCCandlestickCandlestick, &RPCDeriskMmRatioSetDeriskMmRatio, &RPCExecutionBuilderFillHistory, &RPCExecutionFillHistory, &RPCExecutionFundingPaymentHistory, &RPCExecutionInterestPaymentHistory, &RPCInitialLeverageGetAllInitialLeverage, &RPCInitialLeverageSetInitialLeverage, &RPCInstrumentGetAllCollateralAssetInfo, &RPCInstrumentGetAllInstruments, &RPCInstrumentGetCurrency, &RPCInstrumentGetFilteredInstruments, &RPCInstrumentGetInstrument, &RPCInstrumentGetMarginRules, &RPCInstrumentGetSupportedAssets, &RPCOrderBulkOrders, &RPCOrderCancelAllOrders, &RPCOrderCancelOnDisconnect, &RPCOrderCancelOrder, &RPCOrderCreateOrder, &RPCOrderGetOrder, &RPCOrderOpenOrders, &RPCOrderOrderHistory, &RPCOrderbookOrderbookLevels, &RPCPositionAddPositionMargin, &RPCPositionGetPositionMarginLimits, &RPCPositionPositionHistory, &RPCPositionPositions, &RPCPositionSetPositionConfig, &RPCRfqCancelRfq, &RPCRfqCreateRfq, &RPCSettlementFundingRate, &RPCSfpTradingScheduleGetSfpTradingSchedule, &RPCSubAccountGetCollateralPreference, &RPCTickerMiniTicker, &RPCTickerTicker, &RPCTradeTrade, &RPCTradeTradeHistory, &RPCTransferDepositHistory, &RPCTransferGetWithdrawalFee, &RPCTransferTransfer, &RPCTransferTransferHistory, &RPCTransferWithdrawal, &RPCTransferWithdrawalHistory, &RPCVaultVaultBurnTokens, &RPCVaultVaultConversionRate, &RPCVaultVaultInvest, &RPCVaultVaultInvestorSummary, &RPCVaultVaultManagerInvestmentHistory, &RPCVaultVaultRedeem, &RPCVaultVaultRedeemCancel, &RPCVaultVaultRedemptionQueue}

RPCs lists every RPC and edge route.

Streams lists every stream.

Functions

func AddressSet

func AddressSet(v string) bool

AddressSet is the builder variant rule: is this address set to something other than zero?

func BackfillPages

func BackfillPages[P Page](ctx context.Context, fetch func(context.Context, string) (P, error), gap GapRange) iter.Seq2[BackfillPage[P], error]

BackfillPages preserves the original gap while reading available history. fetch owns endpoint selection and the time window. Sequence bounds cannot be used as REST cursors, and exhausted history does not prove event visibility.

func Call

func Call[Req, Resp any](ctx context.Context, rt *Runtime, spec *RPCSpec, req *Req, info *RequestInfo[Req], sign SignFunc[Req]) (*Resp, error)

Call runs one RPC: required-field check -> client order id -> BeforeSend -> sign -> encode -> REST or WS -> decode. With EncodingLite the encoded request is renamed to lite just before it is sent and the reply decodes from lite; everything before (and the model returned) is full. Signed requests are copied first, so the caller's request is never changed.

func CheckOrder

func CheckOrder(checks *OrderChecks, order models.OrderInput, meta *Meta) error

CheckOrder checks the order's instrument limits without changing it. It returns the first OrderOutOfBoundsError, or a SigningError for a malformed value.

func ChecksumAddress

func ChecksumAddress(a Address) string

ChecksumAddress is the EIP-55 mixed-case address, as eth_signTypedData tooling prints it.

func DecimalText

func DecimalText(value *models.Decimal) string

DecimalText is used by generated signing code; an absent value stays absent.

func Deref

func Deref[T any](p *T) *T

Deref returns p, or a pointer to a zero T when p is nil. Generated signing code reads nested fields through it.

func Hex0x

func Hex0x(b []byte) string

Hex0x is lowercase 0x-prefixed hex.

func Pages

func Pages[P Page](ctx context.Context, fetch func(context.Context, string) (P, error), cursor string) iter.Seq2[P, error]

Pages fetches complete pages lazily, including empty pages with a next cursor. Breaking iteration sends no more calls. fetch owns the filters and timeout; Each range starts at cursor. ctx cancels the traversal. Cursors do not guarantee a stable server snapshot.

func Ptr

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

Ptr returns a pointer to v, for optional model fields: Ptr(true), Ptr[uint64](123).

func Redact

func Redact(data []byte, limit int) string

Redact hides secrets in a JSON body, cookie string or log line. It truncates to limit bytes first.

func ScaleDecimal

func ScaleDecimal(s string, decimals uint32) (*big.Int, error)

ScaleDecimal turns "65000.1" with 9 decimals into 65000100000000. More decimal places than decimals is an error.

func Selector

func Selector(primary, secondary []string) string

Selector joins the set fields as "p1-p2@s1-s2" (empty values skipped).

func SelectorInt

func SelectorInt[T ~uint8 | ~uint16 | ~uint32 | ~uint64](v *T) string

SelectorInt formats an optional integer selector field ("" when nil).

func SignDeriskMmRatioSetDeriskMmRatio

func SignDeriskMmRatioSetDeriskMmRatio(ctx context.Context, rt *Runtime, req *models.ApiSetDeriskToMaintenanceMarginRatioRequestInput) error

SignDeriskMmRatioSetDeriskMmRatio signs derisk_mm_ratio.set_derisk_mm_ratio in place. always SetDeriskToMaintenanceMarginRatio

func SignEdgeWalletLogin

func SignEdgeWalletLogin(ctx context.Context, rt *Runtime, req *models.EdgeWalletLoginRequestInput) error

SignEdgeWalletLogin signs edge.wallet_login in place. always WalletLogin

func SignOrderBulkOrders

func SignOrderBulkOrders(ctx context.Context, rt *Runtime, req *models.ApiBulkOrdersRequestInput) error

SignOrderBulkOrders signs order.bulk_orders in place: every element of orders on its own, with its own nonce and expiration. Each order is signed on its own, like create_order: OrderWithBuilderFee when that order's builder is set to a non-zero address, otherwise Order. The cancel lists and time_to_live_ms are not signed.

func SignOrderCreateOrder

func SignOrderCreateOrder(ctx context.Context, rt *Runtime, req *models.ApiCreateOrderRequestInput) error

SignOrderCreateOrder signs order.create_order in place. Use OrderWithBuilderFee when order.builder is set to a non-zero address, otherwise Order.

func SignPositionAddPositionMargin

func SignPositionAddPositionMargin(ctx context.Context, rt *Runtime, req *models.ApiAddIsolatedPositionMarginRequestInput) error

SignPositionAddPositionMargin signs position.add_position_margin in place. always AddIsolatedPositionMargin

func SignPositionSetPositionConfig

func SignPositionSetPositionConfig(ctx context.Context, rt *Runtime, req *models.ApiSetSubAccountPositionMarginConfigRequestInput) error

SignPositionSetPositionConfig signs position.set_position_config in place. always SetSubAccountPositionMarginConfig

func SignTransferTransfer

func SignTransferTransfer(ctx context.Context, rt *Runtime, req *models.ApiTransferRequestInput) error

SignTransferTransfer signs transfer.transfer in place. If from_wallet_type and to_wallet_type are both set: TransferV2 when the currency id fits uint8 (<= 255), else TransferV3. If neither is set: Transfer (only for currency ids <= 255). Setting only one...

func SignTransferWithdrawal

func SignTransferWithdrawal(ctx context.Context, rt *Runtime, req *models.ApiWithdrawalRequestInput) error

SignTransferWithdrawal signs transfer.withdrawal in place. Withdrawal when the currency id fits uint8 (<= 255), else WithdrawalV2.

func SignVaultVaultBurnTokens

func SignVaultVaultBurnTokens(ctx context.Context, rt *Runtime, req *models.ApiVaultBurnTokensRequestInput) error

SignVaultVaultBurnTokens signs vault.vault_burn_tokens in place. always VaultBurnLpToken

func SignVaultVaultInvest

func SignVaultVaultInvest(ctx context.Context, rt *Runtime, req *models.ApiVaultInvestV2RequestInput) error

SignVaultVaultInvest signs vault.vault_invest in place. always VaultInvestV3

func SignVaultVaultRedeem

func SignVaultVaultRedeem(ctx context.Context, rt *Runtime, req *models.ApiVaultRedeemV2RequestInput) error

SignVaultVaultRedeem signs vault.vault_redeem in place. always VaultRedeemV3

Types

type APIError

type APIError struct {
	Code    int
	Message string
	// Status is the HTTP status (0 over WebSocket).
	Status int
	// RPC is the method that failed, e.g. "v1/create_order".
	RPC string
	// Retryable follows the contract rule: rate limit, a retryable code, or HTTP 502/503/504.
	Retryable bool
}

APIError is an error code from the server.

func (*APIError) Error

func (e *APIError) Error() string

type Address

type Address [20]byte

Address is a 20-byte EVM address.

type BackfillPage

type BackfillPage[P Page] struct {
	Page             P
	Gap              GapRange
	HistoryExhausted bool
}

BackfillPage is available REST history, not proof of complete event recovery.

func (BackfillPage[P]) Continuity

func (p BackfillPage[P]) Continuity() string

type Backoff

type Backoff struct {
	Base, Cap time.Duration
	Attempt   int
	// contains filtered or unexported fields
}

Backoff is full jitter: sleep uniform(0, min(cap, base * 2^attempt)).

func (*Backoff) Next

func (b *Backoff) Next() time.Duration

func (*Backoff) Reset

func (b *Backoff) Reset()

type BookError

type BookError struct {
	Reason string
	Gap    *GapRange
}

func (*BookError) Error

func (e *BookError) Error() string

type BookMode

type BookMode string
const (
	BookDelta     BookMode = "delta"
	BookSnapshots BookMode = "snapshot"
)

type BookSnapshot

type BookSnapshot struct {
	Instrument     string
	SequenceNumber uint64
	EventTime      time.Time
	Bids, Asks     []models.OrderbookLevel
}

type Client

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

Client is one Grvt client for one environment and account. Safe for concurrent use.

Every RPC and stream is a Client method, client.<Method>(ctx, ...), generated from the contract and not grouped by namespace. An RPC takes the request model and returns the response model; a stream takes the selector model and returns a *Subscription. Every stream method ends in "Stream" (client.TradeStream), so it never shares a name with an RPC.

func New

func New(cfg Config) (*Client, error)

New builds a client. It does not connect: sockets open and the api key logs in on first use.

func (*Client) AddPositionMargin

AddPositionMargin The request to add margin to a isolated position

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id, instrument, amount.

func (*Client) AggregatedAccountSummary

func (c *Client) AggregatedAccountSummary(ctx context.Context, req *models.EmptyRequest) (*models.ApiAggregatedAccountSummaryResponse, error)

AggregatedAccountSummary Used for requests that do not require any parameters

func (*Client) AlgoOrderHistory

AlgoOrderHistory Retrieves the algo order history for the account. Returns one row per terminated or filled parent algo order, not per sub-order.

Required: sub_account_id.

func (*Client) AlgoOrderStream

AlgoOrderStream Subscribes to a feed of algo order updates pertaining to algo orders made by your account.

Stream v1.algo.order, selector <sub_account_id>[-<instrument>] (e.g. <sub_account_id>-BTC_USDT_Perp).

func (*Client) AlgoSubOrderHistory

AlgoSubOrderHistory Retrieves the terminal sub-orders of an algo order. A sub-order appears once it reaches a terminal state: partially filled and superseded, fully filled, cancelled or rejected. Re-price cancels and...

Required: sub_account_id, algo_order_id.

func (*Client) BuilderFillHistory

BuilderFillHistory The request to get the historical builder trade of a builder

Only for builders. Other accounts get an empty list.

func (*Client) BulkOrders

BulkOrders Bulk create, cancel, or cancel-replace orders for a single subaccount.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id.

func (*Client) CancelAlgoOrder

func (c *Client) CancelAlgoOrder(ctx context.Context, req *models.ApiCancelAlgoOrderRequest) (*models.AckResponse, error)

CancelAlgoOrder Cancel an algo order for this trading account. This cascades to a full cancel of the sub-order currently resting on the orderbook. Either `algo_order_id` or `client_order_id` must be provided.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id.

func (*Client) CancelAllOrders

func (c *Client) CancelAllOrders(ctx context.Context, req *models.ApiCancelAllOrdersRequest) (*models.AckResponse, error)

CancelAllOrders Cancel all orders on the orderbook for this trading account. This may not match new orders in flight.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id.

func (*Client) CancelOnDisconnect

func (c *Client) CancelOnDisconnect(ctx context.Context, req *models.ApiCancelOnDisconnectRequest) (*models.AckResponse, error)

CancelOnDisconnect Arm, refresh or stop a dead man's switch for one sub-account: if the countdown reaches zero before you call again, the exchange cancels all of that sub-account's open orders.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id.

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, req *models.ApiCancelOrderRequest) (*models.AckResponse, error)

CancelOrder Cancel an order on the orderbook for this trading account. Either `order_id` or `client_order_id` must be provided.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id.

func (*Client) CancelRfq

CancelRfq Cancels an open RFQ identified by its `rfq_id` before it is accepted or expires.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id, rfq_id.

func (*Client) CancelStatusStream

CancelStatusStream Subscribes to a feed of time-to-live expiry events for order cancellations requested by a given subaccount.

Stream v1.cancel, selector <sub_account_id> (e.g. <sub_account_id>).

func (*Client) Candlestick

Candlestick Kline/Candlestick bars for an instrument. Klines are uniquely identified by their instrument, type, interval, and open time.

Required: instrument, interval, type.

func (*Client) CandlestickStream

CandlestickStream Subscribes to a stream of Kline/Candlestick updates for an instrument. A Kline is uniquely identified by its open time.

Stream v1.candle, selector <instrument>[@<interval>-<type>] (e.g. BTC_USDT_Perp@CI_1_M-TRADE).

func (*Client) Close

func (c *Client) Close() error

Close closes both sockets and stops background work. Writes still waiting for a reply return *OrderStateUnknownError.

func (*Client) CreateAlgoOrder

CreateAlgoOrder Create an algo order for this trading account. Algo trading must be enabled (opted in) for the sub account before creating an algo order. The algo order is unsigned; GRVT Backend places signed...

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: order.

func (*Client) CreateOrder

CreateOrder Create an order on the orderbook for this trading account. STABLE_PERP orders require the sub-account to be in multi-asset mode.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: order.

func (*Client) CreateRfq

CreateRfq Creates a new RFQ (Request For Quote): a taker solicits private quotes for a single STABLE_PERP instrument by specifying a size, and optionally a direction (`rfq.side`; omit for a two-way request)...

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: rfq.

func (*Client) DepositHistory

DepositHistory The request to get the historical deposits of an account

Required: currency.

func (*Client) DepositStream

DepositStream Subscribes to a feed of deposits. This will execute when there is any deposit to selected account.

Stream v1.deposit, selector <main_account_id> (e.g. <main_account_id>).

func (*Client) FillHistory

FillHistory Query for all historical fills made by a single account. A single order can be matched multiple times, hence there is no real way to uniquely identify a trade.

Required: sub_account_id.

func (*Client) FillStream

FillStream Subscribes to a feed of private trade updates. This happens when a trade is executed.

Stream v1.fill, selector <sub_account_id>[-<instrument>] (e.g. <sub_account_id>-BTC_USDT_Perp).

func (*Client) FundingAccountSummary

func (c *Client) FundingAccountSummary(ctx context.Context, req *models.EmptyRequest) (*models.ApiFundingAccountSummaryResponse, error)

FundingAccountSummary Used for requests that do not require any parameters

func (*Client) FundingPaymentHistory

FundingPaymentHistory Query for all historical funding payments made by a single account.

Required: sub_account_id.

func (*Client) FundingRate

FundingRate Lookup the historical funding rate of a perpetual future.

Required: instrument.

func (*Client) GetAlgoOrder

GetAlgoOrder Retrieve an algo order for the account. Either `algo_order_id` or `client_order_id` must be provided.

Required: sub_account_id.

func (*Client) GetAllCollateralAssetInfo

func (c *Client) GetAllCollateralAssetInfo(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetAllCollateralAssetInfoResponse, error)

GetAllCollateralAssetInfo Used for requests that do not require any parameters

func (*Client) GetAllInitialLeverage

GetAllInitialLeverage The request to get the initial leverage of a sub account

Required: sub_account_id.

func (*Client) GetAllInstruments

GetAllInstruments Fetch all instruments

func (*Client) GetAuthorizedBuilders

func (c *Client) GetAuthorizedBuilders(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetAuthorizedBuildersResponse, error)

GetAuthorizedBuilders Used for requests that do not require any parameters

func (*Client) GetCollateralPreference

GetCollateralPreference Fetch the per-currency collateral enable/disable state for a Multi-Asset Mode sub account.

Required: sub_account_id.

func (*Client) GetCurrency

GetCurrency Fetch all currencies

func (*Client) GetFilteredInstruments

GetFilteredInstruments Fetch a list of instruments based on the filters provided

func (*Client) GetInstrument

GetInstrument Fetch a single instrument by supplying the asset or instrument name

Required: instrument.

func (*Client) GetMarginRules

GetMarginRules API request payload to get margin rules for a particular instrument

Required: instrument.

func (*Client) GetOrder

GetOrder Retrieve the order for the account. Either `order_id` or `client_order_id` must be provided.

Required: sub_account_id.

func (*Client) GetPositionMarginLimits

GetPositionMarginLimits The request to get the max addable and removable amount for an isolated position

Required: sub_account_id, instrument.

func (*Client) GetSfpTradingSchedule

func (c *Client) GetSfpTradingSchedule(ctx context.Context, req *models.EmptyRequest) (*models.ApiSfpTradingScheduleResponse, error)

GetSfpTradingSchedule Used for requests that do not require any parameters

func (*Client) GetSubAccounts

GetSubAccounts Used for requests that do not require any parameters

func (*Client) GetSupportedAssets

func (c *Client) GetSupportedAssets(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetSupportedAssetsResponse, error)

GetSupportedAssets Used for requests that do not require any parameters

func (*Client) GetWithdrawalFee

GetWithdrawalFee Query the flat withdrawal fee for a native (L2 -> L1) bridge withdrawal, expressed in the requested currency

Required: token_currency.

func (*Client) InterestPaymentHistory

InterestPaymentHistory Query for all historical MAM hourly interest payments charged to a single sub account.

Required: sub_account_id.

func (*Client) MiniTicker

MiniTicker Retrieves a single mini ticker value for a single instrument. Please do not use this to repeatedly poll for data -- a websocket subscription is much more performant, and useful.

Required: instrument.

func (*Client) MiniTickerDeltaStream

MiniTickerDeltaStream Subscribes to a mini ticker feed for a single instrument. The `mini.s` channel offers simpler integration. To experience higher publishing rates, please use the `mini.d` channel.

Stream v1.mini.d, selector <instrument>[@<rate>] (e.g. BTC_USDT_Perp@500).

func (*Client) MiniTickerSnapStream

MiniTickerSnapStream Subscribes to a mini ticker feed for a single instrument. The `mini.s` channel offers simpler integration. To experience higher publishing rates, please use the `mini.d` channel.

Stream v1.mini.s, selector <instrument>[@<rate>] (e.g. BTC_USDT_Perp@500).

func (*Client) OpenAlgoOrders

OpenAlgoOrders Retrieves all open algo orders for the account, including algo orders still pending on their trigger.

Required: sub_account_id.

func (*Client) OpenOrders

OpenOrders Retrieves all open orders for the account. This may not match new orders in flight.

Required: sub_account_id.

func (*Client) OrderHistory

OrderHistory Retrieves the order history for the account.

Required: sub_account_id.

func (*Client) OrderStateStream

OrderStateStream Subscribes to a feed of order updates pertaining to orders made by your account.

Stream v1.state, selector <sub_account_id>[-<instrument>] (e.g. <sub_account_id>-BTC_USDT_Perp).

func (*Client) OrderStream

OrderStream Subscribes to a feed of order updates pertaining to orders made by your account.

Stream v1.order, selector <sub_account_id>[-<instrument>] (e.g. <sub_account_id>-BTC_USDT_Perp).

func (*Client) OrderbookDeltaStream

OrderbookDeltaStream Subscribes to aggregated orderbook updates for a single instrument. The `book.s` channel offers simpler integration. To experience higher publishing rates, please use the `book.d` channel.

Stream v1.book.d, selector <instrument>[@<rate>-<depth>] (e.g. BTC_USDT_Perp@500-50).

func (*Client) OrderbookLevels

OrderbookLevels Retrieves aggregated price depth for a single instrument, with a maximum depth of 10 levels. Do not use this to poll for data -- a websocket subscription is much more performant, and useful.

Required: instrument, depth.

func (*Client) OrderbookSnapStream

OrderbookSnapStream Subscribes to aggregated orderbook updates for a single instrument. The `book.s` channel offers simpler integration. To experience higher publishing rates, please use the `book.d` channel.

Stream v1.book.s, selector <instrument>[@<rate>-<depth>] (e.g. BTC_USDT_Perp@500-50).

func (*Client) PositionHistory

PositionHistory Query for position lifecycle records for a single sub account.

Required: sub_account_id.

func (*Client) Positions

Positions Query the positions of a sub account

Required: sub_account_id.

func (*Client) PositionsStream

PositionsStream Subscribes to a feed of position updates.

Stream v1.position, selector <sub_account_id>[-<instrument>] (e.g. <sub_account_id>-BTC_USDT_Perp).

func (*Client) RfqQuoteStream

RfqQuoteStream Taker feed. Subscribe with selector `(sub_account_id, instrument)` to receive your private RFQ quote book — best bid/ask and all private quote levels — for your open RFQ on that instrument.

Stream v1.quote, selector <sub_account_id>[-<instrument>] (e.g. <sub_account_id>-AAPL_USDC_SFP).

func (*Client) Runtime

func (c *Client) Runtime() *Runtime

Runtime is the shared runtime: environment, sockets, session, metadata cache.

func (*Client) SetDeriskMmRatio

SetDeriskMmRatio The request to set the derisk margin to maintenance margin ratio of a sub account

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id, ratio.

func (*Client) SetInitialLeverage

SetInitialLeverage The request to set the initial leverage of a sub account.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id, instrument, leverage.

func (*Client) SetPositionConfig

SetPositionConfig Sets the margin type and leverage configuration for a specific position (instrument) within a sub account.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: sub_account_id, instrument, margin_type, leverage.

func (*Client) SpotAccountSummary

SpotAccountSummary The spot account summary, that reports the total equity and spot balances of a spot sub account

Required: sub_account_id.

func (*Client) SubAccountSummary

SubAccountSummary Query for sub-account details, including base currency balance, all derivative positions, margin levels, and P&L.

Required: sub_account_id.

func (*Client) Ticker

Ticker Retrieves a single ticker value for a single instrument. Please do not use this to repeatedly poll for data -- a websocket subscription is much more performant, and useful. Rate limit: Perpetual...

Required: instrument.

func (*Client) TickerDeltaStream

TickerDeltaStream Subscribes to a ticker feed for a single instrument. The `ticker.s` channel offers simpler integration. To experience higher publishing rates, please use the `ticker.d` channel.

Stream v1.ticker.d, selector <instrument>[@<rate>] (e.g. BTC_USDT_Perp@500).

func (*Client) TickerSnapStream

TickerSnapStream Subscribes to a ticker feed for a single instrument. The `ticker.s` channel offers simpler integration. To experience higher publishing rates, please use the `ticker.d` channel.

Stream v1.ticker.s, selector <instrument>[@<rate>] (e.g. BTC_USDT_Perp@500).

func (*Client) Trade

Trade Retrieves up to 1000 of the most recent trades in any given instrument. Do not use this to poll for data -- a websocket subscription is much more performant, and useful.

Required: instrument, limit.

func (*Client) TradeHistory

TradeHistory Perform historical lookup of public trades in any given instrument.

Required: instrument.

func (*Client) TradeStream

TradeStream Subscribes to a stream of Public Trades for an instrument.

Stream v1.trade, selector <instrument>[@<limit>] (e.g. BTC_USDT_Perp@500).

func (*Client) Transfer

Transfer Transfer funds:

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: from_account_id, from_sub_account_id, to_account_id, to_sub_account_id, currency, num_tokens, transfer_type.

func (*Client) TransferHistory

TransferHistory The request to get the historical transfers of an account

Required: currency.

func (*Client) TransferStream

TransferStream Subscribes to a feed of transfers. This will execute when there is any transfer to or from the selected account.

Stream v1.transfer, selector <main_account_id>[-<sub_account_id>] (e.g. <main_account_id>-<sub_account_id>).

func (*Client) VaultBurnTokens

VaultBurnTokens Request payload for burning tokens in a vault.

Only for vault managers. Other accounts get error 1001.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: vault_id, currency, num_tokens.

func (*Client) VaultConversionRate

VaultConversionRate Request payload for the highest exchange rate the gateway currently accepts for a vault investment or redemption that converts `fromCurrency` into `toCurrency`.

Required: from_currency, to_currency.

func (*Client) VaultInvest

VaultInvest Request payload for investing in a vault from the funding account or from a trading account, converting the source currency into the vault's investment currency when they differ.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: vault_id, from_sub_account_id, from_wallet_type, from_currency, from_num_tokens, to_currency, exchange_rate.

func (*Client) VaultInvestorSummary

VaultInvestorSummary Request payload for fetching the summary of a vault investor.

func (*Client) VaultManagerInvestmentHistory

VaultManagerInvestmentHistory Request for the manager to retrieve the vault investor history for their vault

Only for vault managers. Other accounts get error 1001.

Required: vault_id, only_own_investments.

func (*Client) VaultRedeem

VaultRedeem Request payload for redeeming from a vault, paid in the vault's investment currency or converted into another currency.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: vault_id, from_currency, to_currency, num_tokens, exchange_rate.

func (*Client) VaultRedeemCancel

func (c *Client) VaultRedeemCancel(ctx context.Context, req *models.ApiVaultRedeemCancelRequest) (*models.AckResponse, error)

VaultRedeemCancel Request payload for canceling a vault redemption.

Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: vault_id.

func (*Client) VaultRedemptionQueue

VaultRedemptionQueue Request payload for a vault manager to view the redemption queue for their vault.

Only for vault managers. Other accounts get error 1001.

Required: vault_id.

func (*Client) Withdrawal

Withdrawal Leverage this API to initialize a withdrawal from GRVT's Hyperchain onto Ethereum.

Signed with the client's signer (signature fields left empty are filled in). Never retried; an ambiguous failure is *OrderStateUnknownError.

Required: from_account_id, to_eth_address, currency, num_tokens.

func (*Client) WithdrawalHistory

WithdrawalHistory The request to get the historical withdrawals of an account

Required: currency.

func (*Client) WithdrawalStream

WithdrawalStream Subscribes to a feed of withdrawals. This will execute when there is any withdrawal from the selected account.

Stream v1.withdrawal, selector <main_account_id> (e.g. <main_account_id>).

type ClientOrderIDProvider

type ClientOrderIDProvider interface {
	NextClientOrderID() uint64
}

ClientOrderIDProvider gives client_order_id values for orders that have none.

type Clock

type Clock interface {
	// NowNs is nanoseconds since the Unix epoch.
	NowNs() int64
}

Clock gives the time used for signature expirations. Client options so tests can pin it.

type Config

type Config struct {
	// SubAccountID fills omitted request and stream account IDs. Zero means unset.
	SubAccountID uint64
	// Env is where to connect: Testnet(), Prod() or your own Environment.
	Env Environment
	// APIKey logs in on the first authenticated call (gravity cookie + X-Grvt-Account-Id).
	APIKey string
	// Signer signs orders, transfers, withdrawals and wallet logins.
	Signer Signer
	// OrderTransport: OrderTransportREST (default) or OrderTransportWS.
	OrderTransport OrderTransport
	// Encoding: EncodingLite (default) or EncodingFull, for both HTTP and WebSocket.
	Encoding Encoding
	// CheckOrders checks each order against its instrument's limits before signing (nil means on).
	// grvt.Ptr(false) skips the check and leaves the limits to the exchange.
	CheckOrders *bool

	// Clock, Nonces and ClientOrderIDs default to the wall clock, random nonces and
	// 1<<63|seconds<<31|counter ids. Tests pin them.
	Clock          Clock
	Nonces         NonceProvider
	ClientOrderIDs ClientOrderIDProvider

	// HTTPClient is the HTTP plug-in (default: a keep-alive client). A custom client Timeout
	// is an additional cap; HTTPAttemptTimeout and the caller deadline still apply.
	// The SDK copies client settings and disables redirects. Custom RoundTrippers
	// must not replay POSTs and must honor request contexts. Once handed to a custom
	// transport, a write with no trustworthy reply is conservatively uncertain.
	HTTPClient *http.Client

	// BeforeSend runs for every RPC before signing (REST or WS). It may change call.Params in place.
	BeforeSend func(call *OutgoingCall)
	// OnEvent gets connection, stream and retry events. It runs on the socket's read goroutine and
	// must not block.
	OnEvent func(e Event)

	// CallTimeout bounds the whole RPC, including signing, login and retries (default 30s).
	CallTimeout time.Duration
	// HTTPAttemptTimeout bounds each HTTP attempt (default 10s).
	HTTPAttemptTimeout time.Duration
	// WSRequestTimeout bounds a WS request or subscribe (default 5s).
	WSRequestTimeout time.Duration
	// ResyncTimeout bounds the wait for a fresh snapshot after a gap re-subscribe; past it the socket
	// reconnects (default 5s).
	ResyncTimeout time.Duration
	// QueueSize bounds each subscription's queue (default 4096).
	QueueSize int
	// Logger receives debug logs (redacted). Default: GRVT_LOG=debug logs to stderr, otherwise nothing.
	Logger *slog.Logger
}

Config holds the client options. Only Env is required.

grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: key, Signer: signer})

func (Config) GoString

func (c Config) GoString() string

GoString keeps the API key out of %#v.

func (Config) LogValue

func (c Config) LogValue() slog.Value

LogValue keeps the API key out of slog output.

func (Config) String

func (c Config) String() string

String keeps the API key out of %v and %+v.

type ConfigError

type ConfigError struct{ Message string }

ConfigError: the client is missing something the call needs (signer, api key, a required field) or was given a bad option.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type CountdownClient

type CountdownClient interface {
	CancelOnDisconnect(context.Context, *models.ApiCancelOnDisconnectRequest) (*models.AckResponse, error)
}

type CountdownReceipt

type CountdownReceipt struct {
	SubAccountID     uint64
	CountdownSeconds uint16
	Acknowledged     bool
}

CountdownReceipt records an acknowledgment, not proof that a timer is still active. Another caller can replace the same sub-account's countdown.

func RefreshCancelCountdown

func RefreshCancelCountdown(ctx context.Context, client CountdownClient, subAccountID uint64, countdownSeconds uint16) (CountdownReceipt, error)

RefreshCancelCountdown arms or refreshes once. It never retries, disarms, or extends the countdown automatically on reconnect. Ambiguous writes propagate.

func (CountdownReceipt) Scope

func (r CountdownReceipt) Scope() string

type CurrencyMeta

type CurrencyMeta struct {
	ID              uint32
	Symbol          string
	BalanceDecimals uint32
}

CurrencyMeta is what signing needs from a currency (get_currency).

type DecodeError

type DecodeError struct {
	RPC string
	Err error
}

DecodeError: the response did not match the expected type.

func (*DecodeError) Error

func (e *DecodeError) Error() string

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

type Domain

type Domain struct {
	Name              string
	Version           string
	ChainID           uint64
	VerifyingContract *Address
	// contains filtered or unexported fields
}

Domain is an EIP-712 domain with its separator computed once.

func ExchangeDomain

func ExchangeDomain(chainID uint64) *Domain

ExchangeDomain is the "GRVT Exchange" domain for a chain id. Domains are cached per chain id.

func NewDomain

func NewDomain(name, version string, chainID uint64, verifyingContract *Address) *Domain

NewDomain builds a domain. verifyingContract may be nil (Grvt's domain has none).

func (*Domain) Separator

func (d *Domain) Separator() [32]byte

Separator is the domain separator.

type Encoding

type Encoding int

Encoding is the JSON encoding of every gateway call and stream. Chosen once per client.

const (
	// EncodingLite (the default) uses the gateways' short field names: the same API and values in
	// smaller messages (order book frames are about a third smaller). Only the wire changes; models,
	// errors and signing stay the same. Login and the server-time call stay full.
	EncodingLite Encoding = iota
	// EncodingFull uses the full JSON field names, as shown in the API reference.
	EncodingFull
)

func (Encoding) String

func (e Encoding) String() string

type Environment

type Environment struct {
	Name string
	// MarketDataURL, TradingURL and EdgeURL are the REST bases (edge serves login).
	MarketDataURL string
	TradingURL    string
	EdgeURL       string
	MarketDataWS  string
	TradingWS     string
	// MarketDataWSLite and TradingWSLite are the WebSocket URLs for the lite encoding (Config.Encoding).
	// Empty, each is the full URL with its ending /ws/full swapped for /ws/lite; set one only when that
	// rule does not fit.
	MarketDataWSLite string
	TradingWSLite    string
	// ChainID is the EIP-712 domain chainId.
	ChainID uint64
	// WSMaxFrameBytes is the largest WS frame the gateway accepts; 0 means do not check. The deployed
	// value is not published yet, so the named environments leave it 0.
	WSMaxFrameBytes int
}

Environment says where the SDK connects and which chain id it signs for. Use Testnet() or Prod(), or build one (a local gateway, a test server).

func EnvironmentNamed

func EnvironmentNamed(name string) (Environment, error)

EnvironmentNamed returns "testnet" or "prod".

func Prod

func Prod() Environment

Prod is Grvt production (chain id 325).

func Testnet

func Testnet() Environment

Testnet is the Grvt testnet (chain id 326).

func (*Environment) Validate

func (e *Environment) Validate() error

Validate reports a missing URL or chain id. Every field of a custom Environment is used as given: nothing falls back to a named environment, so a zero ChainID or an empty URL is an error, not a default.

type ErrorInfo

type ErrorInfo struct {
	Code      int
	Name      string
	Status    int
	Message   string
	Retryable bool
}

ErrorInfo is one row of the contract's error table.

type ErrorTable

type ErrorTable []ErrorInfo

ErrorTable is the contract's error table, sorted by code (generated: errorTable).

func (ErrorTable) Get

func (t ErrorTable) Get(code int) (ErrorInfo, bool)

Get returns the row for code.

func (ErrorTable) Retryable

func (t ErrorTable) Retryable(code, status int) bool

Retryable is the contract rule: the rate-limit code, a code the table marks retryable, or a read retry status.

type Event

type Event struct {
	Kind EventKind
	Gap  *GapRange
	// Socket is "md" (market data) or "td" (trading); empty for REST and session events.
	Socket string

	// Disconnect: the close code (0 if none) and why.
	Code   int
	Reason string

	// Subscribe and Gap.
	Stream   string
	Selector string
	// Subscribe: the server's latest sequence number and how many snapshot frames follow.
	LatestSequenceNumber uint64
	NumSnapshots         uint64
	// Sequence-mismatch gaps only: expected prev and the frame's prev / sequence.
	// For disconnect and overflow these zero values are not sequence bounds; use Gap.
	ExpectedPrev uint64
	Prev         uint64
	Seq          uint64

	// Retry: a REST read retried after Delay, or a socket reconnect after a failed connect.
	RPC     string
	Attempt int
	Delay   time.Duration

	// Frame: raw bytes as sent (Outgoing) or received. NOT redacted. Read-only: a received frame is the
	// buffer the SDK decodes from.
	Raw      []byte
	Outgoing bool

	// SessionRotated: login completed; authenticated WebSockets still need to reconnect.
	WebsocketReconnectRequired bool
	Generation                 uint64
	ExpiresAt                  time.Time

	// Error and Retry: the error text. Fatal: the socket stopped for good.
	Err   string
	Fatal bool
}

Event is what Config.OnEvent receives. Only the fields that apply to Kind are set.

type EventKind

type EventKind string

EventKind names an Event.

const (
	EventConnect        EventKind = "connect"
	EventReconnect      EventKind = "reconnect"
	EventDisconnect     EventKind = "disconnect"
	EventSubscribe      EventKind = "subscribe"
	EventGap            EventKind = "gap"
	EventRetry          EventKind = "retry"
	EventFrame          EventKind = "frame"
	EventSessionRotated EventKind = "session_rotated"
	EventError          EventKind = "error"
)

type FieldDef

type FieldDef struct{ Name, Type string }

FieldDef is one EIP-712 field: name and type.

type FixedClock

type FixedClock int64

FixedClock always returns the same time.

func (FixedClock) NowNs

func (c FixedClock) NowNs() int64

type FrameTooLargeError

type FrameTooLargeError struct{ Size, Limit int }

FrameTooLargeError: the encoded WS frame is larger than the server accepts. Nothing was sent.

func (*FrameTooLargeError) Error

func (e *FrameTooLargeError) Error() string

type GapRange

type GapRange struct {
	AfterSequence   *uint64
	ThroughSequence *uint64
	Reason          string
}

GapRange bounds potentially missed sequences: exclusive start, inclusive end. A nil bound is unknown. An open end includes re-subscription; REST history cannot use these sequence numbers as resume cursors.

type Gateway

type Gateway int

Gateway is where an RPC or stream is served.

const (
	GatewayMarketData Gateway = iota
	GatewayTrading
	GatewayEdge
)

func (Gateway) String

func (g Gateway) String() string

type InstrumentMeta

type InstrumentMeta struct {
	InstrumentHash string
	BaseDecimals   uint32
	QuoteDecimals  uint32
	// Limits holds the instrument limits the order checks read (tick_size, min_size, min_notional), as
	// decimal strings.
	Limits map[string]string
}

InstrumentMeta is what signing needs from an instrument (get_instrument).

type List

type List []Value

List is an EIP-712 array value.

func Each

func Each[T any](items []T, f func(*T) Value) List

Each is the each transform: one nested message per list item.

type MessageBuilder

type MessageBuilder struct{ Err error }

MessageBuilder collects the first transform error while a message is built.

func (*MessageBuilder) Address

func (b *MessageBuilder) Address(v, at string) Value

Address is the address transform: absent is the zero address.

func (*MessageBuilder) AssetKey

func (b *MessageBuilder) AssetKey(meta *Meta, name string) Value

AssetKey is the assetKey transform: the instrument hash as a uint256.

func (*MessageBuilder) Copy

func (b *MessageBuilder) Copy(v any, eipType, at string, def any) Value

Copy is the copy, sig.nonce and sig.expiration transforms: the wire value as the EIP-712 type, or def when absent (def nil: the field is required). def is a bool, string or int64.

func (*MessageBuilder) CurrencyBalanceDecimals

func (b *MessageBuilder) CurrencyBalanceDecimals(meta *Meta, symbol string) uint32

CurrencyBalanceDecimals is the scale for currency_balance_decimals.

func (*MessageBuilder) CurrencyID

func (b *MessageBuilder) CurrencyID(meta *Meta, symbol string) Value

CurrencyID is the currencyId transform.

func (*MessageBuilder) EnumCode

func (b *MessageBuilder) EnumCode(v WireEnum, at string) Value

EnumCode is the enumCode transform. Absent is 0; a value this SDK does not know is an error.

func (*MessageBuilder) InstrumentBaseDecimals

func (b *MessageBuilder) InstrumentBaseDecimals(meta *Meta, name string) uint32

InstrumentBaseDecimals is the scale for instrument_base_decimals.

func (*MessageBuilder) InstrumentQuoteDecimals

func (b *MessageBuilder) InstrumentQuoteDecimals(meta *Meta, name string) uint32

InstrumentQuoteDecimals is the scale for instrument_quote_decimals.

func (*MessageBuilder) MainAccount

func (b *MessageBuilder) MainAccount(meta *Meta) Value

MainAccount is the mainAccount transform: the session's main account address.

func (*MessageBuilder) Scaled

func (b *MessageBuilder) Scaled(v string, decimals uint32, at, def string) Value

Scaled is the scaled transform: decimal string x 10^decimals. Over-precision is an error, never rounded. def ("" = none) is used when v is absent.

type Meta

type Meta struct {
	Instruments map[string]InstrumentMeta
	Currencies  map[string]CurrencyMeta
	MainAccount string
}

Meta is the metadata one sign call needs, already loaded: instruments, currencies and, for calls that sign it, the session's main account.

func (*Meta) Currency

func (m *Meta) Currency(symbol string) (CurrencyMeta, error)

func (*Meta) Instrument

func (m *Meta) Instrument(name string) (InstrumentMeta, error)

type MetadataCache

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

MetadataCache holds instrument and currency metadata and the session's main account for signing. Each key loads once; concurrent callers share one load; a failed load is not cached. The main account is loaded once per client.

func (*MetadataCache) Currency

func (c *MetadataCache) Currency(ctx context.Context, symbol string, fn func(context.Context, string) (CurrencyMeta, error)) (CurrencyMeta, error)

func (*MetadataCache) DropInstrument

func (c *MetadataCache) DropInstrument(name string)

DropInstrument forgets an instrument; the next call that needs it loads it again.

func (*MetadataCache) Instrument

func (c *MetadataCache) Instrument(ctx context.Context, name string, fn func(context.Context, string) (InstrumentMeta, error)) (InstrumentMeta, error)

func (*MetadataCache) MainAccount

func (c *MetadataCache) MainAccount(ctx context.Context, fn func(context.Context) (string, error)) (string, error)

MainAccount returns the session's main account address, loading it with fn the first time.

func (*MetadataCache) PutCurrency

func (c *MetadataCache) PutCurrency(symbol string, v CurrencyMeta)

func (*MetadataCache) PutInstrument

func (c *MetadataCache) PutInstrument(name string, v InstrumentMeta)

func (*MetadataCache) PutMainAccount

func (c *MetadataCache) PutMainAccount(address string)

PutMainAccount sets the session's main account address, so signing does not fetch it.

type NonceProvider

type NonceProvider interface {
	NextNonce() uint32
}

NonceProvider gives the uint32 signature nonce (the EIP-712 Order.nonce is uint32).

type OrderBook

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

OrderBook builds one instrument's levels from an SDK subscription. Forward its gap events to OnEvent. In delta mode, Reset after a gap requires a fresh subscription's snapshot; an old queued snapshot must not restore readiness. Methods are safe across goroutines.

func NewOrderBook

func NewOrderBook(instrument string, mode BookMode) (*OrderBook, error)

func (*OrderBook) Apply

func (*OrderBook) Invalidate

func (b *OrderBook) Invalidate(gap *GapRange)

func (*OrderBook) OnEvent

func (b *OrderBook) OnEvent(event Event)

func (*OrderBook) Ready

func (b *OrderBook) Ready() bool

func (*OrderBook) Reset

func (*OrderBook) Snapshot

func (b *OrderBook) Snapshot() (BookSnapshot, error)

type OrderCheckRule

type OrderCheckRule struct {
	Field, Times, Check, Limit string
	SkipIf                     []string
	ServerCode                 int
}

OrderCheckRule is one contract rule (contract.json order_checks.rules).

type OrderChecks

type OrderChecks struct {
	Instrument string
	Scales     map[string]int
	Rules      []OrderCheckRule
}

OrderChecks is the generated table. A scale is fixed decimals, or -1 for the instrument's base_decimals.

type OrderLookup

type OrderLookup interface {
	GetOrder(context.Context, *models.ApiGetOrderRequest) (*models.ApiGetOrderResponse, error)
}

OrderLookup deliberately exposes only the read needed to resolve an order.

type OrderOutOfBoundsError

type OrderOutOfBoundsError struct {
	Instrument string
	// Leg is the index of the failing leg.
	Leg int
	// Field is the leg field checked, or "limit_price * size" for the notional.
	Field string
	// Check is "at_least" or "multiple_of".
	Check string
	// Limit is the instrument field it is checked against: tick_size, min_size or min_notional.
	Limit      string
	Value      string
	LimitValue string
	// Nearest are the nearest valid values of Field (of size, for the notional).
	Nearest []string
	// ServerCode is the gateway error the order would get, e.g. 2064 (invalid limit price tick).
	ServerCode int
	Message    string
}

OrderOutOfBoundsError: an order leg breaks one of its instrument's limits. Returned before signing; nothing was sent. The SDK never rounds an order: pick one of Nearest and send again. Values are decimal strings without trailing zeros.

func (*OrderOutOfBoundsError) Error

func (e *OrderOutOfBoundsError) Error() string

type OrderResolution

type OrderResolution struct {
	Status OrderResolutionStatus
	Order  *models.Order
}

OrderResolution describes an observed ID match, not proof of which submission placed it. Reusing client IDs can make different submissions indistinguishable.

func ResolveOrder

func ResolveOrder(ctx context.Context, client OrderLookup, subAccountID, clientOrderID uint64) (OrderResolution, error)

ResolveOrder only looks up an order. Not found remains unknown: history can lag. Neither outcome means it is safe to resend the original order.

type OrderResolutionStatus

type OrderResolutionStatus string
const (
	OrderFound        OrderResolutionStatus = "found"
	OrderStillUnknown OrderResolutionStatus = "still_unknown"
)

type OrderStateUnknownError

type OrderStateUnknownError struct {
	RPC    string
	Reason string
	// ClientOrderID is the order's client_order_id: 0 when the write has none or carries several.
	ClientOrderID uint64
	// ClientOrderIDs lists every client_order_id the write carried (each order of a bulk call).
	ClientOrderIDs []uint64
	// Err is the original transport, API or decode error.
	Err error
}

OrderStateUnknownError: a write was in flight when the connection dropped or the call timed out. The order may or may not exist; look it up (e.g. by ClientOrderID). The SDK never resends a write.

func (*OrderStateUnknownError) Error

func (e *OrderStateUnknownError) Error() string

func (*OrderStateUnknownError) Unwrap

func (e *OrderStateUnknownError) Unwrap() error

type OrderTransport

type OrderTransport int

OrderTransport is how order-entry writes travel. Chosen once per client.

const (
	// OrderTransportREST sends orders as HTTP POSTs (the default).
	OrderTransportREST OrderTransport = iota
	// OrderTransportWS sends orders over the trading WebSocket (lower latency). A drop or timeout is
	// *OrderStateUnknownError.
	OrderTransportWS
)

type OutgoingCall

type OutgoingCall struct {
	// RPC is the method, e.g. "v1/create_order".
	RPC string
	// Params is the request: a pointer to the generated request model (e.g.
	// *models.ApiCreateOrderRequest). Change it in place. For signed calls it is a copy of the
	// caller's request.
	Params    any
	Transport Via
}

OutgoingCall is one RPC as Config.BeforeSend sees it. The hook runs before signing, so nothing can change a request after it is signed.

type Page

type Page interface{ NextCursor() string }

Page exposes the continuation cursor returned by a paginated endpoint. Generated response models implement this interface.

type PaginationCycleError

type PaginationCycleError struct{ Cursor string }

PaginationCycleError stops a traversal before requesting the same cursor twice.

func (*PaginationCycleError) Error

func (e *PaginationCycleError) Error() string

type PrivateKeySigner

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

PrivateKeySigner signs with an in-process secp256k1 key. Also fits session keys.

func NewPrivateKeySigner

func NewPrivateKeySigner(privateKey string) (*PrivateKeySigner, error)

NewPrivateKeySigner takes a 32-byte key as hex, with or without 0x.

func (*PrivateKeySigner) Address

func (s *PrivateKeySigner) Address() string

func (*PrivateKeySigner) SignDigest

func (s *PrivateKeySigner) SignDigest(digest [32]byte) Signature

SignDigest signs a 32-byte digest (RFC 6979, low-s).

func (*PrivateKeySigner) SignTyped

func (s *PrivateKeySigner) SignTyped(_ context.Context, domain *Domain, primary *StructType, message Value) (Signature, error)

func (*PrivateKeySigner) String

func (s *PrivateKeySigner) String() string

String never prints the key.

type RPCSpec

type RPCSpec struct {
	// Method is the JSON-RPC method, e.g. "v1/create_order" (for edge routes, the path without "/").
	Method  string
	Gateway Gateway
	// Path is the REST path, e.g. "/full/v1/create_order".
	Path string
	// LitePath is the REST path in the lite encoding, e.g. "/lite/v1/create_order"; empty for edge
	// routes, which have no lite form.
	LitePath string
	// Auth: needs the session cookie.
	Auth bool
	// Write: never retried; an ambiguous failure is *OrderStateUnknownError.
	Write bool
	// OrderEntry: goes over the trading WebSocket when the client uses OrderTransportWS.
	OrderEntry bool
	// RefreshMetadataOn: error codes that mean the cached instrument limits may be stale. The runtime
	// drops the request's leg instruments from the metadata cache; the order itself is never resent.
	RefreshMetadataOn []int
}

RPCSpec describes one RPC or edge route (generated in specs_gen.go).

type RandomNonce

type RandomNonce struct{}

RandomNonce draws nonces from crypto/rand.

func (RandomNonce) NextNonce

func (RandomNonce) NextNonce() uint32

type RateLimitError

type RateLimitError struct {
	Message string
	Status  int
	RPC     string
}

RateLimitError is code 1006. errors.As also finds it as an *APIError.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the same error as an *APIError.

type RequestInfo

type RequestInfo[Req any] struct {
	DefaultAccount func(*Req, uint64)
	// Missing returns the first required field that is not set ("" when all are).
	Missing func(*Req) string
	// ClientOrderID (order writes only) sets order.metadata.client_order_id when absent and returns it.
	ClientOrderID func(*Req, ClientOrderIDProvider) uint64
	// ClientOrderIDs (writes carrying a list of orders, e.g. bulk orders) sets each order's
	// metadata.client_order_id when absent and returns them all, in list order.
	ClientOrderIDs func(*Req, ClientOrderIDProvider) []uint64
}

RequestInfo is what generated code knows about a request type.

type Runtime

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

Runtime is the one object generated code talks to. It holds the environment, both sockets, the session and the metadata cache. Same size however many RPCs or streams exist.

func NewRuntime

func NewRuntime(cfg Config, errors ErrorTable) (*Runtime, error)

NewRuntime builds the runtime. errors is the generated error table; New passes it.

func (*Runtime) Close

func (rt *Runtime) Close() error

Close closes both sockets and stops background work. Pending writes become *OrderStateUnknownError.

func (*Runtime) Domain

func (rt *Runtime) Domain() *Domain

Domain is the EIP-712 domain for this environment's chain id.

func (*Runtime) Encoding

func (rt *Runtime) Encoding() Encoding

Encoding is the JSON encoding of this runtime's gateway calls and streams.

func (*Runtime) Env

func (rt *Runtime) Env() Environment

Env is the environment this runtime talks to.

func (*Runtime) Metadata

func (rt *Runtime) Metadata() *MetadataCache

Metadata is the signing metadata cache (instrument hashes and decimals, currency ids).

func (*Runtime) PrepareSignature

func (rt *Runtime) PrepareSignature(signer *string, nonce **uint32, expiration **time.Time, chainID **uint64, ttlNs int64) error

PrepareSignature fills signer, nonce, expiration and chain_id when absent (expiration 0 and an empty signer count as absent).

func (*Runtime) Session

func (rt *Runtime) Session() SessionState

Session is the current login (zero before the first authenticated call).

func (*Runtime) Sign

func (rt *Runtime) Sign(ctx context.Context, chainID *uint64, st *StructType, message Value) (Signature, error)

Sign signs with the Grvt domain for chainID (nil or 0: this environment's chain id).

func (*Runtime) Signer

func (rt *Runtime) Signer() Signer

Signer is the configured signer (nil if none).

func (*Runtime) Socket

func (rt *Runtime) Socket(g Gateway) *Socket

Socket is the managed socket for a gateway (market data, or trading for everything else).

func (*Runtime) SyncClock

func (rt *Runtime) SyncClock(ctx context.Context, clock *SystemClock) error

SyncClock reads GET {market data}/time ({"server_time": ms}) and feeds it to clock.

type Sequencer

type Sequencer struct {
	Last          uint64
	SnapshotsLeft uint64
	Gaps          uint64
	// ResyncStarted is set when the subscription re-subscribes after a gap; cleared by the snapshot.
	ResyncStarted time.Time
	// contains filtered or unexported fields
}

Sequencer tracks one subscription's sequence numbers.

func (*Sequencer) OnAck

func (s *Sequencer) OnAck(latest, numSnapshots uint64)

OnAck records a subscribe reply.

func (*Sequencer) OnFrame

func (s *Sequencer) OnFrame(seq, prev uint64, hasPrev bool) Verdict

OnFrame judges one frame. seq 0 (or absent) is a snapshot or an unsequenced frame; hasPrev says whether the frame carried prev_sequence_number.

func (*Sequencer) Reset

func (s *Sequencer) Reset()

Reset drops every frame until the next subscribe reply.

func (*Sequencer) ResyncOverdue

func (s *Sequencer) ResyncOverdue(now time.Time, limit time.Duration) bool

ResyncOverdue reports whether a re-subscribe has waited longer than limit for its snapshot.

type SessionState

type SessionState struct {
	Cookie    string
	AccountID string
	IssuedAt  time.Time
	ExpiresAt time.Time
	// Generation bumps on every successful login.
	Generation            uint64
	FundingAccountAddress string
}

SessionState is the current login. Printing or logging it (%v, %+v, %#v, slog) shows the cookie as <redacted>; read the Cookie field directly when you need it.

func (SessionState) GoString

func (s SessionState) GoString() string

GoString keeps the cookie out of %#v.

func (SessionState) LogValue

func (s SessionState) LogValue() slog.Value

LogValue keeps the cookie out of slog output.

func (SessionState) RefreshDue

func (s SessionState) RefreshDue() time.Time

RefreshDue is when a re-login should happen.

func (SessionState) String

func (s SessionState) String() string

String keeps the cookie out of %v and %+v.

type SignFunc

type SignFunc[Req any] func(ctx context.Context, rt *Runtime, req *Req) error

SignFunc is a generated sign function: it fills the request's signature in place.

type Signature

type Signature struct {
	// Signer is the 0x-prefixed lowercase address.
	Signer string
	// R and S are 0x-prefixed 32-byte hex; S is low-s (the server rejects high s, code 2007).
	R, S string
	// V is 27 or 28.
	V uint8
}

Signature is what a Signer returns.

type Signer

type Signer interface {
	// Address is the 0x-prefixed lowercase signer address.
	Address() string
	SignTyped(ctx context.Context, domain *Domain, primary *StructType, message Value) (Signature, error)
}

Signer plug-in. A signer gets the exact EIP-712 input (domain, one of Grvt's generated signed types, message) and returns r/s/v. It needs no Grvt knowledge: a KMS/HSM/wallet signer can call primary.TypedData(domain, message) and hand that JSON to its backend. The runtime checks that the returned signature recovers to Address() for the SDK's own digest and rejects it otherwise.

type SigningError

type SigningError struct{ Message string }

SigningError: a request could not be signed (missing field, over-precise decimal, unknown metadata). Always returned before anything is signed or sent.

func (*SigningError) Error

func (e *SigningError) Error() string

type Socket

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

Socket is one managed WebSocket. Safe for concurrent use.

func (*Socket) ForceReconnect

func (s *Socket) ForceReconnect(reason string)

ForceReconnect drops the connection; it reconnects and every subscription re-syncs from a snapshot.

func (*Socket) Name

func (s *Socket) Name() string

Name is "md" or "td".

func (*Socket) SetResyncTimeout

func (s *Socket) SetResyncTimeout(d time.Duration)

SetResyncTimeout sets how long to wait for the snapshot after a gap re-subscribe before reconnecting.

type StreamOverflowError

type StreamOverflowError struct {
	Stream   string
	Selector string
	Capacity int
}

StreamOverflowError: the consumer fell behind a stream that may not drop items. The queue was cleared and the subscription re-synced; items in between are lost.

func (*StreamOverflowError) Error

func (e *StreamOverflowError) Error() string

type StreamSpec

type StreamSpec struct {
	// Stream is the channel, e.g. "v1.book.d".
	Stream  string
	Gateway Gateway
	Auth    bool
	// SnapshotFeed: every frame is complete (e.g. v1.ticker.s), so a gap needs no re-sync.
	SnapshotFeed bool
	// Conflate: old items may be dropped for a slow consumer: snapshot streams only. Every other
	// stream (deltas, events, private) gives the consumer a *StreamOverflowError and re-syncs.
	Conflate bool
}

StreamSpec describes one stream (generated in specs_gen.go).

type Struct

type Struct []Value

Struct is an EIP-712 struct value: field values in the type's field order.

type StructType

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

StructType is one of Grvt's signed EIP-712 types (signing_gen.go), with its generated encoder. Only the SDK builds them: signers receive one and can read its name, definitions and typed data.

func (*StructType) Digest

func (st *StructType) Digest(d *Domain, message Value) ([32]byte, error)

Digest is keccak256(0x1901 || domainSeparator || hashStruct(message)): what gets signed.

func (*StructType) EncodeType

func (st *StructType) EncodeType() string

EncodeType is the primary type's encodeType string.

func (*StructType) HashStruct

func (st *StructType) HashStruct(message Value) ([32]byte, error)

HashStruct is hashStruct(message) for the primary type. message must be a Struct.

func (*StructType) Name

func (st *StructType) Name() string

Name is the primary type name, e.g. "Order".

func (*StructType) TypeHash

func (st *StructType) TypeHash() [32]byte

TypeHash is keccak256(encodeType) of the primary type.

func (*StructType) TypedData

func (st *StructType) TypedData(d *Domain, message Value) (map[string]any, error)

TypedData is the standard eth_signTypedData_v4 JSON, for signers that need the full struct (KMS, wallets).

func (*StructType) Types

func (st *StructType) Types() []TypeDef

Types are the definitions of the primary type and every struct it references.

type Subscription

type Subscription[F any] struct {
	// contains filtered or unexported fields
}

Subscription is a live stream subscription. Read it with All (a Go 1.23 iterator) or Next; Close unsubscribes.

After a gap, an overflow or a reconnect the subscription re-syncs: the next frame is a fresh snapshot (sequence_number "0") when the stream sends snapshots.

func Subscribe

func Subscribe[F any](ctx context.Context, rt *Runtime, spec *StreamSpec, selector string) (*Subscription[F], error)

Subscribe subscribes to a stream (waits for the server's ack) and returns the subscription. Frames are decoded into F when the consumer reads them.

func (*Subscription[F]) All

func (s *Subscription[F]) All() iter.Seq2[*F, error]

All yields frames until the subscription is closed:

for frame, err := range sub.All() { ... }

A non-nil err is a StreamOverflowError, DecodeError or similar; the loop goes on after it. The loop ends after Close, or after a fatal error (which is yielded first). Breaking out of the loop does not unsubscribe; call Close.

func (*Subscription[F]) Close

func (s *Subscription[F]) Close() error

Close unsubscribes. Safe to call more than once.

func (*Subscription[F]) Dropped

func (s *Subscription[F]) Dropped() uint64

Dropped counts frames dropped because the consumer was slow (conflating streams only).

func (*Subscription[F]) Next

func (s *Subscription[F]) Next(ctx context.Context) (*F, error)

Next waits for the next frame. Errors that do not end the subscription (StreamOverflowError, a failed re-subscribe, DecodeError) are returned once and the next call continues. After Close (or a fatal socket error, returned first) it returns ErrClosed.

func (*Subscription[F]) Selector

func (s *Subscription[F]) Selector() string

Selector is the selector sent, e.g. "BTC_USDT_Perp@500".

func (*Subscription[F]) Stream

func (s *Subscription[F]) Stream() string

Stream is the channel, e.g. "v1.book.d".

type SystemClock

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

SystemClock is the local wall clock plus an optional offset to the server clock. Observe (e.g. with GET /time, see Runtime.SyncClock) moves the offset toward the server with exponential smoothing.

func (*SystemClock) NowNs

func (c *SystemClock) NowNs() int64

func (*SystemClock) Observe

func (c *SystemClock) Observe(serverMs int64, rtt time.Duration)

Observe feeds one server time sample (unix ms) and the round trip it took.

func (*SystemClock) OffsetNs

func (c *SystemClock) OffsetNs() int64

OffsetNs is the current estimate of server time minus local time.

type TimeCounterClientOrderID

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

TimeCounterClientOrderID gives 1<<63 | seconds<<31 | counter: unique per process, sortable, and in the API client range [2^63, 2^64). The counter starts at a random 31-bit value, so separate processes rarely collide.

func (*TimeCounterClientOrderID) NextClientOrderID

func (p *TimeCounterClientOrderID) NextClientOrderID() uint64

type TransportError

type TransportError struct {
	Message string
	RPC     string
	Sent    bool
	Err     error
}

TransportError means no usable answer came back. Sent says whether the request may have left this process (a read can be retried either way; a write that was sent becomes OrderStateUnknownError).

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type TypeDef

type TypeDef struct {
	Name   string
	Fields []FieldDef
}

TypeDef is one EIP-712 struct definition.

type Value

type Value = any

Value is an EIP-712 value: *big.Int, bool, Address, string, []byte, List or Struct. Integers are range-checked against the declared type when hashed.

type Verdict

type Verdict int

Verdict is what to do with one stream frame.

const (
	Deliver Verdict = iota
	// Drop: a duplicate, or a frame from before the current subscribe reply.
	Drop
	Gap
)

type Via

type Via string

Via is how an RPC travels.

const (
	ViaREST Via = "rest"
	ViaWS   Via = "ws"
)

type WireEnum

type WireEnum interface {
	String() string
	Code() (int64, bool)
}

WireEnum is a generated enum: its wire name and the integer signed for it.

Directories

Path Synopsis
examples
quickstart command
Read testnet market data; --trade opts into one bounded order lifecycle.
Read testnet market data; --trade opts into one bounded order lifecycle.
internal
behavior
Package behavior holds the runtime constants every Grvt SDK shares, and the write and retry decisions made with them.
Package behavior holds the runtime constants every Grvt SDK shares, and the write and retry decisions made with them.
wirejson
Package wirejson is the JSON reader behind the generated model decoders (models/models_gen.go) and the WebSocket frame router.
Package wirejson is the JSON reader behind the generated model decoders (models/models_gen.go) and the WebSocket frame router.
Package models holds the wire types from the contract.
Package models holds the wire types from the contract.

Jump to

Keyboard shortcuts

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