Developers

Quickstart

Run a public data example, then explicitly opt into one testnet order and its cancellation.

On this page

Run one example to read testnet data. Then, if you want, run it again to place and cancel one testnet order. The full example for each language is in Full examples.

What you need

The SDK for your language. The SDKs are in preview and any 0.x release can change the API, so pin the exact version you install.

SDKNeedsInstall
PythonPython 3.11+pip install grvt
TypeScriptNode.js 24+npm install github:gravity-technologies/grvt-sdk-typescript (from its public GitHub repository; not on the package registry yet)
GoGo 1.27.4+go get github.com/gravity-technologies/grvt-sdk-go
RustRust 1.88+cargo add grvt

What else you need depends on what you run:

PartNeeds
Public dataNothing
Reading your account, for example your sub-account IDAny testnet API key, read-only included (API keys)
The test orderA testnet API key with the Trade permission, its signing key, your sub-account ID, and testnet funds in that sub-account (Get testnet funds)

Your sub-account ID is the number of your Trading Account in the Grvt web app. get_sub_accounts lists it once you log in with the key.

Run public data first

When: you want to check that your setup works. No credentials needed.

  1. In the SDK's folder (the one that contains examples/), run the command for your language:

    SDKCommand
    Pythonpython examples/quickstart.py
    TypeScriptnpm run example
    Gogo run ./examples/quickstart
    Rustcargo run --example quickstart
  2. Check the output: the example prints a ticker and its instrument rules, then exits.

These commands use testnet. The trading quickstarts intentionally stay on testnet, even when the portal's environment selector shows production. For production data in your own app, pick the prod environment (Environments).

Place one testnet order

When: you have a funded testnet account (What you need) and want to see one order placed, watched and cancelled.

  1. Set GRVT_API_KEY, GRVT_PRIVATE_KEY (your signing key) and GRVT_SUB_ACCOUNT_ID for your testnet account. If one is missing, the program stops before it sends anything.

  2. Run the command for your language with --trade:

    SDKCommand
    Pythonpython examples/quickstart.py --trade
    TypeScriptnpm run example -- --trade
    Gogo run ./examples/quickstart --trade
    Rustcargo run --example quickstart -- --trade
  3. Optional: change the spending cap with --max-notional 100 (default 200). Notional is price × size, in the instrument's quote asset (the currency of its price: USDT for BTC_USDT_Perp). If the smallest valid order is worth more than the cap, the program sends nothing.

  4. Save the client order ID that the program prints before it sends the order. You need it if the response is lost.

  5. Read the exit code:

    Exit codeMeaning
    0The program saw the order cancelled or filled.
    3The program saw the order rejected.
    2The outcome is unknown.
    Anything elseSomething failed. Investigate before you run it again.

What the program does:

  1. Reads the instrument's tick size (smallest price step), minimum size and minimum notional.
  2. Sends a post-only buy (an order that is rejected rather than trade at once) one tick below the best bid, with the smallest valid size.
  3. Cancels the order once if it is still open.
  4. Watches the order by its client order ID until it is cancelled or in another final state. A cancel reply alone doesn't prove the order is cancelled.

Watch out:

  • The order is post-only, but it can still fill once it rests on the book.
  • On exit code 2, don't run it again: look up the printed ID first (When a write's outcome is unknown).

Full examples

Python

View the complete Python example

Download this example

"""Read testnet data; add --trade to place, observe and cancel one testnet order."""

import argparse
import asyncio
import os
import secrets
import sys
from decimal import ROUND_CEILING, ROUND_FLOOR, Decimal
from typing import Any
from urllib.parse import urlparse

from grvt import AsyncGrvt, Environment, OrderStateUnknown, PrivateKeySigner, enums, models, resolve_order


