DEV Community

Cover image for Automated Perpetual Trading on Solana: Building Drift Protocol Bots
Wallet Guy
Wallet Guy

Posted on

Automated Perpetual Trading on Solana: Building Drift Protocol Bots

Building high-performance perpetual trading bots on Solana requires more than just market strategies — you need infrastructure that can execute trades instantly, manage risk automatically, and handle complex DeFi operations across multiple protocols. Most developers end up building fragile wallet management, gas optimization, and approval flows from scratch instead of focusing on their trading logic.

When your arbitrage bot spots a price discrepancy between Drift perpetuals and Jupiter spot prices, milliseconds matter. You need infrastructure that can execute multi-step trades (spot buy → perp hedge → position management) without manual intervention or approval delays. Traditional wallet setups create bottlenecks: separate RPC connections, manual transaction signing, no risk controls, and zero visibility into cross-protocol positions.

Why Infrastructure Matters for Trading Bots

Successful trading bots operate in an environment where speed and reliability directly impact profitability. A 100ms delay can mean the difference between capturing an arbitrage opportunity and missing it entirely. Beyond speed, your bot needs sophisticated risk management — spending limits, position size controls, and emergency kill switches that activate automatically without destroying profitable strategies.

Most importantly, modern DeFi strategies span multiple protocols. Your bot might need to swap tokens on Jupiter, open leveraged positions on Drift, provide liquidity to Kamino, and bridge assets via LI.FI — all in coordinated sequences. Managing separate integrations for each protocol creates complexity that scales exponentially with your strategy sophistication.

WAIaaS for High-Performance Trading Infrastructure

WAIaaS provides a unified API that handles all wallet operations, transaction management, and cross-protocol coordination. Your trading bot makes standard HTTP calls while WAIaaS manages gas optimization, transaction sequencing, and risk enforcement behind the scenes.

Here's how a typical perpetual trading bot looks with WAIaaS handling the infrastructure:

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

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

// Step 1: Check current positions across all DeFi protocols
const positions = await client.getDeFiPositions();
const driftPosition = positions.find(p => p.protocol === 'drift');

// Step 2: Execute Jupiter swap for position hedging
const swapResult = await client.executeAction('jupiter-swap', 'swap', {
  inputMint: 'So11111111111111111111111111111111111111112', // SOL
  outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
  amount: '1000000000', // 1 SOL
  slippageBps: 50
});

// Step 3: Open Drift perp position
const perpResult = await client.executeAction('drift', 'open_position', {
  marketIndex: 0, // SOL-PERP
  direction: 'long',
  baseAmount: '500000000', // 0.5 SOL
  leverage: 5
});

console.log(`Swap: ${swapResult.id}, Perp: ${perpResult.id}`);
Enter fullscreen mode Exit fullscreen mode

The power here is that your bot doesn't need to manage Solana RPC connections, transaction signing, or protocol-specific SDKs. WAIaaS handles 15 DeFi protocols through a unified interface, including Drift for perpetuals and Jupiter for spot trading.

Setting Up Gas-Conditional Trading

