Perpetuals API Guide

For advanced users and developers, Yamata provides a comprehensive API to interact with the perpetual trading platform programmatically. This allows you to build trading bots, algorithmic strategies, or integrate Yamata’s markets into your applications. This guide covers how to authenticate API requests, key REST endpoints, WebSocket feeds for real-time data, the order execution flow, and rate limits to be aware of.

API Access and Authentication

API Keys: To use Yamata’s private API endpoints, you’ll need to create API keys from your Yamata account dashboard. An API key consists of a public Key ID and a private Secret. The Key ID identifies your account and the Secret is used to sign requests. Keep your Secret safe and do not share it.

  • Key Permissions: When generating keys, you can typically set permissions (e.g., read-only for market data, trading-enabled for order placement, withdrawal permissions if applicable). For trading bots, enable trading and info access but keep withdrawal off for safety.

  • HMAC Signature: Yamata uses HMAC SHA256 signing (JSON/REST) for private requests. Each request must include:

    • A timestamp (to prevent replay attacks).

    • The request method, endpoint, and body concatenated into a string.

    • Use your Secret to generate an HMAC SHA256 signature of that string.

    • Include your Key ID and the signature in the request headers (for example: X-Yamata-APIKey: <your-key> and X-Yamata-Signature: <signature>; the exact header names will be specified in the API docs).

  • No Authentication for Public Endpoints: Public data endpoints (market prices, order books, etc.) do not require any auth. They can be accessed freely via GET requests.

Example Authentication Flow:

  1. Your system captures the current UNIX timestamp (in ms or s as required).

  2. Construct a prehash string like: <timestamp>|<HTTP method>|<request path>|<body> (for a GET with no body, body is empty).

  3. Compute HMAC_SHA256(secret, prehash_string) → get a hex signature.

Add headers: X-Yamata-APIKey: YOUR_KEY_ID

X-Yamata-Timestamp: <timestamp>

X-Yamata-Sign: <signature>

  1. Send the request to Yamata’s API endpoint.

(Refer to Yamata’s official API documentation for the exact signing algorithm and header names, as these can differ slightly.)

REST API Endpoints

Yamata’s REST API base URL (for mainnet) will be something like https://api.yamata.io (and a separate base for testnet, e.g., https://testnet-api.yamata.io). Within the REST API, endpoints are generally grouped by function:

  • Market Data (Public):

    • GET /v1/perp/markets – List all perpetual markets and their details (tick size, lot size, funding rate, etc).

    • GET /v1/perp/orderbook?symbol=BTC-PERP – Get the current order book snapshot for a given market (with configurable depth).

    • GET /v1/perp/trades?symbol=BTC-PERP – Recent trade history for the market.

    • GET /v1/perp/ticker?symbol=BTC-PERP – 24h stats (last price, 24h high/low, volume, funding rate, etc).

    • GET /v1/perp/index-price?symbol=BTC-PERP – (If provided) get the current index price and mark price.

  • Account & Positions (Private):

    • GET /v1/perp/account – Get your account info, including total equity, margin used, margin available, current LTV%, etc.

    • GET /v1/perp/balances – Breakdown of your collateral balances in the Perps account (USDC and other assets, with their USDC values).

    • GET /v1/perp/positions – List of your open positions on all markets, with details (size, entry price, P&L, liq price, etc).

    • GET /v1/perp/orders – List of your open orders (limit orders resting on the book, and active stop orders). You can filter by symbol or get all.

    • GET /v1/perp/order/<order_id> – Details on a specific order by ID (status, filled amount, etc).

    • GET /v1/perp/funding-payments – (Optional) history of funding payments you’ve paid/received.

  • Trading / Orders (Private):