async def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--trade", action="store_true", help="send one real testnet order; it may fill")
    parser.add_argument("--instrument", default="BTC_USDT_Perp")
    parser.add_argument("--max-notional", type=Decimal, default=Decimal("200"), help="quote asset spending limit")
    parser.add_argument("--fixture-url", help=argparse.SUPPRESS)
    args = parser.parse_args()
    env = "testnet"
    encoding = "lite"
    if args.fixture_url:
        url = urlparse(args.fixture_url)
        if (
            url.scheme != "http"
            or url.hostname != "127.0.0.1"
            or url.path
            or url.query
            or url.fragment
            or url.username
            or url.password
            or not url.port
        ):
            parser.error("fixture URL must be an HTTP loopback origin")
        env = Environment(
            "fixture",
            args.fixture_url,
            args.fixture_url,
            args.fixture_url,
            args.fixture_url.replace("http:", "ws:"),
            args.fixture_url.replace("http:", "ws:"),
            326,
        )
        encoding = "full"  # the local fixture gateway speaks full names only
    credentials: dict[str, Any] = {}
    account = ""
    if args.trade:
        names = ("GRVT_API_KEY", "GRVT_PRIVATE_KEY", "GRVT_SUB_ACCOUNT_ID")
        if any(not os.environ.get(name, "").strip() for name in names):
            parser.error("trading requires GRVT_API_KEY, GRVT_PRIVATE_KEY and GRVT_SUB_ACCOUNT_ID")
        account = os.environ["GRVT_SUB_ACCOUNT_ID"]
        if not account.isascii() or not account.isdigit() or not 0 < int(account) < 2**64:
            parser.error("GRVT_SUB_ACCOUNT_ID must be a positive uint64")
        credentials = dict(api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]))
        if not args.max_notional.is_finite() or args.max_notional <= 0:
            parser.error("max-notional must be finite and positive")
    async with AsyncGrvt(env=env, encoding=encoding, http_attempt_timeout=5, **credentials) as client:
        ticker = (await client.ticker(instrument=args.instrument)).result
        instrument = (await client.get_instrument(instrument=args.instrument)).result
        print("mark price", ticker.mark_price, flush=True)
        if not args.trade:
            return 0
        tick, step = instrument.tick_size, instrument.min_size
        bid = ticker.best_bid_price
        if tick <= 0 or step <= 0 or bid is None or bid <= tick:
            raise ValueError("instrument has no usable bid, tick or size")
        price = ((bid / tick).to_integral_value(rounding=ROUND_FLOOR) - 1) * tick
        if price <= 0:
            print("no positive passive price; no order sent", file=sys.stderr)
            return 1
        count = max(Decimal(1), (instrument.min_notional / (price * step)).to_integral_value(rounding=ROUND_CEILING))
        size = step * count
        if size * price > args.max_notional:
            raise ValueError("minimum order exceeds max-notional; no order sent")
        order_id = str(secrets.randbits(63) | (1 << 63))
        print("client_order_id", order_id, "price", price, "size", size, flush=True)
        order = models.OrderInput(
            sub_account_id=account,
            time_in_force=enums.TimeInForce.GOOD_TILL_TIME,
            post_only=True,
            legs=[models.OrderLeg(instrument=args.instrument, size=size, limit_price=price, is_buying_asset=True)],
            metadata=models.OrderMetadataInput(client_order_id=order_id),
        )
        try:
            await client.create_order(order=order)
        except OrderStateUnknown:
            print("create outcome unknown; looking up the same ID", flush=True)
        # Acknowledgements do not prove terminal state. Observe before and after one cancel.
        cancelled = False
        for _ in range(8):
            try:
                found = await resolve_order(client, sub_account_id=account, client_order_id=order_id)
            except Exception as error:
                print("lookup unavailable:", type(error).__name__, flush=True)
                await asyncio.sleep(0.5)
                continue
            if found.status == "found" and found.order.state:
                status = found.order.state.status.value
                print("order status", status, flush=True)
                if status in ("CANCELLED", "FILLED", "REJECTED"):
                    return 0 if status != "REJECTED" else 3
                if status == "OPEN" and not cancelled:
                    cancelled = True
                    try:
                        await client.cancel_order(sub_account_id=account, client_order_id=order_id)
                    except Exception as error:
                        # Even a failed cancel may have reached the server. Observe; do not retry.
                        print("cancel response unavailable:", type(error).__name__, flush=True)
            await asyncio.sleep(0.5)
        print("outcome still unknown; retain client_order_id and reconcile manually; do not resend", flush=True)
        return 2


