Perpetuals Trading

New

This example demonstrates how to interact with perpetual trading protocols like GMX and Hyperliquid to open leveraged positions.

[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop

The Code

07-perps-trading.ts
import {
  Chaos,
  WALLET_MODEL,
  extractText,
  extractBlocks,
  isTableBlock,
  isTransactionActionBlock,
  hasRisks,
  hasBlockers,
  type Response,
  type RequestMetadata,
} from '@chaoslabs/ai-sdk';
 
const config = {
  apiKey: process.env.CHAOS_STAGING_API_KEY || 'your-api-key',
  baseUrl: process.env.CHAOS_STAGING_URL || 'https://ai-staging.chaoslabs.co',
};
 
const walletConfig: RequestMetadata = {
  user_id: 'example-user',
  session_id: `example-session-${Date.now()}`,
  wallet_id: process.env.TEST_PORTFOLIO_ID || '0x...',
};
 
async function main() {
  const chaos = new Chaos({
    apiKey: config.apiKey,
    baseUrl: config.baseUrl,
    timeout: 120000,
  });
 
  // Query perpetual trading options
  const response = await chaos.chat.responses.create({
    model: WALLET_MODEL,
    input: [{ type: 'message', role: 'user', content: 'Go 10x ETH long on GMX' }],
    metadata: walletConfig,
  });
 
  if (response.status === 'failed') {
    console.error('Failed:', response.error);
    return;
  }
 
  // Display response
  console.log('Agent Response:', extractText(response));
 
  const blocks = extractBlocks(response);
 
  // Display protocol comparison tables
  const tables = blocks.filter(isTableBlock);
  for (const table of tables) {
    console.log(`\nTable: ${table.title}`);
    console.log(`Columns: ${table.tableHeaders.join(', ')}`);
    for (const row of table.tableRows.slice(0, 5)) {
      console.log(`  ${row.join(' | ')}`);
    }
  }
 
  // Display transaction actions
  const actions = blocks.filter(isTransactionActionBlock);
  for (const action of actions) {
    console.log(`\nTransaction: ${action.notes}`);
    if (action.primitives) {
      for (const prim of action.primitives) {
        console.log(`  ${prim.primitive}`);
        if (prim.display?.headline) {
          console.log(`    ${prim.display.headline}`);
        }
      }
    }
  }
 
  // Risk assessment - critical for leveraged trading
  if (hasBlockers(response)) {
    console.log('\n[BLOCKED] Cannot execute - review blockers');
  } else if (hasRisks(response)) {
    console.log('\n[WARNING] Review risks before proceeding');
  }
}
 
main();

Supported Protocols

The Chaos AI supports major perpetual trading protocols:

ProtocolChainMax LeverageKey Features
GMX V2Arbitrum100xZero slippage, oracle pricing
HyperliquidHyperliquid L150xLowest fees, high liquidity
Jupiter PerpsSolana100xFast execution, Solana native

Common Perps Queries

The AI understands natural language for perpetuals trading:

Opening Positions

  • "Go 10x ETH long on GMX"
  • "Open a 5x short on BTC"
  • "Long SOL with 20x leverage on Hyperliquid"

Querying Markets

  • "What perpetual trading options do I have?"
  • "Compare perps protocols for ETH"
  • "Show me funding rates across protocols"

Understanding the Response

Perps queries typically return:

  1. Protocol Comparison Tables - Compare chains, leverage limits, and fees
  2. Transaction Actions - The actual position opening transaction
  3. Risk Assessment - Leverage-specific warnings
parse-perps-response.ts
// Protocol comparison table
if (isTableBlock(block)) {
  // Headers typically: Protocol, Chain, Max Leverage, Fees
  console.log(`Protocol options: ${block.tableRows.length}`);
  for (const row of block.tableRows) {
    const [protocol, chain, leverage, fees] = row;
    console.log(`${protocol} on ${chain}: up to ${leverage}`);
  }
}
 
// Position opening transaction
if (isTransactionActionBlock(block)) {
  for (const prim of block.primitives || []) {
    // Perps primitives include:
    // - leverage, direction (long/short)
    // - collateral amount, position size
    // - liquidation price, entry price
    console.log(`${prim.primitive}: ${prim.display?.headline}`);
  }
}
[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop
[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop

Next Steps