POST /v1/perp/order – Place a new order. You will provide JSON in the body like: {

"symbol": "ETH-PERP",

"side": "buy", // or "sell"

"type": "limit", // or "market" or "stop_limit" or "stop_market"

"price": 1600.0, // required for limit, optional for stop (stop-limit uses this as limit price)

"size": 5, // number of contracts (or base asset amount)

"triggerPrice": 1500.0, // if a stop order, the trigger price

"reduceOnly": true, // optional, false by default

"postOnly": true // optional, for limit orders if you want maker only

}

  • The response will include an order_id and the initial status (e.g., open if resting or filled if it executed immediately, etc).

    • DELETE /v1/perp/order/<order_id> – Cancel an order by ID. (Alternatively, some APIs allow POST /v1/perp/cancel with ID in body or cancel by client order ID.)

    • POST /v1/perp/orders/cancel_all?symbol=BTC-PERP – (If available) cancel all open orders (or all on a specific symbol).

    • POST /v1/perp/transfer – Move funds between your Spot and Perps wallets via API (specify asset and amount, which direction). This could trigger an on-chain transaction if using the API from a non-custodial context; not all users will use this via API, but institutional ones might.

  • Historical Data (Private):

    • GET /v1/perp/fills – List of your recent fills/trades (executed orders) with details like price, size, fee, timestamp.

    • GET /v1/perp/order_history – Past orders, including cancelled and filled, perhaps with filters for date range.

    • GET /v1/perp/position_history – History of positions opened/closed (realized P&L for each).

Note: The exact paths and schemas are subject to change; always refer to the official Yamata API reference. The above is indicative of typical functions.

WebSocket API

For real-time data streaming, Yamata offers WebSocket channels. The WebSocket API is essential for low-latency updates such as live order book changes and execution feeds.

  • Endpoint: The WebSocket server URL might be wss://api.yamata.io/perp/ws or similar. Check docs for the exact endpoint and any query parameters required (some systems require your API key in the connection URL for private feeds, others do a separate auth message).

  • Subscriptions: After connecting, you will send a subscription message (usually in JSON) to specify which streams you want. Common streams:

    • Order Book Updates: Subscribe to a symbol’s order book. Yamata may provide a channel like "orderbook:BTC-PERP" that streams level 2 updates (bids and asks changes). Expect messages with either full depth snapshots followed by incremental deltas, or continuous snapshots at intervals.

    • Trades: Subscribe to "trades:BTC-PERP" to get a feed of every trade that occurs (with price, size, side, timestamp).

    • Tickers: Perhaps a "ticker:BTC-PERP" channel for updates on last price, 24h stats in real-time.

    • Index/Funding: Possibly a feed for index price updates or current funding rate moves if needed.

  • Private Data Streams: If you authenticate on the WebSocket (by sending an auth payload with your API key and a signature/timestamp similar to REST auth), you can subscribe to private topics:

    • Order Updates: You’ll receive messages whenever one of your orders is filled, partially filled, or canceled (including liquidations). This is crucial for a trading bot to know the status without polling REST.

    • Position Updates: Notifications when a position’s size or P&L changes significantly, or when funding is applied to you.

    • Balance Updates: Notifications on changes in your balance (e.g., after a trade fee deduction, funding payment, or manual transfer).

Example Subscribe Message: (format can differ, but as an illustration) {

"action": "subscribe",

"channels": [

{ "name": "orderbook", "symbol": "BTC-PERP" },

{ "name": "trades", "symbol": "BTC-PERP" }

]

}

After authenticating: {

"action": "subscribe",

"channels": [

{ "name": "user.orders" },

{ "name": "user.positions" }

]

}

  • Heartbeat/Ping-Pong: The WebSocket server may require periodic ping/pong to keep connection alive. Yamata’s docs will specify if you need to respond to pings or if they send heartbeats.

Trading Flow Overview (Putting it Together)

