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
- Variables
- func AddressSet(v string) bool
- func BackfillPages[P Page](ctx context.Context, fetch func(context.Context, string) (P, error), ...) iter.Seq2[BackfillPage[P], error]
- func Call[Req, Resp any](ctx context.Context, rt *Runtime, spec *RPCSpec, req *Req, ...) (*Resp, error)
- func CheckOrder(checks *OrderChecks, order models.OrderInput, meta *Meta) error
- func ChecksumAddress(a Address) string
- func DecimalText(value *models.Decimal) string
- func Deref[T any](p *T) *T
- func Hex0x(b []byte) string
- func Pages[P Page](ctx context.Context, fetch func(context.Context, string) (P, error), ...) iter.Seq2[P, error]
- func Ptr[T any](v T) *T
- func Redact(data []byte, limit int) string
- func ScaleDecimal(s string, decimals uint32) (*big.Int, error)
- func Selector(primary, secondary []string) string
- func SelectorInt[T ~uint8 | ~uint16 | ~uint32 | ~uint64](v *T) string
- func SignDeriskMmRatioSetDeriskMmRatio(ctx context.Context, rt *Runtime, ...) error
- func SignEdgeWalletLogin(ctx context.Context, rt *Runtime, req *models.EdgeWalletLoginRequestInput) error
- func SignOrderBulkOrders(ctx context.Context, rt *Runtime, req *models.ApiBulkOrdersRequestInput) error
- func SignOrderCreateOrder(ctx context.Context, rt *Runtime, req *models.ApiCreateOrderRequestInput) error
- func SignPositionAddPositionMargin(ctx context.Context, rt *Runtime, ...) error
- func SignPositionSetPositionConfig(ctx context.Context, rt *Runtime, ...) error
- func SignTransferTransfer(ctx context.Context, rt *Runtime, req *models.ApiTransferRequestInput) error
- func SignTransferWithdrawal(ctx context.Context, rt *Runtime, req *models.ApiWithdrawalRequestInput) error
- func SignVaultVaultBurnTokens(ctx context.Context, rt *Runtime, req *models.ApiVaultBurnTokensRequestInput) error
- func SignVaultVaultInvest(ctx context.Context, rt *Runtime, req *models.ApiVaultInvestV2RequestInput) error
- func SignVaultVaultRedeem(ctx context.Context, rt *Runtime, req *models.ApiVaultRedeemV2RequestInput) error
- type APIError
- type Address
- type BackfillPage
- type Backoff
- type BookError
- type BookMode
- type BookSnapshot
- type Client
- func (c *Client) AddPositionMargin(ctx context.Context, req *models.ApiAddIsolatedPositionMarginRequestInput) (*models.ApiAddIsolatedPositionMarginResponse, error)
- func (c *Client) AggregatedAccountSummary(ctx context.Context, req *models.EmptyRequest) (*models.ApiAggregatedAccountSummaryResponse, error)
- func (c *Client) AlgoOrderHistory(ctx context.Context, req *models.ApiAlgoOrderHistoryRequest) (*models.ApiAlgoOrderHistoryResponse, error)
- func (c *Client) AlgoOrderStream(ctx context.Context, sel *models.WSAlgoOrderFeedSelectorV1) (*Subscription[models.WSAlgoOrderFeedDataV1], error)
- func (c *Client) AlgoSubOrderHistory(ctx context.Context, req *models.ApiAlgoSubOrderHistoryRequest) (*models.ApiAlgoSubOrderHistoryResponse, error)
- func (c *Client) BuilderFillHistory(ctx context.Context, req *models.ApiBuilderFillHistoryRequest) (*models.ApiBuilderFillHistoryResponse, error)
- func (c *Client) BulkOrders(ctx context.Context, req *models.ApiBulkOrdersRequestInput) (*models.ApiBulkOrdersResponse, error)
- func (c *Client) CancelAlgoOrder(ctx context.Context, req *models.ApiCancelAlgoOrderRequest) (*models.AckResponse, error)
- func (c *Client) CancelAllOrders(ctx context.Context, req *models.ApiCancelAllOrdersRequest) (*models.AckResponse, error)
- func (c *Client) CancelOnDisconnect(ctx context.Context, req *models.ApiCancelOnDisconnectRequest) (*models.AckResponse, error)
- func (c *Client) CancelOrder(ctx context.Context, req *models.ApiCancelOrderRequest) (*models.AckResponse, error)
- func (c *Client) CancelRfq(ctx context.Context, req *models.ApiCancelRfqRequest) (*models.AckResponse, error)
- func (c *Client) CancelStatusStream(ctx context.Context, sel *models.WSCancelFeedSelectorV1) (*Subscription[models.WSCancelFeedDataV1], error)
- func (c *Client) Candlestick(ctx context.Context, req *models.ApiCandlestickRequest) (*models.ApiCandlestickResponse, error)
- func (c *Client) CandlestickStream(ctx context.Context, sel *models.WSCandlestickFeedSelectorV1) (*Subscription[models.WSCandlestickFeedDataV1], error)
- func (c *Client) Close() error
- func (c *Client) CreateAlgoOrder(ctx context.Context, req *models.ApiCreateAlgoOrderRequest) (*models.ApiCreateAlgoOrderResponse, error)
- func (c *Client) CreateOrder(ctx context.Context, req *models.ApiCreateOrderRequestInput) (*models.ApiCreateOrderResponse, error)
- func (c *Client) CreateRfq(ctx context.Context, req *models.ApiCreateRfqRequestInput) (*models.ApiCreateRfqResponse, error)
- func (c *Client) DepositHistory(ctx context.Context, req *models.ApiDepositHistoryRequest) (*models.ApiDepositHistoryResponse, error)
- func (c *Client) DepositStream(ctx context.Context, sel *models.WSDepositFeedSelectorV1) (*Subscription[models.WSDepositFeedDataV1], error)
- func (c *Client) FillHistory(ctx context.Context, req *models.ApiFillHistoryRequest) (*models.ApiFillHistoryResponse, error)
- func (c *Client) FillStream(ctx context.Context, sel *models.WSFillFeedSelectorV1) (*Subscription[models.WSFillFeedDataV1], error)
- func (c *Client) FundingAccountSummary(ctx context.Context, req *models.EmptyRequest) (*models.ApiFundingAccountSummaryResponse, error)
- func (c *Client) FundingPaymentHistory(ctx context.Context, req *models.ApiFundingPaymentHistoryRequest) (*models.ApiFundingPaymentHistoryResponse, error)
- func (c *Client) FundingRate(ctx context.Context, req *models.ApiFundingRateRequest) (*models.ApiFundingRateResponse, error)
- func (c *Client) GetAlgoOrder(ctx context.Context, req *models.ApiGetAlgoOrderRequest) (*models.ApiGetAlgoOrderResponse, error)
- func (c *Client) GetAllCollateralAssetInfo(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetAllCollateralAssetInfoResponse, error)
- func (c *Client) GetAllInitialLeverage(ctx context.Context, req *models.ApiGetAllInitialLeverageRequest) (*models.ApiGetAllInitialLeverageResponse, error)
- func (c *Client) GetAllInstruments(ctx context.Context, req *models.ApiGetAllInstrumentsRequest) (*models.ApiGetAllInstrumentsResponse, error)
- func (c *Client) GetAuthorizedBuilders(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetAuthorizedBuildersResponse, error)
- func (c *Client) GetCollateralPreference(ctx context.Context, req *models.ApiGetSubAccountCollateralPreferenceRequest) (*models.ApiGetSubAccountCollateralPreferenceResponse, error)
- func (c *Client) GetCurrency(ctx context.Context, req *models.ApiGetCurrencyRequest) (*models.ApiGetCurrencyResponse, error)
- func (c *Client) GetFilteredInstruments(ctx context.Context, req *models.ApiGetFilteredInstrumentsRequest) (*models.ApiGetFilteredInstrumentsResponse, error)
- func (c *Client) GetInstrument(ctx context.Context, req *models.ApiGetInstrumentRequest) (*models.ApiGetInstrumentResponse, error)
- func (c *Client) GetMarginRules(ctx context.Context, req *models.ApiGetMarginRulesRequest) (*models.ApiGetMarginRulesResponse, error)
- func (c *Client) GetOrder(ctx context.Context, req *models.ApiGetOrderRequest) (*models.ApiGetOrderResponse, error)
- func (c *Client) GetPositionMarginLimits(ctx context.Context, req *models.ApiGetIsolatedPositionMarginLimitsRequest) (*models.ApiGetIsolatedPositionMarginLimitsResponse, error)
- func (c *Client) GetSfpTradingSchedule(ctx context.Context, req *models.EmptyRequest) (*models.ApiSfpTradingScheduleResponse, error)
- func (c *Client) GetSubAccounts(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetSubAccountsResponse, error)
- func (c *Client) GetSupportedAssets(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetSupportedAssetsResponse, error)
- func (c *Client) GetWithdrawalFee(ctx context.Context, req *models.ApiWithdrawalFeeRequest) (*models.ApiWithdrawalFeeResponse, error)
- func (c *Client) InterestPaymentHistory(ctx context.Context, req *models.ApiInterestPaymentHistoryRequest) (*models.ApiInterestPaymentHistoryResponse, error)
- func (c *Client) MiniTicker(ctx context.Context, req *models.ApiMiniTickerRequest) (*models.ApiMiniTickerResponse, error)
- func (c *Client) MiniTickerDeltaStream(ctx context.Context, sel *models.WSMiniTickerFeedSelectorV1) (*Subscription[models.PartialWSMiniTickerFeedDataV1], error)
- func (c *Client) MiniTickerSnapStream(ctx context.Context, sel *models.WSMiniTickerFeedSelectorV1) (*Subscription[models.WSMiniTickerFeedDataV1], error)
- func (c *Client) OpenAlgoOrders(ctx context.Context, req *models.ApiOpenAlgoOrdersRequest) (*models.ApiOpenAlgoOrdersResponse, error)
- func (c *Client) OpenOrders(ctx context.Context, req *models.ApiOpenOrdersRequest) (*models.ApiOpenOrdersResponse, error)
- func (c *Client) OrderHistory(ctx context.Context, req *models.ApiOrderHistoryRequest) (*models.ApiOrderHistoryResponse, error)
- func (c *Client) OrderStateStream(ctx context.Context, sel *models.WSOrderStateFeedSelectorV1) (*Subscription[models.WSOrderStateFeedDataV1], error)
- func (c *Client) OrderStream(ctx context.Context, sel *models.WSOrderFeedSelectorV1) (*Subscription[models.WSOrderFeedDataV1], error)
- func (c *Client) OrderbookDeltaStream(ctx context.Context, sel *models.WSOrderbookLevelsFeedSelectorV1) (*Subscription[models.WSOrderbookLevelsFeedDataV1], error)
- func (c *Client) OrderbookLevels(ctx context.Context, req *models.ApiOrderbookLevelsRequest) (*models.ApiOrderbookLevelsResponse, error)
- func (c *Client) OrderbookSnapStream(ctx context.Context, sel *models.WSOrderbookLevelsFeedSelectorV1) (*Subscription[models.WSOrderbookLevelsFeedDataV1], error)
- func (c *Client) PositionHistory(ctx context.Context, req *models.ApiPositionHistoryRequest) (*models.ApiPositionHistoryResponse, error)
- func (c *Client) Positions(ctx context.Context, req *models.ApiPositionsRequest) (*models.ApiPositionsResponse, error)
- func (c *Client) PositionsStream(ctx context.Context, sel *models.WSPositionsFeedSelectorV1) (*Subscription[models.WSPositionsFeedDataV1], error)
- func (c *Client) RfqQuoteStream(ctx context.Context, sel *models.WSRfqQuoteFeedSelectorV1) (*Subscription[models.WSRfqQuoteFeedDataV1], error)
- func (c *Client) Runtime() *Runtime
- func (c *Client) SetDeriskMmRatio(ctx context.Context, ...) (*models.ApiSetDeriskToMaintenanceMarginRatioResponse, error)
- func (c *Client) SetInitialLeverage(ctx context.Context, req *models.ApiSetInitialLeverageRequest) (*models.ApiSetInitialLeverageResponse, error)
- func (c *Client) SetPositionConfig(ctx context.Context, ...) (*models.ApiSetSubAccountPositionMarginConfigResponse, error)
- func (c *Client) SpotAccountSummary(ctx context.Context, req *models.ApiSpotSubAccountSummaryRequest) (*models.ApiSpotSubAccountSummaryResponse, error)
- func (c *Client) SubAccountSummary(ctx context.Context, req *models.ApiSubAccountSummaryRequest) (*models.ApiSubAccountSummaryResponse, error)
- func (c *Client) Ticker(ctx context.Context, req *models.ApiTickerRequest) (*models.ApiTickerResponse, error)
- func (c *Client) TickerDeltaStream(ctx context.Context, sel *models.WSTickerFeedSelectorV1) (*Subscription[models.PartialWSTickerFeedDataV1], error)
- func (c *Client) TickerSnapStream(ctx context.Context, sel *models.WSTickerFeedSelectorV1) (*Subscription[models.WSTickerFeedDataV1], error)
- func (c *Client) Trade(ctx context.Context, req *models.ApiTradeRequest) (*models.ApiTradeResponse, error)
- func (c *Client) TradeHistory(ctx context.Context, req *models.ApiTradeHistoryRequest) (*models.ApiTradeHistoryResponse, error)
- func (c *Client) TradeStream(ctx context.Context, sel *models.WSTradeFeedSelectorV1) (*Subscription[models.WSTradeFeedDataV1], error)
- func (c *Client) Transfer(ctx context.Context, req *models.ApiTransferRequestInput) (*models.ApiTransferResponse, error)
- func (c *Client) TransferHistory(ctx context.Context, req *models.ApiTransferHistoryRequest) (*models.ApiTransferHistoryResponse, error)
- func (c *Client) TransferStream(ctx context.Context, sel *models.WSTransferFeedSelectorV1) (*Subscription[models.WSTransferFeedDataV1], error)
- func (c *Client) VaultBurnTokens(ctx context.Context, req *models.ApiVaultBurnTokensRequestInput) (*models.AckResponse, error)
- func (c *Client) VaultConversionRate(ctx context.Context, req *models.ApiVaultConversionRateRequest) (*models.ApiVaultConversionRateResponse, error)
- func (c *Client) VaultInvest(ctx context.Context, req *models.ApiVaultInvestV2RequestInput) (*models.ApiVaultInvestV2Response, error)
- func (c *Client) VaultInvestorSummary(ctx context.Context, req *models.ApiVaultInvestorSummaryRequest) (*models.ApiVaultInvestorSummaryResponse, error)
- func (c *Client) VaultManagerInvestmentHistory(ctx context.Context, req *models.ApiQueryVaultManagerInvestorHistoryRequest) (*models.ApiQueryVaultManagerInvestorHistoryResponse, error)
- func (c *Client) VaultRedeem(ctx context.Context, req *models.ApiVaultRedeemV2RequestInput) (*models.AckResponse, error)
- func (c *Client) VaultRedeemCancel(ctx context.Context, req *models.ApiVaultRedeemCancelRequest) (*models.AckResponse, error)
- func (c *Client) VaultRedemptionQueue(ctx context.Context, req *models.ApiVaultViewRedemptionQueueRequest) (*models.ApiVaultViewRedemptionQueueResponse, error)
- func (c *Client) Withdrawal(ctx context.Context, req *models.ApiWithdrawalRequestInput) (*models.AckResponse, error)
- func (c *Client) WithdrawalHistory(ctx context.Context, req *models.ApiWithdrawalHistoryRequest) (*models.ApiWithdrawalHistoryResponse, error)
- func (c *Client) WithdrawalStream(ctx context.Context, sel *models.WSWithdrawalFeedSelectorV1) (*Subscription[models.WSWithdrawalFeedDataV1], error)
- type ClientOrderIDProvider
- type Clock
- type Config
- type ConfigError
- type CountdownClient
- type CountdownReceipt
- type CurrencyMeta
- type DecodeError
- type Domain
- type Encoding
- type Environment
- type ErrorInfo
- type ErrorTable
- type Event
- type EventKind
- type FieldDef
- type FixedClock
- type FrameTooLargeError
- type GapRange
- type Gateway
- type InstrumentMeta
- type List
- type MessageBuilder
- func (b *MessageBuilder) Address(v, at string) Value
- func (b *MessageBuilder) AssetKey(meta *Meta, name string) Value
- func (b *MessageBuilder) Copy(v any, eipType, at string, def any) Value
- func (b *MessageBuilder) CurrencyBalanceDecimals(meta *Meta, symbol string) uint32
- func (b *MessageBuilder) CurrencyID(meta *Meta, symbol string) Value
- func (b *MessageBuilder) EnumCode(v WireEnum, at string) Value
- func (b *MessageBuilder) InstrumentBaseDecimals(meta *Meta, name string) uint32
- func (b *MessageBuilder) InstrumentQuoteDecimals(meta *Meta, name string) uint32
- func (b *MessageBuilder) MainAccount(meta *Meta) Value
- func (b *MessageBuilder) Scaled(v string, decimals uint32, at, def string) Value
- type Meta
- type MetadataCache
- func (c *MetadataCache) Currency(ctx context.Context, symbol string, ...) (CurrencyMeta, error)
- func (c *MetadataCache) DropInstrument(name string)
- func (c *MetadataCache) Instrument(ctx context.Context, name string, ...) (InstrumentMeta, error)
- func (c *MetadataCache) MainAccount(ctx context.Context, fn func(context.Context) (string, error)) (string, error)
- func (c *MetadataCache) PutCurrency(symbol string, v CurrencyMeta)
- func (c *MetadataCache) PutInstrument(name string, v InstrumentMeta)
- func (c *MetadataCache) PutMainAccount(address string)
- type NonceProvider
- type OrderBook
- func (b *OrderBook) Apply(frame models.WSOrderbookLevelsFeedDataV1) error
- func (b *OrderBook) Invalidate(gap *GapRange)
- func (b *OrderBook) OnEvent(event Event)
- func (b *OrderBook) Ready() bool
- func (b *OrderBook) Reset(frame models.WSOrderbookLevelsFeedDataV1) error
- func (b *OrderBook) Snapshot() (BookSnapshot, error)
- type OrderCheckRule
- type OrderChecks
- type OrderLookup
- type OrderOutOfBoundsError
- type OrderResolution
- type OrderResolutionStatus
- type OrderStateUnknownError
- type OrderTransport
- type OutgoingCall
- type Page
- type PaginationCycleError
- type PrivateKeySigner
- type RPCSpec
- type RandomNonce
- type RateLimitError
- type RequestInfo
- type Runtime
- func (rt *Runtime) Close() error
- func (rt *Runtime) Domain() *Domain
- func (rt *Runtime) Encoding() Encoding
- func (rt *Runtime) Env() Environment
- func (rt *Runtime) Metadata() *MetadataCache
- func (rt *Runtime) PrepareSignature(signer *string, nonce **uint32, expiration **time.Time, chainID **uint64, ...) error
- func (rt *Runtime) Session() SessionState
- func (rt *Runtime) Sign(ctx context.Context, chainID *uint64, st *StructType, message Value) (Signature, error)
- func (rt *Runtime) Signer() Signer
- func (rt *Runtime) Socket(g Gateway) *Socket
- func (rt *Runtime) SyncClock(ctx context.Context, clock *SystemClock) error
- type Sequencer
- type SessionState
- type SignFunc
- type Signature
- type Signer
- type SigningError
- type Socket
- type StreamOverflowError
- type StreamSpec
- type Struct
- type StructType
- func (st *StructType) Digest(d *Domain, message Value) ([32]byte, error)
- func (st *StructType) EncodeType() string
- func (st *StructType) HashStruct(message Value) ([32]byte, error)
- func (st *StructType) Name() string
- func (st *StructType) TypeHash() [32]byte
- func (st *StructType) TypedData(d *Domain, message Value) (map[string]any, error)
- func (st *StructType) Types() []TypeDef
- type Subscription
- type SystemClock
- type TimeCounterClientOrderID
- type TransportError
- type TypeDef
- type Value
- type Verdict
- type Via
- type WireEnum
Constants ¶
const ( CookieName = "gravity" AccountHeader = "X-Grvt-Account-Id" LoginPath = "/auth/api_key/login" )
const ( 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 = 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 = 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 = 4021 CodeInsufficientTradingVaultShares = 4022 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 { ... }
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 )
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 )
const BaseDecimals = -1
BaseDecimals marks a field scaled by the instrument's base_decimals in OrderChecks.Scales.
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.
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).
const RateLimitCode = behavior.RateLimitCode
RateLimitCode is the rate-limit error code. Always retryable for reads.
const ReadAttempts = behavior.ReadAttempts
ReadAttempts is how many times a read is tried in all.
Variables ¶
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.
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.
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.
var ErrClosed = errors.New("grvt: client closed")
ErrClosed is returned after Client.Close.
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.
var Streams = []*StreamSpec{&StreamAlgoOrderAlgoOrder, &StreamCandlestickCandlestick, &StreamExecutionFill, &StreamExecutionPositions, &StreamOrderCancelStatus, &StreamOrderOrder, &StreamOrderOrderState, &StreamOrderbookOrderbookDelta, &StreamOrderbookOrderbookSnap, &StreamRfqRfqQuote, &StreamTickerMiniTickerDelta, &StreamTickerMiniTickerSnap, &StreamTickerTickerDelta, &StreamTickerTickerSnap, &StreamTradeTrade, &StreamTransferDeposit, &StreamTransferTransfer, &StreamTransferWithdrawal}
Streams lists every stream.
Functions ¶
func AddressSet ¶
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 ¶
ChecksumAddress is the EIP-55 mixed-case address, as eth_signTypedData tooling prints it.
func DecimalText ¶
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 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 ¶
Redact hides secrets in a JSON body, cookie string or log line. It truncates to limit bytes first.
func ScaleDecimal ¶
ScaleDecimal turns "65000.1" with 9 decimals into 65000100000000. More decimal places than decimals is an error.
func SelectorInt ¶
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.
type BackfillPage ¶
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)).
type BookSnapshot ¶
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 ¶
New builds a client. It does not connect: sockets open and the api key logs in on first use.
func (*Client) AddPositionMargin ¶
func (c *Client) AddPositionMargin(ctx context.Context, req *models.ApiAddIsolatedPositionMarginRequestInput) (*models.ApiAddIsolatedPositionMarginResponse, error)
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 ¶
func (c *Client) AlgoOrderHistory(ctx context.Context, req *models.ApiAlgoOrderHistoryRequest) (*models.ApiAlgoOrderHistoryResponse, error)
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 ¶
func (c *Client) AlgoOrderStream(ctx context.Context, sel *models.WSAlgoOrderFeedSelectorV1) (*Subscription[models.WSAlgoOrderFeedDataV1], error)
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 ¶
func (c *Client) AlgoSubOrderHistory(ctx context.Context, req *models.ApiAlgoSubOrderHistoryRequest) (*models.ApiAlgoSubOrderHistoryResponse, error)
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 ¶
func (c *Client) BuilderFillHistory(ctx context.Context, req *models.ApiBuilderFillHistoryRequest) (*models.ApiBuilderFillHistoryResponse, error)
BuilderFillHistory The request to get the historical builder trade of a builder
Only for builders. Other accounts get an empty list.
func (*Client) BulkOrders ¶
func (c *Client) BulkOrders(ctx context.Context, req *models.ApiBulkOrdersRequestInput) (*models.ApiBulkOrdersResponse, error)
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 ¶
func (c *Client) CancelRfq(ctx context.Context, req *models.ApiCancelRfqRequest) (*models.AckResponse, error)
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 ¶
func (c *Client) CancelStatusStream(ctx context.Context, sel *models.WSCancelFeedSelectorV1) (*Subscription[models.WSCancelFeedDataV1], error)
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 ¶
func (c *Client) Candlestick(ctx context.Context, req *models.ApiCandlestickRequest) (*models.ApiCandlestickResponse, error)
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 ¶
func (c *Client) CandlestickStream(ctx context.Context, sel *models.WSCandlestickFeedSelectorV1) (*Subscription[models.WSCandlestickFeedDataV1], error)
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 ¶
Close closes both sockets and stops background work. Writes still waiting for a reply return *OrderStateUnknownError.
func (*Client) CreateAlgoOrder ¶
func (c *Client) CreateAlgoOrder(ctx context.Context, req *models.ApiCreateAlgoOrderRequest) (*models.ApiCreateAlgoOrderResponse, error)
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 ¶
func (c *Client) CreateOrder(ctx context.Context, req *models.ApiCreateOrderRequestInput) (*models.ApiCreateOrderResponse, error)
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 ¶
func (c *Client) CreateRfq(ctx context.Context, req *models.ApiCreateRfqRequestInput) (*models.ApiCreateRfqResponse, error)
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 ¶
func (c *Client) DepositHistory(ctx context.Context, req *models.ApiDepositHistoryRequest) (*models.ApiDepositHistoryResponse, error)
DepositHistory The request to get the historical deposits of an account
Required: currency.
func (*Client) DepositStream ¶
func (c *Client) DepositStream(ctx context.Context, sel *models.WSDepositFeedSelectorV1) (*Subscription[models.WSDepositFeedDataV1], error)
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 ¶
func (c *Client) FillHistory(ctx context.Context, req *models.ApiFillHistoryRequest) (*models.ApiFillHistoryResponse, error)
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 ¶
func (c *Client) FillStream(ctx context.Context, sel *models.WSFillFeedSelectorV1) (*Subscription[models.WSFillFeedDataV1], error)
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 ¶
func (c *Client) FundingPaymentHistory(ctx context.Context, req *models.ApiFundingPaymentHistoryRequest) (*models.ApiFundingPaymentHistoryResponse, error)
FundingPaymentHistory Query for all historical funding payments made by a single account.
Required: sub_account_id.
func (*Client) FundingRate ¶
func (c *Client) FundingRate(ctx context.Context, req *models.ApiFundingRateRequest) (*models.ApiFundingRateResponse, error)
FundingRate Lookup the historical funding rate of a perpetual future.
Required: instrument.
func (*Client) GetAlgoOrder ¶
func (c *Client) GetAlgoOrder(ctx context.Context, req *models.ApiGetAlgoOrderRequest) (*models.ApiGetAlgoOrderResponse, error)
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 ¶
func (c *Client) GetAllInitialLeverage(ctx context.Context, req *models.ApiGetAllInitialLeverageRequest) (*models.ApiGetAllInitialLeverageResponse, error)
GetAllInitialLeverage The request to get the initial leverage of a sub account
Required: sub_account_id.
func (*Client) GetAllInstruments ¶
func (c *Client) GetAllInstruments(ctx context.Context, req *models.ApiGetAllInstrumentsRequest) (*models.ApiGetAllInstrumentsResponse, error)
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 ¶
func (c *Client) GetCollateralPreference(ctx context.Context, req *models.ApiGetSubAccountCollateralPreferenceRequest) (*models.ApiGetSubAccountCollateralPreferenceResponse, error)
GetCollateralPreference Fetch the per-currency collateral enable/disable state for a Multi-Asset Mode sub account.
Required: sub_account_id.
func (*Client) GetCurrency ¶
func (c *Client) GetCurrency(ctx context.Context, req *models.ApiGetCurrencyRequest) (*models.ApiGetCurrencyResponse, error)
GetCurrency Fetch all currencies
func (*Client) GetFilteredInstruments ¶
func (c *Client) GetFilteredInstruments(ctx context.Context, req *models.ApiGetFilteredInstrumentsRequest) (*models.ApiGetFilteredInstrumentsResponse, error)
GetFilteredInstruments Fetch a list of instruments based on the filters provided
func (*Client) GetInstrument ¶
func (c *Client) GetInstrument(ctx context.Context, req *models.ApiGetInstrumentRequest) (*models.ApiGetInstrumentResponse, error)
GetInstrument Fetch a single instrument by supplying the asset or instrument name
Required: instrument.
func (*Client) GetMarginRules ¶
func (c *Client) GetMarginRules(ctx context.Context, req *models.ApiGetMarginRulesRequest) (*models.ApiGetMarginRulesResponse, error)
GetMarginRules API request payload to get margin rules for a particular instrument
Required: instrument.
func (*Client) GetOrder ¶
func (c *Client) GetOrder(ctx context.Context, req *models.ApiGetOrderRequest) (*models.ApiGetOrderResponse, error)
GetOrder Retrieve the order for the account. Either `order_id` or `client_order_id` must be provided.
Required: sub_account_id.
func (*Client) GetPositionMarginLimits ¶
func (c *Client) GetPositionMarginLimits(ctx context.Context, req *models.ApiGetIsolatedPositionMarginLimitsRequest) (*models.ApiGetIsolatedPositionMarginLimitsResponse, error)
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 ¶
func (c *Client) GetSubAccounts(ctx context.Context, req *models.EmptyRequest) (*models.ApiGetSubAccountsResponse, error)
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 ¶
func (c *Client) GetWithdrawalFee(ctx context.Context, req *models.ApiWithdrawalFeeRequest) (*models.ApiWithdrawalFeeResponse, error)
GetWithdrawalFee Query the flat withdrawal fee for a native (L2 -> L1) bridge withdrawal, expressed in the requested currency
Required: token_currency.
func (*Client) InterestPaymentHistory ¶
func (c *Client) InterestPaymentHistory(ctx context.Context, req *models.ApiInterestPaymentHistoryRequest) (*models.ApiInterestPaymentHistoryResponse, error)
InterestPaymentHistory Query for all historical MAM hourly interest payments charged to a single sub account.
Required: sub_account_id.
func (*Client) MiniTicker ¶
func (c *Client) MiniTicker(ctx context.Context, req *models.ApiMiniTickerRequest) (*models.ApiMiniTickerResponse, error)
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 ¶
func (c *Client) MiniTickerDeltaStream(ctx context.Context, sel *models.WSMiniTickerFeedSelectorV1) (*Subscription[models.PartialWSMiniTickerFeedDataV1], error)
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 ¶
func (c *Client) MiniTickerSnapStream(ctx context.Context, sel *models.WSMiniTickerFeedSelectorV1) (*Subscription[models.WSMiniTickerFeedDataV1], error)
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 ¶
func (c *Client) OpenAlgoOrders(ctx context.Context, req *models.ApiOpenAlgoOrdersRequest) (*models.ApiOpenAlgoOrdersResponse, error)
OpenAlgoOrders Retrieves all open algo orders for the account, including algo orders still pending on their trigger.
Required: sub_account_id.
func (*Client) OpenOrders ¶
func (c *Client) OpenOrders(ctx context.Context, req *models.ApiOpenOrdersRequest) (*models.ApiOpenOrdersResponse, error)
OpenOrders Retrieves all open orders for the account. This may not match new orders in flight.
Required: sub_account_id.
func (*Client) OrderHistory ¶
func (c *Client) OrderHistory(ctx context.Context, req *models.ApiOrderHistoryRequest) (*models.ApiOrderHistoryResponse, error)
OrderHistory Retrieves the order history for the account.
Required: sub_account_id.
func (*Client) OrderStateStream ¶
func (c *Client) OrderStateStream(ctx context.Context, sel *models.WSOrderStateFeedSelectorV1) (*Subscription[models.WSOrderStateFeedDataV1], error)
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 ¶
func (c *Client) OrderStream(ctx context.Context, sel *models.WSOrderFeedSelectorV1) (*Subscription[models.WSOrderFeedDataV1], error)
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 ¶
func (c *Client) OrderbookDeltaStream(ctx context.Context, sel *models.WSOrderbookLevelsFeedSelectorV1) (*Subscription[models.WSOrderbookLevelsFeedDataV1], error)
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 ¶
func (c *Client) OrderbookLevels(ctx context.Context, req *models.ApiOrderbookLevelsRequest) (*models.ApiOrderbookLevelsResponse, error)
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 ¶
func (c *Client) OrderbookSnapStream(ctx context.Context, sel *models.WSOrderbookLevelsFeedSelectorV1) (*Subscription[models.WSOrderbookLevelsFeedDataV1], error)
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 ¶
func (c *Client) PositionHistory(ctx context.Context, req *models.ApiPositionHistoryRequest) (*models.ApiPositionHistoryResponse, error)
PositionHistory Query for position lifecycle records for a single sub account.
Required: sub_account_id.
func (*Client) Positions ¶
func (c *Client) Positions(ctx context.Context, req *models.ApiPositionsRequest) (*models.ApiPositionsResponse, error)
Positions Query the positions of a sub account
Required: sub_account_id.
func (*Client) PositionsStream ¶
func (c *Client) PositionsStream(ctx context.Context, sel *models.WSPositionsFeedSelectorV1) (*Subscription[models.WSPositionsFeedDataV1], error)
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 ¶
func (c *Client) RfqQuoteStream(ctx context.Context, sel *models.WSRfqQuoteFeedSelectorV1) (*Subscription[models.WSRfqQuoteFeedDataV1], error)
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 ¶
Runtime is the shared runtime: environment, sockets, session, metadata cache.
func (*Client) SetDeriskMmRatio ¶
func (c *Client) SetDeriskMmRatio(ctx context.Context, req *models.ApiSetDeriskToMaintenanceMarginRatioRequestInput) (*models.ApiSetDeriskToMaintenanceMarginRatioResponse, error)
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 ¶
func (c *Client) SetInitialLeverage(ctx context.Context, req *models.ApiSetInitialLeverageRequest) (*models.ApiSetInitialLeverageResponse, error)
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 ¶
func (c *Client) SetPositionConfig(ctx context.Context, req *models.ApiSetSubAccountPositionMarginConfigRequestInput) (*models.ApiSetSubAccountPositionMarginConfigResponse, error)
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 ¶
func (c *Client) SpotAccountSummary(ctx context.Context, req *models.ApiSpotSubAccountSummaryRequest) (*models.ApiSpotSubAccountSummaryResponse, error)
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 ¶
func (c *Client) SubAccountSummary(ctx context.Context, req *models.ApiSubAccountSummaryRequest) (*models.ApiSubAccountSummaryResponse, error)
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 ¶
func (c *Client) Ticker(ctx context.Context, req *models.ApiTickerRequest) (*models.ApiTickerResponse, error)
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 ¶
func (c *Client) TickerDeltaStream(ctx context.Context, sel *models.WSTickerFeedSelectorV1) (*Subscription[models.PartialWSTickerFeedDataV1], error)
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 ¶
func (c *Client) TickerSnapStream(ctx context.Context, sel *models.WSTickerFeedSelectorV1) (*Subscription[models.WSTickerFeedDataV1], error)
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 ¶
func (c *Client) Trade(ctx context.Context, req *models.ApiTradeRequest) (*models.ApiTradeResponse, error)
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 ¶
func (c *Client) TradeHistory(ctx context.Context, req *models.ApiTradeHistoryRequest) (*models.ApiTradeHistoryResponse, error)
TradeHistory Perform historical lookup of public trades in any given instrument.
Required: instrument.
func (*Client) TradeStream ¶
func (c *Client) TradeStream(ctx context.Context, sel *models.WSTradeFeedSelectorV1) (*Subscription[models.WSTradeFeedDataV1], error)
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 ¶
func (c *Client) Transfer(ctx context.Context, req *models.ApiTransferRequestInput) (*models.ApiTransferResponse, error)
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 ¶
func (c *Client) TransferHistory(ctx context.Context, req *models.ApiTransferHistoryRequest) (*models.ApiTransferHistoryResponse, error)
TransferHistory The request to get the historical transfers of an account
Required: currency.
func (*Client) TransferStream ¶
func (c *Client) TransferStream(ctx context.Context, sel *models.WSTransferFeedSelectorV1) (*Subscription[models.WSTransferFeedDataV1], error)
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 ¶
func (c *Client) VaultBurnTokens(ctx context.Context, req *models.ApiVaultBurnTokensRequestInput) (*models.AckResponse, error)
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 ¶
func (c *Client) VaultConversionRate(ctx context.Context, req *models.ApiVaultConversionRateRequest) (*models.ApiVaultConversionRateResponse, error)
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 ¶
func (c *Client) VaultInvest(ctx context.Context, req *models.ApiVaultInvestV2RequestInput) (*models.ApiVaultInvestV2Response, error)
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 ¶
func (c *Client) VaultInvestorSummary(ctx context.Context, req *models.ApiVaultInvestorSummaryRequest) (*models.ApiVaultInvestorSummaryResponse, error)
VaultInvestorSummary Request payload for fetching the summary of a vault investor.
func (*Client) VaultManagerInvestmentHistory ¶
func (c *Client) VaultManagerInvestmentHistory(ctx context.Context, req *models.ApiQueryVaultManagerInvestorHistoryRequest) (*models.ApiQueryVaultManagerInvestorHistoryResponse, error)
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 ¶
func (c *Client) VaultRedeem(ctx context.Context, req *models.ApiVaultRedeemV2RequestInput) (*models.AckResponse, error)
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 ¶
func (c *Client) VaultRedemptionQueue(ctx context.Context, req *models.ApiVaultViewRedemptionQueueRequest) (*models.ApiVaultViewRedemptionQueueResponse, error)
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 ¶
func (c *Client) Withdrawal(ctx context.Context, req *models.ApiWithdrawalRequestInput) (*models.AckResponse, error)
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 ¶
func (c *Client) WithdrawalHistory(ctx context.Context, req *models.ApiWithdrawalHistoryRequest) (*models.ApiWithdrawalHistoryResponse, error)
WithdrawalHistory The request to get the historical withdrawals of an account
Required: currency.
func (*Client) WithdrawalStream ¶
func (c *Client) WithdrawalStream(ctx context.Context, sel *models.WSWithdrawalFeedSelectorV1) (*Subscription[models.WSWithdrawalFeedDataV1], error)
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})
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 ¶
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 ¶
CurrencyMeta is what signing needs from a currency (get_currency).
type DecodeError ¶
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 ¶
ExchangeDomain is the "GRVT Exchange" domain for a chain id. Domains are cached per chain id.
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 )
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 (*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 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 ¶
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 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 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.
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) 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 (*OrderBook) Invalidate ¶
func (*OrderBook) Snapshot ¶
func (b *OrderBook) Snapshot() (BookSnapshot, error)
type OrderCheckRule ¶
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 ¶
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 ¶
Close closes both sockets and stops background work. Pending writes become *OrderStateUnknownError.
func (*Runtime) 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).
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) OnFrame ¶
OnFrame judges one frame. seq 0 (or absent) is a snapshot or an unsequenced frame; hasPrev says whether the frame carried prev_sequence_number.
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 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 ¶
ForceReconnect drops the connection; it reconnects and every subscription re-syncs from a snapshot.
func (*Socket) SetResyncTimeout ¶
SetResyncTimeout sets how long to wait for the snapshot after a gap re-subscribe before reconnecting.
type StreamOverflowError ¶
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 ¶
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 ¶
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 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.
Source Files
¶
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. |