JavaScript / TypeScript SDK

Encrypted JavaScript and TypeScript client for the GoDark API. Package name: @godark/sdk.

Requirements: Node.js 18+
Status: Beta — clone the public examples repo to get started.

Get the SDK

Clone gdx-js-sdk-examples. The repo vendors @godark/sdk under sdk/ so no private npm registry is required:

git clone https://github.com/gq-godark/gdx-js-sdk-examples.git
cd gdx-js-sdk-examples
cp .env.example .env
# set GODARK_API_KEY_ID, GODARK_API_SECRET, GODARK_PASSPHRASE

npm install
npm run quickstart
npm run full-trader

You can also point an LLM / coding agent at the cloned repo and ask it to build a strategy using your credentials in .env. See the repo README for full setup, examples, and packaging details.

Public npm release is not yet available; until then this repo is the supported distribution.

Quickstart

Set credentials, then place a limit order over encrypted WebSocket (GodarkClient). Subscribe to orders before placing so book confirmation can wait on private updates. Limit prices must stay near the oracle or the venue rejects — see Error Codes.

import { Environment, GodarkClient } from "@godark/sdk";

const SYMBOL = "BTC-USDC-PERP";

async function main(): Promise<void> {
  const edge = process.env.GODARK_EDGE_URL?.trim();
  const client = new GodarkClient({
    apiKeyId: process.env.GODARK_API_KEY_ID!,
    apiSecret: process.env.GODARK_API_SECRET!,
    passphrase: process.env.GODARK_PASSPHRASE!,
    environment: Environment.the configured host,
    ...(edge ? { baseUrl: edge } : {}),
  });

  await client.connect();
  await client.subscribe(["orders"]);

  const ack = await client.placeOrder({
    symbol: SYMBOL,
    side: "SELL",
    orderType: "LIMIT",
    price: "68000", // decimal string; within ~10% of oracle
    quantity: "0.01",
  });
  console.log("placed", ack.orderId);

  await new Promise((r) => setTimeout(r, 500));
  const cancel = await client.cancelOrder(ack.orderId, SYMBOL);
  console.log("cancelled", cancel.orderId);

  await client.disconnect();
}

main().catch(console.error);

See WebSocket Trading and Place Order for request fields.

Clients

ClassDescription
GodarkClientWebSocket trading + order/position streams on /ws/v1
GodarkRestClientBearer-authenticated REST trading, order lookup, leverage, account/position snapshots, and public-market queries; trading bodies use one-shot HPKE
MarketDataClientPublic market snapshots on /ws/v1 by default; set GODARK_MARKET_DATA_USE_GOMARKET=1 or GODARK_MARKET_DATA_WS_URL to opt in to /ws/gomarket order-book feeds

The package ships ESM, CJS, and TypeScript declarations (dist/index.js, dist/index.d.ts).

GodarkRestClient places / cancels / modifies with bearer + one-shot HPKE. GodarkClient uses a sealed HPKE WebSocket session for the same ops. Server-side client-order-id registration follows a WebSocket place: when GodarkClient.placeOrder sets clientOrderId, the SDK immediately POSTs /api/v1/orders/_register_coid with client_order_id, decimal order_id, and correlation_id (the same non-zero u128 sent in the place header, as a decimal string). A failed register is not success, and an in-memory map is not a substitute for that HTTP 200. REST place cannot register the id on this edge — forward_encrypted_order does not arm the place correlation — so GodarkRestClient.placeOrder does not call _register_coid. getOrder turns the Zone A encrypted pointer into a decrypted status from the open-orders snapshot, order history, or a cancel this client just sent. GTD expiryTime is unix seconds or milliseconds; the SDK scales it to nanoseconds. Plaintext account_update feeds onBalanceUpdate and onMarginAlert. Plaintext points_update feeds onSettlementUpdate. An unknown channel rejects subscribe() through onError instead of waiting out the command timeout. Public funding_rate snapshots that arrive as a subscribe reply are delivered to onFundingRateUpdate.

Public place / modify / mass-quote / batch-modify / TP-SL prices, sizes, quote notional, min fill, trigger, take-profit, and stop-loss are decimal strings only (for example "68000", "0.01"). Numbers and floats are rejected. The SDK validates each value against the instrument’s price_decimals / quantity_decimals from GET /api/v1/instruments before sealing (PlaceOrderInput.price field 23, quantity field 24).

