DEV Community

Cover image for Perpetual Trading Bots with Drift and Hyperliquid
Wallet Guy
Wallet Guy

Posted on

Perpetual Trading Bots with Drift and Hyperliquid

Your arbitrage bot spotted a 2% price difference between Solana and Ethereum. The opportunity window is maybe 30 seconds before other bots close the gap. But your current setup needs to manage separate wallets, coordinate gas across chains, and manually monitor each transaction. By the time everything executes, the opportunity is gone.

This is the daily reality for algorithmic trading operations. The infrastructure overhead of managing wallets, gas optimization, cross-chain coordination, and risk controls often eats more development time than the actual trading logic. You end up building and maintaining a complete wallet management system just to execute your trading strategies.

The Multi-Protocol Trading Challenge

Modern trading strategies span multiple protocols and chains. A single arbitrage might involve swapping on Jupiter (Solana), hedging with perpetuals on Drift, then bridging back to Ethereum via LI.FI to capitalize on another opportunity. Each step requires:

  • Separate wallet infrastructure for each chain
  • Gas price monitoring and optimization
  • Transaction sequencing and failure handling
  • Risk controls to prevent runaway losses
  • Real-time position tracking across protocols

Building this infrastructure from scratch can take months. Maintaining it as protocols update their APIs and new opportunities emerge becomes a full-time job.

Unified Trading Infrastructure

WAIaaS provides a single API for trading across 14 DeFi protocols including Drift, Hyperliquid, Jupiter, Across, and LI.FI. Instead of integrating with each protocol individually, your bot makes standardized API calls while WAIaaS handles the protocol-specific implementation details.

The key advantage is gas conditional execution. Your bot can queue transactions that only execute when gas prices meet your thresholds:

curl -X POST http://127.0.0.1:3100/v1/actions/jupiter-swap/swap \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "inputMint": "So11111111111111111111111111111111111111112",
    "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    "amount": "1000000000",
    "gasCondition": {
      "maxPriorityFee": "0.000001",
      "timeout": 300
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This prevents your bot from executing trades during gas spikes that would eat into profits.

Perpetual Futures Integration

Drift and Hyperliquid integration enables sophisticated hedging strategies. While your bot executes spot arbitrage, it can simultaneously open perpetual positions to hedge directional risk:

# Open short position on Drift to hedge long spot exposure
curl -X POST http://127.0.0.1:3100/v1/actions/drift/open-position \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "market": "SOL-PERP",
    "side": "SHORT",
    "size": "10",
    "leverage": "5x",
    "orderType": "MARKET"
  }'
Enter fullscreen mode Exit fullscreen mode

For more sophisticated strategies, Hyperliquid offers sub-account support for isolated risk management:

# Execute on specific sub-account for strategy isolation
curl -X POST http://127.0.0.1:3100/v1/actions/hyperliquid/trade \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "subAccount": "strategy-a",
    "market": "ETH-USD",
    "side": "BUY",
    "quantity": "1.5",
    "orderType": "LIMIT",
    "price": "2450"
  }'
Enter fullscreen mode Exit fullscreen mode

Risk Controls That Scale

Production trading bots need multiple layers of risk management. WAIaaS provides a policy engine with 21 policy types that can halt trading when limits are breached:

curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "PERP_MAX_POSITION_USD",
    "rules": {
      "maxPositionUsd": 50000,
      "markets": ["ETH-USD", "BTC-USD", "SOL-USD"]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This policy automatically blocks new perpetual positions once your total exposure exceeds $50,000 across specified markets. Combined with spending limits and rate limiting, you get comprehensive protection against runaway algorithms:

curl -X POST http://127.0.0.1:3100/v1/policies \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "RATE_LIMIT",
    "rules": {
      "maxTransactions": 1000,
      "period": "hourly"
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Cross-Chain Arbitrage Made Simple

Cross-chain arbitrage requires coordinating multiple transactions across different networks. WAIaaS's 7-stage transaction pipeline handles the complexity while your bot focuses on identifying opportunities:

import { WAIaaSClient } from '@waiaas/sdk';

const client = new WAIaaSClient({
  baseUrl: 'http://127.0.0.1:3100',
  sessionToken: process.env.WAIAAS_SESSION_TOKEN,
});

// Step 1: Execute spot buy on Solana via Jupiter
const jupiterSwap = await client.executeAction('jupiter-swap', {
  inputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
  outputMint: 'So11111111111111111111111111111111111111112',   // SOL
  amount: '1000000000' // 1000 USDC
});

// Step 2: Bridge to Ethereum via LI.FI
const bridge = await client.executeAction('lifi', {
  fromChain: 'solana',
  toChain: 'ethereum',
  fromToken: 'SOL',
  toToken: 'ETH',
  amount: jupiterSwap.outputAmount
});

// Step 3: Sell on Ethereum via 0x
const zeroXSwap = await client.executeAction('zerox-swap', {
  sellToken: 'ETH',
  buyToken: 'USDC',
  sellAmount: bridge.outputAmount
});
Enter fullscreen mode Exit fullscreen mode

The SDK handles transaction confirmation, retry logic, and error handling. Your bot gets simple async/await calls while the infrastructure manages the blockchain complexity.

Simulation and Backtesting

Before risking capital, use the dry-run API to simulate complete trading strategies:

curl -X POST http://127.0.0.1:3100/v1/transactions/send \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "type": "TRANSFER",
    "to": "recipient-address",
    "amount": "0.1",
    "dryRun": true
  }'
Enter fullscreen mode Exit fullscreen mode

This returns the exact same response as a real transaction, including gas estimates and policy checks, but without broadcasting to the blockchain. Perfect for backtesting strategies against historical data or validating new algorithms before deployment.

Quick Start for Trading Bots

Get your trading infrastructure running in under 5 minutes:

  1. Deploy via Docker:
   git clone https://github.com/minhoyoo-iotrust/WAIaaS.git
   cd WAIaaS
   docker compose up -d
Enter fullscreen mode Exit fullscreen mode
  1. Create trading wallets:
   # Install CLI
   npm install -g @waiaas/cli

   # Create Solana wallet for DEX trading
   waiaas wallet create --name solana-trading --chain solana --environment mainnet

   # Create Ethereum wallet for perpetuals
   waiaas wallet create --name eth-trading --chain evm --environment ethereum-mainnet
Enter fullscreen mode Exit fullscreen mode
  1. Set up risk policies:
   # Spending limits for automated trading
   curl -X POST http://127.0.0.1:3100/v1/policies \
     -H "Content-Type: application/json" \
     -H "X-Master-Password: <password>" \
     -d '{
       "walletId": "<wallet-uuid>",
       "type": "SPENDING_LIMIT",
       "rules": {
         "instant_max_usd": 1000,
         "daily_limit_usd": 10000
       }
     }'
Enter fullscreen mode Exit fullscreen mode
  1. Create session for your bot:
   waiaas session create --wallet-id <uuid>
   # Returns: wai_sess_<token>
Enter fullscreen mode Exit fullscreen mode
  1. Start trading with the SDK:
   import { WAIaaSClient } from '@waiaas/sdk';

   const client = new WAIaaSClient({
     baseUrl: 'http://127.0.0.1:3100',
     sessionToken: 'wai_sess_<your-token>',
   });

   // Your trading logic here
   const balance = await client.getBalance();
   console.log(`Available: ${balance.balance} ${balance.symbol}`);
Enter fullscreen mode Exit fullscreen mode

What's Next

This setup gives you production-ready wallet infrastructure with built-in risk controls and multi-protocol access. Your trading algorithms can now focus on alpha generation rather than blockchain infrastructure management.

For complete API documentation and advanced configuration, check out the full implementation at https://github.com/minhoyoo-iotrust/WAIaaS or explore the interactive API reference at https://waiaas.ai.

Top comments (0)