async def bounded_main():
    try:
        async with asyncio.timeout(60):
            return await main()
    except TimeoutError:
        print("deadline reached; retain any printed client_order_id and reconcile; do not resend", flush=True)
        return 2


if __name__ == "__main__":
    raise SystemExit(asyncio.run(bounded_main()))

TypeScript

View the complete TypeScript example

Download this example

// Public testnet data by default. --trade places one real order which may fill.
import { randomBytes } from "node:crypto";
import { Grvt, Decimal, OrderStateUnknown, PrivateKeySigner, resolveOrder } from "grvt";

const args = process.argv.slice(2);
const option = (name: string, fallback: string) => {
  const i = args.indexOf(name);
  if (i < 0) return fallback;
  if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`missing ${name} value`);
  return args[i + 1];
};
for (let i = 0; i < args.length; i++) {
  if (args[i] === "--trade") continue;
  if (!["--instrument", "--max-notional", "--fixture-url"].includes(args[i]))
    throw new Error(`unknown option ${args[i]}`);
  i++;
}
const trade = args.includes("--trade");
const instrument = option("--instrument", "BTC_USDT_Perp");
const fixture = option("--fixture-url", "");
let env: NonNullable<ConstructorParameters<typeof Grvt>[0]>["env"] = "testnet";
let encoding: "full" | "lite" = "lite";
if (fixture) {
  const url = new URL(fixture);
  if (
    url.protocol !== "http:" ||
    url.hostname !== "127.0.0.1" ||
    url.pathname !== "/" ||
    url.search ||
    url.hash ||
    url.username ||
    url.password ||
    !url.port
  )
    throw new Error("fixture URL must be an HTTP loopback origin");
  env = {
    name: "fixture",
    mdUrl: fixture,
    tdUrl: fixture,
    edgeUrl: fixture,
    mdWsUrl: fixture.replace("http:", "ws:"),
    tdWsUrl: fixture.replace("http:", "ws:"),
    chainId: 326,
  };
  encoding = "full"; // the local fixture gateway speaks full names only
}
// Keep arithmetic exact: Decimal is a wire value, while BigInt calculates tick counts.
function fraction(text: string) {
  if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("expected a positive plain decimal");
  const [whole, tail = ""] = text.split(".");
  return { n: BigInt(whole + tail), d: 10n ** BigInt(tail.length), scale: tail.length };
}
function multiple(text: string, count: bigint) {
  const { n, scale } = fraction(text);
  const digits = (n * count).toString().padStart(scale + 1, "0");
  return scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits;
}
const cap = fraction(option("--max-notional", "200"));
if (cap.n <= 0n) throw new Error("max-notional must be positive");
let credentials = {};
const account = process.env.GRVT_SUB_ACCOUNT_ID ?? "";
if (trade) {
  if (
    !process.env.GRVT_API_KEY?.trim() ||
    !process.env.GRVT_PRIVATE_KEY?.trim() ||
    !/^\d+$/.test(account) ||
    BigInt(account) <= 0n ||
    BigInt(account) >= 1n << 64n
  )
    throw new Error(
      "trading requires GRVT_API_KEY, GRVT_PRIVATE_KEY and a positive uint64 GRVT_SUB_ACCOUNT_ID",
    );
  credentials = {
    apiKey: process.env.GRVT_API_KEY,
    signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY),
  };
}
const deadline = setTimeout(() => {
  console.error(
    "deadline reached; retain any printed client_order_id and reconcile; do not resend",
  );
  process.exit(2);
}, 60_000);
const client = new Grvt({ env, encoding, httpAttemptTimeoutMs: 5000, ...credentials });
try {
  const ticker = (await client.ticker({ instrument })).result;
  const metadata = (await client.getInstrument({ instrument })).result;
  console.log("mark price", ticker.mark_price?.toString());
  if (trade) {
    const bid = fraction(ticker.best_bid_price?.toString() ?? "0");
    const tick = fraction(metadata.tick_size.toString());
    const step = fraction(metadata.min_size.toString());
    if (!tick.n || !step.n) throw new Error("instrument has no usable tick or size");
    const ticks = (bid.n * tick.d) / (bid.d * tick.n) - 1n;
    if (ticks <= 0n) throw new Error("instrument has no usable bid");
    const price = multiple(metadata.tick_size.toString(), ticks);
    const p = fraction(price);
    const minimum = fraction(metadata.min_notional.toString());
    const numerator = minimum.n * p.d * step.d;
    const denominator = minimum.d * p.n * step.n;
    const count = (numerator + denominator - 1n) / denominator;
    const size = multiple(metadata.min_size.toString(), count > 0n ? count : 1n);
    const s = fraction(size);
    if (p.n * s.n * cap.d > cap.n * p.d * s.d)
      throw new Error("minimum order exceeds max-notional; no order sent");
    const id = (randomBytes(8).readBigUInt64BE() | (1n << 63n)).toString();
    console.log("client_order_id", id, "price", price, "size", size);
    try {
      await client.createOrder({
        order: {
          sub_account_id: account,
          time_in_force: "GOOD_TILL_TIME",
          post_only: true,
          legs: [
            {
              instrument,
              size: new Decimal(size),
              limit_price: new Decimal(price),
              is_buying_asset: true,
            },
          ],
          metadata: { client_order_id: id },
        },
      });
    } catch (error) {
      if (!(error instanceof OrderStateUnknown)) throw error;
      console.log("create outcome unknown; looking up the same ID");
    }
    let cancelled = false;
    process.exitCode = 2;
    for (let attempt = 0; attempt < 8; attempt++) {
      let found;
      try {
        found = await resolveOrder(client, { sub_account_id: account, client_order_id: id });
      } catch {
        console.log("lookup unavailable; continuing bounded observation");
        await new Promise((resolve) => setTimeout(resolve, 500));
        continue;
      }
      if (found.status === "found") {
        const status = found.order.state?.status;
        console.log("order status", status);
        if (status === "CANCELLED" || status === "FILLED" || status === "REJECTED") {
          process.exitCode = status === "REJECTED" ? 3 : 0;
          break;
        }
        if (status === "OPEN" && !cancelled) {
          cancelled = true;
          try {
            await client.cancelOrder({ sub_account_id: account, client_order_id: id });
          } catch {
            console.log("cancel response unavailable; observing without retry");
          }
        }
      }
      await new Promise((resolve) => setTimeout(resolve, 500));
    }
    if (process.exitCode === 2)
      console.log(
        "outcome still unknown; retain client_order_id and reconcile manually; do not resend",
      );
  }
} finally {
  await client.close();
  clearTimeout(deadline);
}

