Connect Orderly to AI Agents: Automate Trading and Asset Transfers
Learn how to connect Orderly to ai agents using Truto. Step-by-step guide to tool calling, API quirks, and autonomous workflows.
You want to connect Orderly Network to an AI agent so your system can autonomously execute perpetual futures trades, manage margin risk, rebalance portfolios, and handle complex PnL settlements. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom omnichain integration from scratch.
Giving a Large Language Model (LLM) read and write access to a decentralized trading infrastructure like Orderly is high-stakes engineering. A hallucinated parameter or a mismanaged rate limit does not just cause an error - it executes unintended trades. If your team uses ChatGPT, check out our guide on connecting Orderly to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Orderly to Claude. For developers building custom autonomous workflows, you need a programmatic, strictly typed way to fetch these tools and bind them to your agent framework.
This guide breaks down exactly how to fetch AI-ready tools for Orderly, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex trading operations safely. For a broader look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.
The Engineering Reality of the Orderly API
Building an AI agent is fundamentally an exercise in state management and prompting. Giving that agent reliable access to external trading systems is where projects stall. If you decide to build a custom Orderly connector, you own the entire API lifecycle. You must write the JSON schemas for the LLM to understand the endpoints, handle the complex cryptographic requirements, and deal with strict precision constraints.
Orderly Network's API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.
EIP-712 Signatures and Strict Nonce Management
Standard B2B APIs use OAuth 2.0 or static API keys. Orderly, being an omnichain infrastructure, requires EIP-712 cryptographic signatures for critical actions like PnL settlements, account registrations, and asset withdrawals.
Standard LLMs cannot natively generate an EIP-712 signature for an EVM or Solana wallet. They do not hold private keys, nor should they. When building an agent, you must orchestrate a two-step dance: the agent determines the intent (e.g., "We need to withdraw 500 USDC"), requests the current nonce via orderly_withdrawals_get_nonce, and then passes the structured payload to a secure execution layer in your backend where the actual cryptographic signing occurs before submitting to create_a_orderly_withdrawal.
Precision Constraints and Tick Sizes
LLMs are notoriously bad at arbitrary math and strict decimal precision. If an agent decides to place a limit order for ETH-PERP, it might attempt to send a price payload of 2450.12345.
Orderly's matching engine enforces strict quote_tick and base_tick rules. If the tick size for a symbol is 0.01, the API will instantly reject 2450.12345. Your integration layer must fetch these rules via orderly_symbols_get_order_rules and either explicitly prompt the LLM to round the integers, or enforce truncation at the API proxy layer. Truto's standardized schemas help enforce these types before they hit the network, preventing wasted API calls.
Punishing Rate Limits and Market Data Constraints
Market data APIs are heavily restricted. Orderly applies strict rate limits across its endpoints - for instance, historical daily statistics with include_historical_data set to true drops your limit to 1 request per 60 seconds.
Truto does not retry, throttle, or apply backoff on rate limit errors. When the Orderly API returns an HTTP 429 Too Many Requests, Truto passes that error directly to the caller. However, Truto normalizes the upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) following the IETF specification. Your agent framework is strictly responsible for intercepting the 429 error, reading the ratelimit-reset header, and pausing execution. If your agent is allowed to spin endlessly on a 429, you will be temporarily banned by Orderly's edge firewall.
Available Orderly Tools for AI Agents
Instead of exposing the raw Orderly API to your LLM, Truto collapses the endpoints into standardized, schema-backed tools. The LLM only sees predictable function names and strict JSON parameters. Here are the core tools you will use to build trading agents.
create_a_orderly_order
This is the primary engine for execution. It creates a new order in Orderly and immediately returns the order_id and execution status. It requires the symbol, order type, and side (BUY/SELL).
"Buy 0.5 BTC-PERP at market price and give me the client_order_id so we can track the execution status."
list_all_orderly_positions
Before making trading decisions, an agent needs context. This tool retrieves all open positions for the authenticated account, returning critical risk metrics like the estimated liquidation price, maintenance margin ratio (MMR), and unrealized PnL.
"Retrieve my current open positions. If any position has an open margin ratio dangerously close to the maintenance margin ratio, flag it for risk reduction."
update_a_orderly_position_margin_by_id
For accounts trading in ISOLATED margin mode, active risk management is required. This tool allows the agent to add or reduce the position margin for a specific isolated position to prevent liquidation.
"Our ETH-PERP short is nearing liquidation. Add 500 USDC to the isolated position margin immediately to increase our buffer."
create_a_orderly_algo_order
Basic limit orders are not enough for autonomous trading. This tool submits algorithmic orders, supporting STOP, TAKE_PROFIT, and BRACKET types with nested child orders. This allows an agent to define an entire entry and exit strategy in a single tool call.
"Place a bracket order for 100 SOL-PERP. Set a take-profit at 150 and a stop-loss at 135 to strictly bound our risk on this trade."
orderly_markets_get_info
Agents need real-time market context to execute yield strategies. This tool returns the index price, mark price, and critical funding rate information (estimated and last funding rate) for a specific symbol.
"Check the current estimated funding rate for WIF-PERP. If the funding rate is highly positive, prepare a short position strategy to harvest the yield."
orderly_pnl_settlement_request
In perpetual futures, unrealized PnL cannot be withdrawn or used as free collateral until it is settled. This tool requests a PnL settlement (requiring a signed message payload prepared by your secure backend) to convert unrealized gains into usable account balance.
"Our unrealized PnL is over 10,000 USDC. Request a PnL settlement so we can free up collateral for new positions."
To view the complete inventory of available tools, query parameters, and JSON schemas, visit the Orderly integration page.
Building Multi-Step Workflows
Connecting Orderly to an AI agent requires fetching the tool definitions from Truto and binding them to your LLM. Because Truto handles the authentication, pagination, and schema normalization, your integration code remains entirely focused on the orchestration logic.
This approach works with LangChain, LangGraph, CrewAI, Vercel AI SDK, or standard OpenAI API clients. Below is a concrete example using the Truto Langchain.js SDK.
1. Fetch and Bind the Tools
First, initialize the Truto Tool Manager with your Integrated Account ID. This ID represents the specific Orderly account the agent is acting upon.
import { TrutoToolManager } from "@trutohq/langchainjs-toolset";
import { ChatOpenAI } from "@langchain/openai";
// Initialize the Truto Tool Manager with your specific Orderly account ID
const trutoManager = new TrutoToolManager({
integratedAccountId: "ord_acc_987654321",
trutoApiKey: process.env.TRUTO_API_KEY
});
// Fetch all tools or filter for specific ones
await trutoManager.initialize({
methods: ["create_a_orderly_order", "list_all_orderly_positions", "update_a_orderly_position_margin_by_id"]
});
// Bind the Orderly tools to your LLM
const llm = new ChatOpenAI({ model: "gpt-4o", temperature: 0 });
const llmWithTools = llm.bindTools(trutoManager.getTools());2. Architecting the Agent Loop and Handling Rate Limits
Because Truto strictly passes through HTTP 429 Rate Limit errors without absorbing them, your agent loop must catch these exceptions, read the standardized IETF headers, and backoff accordingly. Failing to implement this will cause your agent to crash mid-workflow.
sequenceDiagram
participant Agent as AI Agent
participant Truto as Truto API
participant Orderly as Upstream API (Orderly)
Agent->>Truto: Call list_all_orderly_positions()
Truto->>Orderly: GET /v1/positions
Orderly-->>Truto: 429 Too Many Requests
Truto-->>Agent: 429 Error (ratelimit-reset: 1718000000)
Note over Agent: Agent parses header,<br>sleeps until reset time
Agent->>Truto: Retry list_all_orderly_positions()
Truto->>Orderly: GET /v1/positions
Orderly-->>Truto: 200 OK (Positions Data)
Truto-->>Agent: Normalized JSON PayloadHere is how you handle this in the execution logic:
import { ToolNode } from "@langchain/langgraph/prebuilt";
// Define the tool execution node
const toolNode = new ToolNode(trutoManager.getTools());
async function executeAgentWorkflow(prompt: string) {
try {
// Agent evaluates the prompt and selects a tool
const response = await llmWithTools.invoke(prompt);
if (response.tool_calls && response.tool_calls.length > 0) {
console.log(`Agent selected tool: ${response.tool_calls[0].name}`);
// Execute the tool
const toolResults = await toolNode.invoke({
messages: [response]
});
return toolResults;
}
} catch (error) {
// Explicit 429 Rate Limit Handling
if (error.status === 429) {
const resetHeader = error.headers['ratelimit-reset'];
const resetTime = parseInt(resetHeader, 10) * 1000;
const delay = resetTime - Date.now();
console.warn(`Rate limit hit. Backing off for ${delay}ms`);
// Sleep function to pause execution
await new Promise(resolve => setTimeout(resolve, delay));
// Retry logic would be implemented here
return await executeAgentWorkflow(prompt);
}
throw error;
}
}
// Trigger the workflow
await executeAgentWorkflow(
"Check my open positions. If I have less than 5 ETH-PERP short, sell 1 ETH-PERP at market price."
);Workflows in Action
Providing an agent with atomic tools is only half the battle. The true value emerges when the agent chains these tools together to execute multi-step financial operations autonomously. Here are two real-world scenarios showing the exact tool sequences.
Scenario 1: Autonomous Position Management & Risk Mitigation
Volatility in crypto markets requires 24/7 monitoring. Instead of paging a trader when a position moves against them, an AI agent can continuously monitor margin requirements and dynamically deploy capital to prevent liquidations.
"Check open positions. If the ETH-PERP unrealized PnL is negative and the open margin ratio drops below 15%, add 100 USDC to the position margin to defend the liquidation price. Then, submit a stop-loss algo order 2% below the current mark price."
Execution Steps:
list_all_orderly_positions: The agent fetches the portfolio state and filters forETH-PERP. It reads themargin_ratioandunsettled_pnl.update_a_orderly_position_margin_by_id: Noting a margin ratio of 14%, the agent invokes this tool withamount: 100andtype: ADDfor the specific symbol.orderly_markets_get_info: The agent fetches current market data to establish the exactmark_price.create_a_orderly_algo_order: The agent calculates the stop price (98% of the mark price) and submits aSTOP_LOSSalgo order for the exact position quantity.
Result: The agent successfully defends the position from immediate liquidation and institutes a hard stop-loss, reporting the new estimated liquidation price back to the user.
Scenario 2: Delta-Neutral Yield Harvesting
Funding rates on perpetual futures diverge significantly during volatile periods. An agent can monitor these rates across assets and autonomously enter positions to harvest yield while remaining delta-neutral elsewhere.
"Find perpetual markets on Orderly with an estimated funding rate greater than 0.05%. If you find one, open a short position for 5,000 USDC notional value. After executing, request a PnL settlement on the account so our balance is updated."
Execution Steps:
orderly_funding_rate_list_predicted_all_markets: The agent scans all available markets and identifiesSOL-PERPcurrently projecting a 0.08% funding rate.orderly_markets_get_info: The agent pulls the exactmark_priceforSOL-PERPto calculate the required quantity for a 5,000 USDC notional short.create_a_orderly_order: The agent executes aSELLmarket order for the calculated quantity.orderly_pnl_settlement_get_nonce: To clean up the account balance and compound previous yields, the agent fetches the settlement nonce.orderly_pnl_settlement_request: The agent prepares the payload. (Note: The backend intercepts this to append the required EIP-712 signature before Truto relays it to Orderly).
Result: The agent successfully identifies a high-yield opportunity, executes the short position, and settles the account's historical PnL, all without human intervention.
The Strategic Advantage of Unified Tools
Giving AI agents access to financial infrastructure like Orderly Network is no longer a parsing challenge - it is an orchestration challenge. By utilizing a unified tool layer, you remove the burden of managing pagination, standardizing payloads, and mapping raw HTTP responses from your agent's context window.
Instead of wasting tokens trying to teach an LLM how to format an Orderly tick size or properly structure a JSON:API payload, the model spends its compute on financial reasoning. The agent chooses the intent, Truto enforces the schema, and you maintain complete control over the execution loop. This is how you build trading agents that survive production.