Environment.the configured host is the hosted default and Environment.the configured host selects the configured host. JavaScript accepts ws(s) or http(s) edge URLs, rewrites http → ws and https → wss, upgrades a trailing /ws, and otherwise appends /ws/v1. See Base URLs.

GodarkClient methods

MethodDocs reference
connect() / disconnect()Authentication, Encryption
subscribe(...)WebSocket Trading
placeOrder(...)Place Order, WebSocket Trading
cancelOrder(...)Cancel Order
modifyOrder(...)Modify Order
massQuote(...)Mass Quote
batchCancel(...)Cancel Order
Order update callbacksOrders Channel
Position update callbacksPositions Channel

Types and errors

Exported types include Environment, OrderAck, OrderUpdate, PositionUpdate, Side, OrderType, TimeInForce, and typed error classes (AuthenticationError, SessionError, OrderError, and similar).

The HPKE login conn_id is represented as a JavaScript bigint because it is an unsigned 64-bit wire value.

Environment variables: OS GODARK_*, then OS GDX_*, then .env GODARK_*, then .env GDX_*. The process environment always wins over .env. Quickstart snippets use the canonical GODARK_* names.

Bundled examples

Runnable samples in the examples repo include quickstart.ts (connect → subscribe → place → cancel) and full-trader-example.ts (modify, mass quote, batch cancel) — npm run quickstart, npm run full-trader.

See also


Shared trading fields

Prices, sizes, quote notional, trigger, take-profit, and stop-loss are decimal strings.

Place options (names follow each language): reduce_only, post_only, stp_mode (UNSPECIFIED, CANCEL_RESTING, CANCEL_AGGRESSOR, CANCEL_BOTH), quote_notional, peg_offset_bps, trigger_price, take_profit_price, stop_loss_price, slippage_bps, client_order_id.

confirmation: ack returns on the sequencer acknowledgement. book waits for a terminal private order update until the place timeout.

Time in force: GTC, IOC, FOK, GTD. Order types: MARKET, LIMIT, PEG, STOP_MARKET, STOP_LIMIT. Side: BUY, SELL.

Mass quote: 1 to 20 legs. Each leg has side, price, quantity, optional cancel_order_id, time_in_force, expiry_time. post_only omitted uses the venue default.

Batch modify legs: order_id plus at least one of new_price, new_quantity.

WebSocket implements cancel-all, close-all, reverse, and TP/SL amend or cancel. REST implements one-shot encrypted place, cancel, modify, mass quote, batch cancel, batch modify, plus snapshots. REST does not implement cancel-all, close-all, reverse, or TP/SL amend.

A WebSocket place that sets client_order_id registers it after the ack. REST leaves that id unregistered.

Errors: authentication, session, connection, encryption, timeout, and order rejection with a numeric code and symbolic name. See Error Codes.

JavaScript reference

new GodarkClient(opts) and new GodarkRestClient(opts). opts accepts apiKey or apiKeyId + apiSecret + passphrase, environment, baseUrl or restBaseUrl, account, symbolMap, hpkeStaticPublicKeyHex, and for the socket client autoReconnect, transportOptions, streamBufferSize, placeOrderTerminalTimeoutMs, onError.

Socket methods return promises: connect, disconnect, logout, placeOrder, cancelOrder, modifyOrder, updateLeverage, cancelAllOrders, closeAll, reversePosition, amendTpsl, cancelTpsl, massQuote, batchCancel, batchModify, subscribe, unsubscribe.

Streams: onOrderUpdate, onPositionUpdate, onPositionsSnapshot, onOpenOrdersSnapshot, onSystemHealth, onBalanceUpdate, onMarginAlert, onFundingRateUpdate, onSettlementUpdate, onLeverageSettings, onReconnect, onError, plus matching async iterators.

REST: getOpenOrders, getPositions, getAccount, getLeverage, getOrder, getOrderByClientOrderId, getFundingRates, getOpenInterest, getVolume, placeOrder, cancelOrder, cancelOrderByClientId, modifyOrder, updateLeverage, massQuote, batchCancel, batchModify, awaitTerminalStatus.

MarketDataClient: subscribeOrderbook and subscribeTrades on the market-data socket; subscribePublicChannel for volume, open_interest, funding_rate.

Exported response types include OrderAck, OrderUpdate, CountAck, TpslAck, MassQuoteAck, BatchCancelAck, BatchModifyAck, PositionsSnapshot, OpenOrdersSnapshot, AccountMarginUpdate, LeverageSettings, BalanceUpdate.