21 Ways to Control Your Trading Bot: Complete Policy Engine Guide

typescript dev.to

Trading bot builders face a complex challenge: how do you create reliable risk controls that protect your capital without slowing down profitable trades? The wrong policy configuration can either block legitimate opportunities or expose you to catastrophic losses when market conditions change rapidly.

Why Policy Engines Matter for Trading Systems

In automated trading, milliseconds matter — but so does risk management. Professional trading firms use sophisticated policy engines to enforce position limits, validate counterparties, and implement circuit breakers. Your bot needs the same level of control, but most wallet infrastructure forces you to choose between speed and safety.

Traditional approaches require building custom risk management from scratch, integrating multiple wallet providers, and maintaining complex approval workflows. This creates technical debt that slows development and introduces failure points during critical market events.

WAIaaS Policy Engine: 21 Policy Types for Trading Control

WAIaaS provides a production-ready policy engine with 21 policy types designed for automated trading scenarios. The system uses 4 security tiers (INSTANT, NOTIFY, DELAY, APPROVAL) to balance execution speed with risk management.

Core Trading Policies

SPENDING_LIMIT provides amount-based risk tiers that automatically adjust execution requirements based on trade size:

curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 100,
      "notify_max_usd": 1000,
      "delay_max_usd": 10000,
      "delay_seconds": 300,
      "daily_limit_usd": 50000,
      "monthly_limit_usd": 500000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

This configuration executes small trades instantly, adds monitoring for medium trades, implements time delays for large trades, and requires approval for exceptional amounts.

ALLOWED_TOKENS implements default-deny token filtering, crucial for preventing your bot from trading unknown or manipulated tokens:

curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "ALLOWED_TOKENS",
    "rules": {
      "tokens": [
        {"address": "So11111111111111111111111111111111111111112", "symbol": "SOL", "chain": "solana"},
        {"address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "symbol": "USDC", "chain": "solana"},
        {"address": "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "symbol": "USDT", "chain": "solana"}
      ]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

CONTRACT_WHITELIST restricts your bot to vetted protocols, preventing interaction with malicious or unaudited contracts:

curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "CONTRACT_WHITELIST",
    "rules": {
      "contracts": [
        {"address": "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4", "name": "Jupiter", "chain": "solana"},
        {"address": "DRiFtupJYLTosbwoN8koMbEYSx54aFAVLddWsbksjwg7", "name": "Drift", "chain": "solana"}
      ]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Advanced Trading Controls

RATE_LIMIT prevents your bot from overwhelming markets or triggering exchange rate limits:

{"maxTransactions":100,"period":"hourly"}
Enter fullscreen mode Exit fullscreen mode

TIME_RESTRICTION limits trading to specific hours, useful for strategies that depend on market sessions:

{"allowedHours":{"start":9,"end":16},"timezone":"America/New_York"}
Enter fullscreen mode Exit fullscreen mode

PERP_MAX_LEVERAGE and PERP_MAX_POSITION_USD control perpetual futures exposure:

{"maxLeverage":5.0,"maxPositionUsd":100000}
Enter fullscreen mode Exit fullscreen mode

DeFi-Specific Policies

LENDING_LTV_LIMIT prevents over-leveraging in lending protocols:

{"maxLtv":0.75}
Enter fullscreen mode Exit fullscreen mode

VENUE_WHITELIST restricts trading to approved exchanges and DEXes:

{"venues":["jupiter","drift","hyperliquid"]}
Enter fullscreen mode Exit fullscreen mode

ACTION_CATEGORY_LIMIT sets spending caps per DeFi category:

{"limits":{"SWAP":{"daily_limit_usd":10000},"LENDING":{"daily_limit_usd":50000},"PERP":{"daily_limit_usd":25000}}}
Enter fullscreen mode Exit fullscreen mode

Multi-Protocol Trading Example

Here's how to configure a bot that trades across Solana and Ethereum with appropriate risk controls:

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

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

// Execute arbitrage trade: buy on Jupiter, hedge on Drift
async function executeArbitrage() {
  // Step 1: Swap SOL for USDC on Jupiter
  const swapResult = await client.executeAction('jupiter-swap', {
    inputMint: 'So11111111111111111111111111111111111111112',
    outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    amount: '1000000000' // 1 SOL
  });

  // Step 2: Open short position on Drift to hedge
  const hedgeResult = await client.executeAction('drift', {
    market: 'SOL-PERP',
    side: 'short',
    amount: '1.0',
    leverage: 2
  });

  return { swap: swapResult, hedge: hedgeResult };
}
Enter fullscreen mode Exit fullscreen mode

The policy engine automatically validates each transaction against your configured rules before execution.

Gas Conditional Execution

WAIaaS includes gas conditional execution for optimal timing:

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": "50000000000",
      "timeout": 3600
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Your transaction executes only when gas prices drop below the threshold, maximizing profitability for non-urgent trades.

All 21 Policy Types

The complete policy engine includes:

Core Security:

  • SPENDING_LIMIT — Amount-based 4-tier security
  • WHITELIST — Allowed recipient addresses
  • TIME_RESTRICTION — Allowed transaction hours
  • RATE_LIMIT — Max transactions per period

Asset Controls:

  • ALLOWED_TOKENS — Token transfer whitelist (default-deny)
  • CONTRACT_WHITELIST — Contract call whitelist (default-deny)
  • METHOD_WHITELIST — Allowed function selectors
  • APPROVED_SPENDERS — Token approval whitelist (default-deny)
  • APPROVE_AMOUNT_LIMIT — Max approve amount, block unlimited
  • APPROVE_TIER_OVERRIDE — Force tier for APPROVE transactions

Network & Protocol:

  • ALLOWED_NETWORKS — Network restriction
  • X402_ALLOWED_DOMAINS — x402 payment domain whitelist
  • ERC8128_ALLOWED_DOMAINS — ERC-8128 HTTP signing domains
  • REPUTATION_THRESHOLD — ERC-8004 onchain reputation threshold

DeFi Trading:

  • LENDING_LTV_LIMIT — Max loan-to-value ratio
  • LENDING_ASSET_WHITELIST — Allowed lending assets
  • PERP_MAX_LEVERAGE — Max perpetual futures leverage
  • PERP_MAX_POSITION_USD — Max position size in USD
  • PERP_ALLOWED_MARKETS — Allowed perpetual markets
  • VENUE_WHITELIST — Allowed trading venues
  • ACTION_CATEGORY_LIMIT — DeFi action category limits

Quick Start: Set Up Trading Bot Policies

  1. Install and start WAIaaS:
npm install -g @waiaas/cli
waiaas quickstart
Enter fullscreen mode Exit fullscreen mode
  1. Create a trading wallet:
curl -X POST http://127.0.0.1:3100/v1/wallets \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{"name": "trading-bot", "chain": "solana", "environment": "mainnet"}'
Enter fullscreen mode Exit fullscreen mode
  1. Set spending limits:
# Configure the SPENDING_LIMIT policy from the example above
Enter fullscreen mode Exit fullscreen mode
  1. Add token whitelist:
# Configure the ALLOWED_TOKENS policy from the example above
Enter fullscreen mode Exit fullscreen mode
  1. Test your bot:
waiaas status
# Verify policies are active and wallet is ready for automated trading
Enter fullscreen mode Exit fullscreen mode

Your trading bot now has enterprise-grade risk controls with minimal latency overhead.

What's Next

The policy engine provides the foundation for sophisticated trading strategies across 15 DeFi protocols. Next, explore gas optimization techniques and cross-chain arbitrage patterns to maximize your bot's profitability.

Ready to build? Get the complete WAIaaS trading infrastructure at GitHub or learn more at waiaas.ai.

Source: dev.to

arrow_back Back to Tutorials