Go

View the complete Go example

Download this example

// Read testnet market data; --trade opts into one bounded order lifecycle.
package main

import (
	"context"
	"crypto/rand"
	"encoding/binary"
	"errors"
	"flag"
	"fmt"
	grvt "github.com/gravity-technologies/grvt-sdk-go"
	"github.com/gravity-technologies/grvt-sdk-go/models"
	"math/big"
	"net"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() { os.Exit(run()) }
func run() int {
	trade := flag.Bool("trade", false, "place and cancel one testnet order")
	fixture := flag.String("fixture-url", "", "loopback test gateway URL")
	instrument := flag.String("instrument", "BTC_USDT_Perp", "instrument")
	capText := flag.String("max-notional", "200", "maximum quote amount")
	flag.Parse()
	fail := func(err error) int { fmt.Fprintln(os.Stderr, err); return 1 }
	capValue, err := models.ParseDecimal(*capText)
	if err != nil || capValue.Rat().Sign() <= 0 {
		return fail(errors.New("max-notional must be positive"))
	}
	config := grvt.Config{Env: grvt.Testnet(), HTTPAttemptTimeout: 5 * time.Second}
	if *fixture != "" {
		u, parseErr := url.Parse(*fixture)
		if parseErr != nil || u.Scheme != "http" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
			return fail(errors.New("fixture-url must be a loopback HTTP base URL"))
		}
		ip := net.ParseIP(u.Hostname())
		if ip == nil || !ip.IsLoopback() {
			return fail(errors.New("fixture-url must use a loopback IP"))
		}
		config.Env.MarketDataURL, config.Env.TradingURL, config.Env.EdgeURL = *fixture, *fixture, *fixture
		// The local fixture gateway speaks full names only.
		config.Encoding = grvt.EncodingFull
	}
	// Check credentials before the first network request.
	if *trade {
		config.APIKey = strings.TrimSpace(os.Getenv("GRVT_API_KEY"))
		config.SubAccountID, err = strconv.ParseUint(os.Getenv("GRVT_SUB_ACCOUNT_ID"), 10, 64)
		if config.APIKey == "" || err != nil || config.SubAccountID == 0 || os.Getenv("GRVT_PRIVATE_KEY") == "" {
			return fail(errors.New("--trade requires GRVT_API_KEY, GRVT_PRIVATE_KEY and a positive GRVT_SUB_ACCOUNT_ID"))
		}
		config.Signer, err = grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY"))
		if err != nil {
			return fail(err)
		}
	}
	client, err := grvt.New(config)
	if err != nil {
		return fail(err)
	}
	defer client.Close()
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	ticker, err := client.Ticker(ctx, &models.ApiTickerRequest{Instrument: *instrument})
	if err != nil {
		return fail(err)
	}
	info, err := client.GetInstrument(ctx, &models.ApiGetInstrumentRequest{Instrument: *instrument})
	if err != nil {
		return fail(err)
	}
	fmt.Println("mark price", ticker.Result.MarkPrice)
	if !*trade {
		return 0
	}
	if ticker.Result.BestBidPrice == nil {
		return fail(errors.New("ticker has no best bid"))
	}
	price, size, err := orderAmounts(*ticker.Result.BestBidPrice, info.Result.TickSize, info.Result.MinSize, info.Result.MinNotional, capValue)
	if err != nil {
		return fail(err)
	}
	var rawID [8]byte
	if _, err = rand.Read(rawID[:]); err != nil {
		return fail(err)
	}
	id := binary.BigEndian.Uint64(rawID[:]) | 1<<63
	// Keep this ID when submission is uncertain. Never resend the order.
	fmt.Println("client_order_id", id)
	_, err = client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: models.OrderInput{
		SubAccountID: grvt.Ptr(config.SubAccountID), TimeInForce: models.TimeInForceGoodTillTime, PostOnly: grvt.Ptr(true),
		Metadata: &models.OrderMetadataInput{ClientOrderID: &id},
		Legs:     []models.OrderLeg{{Instrument: *instrument, Size: size, LimitPrice: &price, IsBuyingAsset: true}},
	}})
	if err != nil {
		fmt.Fprintln(os.Stderr, "submission failed or uncertain; looking up client_order_id", id, err)
	}
	cancelled := false
	for attempt := 0; attempt < 8; attempt++ {
		result, lookupErr := grvt.ResolveOrder(ctx, client, config.SubAccountID, id)
		if lookupErr != nil {
			fmt.Fprintln(os.Stderr, "lookup failed; preserving client_order_id", id, lookupErr)
		}
		if lookupErr == nil && result.Status == grvt.OrderFound && result.Order.State != nil {
			status := result.Order.State.Status
			fmt.Println("order status", status)
			switch string(status) {
			case "CANCELLED", "FILLED":
				return 0
			case "REJECTED":
				return 3
			case "OPEN":
				if !cancelled {
					cancelled = true
					if _, cancelErr := client.CancelOrder(ctx, &models.ApiCancelOrderRequest{SubAccountID: config.SubAccountID, ClientOrderID: &id}); cancelErr != nil {
						fmt.Fprintln(os.Stderr, "cancel outcome uncertain; continue lookup", id, cancelErr)
					}
				}
			}
		}
		if attempt < 7 {
			select {
			case <-time.After(500 * time.Millisecond):
			case <-ctx.Done():
				fmt.Fprintln(os.Stderr, "still unknown; reconcile client_order_id", id)
				return 2
			}
		}
	}
	fmt.Fprintln(os.Stderr, "still unknown; reconcile client_order_id", id, "before further trading")
	return 2
}

