Quick Start Trading Guide
Start trading on GaiaEx in 5 minutes. Code examples in Python, JavaScript, and curl — place your first order with no KYC.
Prerequisites
IF YOU ALREADY HAVE MONEY IN THE APP, YOU CAN TRADE TODAY
Deposited USDC plus a freshly created API key is all you need. The snippets below are copy-paste runnable — plug in your api_key, api_secret, and wallet address, and the first GET /balance call should return data in under 10 seconds.
- A GaiaEx account, set up in the mobile app (account handshake is a one-time in-app flow)
- USDC already deposited into the account via the mobile app — API keys trade against your existing balance and cannot deposit or withdraw funds
- A programming environment for your language of choice
Step 1: Create an API Key
API keys are created exclusively in the GaiaEx mobile app.
- Open the GaiaEx mobile app (iOS / Android)
- Tap the Settings icon (gear, bottom-right)
- Tap API Keys
- Tap Create API Key
- Set permissions:
readfor data access,tradefor order execution - Copy and securely store your API Key and API Secret
DANGER
Your API Secret is only shown once at creation time. Store it securely. If lost, revoke the key and create a new one.
PROGRAMMATIC MANAGEMENT
After creating your first API key via the mobile app, you can list, update, and revoke keys programmatically using the /api-keys REST endpoints. See the API Keys page for details.
Step 2: Install Dependencies
pip install requestsnpm install axiosGo standard library only — no external dependencies.
go mod init gaiaex-botcargo add reqwest --features json,blocking
cargo add hmac sha2 hex serde serde_json# Install libcurl and OpenSSL (Ubuntu/Debian)
sudo apt install libcurl4-openssl-dev libssl-dev nlohmann-json3-dev<!-- Maven: pom.xml -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>.NET HttpClient is built-in — no NuGet packages needed.
dotnet new console -n GaiaExBot# curl + openssl (pre-installed on most systems)
curl --version
openssl versionStep 3: Set Up Authentication
Every private API call requires HMAC-SHA256 signing. Set up a reusable helper in your language — the helper signs each call and reads credentials from config.json so you never hardcode a secret.
config.json convention
Every example on this page assumes a config.json in the working directory shaped like this:
{
"api_key": "your_api_key_here",
"api_secret": "your_api_secret_here",
"user_address": "0xYourWalletAddress"
}Rotate your key by editing this file — the code never changes. Add config.json to .gitignore.
import hmac, hashlib, json, time, requests
# Credentials load from config.json — never hardcoded, never committed.
cfg = json.load(open("config.json"))
API_KEY = cfg["api_key"]
API_SECRET = cfg["api_secret"]
ADDRESS = cfg["user_address"]
BASE_URL = "https://openapi.gaiaex.com/v1/trade"
def sign_request(method, path, body=""):
ts = str(int(time.time() * 1000))
message = ts + method.upper() + path + body
sig = hmac.new(
API_SECRET.encode(), message.encode(), hashlib.sha256
).hexdigest()
return {
"X-GAIAEX-APIKEY": API_KEY,
"X-GAIAEX-TIMESTAMP": ts,
"X-GAIAEX-SIGNATURE": sig,
"Content-Type": "application/json",
}
def gaiaex_get(path):
headers = sign_request("GET", path)
return requests.get(BASE_URL + path, headers=headers).json()
def gaiaex_post(path, data):
body = json.dumps(data)
headers = sign_request("POST", path, body)
return requests.post(BASE_URL + path, headers=headers, data=body).json()const crypto = require('crypto');
const axios = require('axios');
const cfg = require('./config.json');
const API_KEY = cfg.api_key;
const API_SECRET = cfg.api_secret;
const ADDRESS = cfg.user_address;
const BASE_URL = 'https://openapi.gaiaex.com/v1/trade';
function signRequest(method, path, body = '') {
const ts = Date.now().toString();
const message = ts + method.toUpperCase() + path + body;
const sig = crypto.createHmac('sha256', API_SECRET)
.update(message).digest('hex');
return {
'X-GAIAEX-APIKEY': API_KEY,
'X-GAIAEX-TIMESTAMP': ts,
'X-GAIAEX-SIGNATURE': sig,
'Content-Type': 'application/json',
};
}
async function gaiaexGet(path) {
const { data } = await axios.get(BASE_URL + path,
{ headers: signRequest('GET', path) });
return data;
}
async function gaiaexPost(path, payload) {
const body = JSON.stringify(payload);
const { data } = await axios.post(BASE_URL + path, body,
{ headers: signRequest('POST', path, body) });
return data;
}package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
APIKey string `json:"api_key"`
APISecret string `json:"api_secret"`
UserAddress string `json:"user_address"`
}
var cfg = func() Config {
data, _ := os.ReadFile("config.json")
var c Config
_ = json.Unmarshal(data, &c)
return c
}()
var (
apiKey = cfg.APIKey
apiSecret = cfg.APISecret
address = cfg.UserAddress
baseURL = "https://openapi.gaiaex.com/v1/trade"
)
func signRequest(method, path, body string) http.Header {
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
message := ts + strings.ToUpper(method) + path + body
mac := hmac.New(sha256.New, []byte(apiSecret))
mac.Write([]byte(message))
sig := hex.EncodeToString(mac.Sum(nil))
h := http.Header{}
h.Set("X-GAIAEX-APIKEY", apiKey)
h.Set("X-GAIAEX-TIMESTAMP", ts)
h.Set("X-GAIAEX-SIGNATURE", sig)
h.Set("Content-Type", "application/json")
return h
}
func gaiaexGet(path string) (map[string]interface{}, error) {
req, _ := http.NewRequest("GET", baseURL+path, nil)
req.Header = signRequest("GET", path, "")
resp, err := http.DefaultClient.Do(req)
if err != nil { return nil, err }
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(b, &result)
return result, nil
}
func gaiaexPost(path string, payload interface{}) (map[string]interface{}, error) {
body, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", baseURL+path, strings.NewReader(string(body)))
req.Header = signRequest("POST", path, string(body))
resp, err := http.DefaultClient.Do(req)
if err != nil { return nil, err }
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(b, &result)
return result, nil
}use hmac::{Hmac, Mac};
use sha2::Sha256;
use serde::Deserialize;
use std::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use std::fs::File;
use once_cell::sync::Lazy;
#[derive(Deserialize)]
struct Config { api_key: String, api_secret: String, user_address: String }
static CFG: Lazy<Config> = Lazy::new(||
serde_json::from_reader(File::open("config.json").unwrap()).unwrap()
);
const BASE_URL: &str = "https://openapi.gaiaex.com/v1/trade";
type HmacSha256 = Hmac<Sha256>;
fn sign_request(method: &str, path: &str, body: &str)
-> HashMap<String, String>
{
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH).unwrap()
.as_millis().to_string();
let message = format!("{}{}{}{}", ts, method.to_uppercase(), path, body);
let mut mac = HmacSha256::new_from_slice(CFG.api_secret.as_bytes()).unwrap();
mac.update(message.as_bytes());
let sig = hex::encode(mac.finalize().into_bytes());
HashMap::from([
("X-GAIAEX-APIKEY".into(), CFG.api_key.clone()),
("X-GAIAEX-TIMESTAMP".into(), ts),
("X-GAIAEX-SIGNATURE".into(), sig),
("Content-Type".into(), "application/json".into()),
])
}
fn gaiaex_get(path: &str) -> serde_json::Value {
let hdrs = sign_request("GET", path, "");
let client = reqwest::blocking::Client::new();
let mut req = client.get(format!("{}{}", BASE_URL, path));
for (k, v) in &hdrs { req = req.header(k.as_str(), v.as_str()); }
req.send().unwrap().json().unwrap()
}
fn gaiaex_post(path: &str, payload: &serde_json::Value) -> serde_json::Value {
let body = serde_json::to_string(payload).unwrap();
let hdrs = sign_request("POST", path, &body);
let client = reqwest::blocking::Client::new();
let mut req = client.post(format!("{}{}", BASE_URL, path)).body(body);
for (k, v) in &hdrs { req = req.header(k.as_str(), v.as_str()); }
req.send().unwrap().json().unwrap()
}#include <curl/curl.h>
#include <openssl/hmac.h>
#include <nlohmann/json.hpp>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <sstream>
using json = nlohmann::json;
// Load credentials from config.json at startup — never hardcoded.
static const json CFG = []{
std::ifstream f("config.json");
return json::parse(f);
}();
const std::string API_KEY = CFG["api_key"];
const std::string API_SECRET = CFG["api_secret"];
const std::string ADDRESS = CFG["user_address"];
const std::string BASE_URL = "https://openapi.gaiaex.com/v1/trade";
std::string hmac_sha256(const std::string& key, const std::string& msg) {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int len = 0;
HMAC(EVP_sha256(), key.c_str(), key.size(),
(unsigned char*)msg.c_str(), msg.size(), digest, &len);
std::ostringstream ss;
for (unsigned i = 0; i < len; i++)
ss << std::hex << std::setfill('0') << std::setw(2) << (int)digest[i];
return ss.str();
}
static size_t write_cb(void* p, size_t s, size_t n, std::string* d) {
d->append((char*)p, s * n); return s * n;
}
json gaiaex_request(const std::string& method, const std::string& path,
const std::string& body = "") {
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
std::string ts = std::to_string(ms);
std::string sig = hmac_sha256(API_SECRET, ts + method + path + body);
CURL* curl = curl_easy_init();
std::string resp;
struct curl_slist* hdrs = nullptr;
hdrs = curl_slist_append(hdrs, ("X-GAIAEX-APIKEY: " + API_KEY).c_str());
hdrs = curl_slist_append(hdrs, ("X-GAIAEX-TIMESTAMP: " + ts).c_str());
hdrs = curl_slist_append(hdrs, ("X-GAIAEX-SIGNATURE: " + sig).c_str());
hdrs = curl_slist_append(hdrs, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_URL, (BASE_URL + path).c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hdrs);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp);
if (method == "POST") {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
}
curl_easy_perform(curl);
curl_slist_free_all(hdrs);
curl_easy_cleanup(curl);
return json::parse(resp);
}import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.*;
import okhttp3.*;
import org.json.*;
public class GaiaEx {
// Load credentials from config.json on class init.
static final JSONObject CFG;
static {
try { CFG = new JSONObject(new String(Files.readAllBytes(Paths.get("config.json")))); }
catch (Exception e) { throw new RuntimeException(e); }
}
static final String API_KEY = CFG.getString("api_key");
static final String API_SECRET = CFG.getString("api_secret");
static final String ADDRESS = CFG.getString("user_address");
static final String BASE_URL = "https://openapi.gaiaex.com/v1/trade";
static final OkHttpClient client = new OkHttpClient();
static String hmacSha256(String key, String msg) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
byte[] digest = mac.doFinal(msg.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) sb.append(String.format("%02x", b));
return sb.toString();
}
static JSONObject gaiaexGet(String path) throws Exception {
String ts = String.valueOf(System.currentTimeMillis());
String sig = hmacSha256(API_SECRET, ts + "GET" + path);
Request req = new Request.Builder()
.url(BASE_URL + path)
.addHeader("X-GAIAEX-APIKEY", API_KEY)
.addHeader("X-GAIAEX-TIMESTAMP", ts)
.addHeader("X-GAIAEX-SIGNATURE", sig)
.build();
try (Response resp = client.newCall(req).execute()) {
return new JSONObject(resp.body().string());
}
}
static JSONObject gaiaexPost(String path, JSONObject payload) throws Exception {
String body = payload.toString();
String ts = String.valueOf(System.currentTimeMillis());
String sig = hmacSha256(API_SECRET, ts + "POST" + path + body);
Request req = new Request.Builder()
.url(BASE_URL + path)
.addHeader("X-GAIAEX-APIKEY", API_KEY)
.addHeader("X-GAIAEX-TIMESTAMP", ts)
.addHeader("X-GAIAEX-SIGNATURE", sig)
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();
try (Response resp = client.newCall(req).execute()) {
return new JSONObject(resp.body().string());
}
}
}using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
class GaiaEx {
// Load credentials from config.json at startup.
static readonly JsonDocument Cfg = JsonDocument.Parse(File.ReadAllText("config.json"));
static readonly string ApiKey = Cfg.RootElement.GetProperty("api_key").GetString()!;
static readonly string ApiSecret = Cfg.RootElement.GetProperty("api_secret").GetString()!;
static readonly string Address = Cfg.RootElement.GetProperty("user_address").GetString()!;
const string BaseUrl = "https://openapi.gaiaex.com/v1/trade";
static readonly HttpClient http = new();
static string HmacSha256(string key, string msg) {
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
return Convert.ToHexString(
hmac.ComputeHash(Encoding.UTF8.GetBytes(msg))).ToLower();
}
static async Task<JsonDocument> GaiaexGet(string path) {
var ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
var sig = HmacSha256(ApiSecret, ts + "GET" + path);
var req = new HttpRequestMessage(HttpMethod.Get, BaseUrl + path);
req.Headers.Add("X-GAIAEX-APIKEY", ApiKey);
req.Headers.Add("X-GAIAEX-TIMESTAMP", ts);
req.Headers.Add("X-GAIAEX-SIGNATURE", sig);
var resp = await http.SendAsync(req);
return JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
}
static async Task<JsonDocument> GaiaexPost(string path, object payload) {
var body = JsonSerializer.Serialize(payload);
var ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
var sig = HmacSha256(ApiSecret, ts + "POST" + path + body);
var req = new HttpRequestMessage(HttpMethod.Post, BaseUrl + path);
req.Headers.Add("X-GAIAEX-APIKEY", ApiKey);
req.Headers.Add("X-GAIAEX-TIMESTAMP", ts);
req.Headers.Add("X-GAIAEX-SIGNATURE", sig);
req.Content = new StringContent(body, Encoding.UTF8, "application/json");
var resp = await http.SendAsync(req);
return JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
}
}# Load credentials from config.json (requires: apt install jq).
API_KEY=$(jq -r .api_key config.json)
API_SECRET=$(jq -r .api_secret config.json)
ADDRESS=$(jq -r .user_address config.json)
BASE_URL="https://openapi.gaiaex.com/v1/trade"
# Helper: sign and send a GET request
gaiaex_get() {
local path="$1"
local ts=$(date +%s000)
local msg="${ts}GET${path}"
local sig=$(echo -n "$msg" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
curl -s -H "X-GAIAEX-APIKEY: $API_KEY" \
-H "X-GAIAEX-TIMESTAMP: $ts" \
-H "X-GAIAEX-SIGNATURE: $sig" \
"${BASE_URL}${path}"
}
# Helper: sign and send a POST request
gaiaex_post() {
local path="$1" body="$2"
local ts=$(date +%s000)
local msg="${ts}POST${path}${body}"
local sig=$(echo -n "$msg" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
curl -s -X POST -H "X-GAIAEX-APIKEY: $API_KEY" \
-H "X-GAIAEX-TIMESTAMP: $ts" \
-H "X-GAIAEX-SIGNATURE: $sig" \
-H "Content-Type: application/json" \
-d "$body" "${BASE_URL}${path}"
}Step 4: Check Your Balance
balance = gaiaex_get(f"/user/{ADDRESS}/balance")
print(f"Available: ${balance['available']} USDC")const balance = await gaiaexGet(`/user/${ADDRESS}/balance`);
console.log(`Available: $${balance.available} USDC`);func main() {
balance, _ := gaiaexGet("/user/" + address + "/balance")
fmt.Printf("Available: %s USDC\n", balance["available"])
}fn main() {
let path = format!("/user/{}/balance", ADDRESS);
let balance = gaiaex_get(&path);
println!("Available: {} USDC", balance["available"]);
}int main() {
auto balance = gaiaex_request("GET", "/user/" + ADDRESS + "/balance");
std::cout << "Available: " << balance["available"] << " USDC" << std::endl;
}public static void main(String[] args) throws Exception {
JSONObject balance = gaiaexGet("/user/" + ADDRESS + "/balance");
System.out.println("Available: " + balance.getString("available") + " USDC");
}var balance = await GaiaexGet($"/user/{Address}/balance");
Console.WriteLine($"Available: {balance.RootElement.GetProperty("available")} USDC");gaiaex_get "/user/$ADDRESS/balance" | python3 -m json.toolResponse:
{
"address": "0xYourAddress",
"usdc_balance": "1000.00",
"available": "850.00",
"unrealized_pnl": "12.50",
"margin_used": "150.00",
"timestamp": 1743508800000
}Step 5: Check Your Positions
Returns all open positions with entry price, current PnL, leverage, and liquidation price.
positions = gaiaex_get(f"/user/{ADDRESS}/positions")
for p in positions.get("positions", []):
print(p["symbol"], p["size"], "entry", p["entry_price"], "PnL", p["unrealized_pnl"])const positions = await gaiaexGet(`/user/${ADDRESS}/positions`);
for (const p of positions.positions || []) {
console.log(p.symbol, p.size, 'entry', p.entry_price, 'PnL', p.unrealized_pnl);
}positions, _ := gaiaexGet("/user/" + address + "/positions")
for _, p := range positions["positions"].([]interface{}) {
m := p.(map[string]interface{})
fmt.Println(m["symbol"], m["size"], "entry", m["entry_price"], "PnL", m["unrealized_pnl"])
}let positions = gaiaex_get(&format!("/user/{}/positions", CFG.user_address));
for p in positions["positions"].as_array().unwrap_or(&vec![]) {
println!("{} {} entry {} PnL {}", p["symbol"], p["size"], p["entry_price"], p["unrealized_pnl"]);
}auto positions = gaiaex_request("GET", "/user/" + ADDRESS + "/positions");
for (auto& p : positions["positions"]) {
std::cout << p["symbol"] << " " << p["size"] << " entry " << p["entry_price"] << " PnL " << p["unrealized_pnl"] << "\n";
}JSONObject positions = gaiaexGet("/user/" + ADDRESS + "/positions");
for (Object o : positions.optJSONArray("positions")) {
JSONObject p = (JSONObject) o;
System.out.println(p.get("symbol") + " " + p.get("size") + " entry " + p.get("entry_price") + " PnL " + p.get("unrealized_pnl"));
}var positions = await GaiaexGet($"/user/{Address}/positions");
foreach (var p in positions.RootElement.GetProperty("positions").EnumerateArray()) {
Console.WriteLine($"{p.GetProperty("symbol")} {p.GetProperty("size")} entry {p.GetProperty("entry_price")} PnL {p.GetProperty("unrealized_pnl")}");
}gaiaex_get "/user/$ADDRESS/positions" | python3 -m json.toolResponse:
{
"address": "0xYourAddress",
"positions": [
{
"symbol": "BTC", "size": "0.05", "is_long": true,
"entry_price": "74200.00", "mark_price": "75100.00",
"unrealized_pnl": "45.00", "leverage": "10",
"liquidation_price": "67400.00", "margin_used": "371.00"
}
],
"count": 1,
"timestamp": 1743508800000
}Step 6: Check Your Open Orders
Lists all resting (unfilled) orders. Use /historicalOrders for filled/canceled history.
opens = gaiaex_get(f"/user/{ADDRESS}/openOrders")
for o in opens.get("orders", []):
print(o["orderId"], o["symbol"], o["side"], o["size"], "@", o["price"])const opens = await gaiaexGet(`/user/${ADDRESS}/openOrders`);
for (const o of opens.orders || []) {
console.log(o.orderId, o.symbol, o.side, o.size, '@', o.price);
}opens, _ := gaiaexGet("/user/" + address + "/openOrders")
for _, o := range opens["orders"].([]interface{}) {
m := o.(map[string]interface{})
fmt.Println(m["orderId"], m["symbol"], m["side"], m["size"], "@", m["price"])
}let opens = gaiaex_get(&format!("/user/{}/openOrders", CFG.user_address));
for o in opens["orders"].as_array().unwrap_or(&vec![]) {
println!("{} {} {} {} @ {}", o["orderId"], o["symbol"], o["side"], o["size"], o["price"]);
}auto opens = gaiaex_request("GET", "/user/" + ADDRESS + "/openOrders");
for (auto& o : opens["orders"]) {
std::cout << o["orderId"] << " " << o["symbol"] << " " << o["side"] << " " << o["size"] << " @ " << o["price"] << "\n";
}JSONObject opens = gaiaexGet("/user/" + ADDRESS + "/openOrders");
for (Object x : opens.optJSONArray("orders")) {
JSONObject o = (JSONObject) x;
System.out.println(o.get("orderId") + " " + o.get("symbol") + " " + o.get("side") + " " + o.get("size") + " @ " + o.get("price"));
}var opens = await GaiaexGet($"/user/{Address}/openOrders");
foreach (var o in opens.RootElement.GetProperty("orders").EnumerateArray()) {
Console.WriteLine($"{o.GetProperty("orderId")} {o.GetProperty("symbol")} {o.GetProperty("side")} {o.GetProperty("size")} @ {o.GetProperty("price")}");
}gaiaex_get "/user/$ADDRESS/openOrders" | python3 -m json.tool
# Historical (filled / canceled):
gaiaex_get "/user/$ADDRESS/historicalOrders" | python3 -m json.toolStep 7: Place a Limit Order
order = gaiaex_post("/order", {
"user_address": ADDRESS,
"symbol": "BTC",
"is_buy": True,
"size": "0.001",
"price": "80000",
"order_type": "limit",
})
print(f"Order placed: {order['orderId']}")const order = await gaiaexPost('/order', {
user_address: ADDRESS,
symbol: 'BTC',
is_buy: true,
size: '0.001',
price: '80000',
order_type: 'limit',
});
console.log(`Order placed: ${order.orderId}`);order, _ := gaiaexPost("/order", map[string]interface{}{
"user_address": address,
"symbol": "BTC",
"is_buy": true,
"size": "0.001",
"price": "80000",
"order_type": "limit",
})
fmt.Printf("Order placed: %v\n", order["orderId"])let order = gaiaex_post("/order", &serde_json::json!({
"user_address": ADDRESS,
"symbol": "BTC",
"is_buy": true,
"size": "0.001",
"price": "80000",
"order_type": "limit"
}));
println!("Order placed: {}", order["orderId"]);json payload = {
{"user_address", ADDRESS}, {"symbol", "BTC"},
{"is_buy", true}, {"size", "0.001"},
{"price", "80000"}, {"order_type", "limit"}
};
auto order = gaiaex_request("POST", "/order", payload.dump());
std::cout << "Order placed: " << order["orderId"] << std::endl;JSONObject order = gaiaexPost("/order", new JSONObject()
.put("user_address", ADDRESS)
.put("symbol", "BTC")
.put("is_buy", true)
.put("size", "0.001")
.put("price", "80000")
.put("order_type", "limit"));
System.out.println("Order placed: " + order.getLong("orderId"));var order = await GaiaexPost("/order", new {
user_address = Address, symbol = "BTC",
is_buy = true, size = "0.001",
price = "80000", order_type = "limit"
});
Console.WriteLine($"Order placed: {order.RootElement.GetProperty("orderId")}");gaiaex_post "/order" '{
"user_address": "'$ADDRESS'",
"symbol": "BTC",
"is_buy": true,
"size": "0.001",
"price": "80000",
"order_type": "limit"
}' | python3 -m json.toolResponse:
{
"success": true,
"orderId": 123456789,
"status": "open",
"symbol": "BTC",
"side": "BUY",
"type": "LIMIT",
"origQty": "0.001",
"price": "80000",
"timestamp": 1743508800000
}Step 8: Modify an Order
MODIFY REPLACES THE ORDER
Calling /order/modify cancels the old order and creates a new one. The response returns a new orderId — the old id is no longer valid. Use orderId from the modify response for any follow-up cancel or modify. oldOrderId is echoed back for convenience.
r = gaiaex_post("/order/modify", {
"user_address": ADDRESS,
"symbol": "BTC",
"order_id": 123456789, # the id you got from place order
"is_buy": True,
"size": "0.001",
"price": "79000", # new price
"order_type": "limit",
"time_in_force": "Gtc",
})
new_oid = r["orderId"]
print(f"Replaced {r['oldOrderId']} -> {new_oid}")const r = await gaiaexPost('/order/modify', {
user_address: ADDRESS, symbol: 'BTC',
order_id: 123456789, is_buy: true,
size: '0.001', price: '79000',
order_type: 'limit', time_in_force: 'Gtc',
});
console.log(`Replaced ${r.oldOrderId} -> ${r.orderId}`);r, _ := gaiaexPost("/order/modify", map[string]interface{}{
"user_address": address, "symbol": "BTC",
"order_id": 123456789, "is_buy": true,
"size": "0.001", "price": "79000",
"order_type": "limit", "time_in_force": "Gtc",
})
fmt.Printf("Replaced %v -> %v\n", r["oldOrderId"], r["orderId"])let r = gaiaex_post("/order/modify", &serde_json::json!({
"user_address": CFG.user_address, "symbol": "BTC",
"order_id": 123456789u64, "is_buy": true,
"size": "0.001", "price": "79000",
"order_type": "limit", "time_in_force": "Gtc"
}));
println!("Replaced {} -> {}", r["oldOrderId"], r["orderId"]);json body = {{"user_address", ADDRESS}, {"symbol", "BTC"},
{"order_id", 123456789}, {"is_buy", true},
{"size", "0.001"}, {"price", "79000"},
{"order_type", "limit"}, {"time_in_force", "Gtc"}};
auto r = gaiaex_request("POST", "/order/modify", body.dump());
std::cout << "Replaced " << r["oldOrderId"] << " -> " << r["orderId"] << "\n";JSONObject body = new JSONObject()
.put("user_address", ADDRESS).put("symbol", "BTC")
.put("order_id", 123456789L).put("is_buy", true)
.put("size", "0.001").put("price", "79000")
.put("order_type", "limit").put("time_in_force", "Gtc");
JSONObject r = gaiaexPost("/order/modify", body);
System.out.println("Replaced " + r.get("oldOrderId") + " -> " + r.get("orderId"));var r = await GaiaexPost("/order/modify", new {
user_address = Address, symbol = "BTC",
order_id = 123456789L, is_buy = true,
size = "0.001", price = "79000",
order_type = "limit", time_in_force = "Gtc"
});
var root = r.RootElement;
Console.WriteLine($"Replaced {root.GetProperty("oldOrderId")} -> {root.GetProperty("orderId")}");gaiaex_post "/order/modify" '{"user_address":"'$ADDRESS'","symbol":"BTC","order_id":123456789,"is_buy":true,"size":"0.001","price":"79000","order_type":"limit","time_in_force":"Gtc"}' | python3 -m json.toolResponse:
{
"success": true,
"orderId": 987654321,
"oldOrderId": 123456789,
"symbol": "BTC",
"side": "BUY",
"type": "LIMIT",
"origQty": "0.001",
"price": "79000",
"status": "MODIFIED",
"note": "The order was replaced. Use 'orderId' for subsequent cancel or modify.",
"timestamp": 1743508800000
}Step 9: Cancel the Order
result = gaiaex_post("/order/cancel", {
"user_address": ADDRESS,
"symbol": "BTC",
"order_id": 123456789,
})
print(f"Cancelled: {result['success']}")const result = await gaiaexPost('/order/cancel', {
user_address: ADDRESS,
symbol: 'BTC',
order_id: 123456789,
});
console.log(`Cancelled: ${result.success}`);result, _ := gaiaexPost("/order/cancel", map[string]interface{}{
"user_address": address,
"symbol": "BTC",
"order_id": 123456789,
})
fmt.Printf("Cancelled: %v\n", result["success"])let result = gaiaex_post("/order/cancel", &serde_json::json!({
"user_address": ADDRESS,
"symbol": "BTC",
"order_id": 123456789
}));
println!("Cancelled: {}", result["success"]);json cancel_payload = {
{"user_address", ADDRESS}, {"symbol", "BTC"}, {"order_id", 123456789}
};
auto result = gaiaex_request("POST", "/order/cancel", cancel_payload.dump());
std::cout << "Cancelled: " << result["success"] << std::endl;JSONObject result = gaiaexPost("/order/cancel", new JSONObject()
.put("user_address", ADDRESS)
.put("symbol", "BTC")
.put("order_id", 123456789));
System.out.println("Cancelled: " + result.getBoolean("success"));var result = await GaiaexPost("/order/cancel", new {
user_address = Address, symbol = "BTC", order_id = 123456789
});
Console.WriteLine($"Cancelled: {result.RootElement.GetProperty("success")}");gaiaex_post "/order/cancel" '{
"user_address": "'$ADDRESS'",
"symbol": "BTC",
"order_id": 123456789
}' | python3 -m json.toolNext Steps
- Give these tools to an LLM via MCP — see AI Agent Integration. The agent trades within the same API key's scope and cannot move funds.
- Read Common Definitions for order types, symbol formats, and margin modes.
- Explore Perpetuals Trading and Spot Trading for full endpoint reference.
- Set up a WebSocket connection for real-time positions, balance, and fill updates.
- Review General Info for timeouts, retries, and the idempotency pattern — important for safe production bots.
- Review Error Codes for error handling best practices.