For DevelopersAPIExchange Endpoint

Exchange Endpoint

The exchange endpoint handles all authenticated write operations: placing orders, cancelling orders, modifying orders, transferring funds, updating leverage, and managing API wallets.

Endpoint

POST /exchange
Content-Type: application/json

Authentication: Every request must include an EIP-712 typed data signature. See Signing for implementation details.

Request Format

{
  "action": { ... },
  "nonce": 1700000000123,
  "signature": { "r": "0x...", "s": "0x...", "v": 27 },
  "vaultAddress": null
}
FieldTypeDescription
actionObjectThe operation to perform (see sections below)
nonceintCurrent Unix timestamp in milliseconds
signatureObjectEIP-712 signature with r, s, v components
vaultAddressaddress?Optional. Set when signing with an agent on behalf of a vault/main address

Response Format

{
  "status": "ok",
  "response": {
    "type": "order",
    "data": { "statuses": [{ "resting": { "oid": 12345 } }] }
  }
}

Error responses:

{ "status": "err", "response": "Insufficient margin" }

Place Order

Places one or more orders in a single request.

Action Payload

{
  "type": "order",
  "orders": [
    {
      "a": 0,
      "b": true,
      "p": "67000.0",
      "s": "0.01",
      "r": false,
      "t": { "limit": { "tif": "Gtc" } },
      "c": "0x1234567890abcdef1234567890abcdef"
    }
  ],
  "grouping": "na"
}

Order Fields

FieldTypeRequiredDescription
aintYesAsset index (from meta or spotMeta)
bboolYestrue = buy, false = sell
pstringYesLimit price (max 5 significant figures)
sstringYesOrder size
rboolYesReduce-only flag
tObjectYesOrder type object
chex?NoClient order ID (16 bytes, hex-encoded)

Order Types

Limit Order:

{ "limit": { "tif": "Gtc" } }
TIFDescription
GtcGood-til-cancelled. Rests on the book until filled or cancelled.
IocImmediate-or-cancel. Fills immediately or cancels remaining.
AloAdd-liquidity-only (post-only). Rejected if it would cross the spread.

Trigger Order (Stop/Take-Profit):

{
  "trigger": {
    "isMarket": true,
    "triggerPx": "65000.0",
    "tpsl": "sl"
  }
}
FieldTypeDescription
isMarketboolIf true, executes as market order when triggered
triggerPxstringTrigger price
tpslstring"tp" for take-profit, "sl" for stop-loss

Grouping

ValueDescription
"na"No grouping. Each order is independent.
"normalTpsl"Link orders as a TP/SL group.
"positionTpsl"Attach TP/SL to the entire position.

Response

{
  "status": "ok",
  "response": {
    "type": "order",
    "data": {
      "statuses": [
        { "resting": { "oid": 12345 } }
      ]
    }
  }
}

Possible status values per order:

  • { "resting": { "oid": 12345 } } — order placed on book
  • { "filled": { "totalSz": "0.01", "avgPx": "67000.0" } } — fully filled immediately
  • { "error": "Insufficient margin" } — order rejected

Cancel Order

Cancels one or more orders by order ID.

{
  "type": "cancel",
  "cancels": [
    { "a": 0, "o": 12345 }
  ]
}
FieldTypeDescription
aintAsset index
ointOrder ID to cancel

Response

{
  "status": "ok",
  "response": {
    "type": "cancel",
    "data": { "statuses": ["success"] }
  }
}

Cancel by Client Order ID

Cancels orders using the client-assigned order ID.

{
  "type": "cancelByCloid",
  "cancels": [
    { "asset": 0, "cloid": "0x1234567890abcdef1234567890abcdef" }
  ]
}
FieldTypeDescription
assetintAsset index
cloidhexClient order ID (16 bytes)

Modify Order

Modifies an existing order’s price and/or size. The order retains its queue priority only if the size decreases or the price improves.

{
  "type": "modify",
  "oid": 12345,
  "order": {
    "a": 0,
    "b": true,
    "p": "67500.0",
    "s": "0.02",
    "r": false,
    "t": { "limit": { "tif": "Gtc" } }
  }
}
FieldTypeDescription
oidintOrder ID to modify
orderObjectNew order parameters (same schema as place order)

Transfer USD

Transfers USD between addresses on GX Exchange.

{
  "type": "usdTransfer",
  "destination": "0xRecipientAddress...",
  "amount": "1000.0"
}
FieldTypeDescription
destinationaddressRecipient Ethereum address
amountstringUSD amount to transfer

Withdraw from Bridge

Initiates a withdrawal from GX Exchange to an external chain.

{
  "type": "withdraw",
  "destination": "0xRecipientAddress...",
  "amount": "500.0"
}
FieldTypeDescription
destinationaddressDestination address on the target chain
amountstringUSD amount to withdraw

Update Leverage

Changes the leverage setting for a specific asset.

{
  "type": "updateLeverage",
  "asset": 0,
  "isCross": true,
  "leverage": 10
}
FieldTypeDescription
assetintAsset index
isCrossbooltrue for cross margin, false for isolated
leverageintLeverage multiplier

Approve Agent (API Wallet)

Authorizes or revokes an agent wallet. See Nonces and API Wallets for the full flow.

{
  "type": "approveAgent",
  "agentAddress": "0xAgentAddress...",
  "agentName": "My Trading Bot",
  "nonce": 1700000000000
}
FieldTypeDescription
agentAddressaddressThe agent’s Ethereum address
agentNamestringHuman-readable label for the agent
nonceintTimestamp used for this authorization

Code Examples

TypeScript — Place and Cancel

import { GxClient } from "@gx-exchange/sdk";
 
const client = new GxClient();
await client.connect("https://api.gx.exchange");
client.setWallet("0xYourPrivateKey...");
 
// Place a limit buy
const order = await client.placeOrder([{
  coin: "BTC",
  isBuy: true,
  sz: 0.001,
  limitPx: 60000,
  tif: "Gtc",
  reduceOnly: false,
}]);
console.log("Order:", order);
 
// Cancel
const oid = order.response.data.statuses[0].resting.oid;
const cancel = await client.cancel([{ coin: "BTC", oid }]);
console.log("Cancel:", cancel);

Python — Place and Cancel

from gx_exchange.exchange import Exchange
from gx_exchange.utils.constants import MAINNET_API_URL
import eth_account
 
account = eth_account.Account.from_key("0xYourPrivateKey...")
exchange = Exchange(account, MAINNET_API_URL)
 
# Place a limit buy
result = exchange.order("BTC", is_buy=True, sz=0.001, limit_px=60000,
                        order_type={"limit": {"tif": "Gtc"}})
print(f"Order: {result}")
 
# Cancel
oid = result["response"]["data"]["statuses"][0]["resting"]["oid"]
cancel = exchange.cancel("BTC", oid=oid)
print(f"Cancel: {cancel}")

Common Errors

Error MessageCauseResolution
Insufficient marginNot enough collateral for the orderReduce size or deposit more funds
Order not foundCancel/modify target does not existVerify order ID is correct and active
Invalid signatureEIP-712 signature verification failedCheck domain, chain ID, and signing key
Price out of rangeLimit price too far from oracleUse a price closer to market
Reduce only violatedReduce-only order would increase positionCheck position direction first
Self-trade preventedOrder would match own resting orderCancel existing order first