// Exact decimals keep the order on tick and size boundaries.
func orderAmounts(bid, tick, minimum, notional, capValue models.Decimal) (models.Decimal, models.Decimal, error) {
	zero := models.Decimal{}
	if bid.Rat().Sign() <= 0 || tick.Rat().Sign() <= 0 || minimum.Rat().Sign() <= 0 || notional.Rat().Sign() < 0 {
		return zero, zero, errors.New("invalid market limits")
	}
	ticks := new(big.Rat).Quo(bid.Rat(), tick.Rat())
	whole := new(big.Int).Quo(ticks.Num(), ticks.Denom())
	whole.Sub(whole, big.NewInt(1))
	price := new(big.Rat).Mul(new(big.Rat).SetInt(whole), tick.Rat())
	if price.Sign() <= 0 {
		return zero, zero, errors.New("no positive passive price")
	}
	lots := new(big.Rat).Quo(notional.Rat(), new(big.Rat).Mul(price, minimum.Rat()))
	count, remainder := new(big.Int), new(big.Int)
	count.QuoRem(lots.Num(), lots.Denom(), remainder)
	if remainder.Sign() > 0 {
		count.Add(count, big.NewInt(1))
	}
	if count.Sign() == 0 {
		count.SetInt64(1)
	}
	size := new(big.Rat).Mul(new(big.Rat).SetInt(count), minimum.Rat())
	if new(big.Rat).Mul(price, size).Cmp(capValue.Rat()) > 0 {
		return zero, zero, errors.New("minimum order exceeds max-notional")
	}
	p := models.MustParseDecimal(price.FloatString(decimalPlaces(tick.String())))
	s := models.MustParseDecimal(size.FloatString(decimalPlaces(minimum.String())))
	return p, s, nil
}
func decimalPlaces(s string) int {
	for i, c := range s {
		if c == '.' {
			return len(s) - i - 1
		}
	}
	return 0
}

