Go SDK
Install the Go module, create a client, call any RPC, stream data, place signed orders and handle errors.
On this page
Help me with: Go SDK. Install the Go module, create a client, call any RPC, stream data, place signed orders and handle errors.
Target environment: {environment} (chain ID {chainId}). Recorded signing cases keep their original environment.
{executionGuidance}
Read this first: {origin}/bundle/sdks/go.md (~33 KB, plain Markdown: this page plus the AGENTS.md rules, Environments).
Fetch other pages from the index at {origin}/llms.txt only as you need them. {origin}/downloads/contract.json is a machine-readable contract for tools, not for reading.
Rules: follow AGENTS.md; do not send requests without the user asking you to; read credentials from environment variables; never retry writes automatically; show me the code and how to run it. Preview. Any 0.x release can change the API. Your
go.modpins the version you get.
The Go SDK has a method for every call and stream in the API reference. It
signs every call that needs a signature (filling in the nonce, expiration and client order ID) and
re-syncs streams after a gap (when frames were missed, it subscribes again to get current data). Every call takes a context.Context.
New here? Install the SDK and run the Quickstart, then read this page down to Track and cancel an order. Later sections are for when you need them.
Install
go get github.com/gravity-technologies/grvt-sdk-go
The SDK is in preview: any 0.x release can change the API, and your go.mod pins the version you get. It needs
Go 1.27.4 or newer.
Create a client
package main
import (
"context"
"fmt"
"log"
"os"
grvt "github.com/gravity-technologies/grvt-sdk-go"
"github.com/gravity-technologies/grvt-sdk-go/models"
)
func main() {
ctx := context.Background()
// The API key logs in; the signer signs orders with your signing key. Leave both out for public data only.
signer, err := grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY"))
if err != nil {
log.Fatal(err)
}
client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: os.Getenv("GRVT_API_KEY"), Signer: signer})
if err != nil {
log.Fatal(err)
}
defer client.Close()
t, err := client.Ticker(ctx, &models.ApiTickerRequest{Instrument: "BTC_USDT_Perp"})
if err != nil {
log.Fatal(err)
}
fmt.Println(t.Result.MarkPrice) // the exchange's fair price, used for margin
}
- Use
grvt.Prod()for production (Environments). - The client sends short (lite) field names on the wire by default; your code still uses the full names.
Encoding: grvt.EncodingFullin theConfigswitches to full names (Encoding). On a customEnvironment, lite WebSocket URLs are the full ones with/ws/fullswapped for/ws/lite; setMarketDataWSLiteandTradingWSLiteonly when your URLs don't end in/ws/full. - The client logs in on the first private call and renews the session before it expires (Authentication). Renewal reconnects the client's WebSockets, so every stream gets a gap (Session renewal).
- To stop, follow Shut down cleanly.
Call an RPC
Every call is a method on the client, client.<Method>(ctx, *Request) (*Response, error): the name on its
reference page in Go style (create_order is client.CreateOrder). Request and response types keep the
contract names, and their JSON tags are the wire field names.
inst, err := client.GetInstrument(ctx, &models.ApiGetInstrumentRequest{Instrument: "BTC_USDT_Perp"})
if err != nil {
return err
}
fmt.Println(inst.Result.TickSize, inst.Result.MinSize)
- Reads are tried up to 3 times; writes are sent once (What the SDK retries).
- Timeouts, in the
Config:CallTimeout(30 s),HTTPAttemptTimeout(10 s),WSRequestTimeout(5 s),ResyncTimeout(5 s),IdleTimeout(30 s). A shorter deadline on thectxyou pass also applies.CallTimeoutcovers the whole call: login, instrument lookups, signing, retries and the reply;HTTPAttemptTimeoutcaps each HTTP try within it. Config.HTTPClientreplaces the default HTTP client, for REST and the WebSocket handshake. The SDK copies it and never follows redirects; aTimeouton it is one more cap per attempt.
Pagination
grvt.Pages follows a history call's cursors one page at a time, without fetching ahead. Pass an empty starting
cursor for the first page, and keep the filters fixed inside your callback.
fetch := func(ctx context.Context, cursor string) (*models.ApiTradeHistoryResponse, error) {
return client.TradeHistory(ctx, &models.ApiTradeHistoryRequest{
Instrument: "BTC_USDT_Perp", Cursor: cursor,
})
}
for page, err := range grvt.Pages(ctx, fetch, "") {
if err != nil {
return err
}
for _, trade := range page.Result {
fmt.Println(trade)
}
}
- An empty page can still have a next cursor.
- Breaking out of the loop stops further calls; the
ctxcancels a fetch in progress. - A cursor seen twice returns
*grvt.PaginationCycleError. Fetch errors pass through, with no extra retries. - Cursors don't give a stable snapshot while records change.
Default sub-account
Set SubAccountID in the Config to fill in the account on requests and stream selectors that leave it out.
- Zero in the
Configmeans no default. Zero in a request or selector means "not set"; in anOrderInput,nilmeans not set. - An account you set yourself always wins.
- Bulk orders take the request's account first, then the client default.
- Transfers never get a default: source and destination stay explicit.
- Defaults are applied to a copy of your request, before signing.
- Without a default, a call that needs an account fails unless the request names one.
Stream data
Every stream method ends in Stream, for example client.TradeStream.
- Call the stream method to get a subscription.
- Range over
All()to read frames, or callNext(ctx)to stop when a context ends. - Call
Close()to unsubscribe. Breaking out of the loop doesn't unsubscribe.
book, err := client.OrderbookDeltaStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{
Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500)}) // Rate: update interval in ms
if err != nil {
return err
}
defer book.Close()
for frame, err := range book.All() {
if err != nil {
log.Print(err) // the loop goes on after an error
continue
}
fmt.Println(frame.SequenceNumber)
}
frame.SequenceNumber is a uint64. It is a string on the wire; the SDK decodes it for you. A gap event's
bounds are *uint64.
Watch out:
- After a gap, older frames can still come first and missed private events aren't replayed (What happens after a gap).
- Each subscription queues up to 4096 frames (
QueueSizein theConfig, at least 1). If your code falls behind,.sstreams (every frame complete) drop their oldest frame and others yield*grvt.StreamOverflowError(stream errors).
Place an order
- Build a
models.OrderInputwithmodels.Decimalprice and size.IsBuyingAssetis true to buy, false to sell.TimeInForceGoodTillTime(GTT) rests until filled, cancelled or expired;PostOnlyrejects the order rather than let it trade at once (TimeInForce). - Call
CreateOrder. The SDK fills in the signature and aclient_order_id, and looks up the instrument details it needs to sign (once per instrument, then cached). It works on a copy, so your request struct is not changed. - Save the
client_order_id: you follow the order by it, because the reply'sOrderIDis always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below).
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
grvt "github.com/gravity-technologies/grvt-sdk-go"
"github.com/gravity-technologies/grvt-sdk-go/models"
)
func main() {
ctx := context.Background()
signer, err := grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY"))
if err != nil {
log.Fatal(err)
}
client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: os.Getenv("GRVT_API_KEY"), Signer: signer})
if err != nil {
log.Fatal(err)
}
defer client.Close()
sub, err := strconv.ParseUint(os.Getenv("GRVT_SUB_ACCOUNT_ID"), 10, 64)
if err != nil {
log.Fatal(err)
}
order := models.OrderInput{
SubAccountID: &sub,
TimeInForce: models.TimeInForceGoodTillTime,
PostOnly: grvt.Ptr(true),
Legs: []models.OrderLeg{{Instrument: "BTC_USDT_Perp", Size: models.MustParseDecimal("0.01"),
LimitPrice: grvt.Ptr(models.MustParseDecimal("60000")), IsBuyingAsset: true}},
}
resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order})
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Result.Metadata.ClientOrderID)
}
To choose the client_order_id yourself, set it before you send the order, following the
client order ID rules:
order.Metadata = &models.OrderMetadataInput{ClientOrderID: grvt.Ptr(1<<63 | rand.Uint64())} // math/rand/v2
Orders go over HTTP by default. Set OrderTransport: grvt.OrderTransportWS in the Config to send them
over the trading WebSocket instead.
Watch out:
- A reply means the exchange received the order, not that it rests on the book (What a create reply means).
- An order still open 24 hours after signing expires (Expiration).
- Sending the same request struct again places a second order, with a new
client_order_idunless you set one. - An order that breaks its instrument's limits returns
*grvt.OrderOutOfBoundsErrorand is not sent (Orders checked before sending).CheckOrders: grvt.Ptr(false)in theConfigturns the check off and leaves the limits to the exchange. - A decimal with more digits than its signed field allows fails with
*grvt.SigningErrorbefore anything is sent. The SDK never rounds.
Track and cancel an order
Private streams need a client with an API key. OrderStream sends every change to your orders, rejections
included; FillStream sends each fill, with its trade ID and client order ID.
- Open
OrderStreambefore you place the order. - Match updates by
Metadata.ClientOrderID. The updates also carry theOrderID. - Stop at a final status:
models.OrderStatusFilled,OrderStatusRejectedorOrderStatusCancelled(order states). - To cancel, call
CancelOrderwithSubAccountIDandClientOrderID(orOrderID), after the create has replied.
orders, err := client.OrderStream(ctx, &models.WSOrderFeedSelectorV1{SubAccountID: sub})
if err != nil {
return err
}
defer orders.Close()
resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order})
if err != nil {
return err
}
id := resp.Result.Metadata.ClientOrderID
if _, err := client.CancelOrder(ctx, &models.ApiCancelOrderRequest{SubAccountID: sub, ClientOrderID: &id}); err != nil {
return err
}
for {
frame, err := orders.Next(ctx)
if ctx.Err() != nil {
return ctx.Err()
}
if errors.Is(err, grvt.ErrClosed) {
return err
}
if err != nil || frame.Feed.Metadata.ClientOrderID != id || frame.Feed.State == nil {
continue
}
switch s := frame.Feed.State; s.Status {
case models.OrderStatusFilled, models.OrderStatusRejected, models.OrderStatusCancelled:
fmt.Println(frame.Feed.OrderID, s.Status, s.RejectReason)
return nil
}
}
Recover a lost order response
When: a write times out or the socket drops before the response arrives. You get
*grvt.OrderStateUnknownError. Look the order up with grvt.ResolveOrder; don't resend it. Steps and code:
When a write's outcome is unknown.
Recovery helpers
These are functions and types in package grvt, not client methods. Pass the client in where they need it.
import grvt "github.com/gravity-technologies/grvt-sdk-go" // grvt.ResolveOrder, grvt.NewOrderBook, grvt.BackfillPages, grvt.RefreshCancelCountdown
| Helper | What it does |
|---|---|
grvt. | Looks up an order whose write outcome is unknown. It never resends. |
grvt. | Keeps a local book from order-book stream frames. |
grvt. | Pages through REST history after a gap. Your callback picks the call and time window. |
grvt. | Arms or refreshes the cancel-on-disconnect countdown once (1 to 300 seconds). The SDK never does this for you. |
Your OnEvent hook gets the grvt.EventGap and grvt.EventSessionRotated events they use. How to use them:
SDK helpers.
Errors
Check errors with errors.As:
| Type | When |
|---|---|
*grvt.APIError | the server answered with an error code; has Code, Message, Status (0 over WebSocket), RPC, Retryable |
*grvt. | code 1006 (HTTP 429); errors.As also finds it as *APIError; reads were already retried |
*grvt. | no usable answer (connection failed, read timed out, socket closed); has RPC, and Sent (whether the request may have left). A write that may have left returns *grvt. instead |
*grvt. | a write may or may not have happened; look it up by ClientOrderID (ClientOrderIDs for a bulk call). It wraps the original failure (errors.Unwrap), such as a *grvt., so check for it first |
*grvt. | an order breaks its instrument's limits; nothing was sent; has Nearest and ServerCode |
*grvt. | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced |
*grvt.SigningError, *grvt.DecodeError, *grvt.ConfigError, *grvt., grvt.ErrClosed | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed |
*grvt.FrameTooLargeError comes only when you set Environment.WSMaxFrameBytes: the named environments don't
check frame size. An oversized frame is not sent over HTTP instead.
Error code constants are grvt.Code<Name>, for example grvt.CodeSignatureExpired. The full list is on
Error codes.
Handle a create like this. Check for *grvt.OrderStateUnknownError first, because it wraps the original
failure:
resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order})
var unknown *grvt.OrderStateUnknownError
var bounds *grvt.OrderOutOfBoundsError
var apiErr *grvt.APIError
switch {
case errors.As(err, &unknown):
// The order may or may not exist. Look it up; never resend it.
_, err = grvt.ResolveOrder(ctx, client, sub, unknown.ClientOrderID)
return err
case errors.As(err, &bounds):
return fmt.Errorf("not sent, breaks %s: %w", bounds.Limit, err)
case errors.As(err, &apiErr):
return fmt.Errorf("rejected with code %d: %w", apiErr.Code, err)
case err != nil:
return err
}
fmt.Println("placed", resp.Result.Metadata.ClientOrderID)
Hooks and logging
GRVT_LOG=debuglogs every request and frame to stderr, with the session cookie, API key, private keys and signatures redacted. SetLogger(a*slog.Logger) in theConfigto send the logs elsewhere.BeforeSendin theConfigruns before each RPC is signed and may change the typed request in place (call.Params). It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an unknown outcome: that fails with a config error before anything is sent.OnEventgets connect, disconnect, reconnect, subscribe, gap, retry, frame, session_rotated and error events. It runs on the socket's read goroutine, so it must return quickly: while it blocks, no frame on that socket is read.
client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), OnEvent: func(e grvt.Event) {
if e.Kind == grvt.EventGap {
log.Printf("re-syncing %s %s", e.Stream, e.Selector)
}
}})
Running in production
- Concurrency. One
*grvt.Clientis safe for concurrent use: share it across goroutines. Calls that need a login at the same time share one login. - Context. Cancelling the
ctxof a read returns the context's error. Cancelling a write after it may have left returns*grvt.OrderStateUnknownError. Cancelling never closes the shared WebSocket.Next(ctx)returns the context's error and the subscription stays open;All()takes no context and ends only afterClose. Close(). Ends every subscription (Nextreturnsgrvt.ErrClosed,Allstops) and fails WebSocket calls still waiting for a reply: writes with*grvt.OrderStateUnknownError. Later calls returngrvt.ErrClosed. An HTTP call already running is bounded by its ownctx, not byClose.- Reconnects. Each socket reconnects on its own with full-jitter backoff: a random wait between 0 and 250 ms × 2^attempt, never more than 30 s. The backoff resets once a connection has stayed up for 10 s. Each connect (login and handshake) gets 10 s. The client reconnects when nothing arrives for 30 s, and pings three times in that window. A refused login or a handshake rejected with 401 or 403 stops that socket for good: its subscriptions and calls return the error.
- Rate limits. The SDK has no client-side rate limiter and doesn't read
Retry-After. A read that gets1006is retried (3 tries in all, waits of up to 100 ms, then twice that). A write returns*grvt.RateLimitErrorat once. Pace your own requests (Rate limits). - Client order IDs. Set your own per order (Place an order) or plug in a
grvt.ClientOrderIDProviderasClientOrderIDsin theConfig. The default is1<<63 | seconds<<31 | counter, from the wall clock (notConfig.Clock). Its counter starts at a random value in each process, so IDs are unique within a process; two processes rarely collide, but can. - Session renewal. After the client logs in again, each socket closes once none of its writes is waiting for a reply (it checks every 500 ms), then reconnects with the new cookie, usually after a wait of up to 250 ms. WebSocket calls made in between wait up to 10 s for the new socket. HTTP calls, including orders on the default transport, are not interrupted. A failed re-login is retried after 5 s (Session renewal).
Data types
- Decimals use
models.Decimal. Parse exact text withmodels.ParseDecimal; useMustParseDecimalonly for constants.Rat()gives an exact*big.Ratfor arithmetic. - Nanosecond timestamps use
time.Time. Values outside the wire range are rejected. - IDs are
uint64and travel as JSON strings; a single ID must arrive as a string. Lists of IDs (models.Uint64s) accept numbers too. - Required fields use plain values. Optional strings and enums use
""for absent. Other optional fields (numbers, bools, decimals, nested types) are pointers, so0andfalsecan be sent: usegrvt.Ptr(...). - Signed requests use
Inputmodels, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield
Partialmodels: every feed field is optional. - Enums are string types with constants for the known values. A value added by a newer server arrives as
its plain string, so give your
switchadefaultcase. - Millisecond schedule fields stay plain integers.
Not supported yet
- Resuming a private stream from a sequence number. After a gap, fill missed events from history with
grvt.BackfillPages(Fill missed events from history). - Wallet login. The client logs in with an API key only.