One of the biggest advantages for automated trading is gas-conditional execution. Your bot can queue transactions that only execute when gas prices meet your profitability thresholds:

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",
    "gasCondition": {
      "maxGasPrice": "0.00001",
      "timeout": 3600
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This transaction will wait up to 1 hour for gas prices to drop below 0.00001 SOL before executing. For high-frequency strategies, this can dramatically improve profitability by avoiding execution during gas spikes.

Risk Management with Policy Engine

Trading bots need sophisticated risk controls that activate automatically. WAIaaS provides 21 policy types with 4 security tiers. Here's how to set up position size limits for a Drift trading bot:

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": 10000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

You can also set spending limits that automatically escalate to human approval for large trades:

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": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 1000,
      "notify_max_usd": 5000,
      "delay_max_usd": 10000,
      "delay_seconds": 300,
      "daily_limit_usd": 50000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This creates a 4-tier system: trades under $1000 execute instantly, $1000-$5000 trigger notifications, $5000-$10000 add a 5-minute delay (cancellable), and anything above $10000 requires manual approval.

Multi-Protocol Arbitrage Bot Example

Here's a more sophisticated example showing how to build an arbitrage bot that trades across Jupiter (spot) and Drift (perpetuals):

async function checkArbitrageOpportunity() {
  // Get current positions to check exposure
  const positions = await client.getDeFiPositions();
  const currentExposure = positions
    .filter(p => p.protocol === 'drift')
    .reduce((sum, p) => sum + parseFloat(p.value_usd || '0'), 0);

  if (currentExposure > 50000) {
    console.log('Max exposure reached, skipping trade');
    return;
  }

  // Check if gas is acceptable before executing
  const gasPrice = await client.getCurrentGasPrice();
  if (gasPrice > 0.00005) {
    console.log('Gas too high, queuing conditional order');
    return await client.sendToken({
      type: 'TRANSFER',
      to: 'target-address',
      amount: '1.0',
      gasCondition: { maxGasPrice: '0.00002', timeout: 1800 }
    });
  }

  // Execute the arbitrage sequence
  const results = await Promise.allSettled([
    // Buy spot on Jupiter
    client.executeAction('jupiter-swap', 'swap', {
      inputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
      outputMint: 'So11111111111111111111111111111111111111112',
      amount: '1000000000'
    }),
    // Short perp on Drift
    client.executeAction('drift', 'open_position', {
      marketIndex: 0,
      direction: 'short',
      baseAmount: '1000000000',
      leverage: 2
    })
  ]);

  return results;
}
Enter fullscreen mode Exit fullscreen mode

Docker Deployment for Production Bots

For production trading bots, you need reliable infrastructure that survives server restarts and automatically recovers from failures. WAIaaS provides Docker deployment with health checks and auto-restart:

# Clone and start — that's it
git clone https://github.com/minhoyoo-iotrust/WAIaaS.git
cd WAIaaS
docker compose up -d
Enter fullscreen mode Exit fullscreen mode

The Docker setup includes automatic health checks, data persistence, and watchtower integration for automatic updates. Your trading bot can connect to the WAIaaS API endpoint and continue operating even if the underlying infrastructure restarts.

For production secrets management, use the Docker Secrets overlay:

# Create secret files
mkdir -p secrets
echo "your-secure-master-password" > secrets/master_password.txt
chmod 600 secrets/master_password.txt

# Deploy with secrets
docker compose -f docker-compose.yml -f docker-compose.secrets.yml up -d
Enter fullscreen mode Exit fullscreen mode

Quick Start: Your First Trading Bot

Here are the minimal steps to get a Drift trading bot running:

Step 1: Install and start WAIaaS

npm install -g @waiaas/cli
waiaas init --auto-provision
waiaas start
waiaas quickset --mode mainnet
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Solana wallet and session

# The quickset command above already created wallets
# Check your session tokens:
cat ~/.waiaas/sessions.json
Enter fullscreen mode Exit fullscreen mode

Step 3: Set up risk policies

waiaas policy create --type SPENDING_LIMIT --instant-max-usd 500
waiaas policy create --type PERP_MAX_LEVERAGE --max-leverage 10
Enter fullscreen mode Exit fullscreen mode

Step 4: Install the SDK and start trading

npm install @waiaas/sdk
Enter fullscreen mode Exit fullscreen mode

Step 5: Copy your session token and build your first strategy using the code examples above.

What's Next

With WAIaaS handling your wallet infrastructure, you can focus entirely on strategy development and market analysis. The unified API eliminates the complexity of managing multiple protocol SDKs, while the policy engine ensures your bot operates within defined risk parameters automatically.

Ready to build your high-performance trading infrastructure? Get started at GitHub or explore the full documentation at waiaas.ai.

Top comments (0)