Rust

View the complete Rust example

Download this example

//! Public testnet data by default. --trade places one real order which may fill.
use grvt::{
    enums::{OrderStatus, TimeInForce},
    models as m, resolve_order, Config, Encoding, Environment, Error, Grvt, OrderResolution, PrivateKeySigner,
};
use rust_decimal::Decimal;
use std::{
    env,
    io::{self, Write},
    str::FromStr,
    time::Duration,
};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

#[tokio::main]
async fn main() -> Result<()> {
    let args: Vec<String> = env::args().skip(1).collect();
    let mut trade = false;
    let mut instrument = "BTC_USDT_Perp".to_owned();
    let mut cap = Decimal::from(200);
    let mut environment = Environment::testnet();
    let mut fixture = false;
    let mut index = 0;
    while index < args.len() {
        if args[index] == "--trade" {
            trade = true;
            index += 1;
            continue;
        }
        let value = args.get(index + 1).ok_or("missing option value")?;
        match args[index].as_str() {
            "--instrument" => instrument = value.clone(),
            "--max-notional" => cap = Decimal::from_str(value)?,
            "--fixture-url" => {
                let port = value
                    .strip_prefix("http://127.0.0.1:")
                    .ok_or("fixture URL must be an HTTP loopback origin")?;
                let _: u16 = port.parse()?;
                environment = Environment {
                    name: "fixture".into(),
                    md_url: value.clone(),
                    td_url: value.clone(),
                    edge_url: value.clone(),
                    md_ws_url: value.replace("http:", "ws:"),
                    td_ws_url: value.replace("http:", "ws:"),
                    chain_id: 326,
                    ws_max_frame_bytes: None,
                };
                fixture = true;
            }
            _ => return Err("unknown option".into()),
        }
        index += 2;
    }
    if cap <= Decimal::ZERO {
        return Err("max-notional must be positive".into());
    }
    let mut config = Config::new(environment).http_attempt_timeout(Duration::from_secs(5));
    if fixture {
        // the local fixture gateway speaks full names only
        config = config.encoding(Encoding::Full);
    }
    let mut account = 0;
    if trade {
        let key = env::var("GRVT_API_KEY")?;
        if key.trim().is_empty() {
            return Err("GRVT_API_KEY is required".into());
        }
        account = env::var("GRVT_SUB_ACCOUNT_ID")?.parse::<u64>()?;
        if account == 0 {
            return Err("GRVT_SUB_ACCOUNT_ID must be positive".into());
        }
        config = config
            .api_key(key)
            .signer(PrivateKeySigner::new(&env::var("GRVT_PRIVATE_KEY")?)?);
    }
    let client = Grvt::new(config)?;
    let outcome = tokio::time::timeout(
        Duration::from_secs(60),
        journey(&client, trade, &instrument, account, cap),
    )
    .await;
    client.close().await;
    let code = match outcome {
        Ok(result) => result?,
        Err(_) => {
            eprintln!("deadline reached; retain any printed client_order_id and reconcile; do not resend");
            2
        }
    };
    std::process::exit(code);
}

