---
title: "Go SDK"
description: "Install the Go module, create a client, call any RPC, stream data, place signed orders and handle errors."
order: 22
llms: trading, market-data, account
---

> [!WARNING]
> **Preview.** Any 0.x release can change the API. Your `go.mod` pins the version you get.

The Go SDK has a method for every call and stream in the [API reference](../reference/index.md). 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](#install) the SDK and run the [Quickstart](../guides/quickstart.md), then read this page
down to
[Track and cancel an order](#track-and-cancel-an-order). Later sections are for when you need them.

## Install

```sh
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

```go
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](../guides/environments.md)).
- The client sends short (lite) field names on the wire by default; your code still uses the full names.
  `Encoding: grvt.EncodingFull` in the `Config` switches to full names
  ([Encoding](../guides/environments.md#encoding-full-or-lite)). On a custom `Environment`, lite WebSocket URLs
  are the full ones with `/ws/full` swapped for `/ws/lite`; set `MarketDataWSLite` and `TradingWSLite` only 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](../guides/authentication.md)). Renewal reconnects the client's WebSockets, so every stream
  gets a gap ([Session renewal](../guides/websocket.md#session-renewal)).
- To stop, follow [Shut down cleanly](../guides/websocket.md#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.

```go
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](../guides/errors-and-retries.md#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 the `ctx` you pass also applies. `CallTimeout` covers the whole
  call: login, instrument lookups, signing, retries and the reply; `HTTPAttemptTimeout` caps each HTTP try
  within it.
- `Config.HTTPClient` replaces the default HTTP client, for REST and the WebSocket handshake. The SDK copies it
  and never follows redirects; a `Timeout` on 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.

```go
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 `ctx` cancels 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 `Config` means no default. Zero in a request or selector means "not set"; in an `OrderInput`,
  `nil` means 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`.

1. Call the stream method to get a subscription.
2. Range over `All()` to read frames, or call `Next(ctx)` to stop when a context ends.
3. Call `Close()` to unsubscribe. Breaking out of the loop doesn't unsubscribe.

```go
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](../guides/recovery.md#what-happens-after-a-gap)).
- Each subscription queues up to 4096 frames (`QueueSize` in the `Config`, at least 1). If your code falls behind,
  [`.s` streams](../guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest
  frame and others yield `*grvt.StreamOverflowError`
  ([stream errors](../guides/websocket.md#read-a-stream)).

## Place an order

1. Build a `models.OrderInput` with `models.Decimal` price and size. `IsBuyingAsset` is true to buy, false to
   sell. `TimeInForceGoodTillTime` (GTT) rests until filled, cancelled or expired; `PostOnly` rejects the order
   rather than let it trade at once ([TimeInForce](../reference/enums.md)).
2. Call `CreateOrder`. The SDK fills in the signature and a `client_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.
3. Save the `client_order_id`: you follow the order by it, because the reply's `OrderID` is 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).

```go
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](../guides/signing.md#rules-that-cause-most-rejections):

```go
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](../guides/errors-and-retries.md#what-a-create-reply-means)).
- An order still open 24 hours after signing expires ([Expiration](../guides/signing.md#rules-that-cause-most-rejections)).
- Sending the same request struct again places a second order, with a new `client_order_id` unless you set one.
- An order that breaks its instrument's limits returns `*grvt.OrderOutOfBoundsError` and is not sent
  ([Orders checked before sending](../guides/errors-and-retries.md#orders-checked-before-sending)).
  `CheckOrders: grvt.Ptr(false)` in the `Config` turns the check off and leaves the limits to the exchange.
- A decimal with more digits than its signed field allows fails with `*grvt.SigningError` before 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.

1. Open `OrderStream` before you place the order.
2. Match updates by `Metadata.ClientOrderID`. The updates also carry the `OrderID`.
3. Stop at a final status: `models.OrderStatusFilled`, `OrderStatusRejected` or `OrderStatusCancelled`
   ([order states](../guides/errors-and-retries.md#what-a-create-reply-means)).
4. To cancel, call `CancelOrder` with `SubAccountID` and `ClientOrderID` (or `OrderID`), after the create has
   replied.

```go
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](../guides/errors-and-retries.md#when-a-writes-outcome-is-unknown).

## Recovery helpers

These are functions and types in package `grvt`, not client methods. Pass the client in where they need it.

```go
import grvt "github.com/gravity-technologies/grvt-sdk-go" // grvt.ResolveOrder, grvt.NewOrderBook, grvt.BackfillPages, grvt.RefreshCancelCountdown
```

| Helper | What it does |
|---|---|
| `grvt.ResolveOrder(ctx, client, subAccountID, clientOrderID)` | Looks up an order whose write outcome is unknown. It never resends. |
| `grvt.NewOrderBook(instrument, grvt.BookDelta)` | Keeps a local book from order-book stream frames. |
| `grvt.BackfillPages(ctx, fetch, gap)` | Pages through REST history after a gap. Your callback picks the call and time window. |
| `grvt.RefreshCancelCountdown(ctx, client, subAccountID, seconds)` | Arms or refreshes the [cancel-on-disconnect countdown](../guides/websocket.md#cancel-orders-if-your-app-stops) 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](../guides/recovery.md#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.RateLimitError` | code `1006` (HTTP 429); `errors.As` also finds it as `*APIError`; reads were already retried |
| `*grvt.TransportError` | 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.OrderStateUnknownError` instead |
| `*grvt.OrderStateUnknownError` | 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.TransportError`, so check for it first |
| `*grvt.OrderOutOfBoundsError` | an order breaks its instrument's limits; nothing was sent; has `Nearest` and `ServerCode` |
| `*grvt.StreamOverflowError` | 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.FrameTooLargeError`, `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](../reference/errors.md).

Handle a create like this. Check for `*grvt.OrderStateUnknownError` first, because it wraps the original
failure:

```go
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=debug` logs every request and frame to stderr, with the session cookie, API key, private keys and
  signatures redacted. Set `Logger` (a `*slog.Logger`) in the `Config` to send the logs elsewhere.
- `BeforeSend` in the `Config` runs 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](../guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): that fails with a config
  error before anything is sent.
- `OnEvent` gets 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.

```go
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.Client` is safe for concurrent use: share it across goroutines. Calls that need a
  login at the same time share one login.
- **Context.** Cancelling the `ctx` of 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 after `Close`.
- **`Close()`.** Ends every subscription (`Next` returns `grvt.ErrClosed`, `All` stops) and fails WebSocket
  calls still waiting for a reply: writes with `*grvt.OrderStateUnknownError`. Later calls return
  `grvt.ErrClosed`. An HTTP call already running is bounded by its own `ctx`, not by `Close`.
- **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 gets
  `1006` is retried (3 tries in all, waits of up to 100 ms, then twice that). A write returns
  `*grvt.RateLimitError` at once. Pace your own requests ([Rate limits](../guides/rate-limits.md)).
- **Client order IDs.** Set your own per order ([Place an order](#place-an-order)) or plug in a
  `grvt.ClientOrderIDProvider` as `ClientOrderIDs` in the `Config`. The default is
  `1<<63 | seconds<<31 | counter`, from the wall clock (not `Config.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](../guides/websocket.md#session-renewal)).

## Data types

- Decimals use `models.Decimal`. Parse exact text with `models.ParseDecimal`; use `MustParseDecimal` only
  for constants. `Rat()` gives an exact `*big.Rat` for arithmetic.
- Nanosecond timestamps use `time.Time`. Values outside the wire range are rejected.
- IDs are `uint64` and 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, so `0` and `false` can be sent: use `grvt.Ptr(...)`.
- Signed requests use `Input` models, so the SDK can fill in signatures and metadata.
- Ticker and mini-ticker delta streams yield `Partial` models: 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 `switch` a `default` case.
- 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](../guides/recovery.md#fill-missed-events-from-history)).
- **Wallet login.** The client logs in with an API key only.