If you’re building a trading application, a typical workflow might be:

  1. Authentication: Load your API key and secret. If using WebSocket for private data, connect and authenticate on the WS.

  2. Get Market Info: Use REST to fetch current market specs, tick sizes, etc., or subscribe to WS tickers for live prices.

  3. Place Orders: When your strategy decides to trade, use the REST POST /order endpoint to send the order. Include any special flags (reduce-only, post-only) as needed. Parse the response:

    1. If immediate fill, you might get the fill info back or you will receive it via the WebSocket user trade update.

    2. If resting, store the order_id to track it.

  4. Monitor via WebSocket: Listen to:

    1. Order book feed for market changes if your strategy uses that.

    2. User order updates: e.g., you placed a limit, you’ll get notified if it gets filled or partially filled.

    3. User position updates: see your position size and P&L update in real time as fills occur or mark price moves.

    4. If you get a stop order trigger fill, it will also come as an order update event.

  5. Manage Orders: If conditions change, you might cancel or modify orders:

    1. Cancel by REST call or possibly by sending a cancel action via WS if supported.

    2. Place new orders as needed (repeat step 3).

  6. Handle Errors: Incorporate logic for errors (like order rejected due to insufficient margin or bad parameters). The API will return error codes/messages – e.g., “1102: price out of range” or “1004: not enough balance”. Handle gracefully (maybe fetch account info again, adjust and retry if appropriate).

  7. Rate Limit Compliance: Ensure your bot does not spam the API beyond allowed limits. Yamata’s rate limits might be something like:

    1. 120 requests per minute for REST per key (just an example).

    2. Or specific limits like “placing orders: max 10 per second” etc.

    3. WebSocket may have limits on subscriptions or messages per second as well.

    4. Check headers in REST responses; sometimes APIs return your remaining rate limit.

  8. Disconnects and Reconnection: Plan for WS disconnects – maintain a loop to reconnect and resubscribe if needed. Also, on reconnect, you may want to fetch a fresh snapshot of order books or positions to reconcile any missed data while disconnected.

Rate Limits and Best Practices

  • REST Rate Limits: Yamata will document exact figures. For instance, you might see limits like:

    • GET market data endpoints: up to 50 requests per second (these are usually generous).

    • POST order endpoints: e.g., max 5–10 order placements per second per account.

    • If you exceed, you’ll get HTTP 429 Too Many Requests. Back off and wait a bit before retrying. Implement exponential backoff in your API client if you hit these errors.

  • WebSocket Limits: Don’t oversubscribe or send too many messages too fast. Typically:

    • Limit how often you send new orders or cancellations via WS (if that’s supported) – using REST might be preferable for a large burst of orders since you can control pacing.

    • Some WS have a limit on incoming messages (like max 30 msg per 5 seconds). Throttle your heartbeat responses or order submissions accordingly.

  • Avoiding Liquidation via API: If you are running an automated strategy, you might want to utilize the API to also set emergency stops. For example, if your bot loses connectivity or identifies an account issue (like margin too low), it could auto-delever or close positions. Yamata’s API allows you to build such safety nets (e.g., periodically check GET /account for LTV, and if above X, then POST /order to reduce position, etc).

  • Testing on Testnet: Yamata provides a testnet (on Monad testnet currently) where the API endpoints are identical but operate on a sandbox environment. Use this for development before moving your bot to mainnet. The base URL differs (e.g., testnet-api.yamata.io). Remember to get testnet API keys separately, and that testnet markets may have different liquidity characteristics.

Example Workflow (Code Snippet Pseudo-code)

# Pseudo-code example for a simple market buy via REST

import time, hmac, hashlib, requests

API_KEY = "your_key_id"

API_SECRET = "your_api_secret".encode('utf-8')

BASE_URL = "https://api.yamata.io"

def sign_request(method, path, body=""):

ts = str(int(time.time() * 1000))

prehash = ts + '|' + method + '|' + path + '|' + body

signature = hmac.new(API_SECRET, prehash.encode('utf-8'), hashlib.sha256).hexdigest()

return ts, signature

# Prepare order

order = {

"symbol": "BTC-PERP",

"side": "buy",

"type": "market",

"size": 0.01 # buying 0.01 BTC

}

body_json = json.dumps(order)

ts, sig = sign_request("POST", "/v1/perp/order", body_json)

headers = {

"X-Yamata-APIKey": API_KEY,

"X-Yamata-Timestamp": ts,

"X-Yamata-Sign": sig,

"Content-Type": "application/json"

}

response = requests.post(BASE_URL + "/v1/perp/order", headers=headers, data=body_json)

print(response.json())

The above would execute a market buy for 0.01 BTC-PERP. The response might return an order id and confirmation of fill (for market orders, typically it fills immediately and you get details of the trade like average price).

Safety Tip: Never hardcode real API secrets in code that is shared or unsecured. Use environment variables or secure vaults in production. And consider IP whitelisting on your API key if Yamata supports it.

Last updated