GaiaExGaiaEx
API

AI Agent Integration Guide

Integrate AI trading agents with GaiaEx: OpenClaw framework, MCP protocol, no-KYC API keys, and code examples for autonomous on-chain trading.

AI Agent Integration

GaiaEx is designed as a bounded execution layer for AI trading agents. You give the agent a trade-scoped API key, it trades against your pre-deposited balance, and the funds themselves stay under your self-custody at all times. The agent never has the ability to move money on or off the platform — that's the point.

WHY GaiaEx FOR AI AGENTS

  • Bounded risk — the worst an agent can do is trade badly within your deposited balance. It cannot withdraw, deposit, transfer, or swap on-chain.
  • Scoped permissionsread-only agents for monitoring and analytics; read + trade agents for execution
  • 130+ markets in one API — crypto, RWA (stocks, commodities, forex), and venture tokens
  • WebSocket bidirectional — place orders directly over WebSocket for lowest latency
  • No manual identity verification for API access — API keys are issued from the mobile app after the user's in-app account setup

Agent Scope — What It Can and Cannot Do

API-key-authenticated agents operate strictly within a trading and read scope. The table below is the complete, accurate picture — please share it with the agent's system prompt so it understands its own capabilities.

Agent canAgent cannot
Place, cancel, and modify perpetual and spot ordersDeposit USDC into the account
Close positions; set TP/SLWithdraw USDC off the platform
Change leverage and margin modeTransfer assets on-chain (sendAsset, dex-transfer)
Read balances, positions, fills, order history, fundingExecute wallet swaps
Subscribe to public and private WebSocket streamsRegister or authenticate passkeys
Query market data, orderbooks, candles, technicalsComplete the account handshake
Read referral and affiliate dataCreate, modify, or delete API keys

FUNDING IS A MANUAL STEP

The user must fund the account in the GaiaEx mobile app before the agent runs. If the account runs out of USDC mid-strategy, the agent will start receiving insufficient-margin errors on new orders — it cannot top up on its own. When the user is ready to pull funds out, they do so in the mobile app, not through the agent.

Agent Authentication Flow

The recommended flow for AI agent authentication:

  1. Human creates API key in GaiaEx mobile app → sets permissions to ["read", "trade"], adds IP whitelist for agent server
  2. Store credentials in config.json on the agent's server (see Security Best Practices)
  3. Agent loads credentials and initializes the API client
  4. Agent trades autonomously within its permission scope
import hmac, hashlib, time, json, requests

with open("/secure/agent_config.json") as f:
    cfg = json.load(f)

API_KEY, API_SECRET = cfg["api_key"], cfg["api_secret"]
ADDRESS = cfg["user_address"]
BASE = "https://openapi.gaiaex.com/v1/trade"

def sign(method, path, body=""):
    ts = str(int(time.time() * 1000))
    sig = hmac.new(API_SECRET.encode(), (ts + method + path + body).encode(), hashlib.sha256).hexdigest()
    return {"X-GAIAEX-APIKEY": API_KEY, "X-GAIAEX-TIMESTAMP": ts, "X-GAIAEX-SIGNATURE": sig, "Content-Type": "application/json"}

# Verify connectivity
health = requests.get(BASE + "/health").json()
assert health["status"] == "healthy"

# Agent can now trade
balance = requests.get(BASE + f"/user/{ADDRESS}/balance", headers=sign("GET", f"/user/{ADDRESS}/balance")).json()
if float(balance.get("available_margin", 0)) > 100:
    body = json.dumps({"user_address": ADDRESS, "symbol": "ETH", "is_buy": True, "size": "0.05", "order_type": "market"})
    requests.post(BASE + "/order", headers=sign("POST", "/order", body), data=body)

SECURITY

Always use IP whitelisting for agent API keys. If the agent server is compromised, IP restrictions prevent the key from being used elsewhere.

OpenClaw Integration

OpenClaw is an open-source AI agent framework for autonomous trading. GaiaEx is a natural execution backend for OpenClaw agents due to its no-KYC API access and comprehensive market coverage.

Architecture

┌──────────────┐     ┌─────────────┐     ┌──────────────┐
│  OpenClaw AI  │────▶│  GaiaEx API  │────▶│  On-Chain     │
│   (Strategy)  │◀────│  (Execution) │◀────│  Settlement   │
└──────────────┘     └─────────────┘     └──────────────┘
       │                                          │
       │           ┌─────────────────┐            │
       └──────────▶│  WebSocket Feed  │◀───────────┘
                   │  (Market Data)   │
                   └─────────────────┘

Setup

import hmac, hashlib, time, json, requests