async fn journey(client: &Grvt, trade: bool, instrument: &str, account: u64, cap: Decimal) -> Result<i32> {
    let ticker = client.ticker().instrument(instrument).await?.result;
    let metadata = client.get_instrument().instrument(instrument).await?.result;
    println!("mark price {:?}", ticker.mark_price);
    if !trade {
        return Ok(0);
    }
    let tick = metadata.tick_size;
    let step = metadata.min_size;
    let bid = ticker.best_bid_price.ok_or("instrument has no usable bid")?;
    if tick <= Decimal::ZERO || step <= Decimal::ZERO || bid <= tick {
        return Err("instrument has no usable tick, bid or size".into());
    }
    let price = ((bid / tick).floor() - Decimal::ONE) * tick;
    if price <= Decimal::ZERO {
        return Err("no positive passive price; no order sent".into());
    }
    let size = (metadata.min_notional / (price * step)).ceil().max(Decimal::ONE) * step;
    if price * size > cap {
        return Err("minimum order exceeds max-notional; no order sent".into());
    }
    let id = rand::random::<u64>() | (1 << 63);
    println!("client_order_id {id} price {price} size {size}");
    io::stdout().flush()?;
    let leg = m::OrderLeg::new(instrument, size, true).with_limit_price(price);
    let order = m::OrderInput::new(TimeInForce::GoodTillTime, Some(vec![leg]))
        .with_sub_account_id(account)
        .with_post_only(true)
        .with_metadata(m::OrderMetadataInput::default().with_client_order_id(id));
    match client.create_order().order(order).await {
        Ok(_) => (),
        Err(Error::OrderStateUnknown { .. }) => println!("create outcome unknown; looking up the same ID"),
        Err(error) => return Err(error.into()),
    }
    let mut cancelled = false;
    for _ in 0..8 {
        let observed = match resolve_order(client, account, id).await {
            Ok(value) => value,
            Err(_) => {
                println!("lookup unavailable; continuing bounded observation");
                tokio::time::sleep(Duration::from_millis(500)).await;
                continue;
            }
        };
        if let OrderResolution::Found(order) = observed {
            if let Some(state) = order.state {
                println!("order status {}", state.status.as_str());
                match state.status {
                    OrderStatus::Cancelled | OrderStatus::Filled => return Ok(0),
                    OrderStatus::Rejected => return Ok(3),
                    OrderStatus::Open if !cancelled => {
                        cancelled = true;
                        if client
                            .cancel_order()
                            .sub_account_id(account)
                            .client_order_id(id)
                            .await
                            .is_err()
                        {
                            println!("cancel response unavailable; observing without retry");
                        }
                    }
                    _ => (),
                }
            }
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
    println!("outcome still unknown; retain client_order_id and reconcile manually; do not resend");
    Ok(2)
}

C++ signing core and reference

Advanced. C++ has a signing core only: your app handles networking and state itself (C++ signing core and reference). This example uses fixed inputs and makes no network calls. Don't send its recorded order as a new request.

View the complete C++ example

Download this example

// Offline reference. Replace the print callback with your own HTTP transport.
#include <cstdio>
// Published conformance inputs. These are test values, never production credentials.
#include "grvt/grvt.hpp"
namespace reference {
inline auto order() {
  grvt::models::OrderLeg leg("BTC_USDT_Perp", *grvt::Decimal::parse("0.01"), true);
  leg.limit_price = *grvt::Decimal::parse("60000");
  grvt::models::OrderInput input(grvt::enums::TimeInForce::GOOD_TILL_TIME, std::vector<grvt::models::OrderLeg>{leg});
  input.sub_account_id = 8289849667772468ULL;
  input.is_market = false;
  input.post_only = true;
  input.reduce_only = false;
  input.metadata.emplace();
  input.metadata->client_order_id = (1ULL << 63) | 1001;  // API client ID range
  input.signature.emplace();
  input.signature->signer = "0x1267c6181aee40f5ddbd70c56ecf4613117326b5";
  input.signature->nonce = 1001;
  input.signature->expiration = grvt::timestamp_from_ns(4102444800000000000LL);
  input.signature->chain_id = 326;
  return grvt::models::ApiCreateOrderRequestInput(std::move(input));
}
inline grvt::SigningMetadata metadata() {
  grvt::SigningMetadata meta;
  meta.instruments["BTC_USDT_Perp"] = {"0x030501", 9, 6};
  return meta;
}
inline constexpr auto test_key = "0xbfe25ff07bd38cb3fbc28a2a296d41aabd68a78c929d257935906489fc9c6d89";
}  // namespace reference

#ifdef GRVT_WITH_SIGNER
#include "grvt/signer.hpp"
#endif

// The host owns HTTP, secrets, cookies and account state. Nothing is sent by this example.
using HostPost = void (*)(std::string_view path, std::string_view cookie, std::string_view account_id,
                          std::string_view body);
void print_wire(std::string_view path, std::string_view cookie, std::string_view account_id, std::string_view body) {
  std::printf("POST %.*s\n", int(path.size()), path.data());
  if (!cookie.empty()) std::printf("Cookie: %.*s\n", int(cookie.size()), cookie.data());
  if (!account_id.empty()) std::printf("X-Grvt-Account-Id: %.*s\n", int(account_id.size()), account_id.data());
  std::printf("%.*s\n", int(body.size()), body.data());
}
int main() {
  HostPost post = &print_wire;
  // API-key login wire shape. Read Set-Cookie gravity and X-Grvt-Account-Id from the
  // real response in the host. Never print real keys or cookies in production logs.
  post("/auth/api_key/login", {}, {}, R"({"api_key":"REPLACE_IN_HOST"})");
  auto order = reference::order();
  auto meta = reference::metadata();
  grvt::SignContext ctx;
  ctx.chain_id = 326;  // caller selects the chain; the core has no environment lookup
  ctx.metadata = &meta;
  auto digest = grvt::signing::digest_order_create_order(order, ctx);
  if (!digest) return 1;
  std::printf("digest: %s\n", grvt::hex0x(digest->digest).c_str());
#ifdef GRVT_WITH_SIGNER
  auto signer = grvt::PrivateKeySigner::from_hex(reference::test_key);
  if (!signer) return 2;
  ctx.signer = &*signer;
  ctx.verify = &grvt::verify_signature;
  if (!grvt::signing::sign_order_create_order(order, ctx)) return 3;
  post("/full/v1/create_order", "gravity=HOST_COOKIE", "HOST_ACCOUNT_ID", grvt::encode(order));
#endif
  // If a write times out after sending, its result is unknown. Keep client_order_id
  // and reconcile with get_order/order history. An absent lookup does not prove that
  // the order was rejected. Keep the result unknown and never automatically resend.
  // A fresh nonce is not a retry guarantee. The host owns this policy and its storage.
  std::puts("unknown write: reconcile by client_order_id; absent lookup stays unknown; never automatically resend");
  return 0;
}
esc

↑ ↓ move↵ open⇧↵ open .mdTry an error code like 2002

Keyboard shortcuts

⌘ K
Search the docs
/
Search
l
Next code language (Python → TypeScript → Go → Rust → curl → WebSocket)
j / k
Next / previous page
t
Light / dark theme
?
This help
Esc
Close dialogs and drawers