DEV Community

Cover image for Gas-Smart Trading Bots: Execute Only When Network Fees Hit Your Target
Wallet Guy
Wallet Guy

Posted on

Gas-Smart Trading Bots: Execute Only When Network Fees Hit Your Target

Your trading bot spots a profitable arbitrage opportunity between Solana and Ethereum, but current gas fees would eat 80% of the profit. Gas conditional execution solves this: queue the transaction now, execute automatically when network fees drop below your threshold.

Traditional trading bots face a brutal tradeoff between speed and profitability. Execute immediately and pay premium gas fees that kill margins, or wait for cheaper gas and miss the opportunity entirely. For high-frequency strategies across multiple chains, this becomes even more complex when you're managing separate wallets, monitoring different fee markets, and coordinating cross-protocol trades.

The Gas Timing Problem

Successful trading bots need three things: speed, cost efficiency, and reliability. But these often conflict:

  • MEV opportunities exist for seconds before other bots capture them
  • Gas spikes during network congestion can turn profitable trades into losses
  • Cross-chain arbitrage requires coordinating transactions on multiple networks with different fee structures
  • Portfolio rebalancing needs to happen regularly but doesn't require immediate execution

The solution is conditional execution: prepare transactions in advance, then execute automatically when conditions are optimal.

Gas Conditional Execution with WAIaaS

WAIaaS includes a 7-stage transaction pipeline with gas condition monitoring. Your bot can queue transactions that execute only when gas prices meet your criteria, while still maintaining the speed needed for time-sensitive opportunities.

Here's how to set up gas conditional execution:

# Queue a swap that executes only when gas is below 50 gwei
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": {
      "maxGasPrice": "50000000000",
      "timeout": 3600
    }
  }'
Enter fullscreen mode Exit fullscreen mode

The transaction enters the pipeline immediately but waits at stage 4 until gas conditions are met. Your bot can queue multiple trades and let the system optimize execution timing.

Multi-Protocol Trading with One API

Real trading strategies often involve multiple protocols and chains. WAIaaS integrates 15 DeFi protocols including Jupiter (Solana DEX aggregation), Hyperliquid (perpetual futures), LI.FI (cross-chain bridging), and Drift (Solana perps).

Here's a complex arbitrage strategy using multiple protocols:

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 opportunity across exchanges
const jupiterPrice = await client.executeAction('jupiter-swap', 'quote', {
  inputMint: 'So11111111111111111111111111111111111111112',
  outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  amount: '1000000000'
});

// Step 2: If profitable, execute multi-step arbitrage
if (isProfitable(jupiterPrice)) {
  // Execute on Jupiter (Solana)
  const jupiterTx = await client.executeAction('jupiter-swap', 'swap', {
    inputMint: 'So11111111111111111111111111111111111111112',
    outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    amount: '1000000000'
  });

  // Bridge to Ethereum via LI.FI
  const bridgeTx = await client.executeAction('lifi', 'bridge', {
    fromChain: 'solana',
    toChain: 'ethereum',
    fromToken: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    toToken: '0xA0b86a33E6417eF2e636065C954Aa0cE5cC0b9dc',
    amount: '1000000000'
  });

  // Hedge position on Hyperliquid perps
  const hedgeTx = await client.executeAction('hyperliquid', 'open-position', {
    market: 'SOL-USD',
    side: 'short',
    size: '10',
    leverage: '5'
  });
}
Enter fullscreen mode Exit fullscreen mode

Risk Management for Trading Bots

Trading bots need sophisticated risk controls to prevent catastrophic losses. WAIaaS includes 21 policy types with 4 security tiers that can enforce position limits, spending caps, and approval workflows.

Create a comprehensive risk policy for your trading bot:

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,
      "notify_max_usd": 5000,
      "delay_max_usd": 25000,
      "delay_seconds": 300,
      "daily_limit_usd": 50000,
      "monthly_limit_usd": 500000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Add perpetual futures limits:

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": "PERP_MAX_LEVERAGE",
    "rules": {
      "maxLeverage": 10
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Production Deployment with Docker

Trading bots need 24/7 uptime with minimal latency. Deploy WAIaaS with Docker for production reliability:

# Clone and deploy
git clone https://github.com/minhoyoo-iotrust/WAIaaS.git
cd WAIaaS
docker compose up -d
Enter fullscreen mode Exit fullscreen mode

The Docker image includes healthchecks, auto-restart policies, and watchtower integration for automatic updates. The daemon binds to 127.0.0.1:3100 by default, perfect for localhost API access from your trading bot.

For production secrets management:

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

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

Real-Time Position Monitoring

Track your DeFi positions across all integrated protocols with a single API call:

curl http://127.0.0.1:3100/v1/defi/positions \
  -H "Authorization: Bearer wai_sess_<token>"
Enter fullscreen mode Exit fullscreen mode

This returns positions from Aave, Drift, Hyperliquid, Kamino, Lido, Pendle, and other integrated protocols. Your monitoring dashboard can track portfolio health, leverage ratios, and liquidation risks in real-time.

Quick Start for Trading Bot Integration

Get your trading bot connected to WAIaaS in 5 steps:

  1. Install and start WAIaaS:
   npm install -g @waiaas/cli
   waiaas init --auto-provision
   waiaas start
Enter fullscreen mode Exit fullscreen mode
  1. Create wallets for your strategies:
   waiaas wallet create --name arbitrage-bot --chain solana
   waiaas wallet create --name ethereum-bot --chain ethereum
Enter fullscreen mode Exit fullscreen mode
  1. Set up risk policies (see examples above)

  2. Create session tokens for API access:

   waiaas session create --wallet arbitrage-bot
Enter fullscreen mode Exit fullscreen mode
  1. Install SDK and start trading:
   npm install @waiaas/sdk
Enter fullscreen mode Exit fullscreen mode

Your bot now has access to 15 DeFi protocols, gas conditional execution, cross-chain bridging, and institutional-grade risk management through a single API.

For more advanced trading infrastructure, check out Building Autonomous DeFi Agents with WAIaaS and Claude MCP and Multi-Chain Wallet Infrastructure for AI Agents.

What's Next

Ready to optimize your trading bot's execution and risk management? Start with the quickstart guide above, then explore the OpenAPI documentation at /reference endpoint for detailed protocol integration guides.

Get started: GitHub | Official Documentation

Top comments (0)