class GaiaExExecutor:
    """OpenClaw-compatible execution backend for GaiaEx."""

    def __init__(self, config_path: str = "config.json"):
        with open(config_path) as f:
            cfg = json.load(f)
        self.key = cfg["api_key"]
        self.secret = cfg["api_secret"]
        self.address = cfg["user_address"]
        self.base = "https://openapi.gaiaex.com/v1/trade"

    def _sign(self, method, path, body=""):
        ts = str(int(time.time() * 1000))
        sig = hmac.new(self.secret.encode(), (ts + method + path + body).encode(), hashlib.sha256).hexdigest()
        return {"X-GAIAEX-APIKEY": self.key, "X-GAIAEX-TIMESTAMP": ts, "X-GAIAEX-SIGNATURE": sig, "Content-Type": "application/json"}

    def get_balance(self) -> float:
        path = f"/user/{self.address}/balance"
        bal = requests.get(self.base + path, headers=self._sign("GET", path)).json()
        return float(bal.get("available_margin", 0))

    def get_positions(self) -> list:
        path = f"/user/{self.address}/positions"
        return requests.get(self.base + path, headers=self._sign("GET", path)).json()

    def execute_signal(self, symbol: str, side: str, size: float) -> dict:
        path = "/order"
        body = json.dumps({"user_address": self.address, "symbol": symbol, "is_buy": side == "BUY", "size": str(size), "order_type": "market"})
        return requests.post(self.base + path, headers=self._sign("POST", path, body), data=body).json()

# Usage with OpenClaw
executor = GaiaExExecutor("config.json")
print(f"Available margin: {executor.get_balance():.2f} USD")
result = executor.execute_signal("ETH", "BUY", 0.1)
print(f"Order: {result}")

MCP (Model Context Protocol)

The Model Context Protocol (MCP) enables large language models (Claude, GPT, etc.) to interact with external tools and APIs. GaiaEx can be exposed as an MCP tool, allowing AI assistants to execute trades on behalf of users.

MCP Tool Definition

{
  "name": "gaiaex_trade",
  "description": "Execute trades on GaiaEx decentralized exchange",
  "parameters": {
    "action": {
      "type": "string",
      "enum": ["get_balance", "get_positions", "place_order", "cancel_order", "get_symbols"],
      "description": "Trading action to perform"
    },
    "symbol": {"type": "string", "description": "Trading symbol (e.g. ETH, BTC)"},
    "side": {"type": "string", "enum": ["BUY", "SELL"]},
    "size": {"type": "string", "description": "Order size"},
    "price": {"type": "string", "description": "Limit price (optional)"},
    "order_type": {"type": "string", "enum": ["market", "limit"], "default": "market"}
  }
}

MCP Server Implementation (Python)

import hmac, hashlib, time, json, requests

with open("config.json") as f:
    cfg = json.load(f)

API_KEY, API_SECRET = cfg["api_key"], cfg["api_secret"]
ADDRESS = cfg["user_address"]
BASE = "https://openapi.gaiaex.com/v1/trade"

def sign(method, path, body=""):
    ts = str(int(time.time() * 1000))
    sig = hmac.new(API_SECRET.encode(), (ts + method + path + body).encode(), hashlib.sha256).hexdigest()
    return {"X-GAIAEX-APIKEY": API_KEY, "X-GAIAEX-TIMESTAMP": ts, "X-GAIAEX-SIGNATURE": sig, "Content-Type": "application/json"}

def handle_mcp_request(action: str, **params) -> dict:
    """MCP tool handler for GaiaEx operations."""
    match action:
        case "get_balance":
            path = f"/user/{ADDRESS}/balance"
            return requests.get(BASE + path, headers=sign("GET", path)).json()
        case "get_positions":
            path = f"/user/{ADDRESS}/positions"
            return requests.get(BASE + path, headers=sign("GET", path)).json()
        case "get_symbols":
            return requests.get(BASE + "/symbols/list").json()
        case "place_order":
            path = "/order"
            body = json.dumps({"user_address": ADDRESS, "symbol": params["symbol"], "is_buy": params["side"] == "BUY", "size": params["size"], "price": params.get("price"), "order_type": params.get("order_type", "market")})
            return requests.post(BASE + path, headers=sign("POST", path, body), data=body).json()
        case "cancel_order":
            path = "/order/cancel"
            body = json.dumps({"user_address": ADDRESS, "symbol": params["symbol"], "order_id": params["order_id"]})
            return requests.post(BASE + path, headers=sign("POST", path, body), data=body).json()
        case _:
            return {"error": f"Unknown action: {action}"}

Use Cases

Use CaseDescription
Portfolio Assistant"Show me my positions and PnL" → AI reads account data via MCP
Strategy Copilot"Buy 0.5 ETH if it drops below 3400" → AI monitors price and places the order against your deposited balance. If the account has insufficient USDC when the trigger fires, the order fails with an insufficient-margin error; the agent cannot top up.
Risk Monitor"Alert me if margin drops below 30%" → AI watches balance via WebSocket
Multi-Market Scanner"Find momentum across all 130 symbols" → AI analyzes market data

Real-Time Data for AI Agents

For low-latency AI agents, use WebSocket streams instead of polling REST endpoints.

import asyncio
import websockets
import json

async def ai_agent():
    uri = "wss://openapi.gaiaex.com/ws/market/ETH"
    async with websockets.connect(uri) as ws:
        count = 0
        async for raw in ws:
            msg = json.loads(raw)
            if msg.get("type") == "orderbook":
                levels = msg.get("levels", [])
                best_bid = levels[0]["px"] if levels else "N/A"
                print(f"ETH best bid: {best_bid}")
                count += 1
                if count >= 5:
                    break

asyncio.run(ai_agent())

PRODUCTION TIP

For production AI agents, run the market data stream and the user data stream concurrently using asyncio.gather. This gives your agent real-time market data and instant position/order updates in a single event loop.