Catalog
affaan-m/llm-trading-agent-security

affaan-m

llm-trading-agent-security

Security patterns for autonomous trading agents with wallet or transaction authority. Covers prompt injection, spend limits, pre-send simulation, circuit breakers, MEV protection, and key handling. Use when an autonomous agent holds wallet or transaction authority and its limits, simulation, or key handling need review.

NewUpdated Sep 9, 2026

LLM Trading Agent Security

Autonomous trading agents have a harsher threat model than normal LLM apps: an injection or bad tool path can turn directly into asset loss.

When to Use

  • Building an AI agent that signs and sends transactions
  • Auditing a trading bot or on-chain execution assistant
  • Designing wallet key management for an agent
  • Giving an LLM access to order placement, swaps, or treasury operations

How It Works

Layer the defenses. No single check is enough. Treat prompt hygiene, spend policy, simulation, execution limits, and wallet isolation as independent controls.

Examples

Treat prompt injection as a financial attack

import re

INJECTION_PATTERNS = [
    r'ignore (previous|all) instructions',
    r'new (task|directive|instruction)',
    r'system prompt',
    r'send .{0,50} to 0x[0-9a-fA-F]{40}',
    r'transfer .{0,50} to',
    r'approve .{0,50} for',
]

def sanitize_onchain_data(text: str) -> str:
    for pattern in INJECTION_PATTERNS:
        if re.search(pattern, text, re.IGNORECASE):
            raise ValueError(f"Potential prompt injection: {text[:100]}")
    return text

Do not blindly inject token names, pair labels, webhooks, or social feeds into an execution-capable prompt.

Hard spend limits

from decimal import Decimal

MAX_SINGLE_TX_USD = Decimal("500")
MAX_DAILY_SPEND_USD = Decimal("2000")

class SpendLimitError(Exception):
    pass

class SpendLimitGuard:
    def check_and_record(self, usd_amount: Decimal) -> None:
        if usd_amount > MAX_SINGLE_TX_USD:
            raise SpendLimitError(f"Single tx ${usd_amount} exceeds max ${MAX_SINGLE_TX_USD}")

        daily = self._get_24h_spend()
        if daily + usd_amount > MAX_DAILY_SPEND_USD:
            raise SpendLimitError(f"Daily limit: ${daily} + ${usd_amount} > ${MAX_DAILY_SPEND_USD}")

        self._record_spend(usd_amount)

Simulate before sending

class SlippageError(Exception):
    pass

async def safe_execute(self, tx: dict, expected_min_out: int | None = None) -> str:
    sim_result = await self.w3.eth.call(tx)

    if expected_min_out is None:
        raise ValueError("min_amount_out is required before send")

    actual_out = decode_uint256(sim_result)
    if actual_out < expected_min_out:
        raise SlippageError(f"Simulation: {actual_out} < {expected_min_out}")

    signed = self.account.sign_transaction(tx)
    return await self.w3.eth.send_raw_transaction(signed.raw_transaction)

Circuit breaker

class TradingCircuitBreaker:
    MAX_CONSECUTIVE_LOSSES = 3
    MAX_HOURLY_LOSS_PCT = 0.05

    def check(self, portfolio_value: float) -> None:
        if self.consecutive_losses >= self.MAX_CONSECUTIVE_LOSSES:
            self.halt("Too many consecutive losses")

        if self.hour_start_value <= 0:
            self.halt("Invalid hour_start_value")
            return

        hourly_pnl = (portfolio_value - self.hour_start_value) / self.hour_start_value
        if hourly_pnl < -self.MAX_HOURLY_LOSS_PCT:
            self.halt(f"Hourly PnL {hourly_pnl:.1%} below threshold")

Wallet isolation

import os
from eth_account import Account

private_key = os.environ.get("TRADING_WALLET_PRIVATE_KEY")
if not private_key:
    raise EnvironmentError("TRADING_WALLET_PRIVATE_KEY not set")

account = Account.from_key(private_key)

Use a dedicated hot wallet with only the required session funds. Never point the agent at a primary treasury wallet.

MEV and deadline protection

import time

PRIVATE_RPC = "https://rpc.flashbots.net"
MAX_SLIPPAGE_BPS = {"stable": 10, "volatile": 50}
deadline = int(time.time()) + 60

Pre-Deploy Checklist

  • External data is sanitized before entering the LLM context
  • Spend limits are enforced independently from model output
  • Transactions are simulated before send
  • min_amount_out is mandatory
  • Circuit breakers halt on drawdown or invalid state
  • Keys come from env or a secret manager, never code or logs
  • Private mempool or protected routing is used when appropriate
  • Slippage and deadlines are set per strategy
  • All agent decisions are audit-logged, not just successful sends
Files1
1 files · 1.0 KB

Select a file to preview

Overall Score

86/100

Grade

A

Excellent

Grades are signals, not a certification. Always review a skill yourself before use.

Safety

85

Quality

88

Clarity

87

Completeness

82

Summary

Security patterns guide for autonomous trading agents with transaction authority. Teaches layered defenses: prompt injection sanitization, hard spend limits, pre-send simulation, circuit breakers, MEV protection, and key management. Designed to reduce asset loss risk from agent compromise or bad execution paths.

Detected Capabilities

environment variable access (private key)transaction simulation (eth_call)wallet/signing operationsspend tracking and policy enforcementcircuit breaker pattern implementation

Trigger Keywords

Phrases that agents use to match this skill to user intent.

trading agent securityautonomous transaction authorityprompt injection preventionspend limits enforcementwallet key managementpre-send simulationcircuit breaker patternMEV protection

Risk Signals

INFO

Environment variable access for private keys (TRADING_WALLET_PRIVATE_KEY)

Wallet isolation example, ~line 85
INFO

Reference to private RPC endpoint (rpc.flashbots.net)

MEV and deadline protection example, ~line 102
INFO

Hardcoded spend limits and thresholds in code examples

Hard spend limits and circuit breaker examples, ~lines 44-78

Referenced Domains

External domains referenced in skill content, detected by static analysis.

rpc.flashbots.net

Use Cases

  • Audit an LLM trading bot for security vulnerabilities
  • Design wallet key management for an autonomous agent
  • Implement spend limit guards and circuit breakers for on-chain execution
  • Prevent prompt injection attacks in execution-capable AI systems
  • Review pre-send transaction simulation patterns
  • Implement slippage and MEV protection for agent trades

Quality Notes

  • Excellent pedagogical structure with layered defense explanation and clear separation of concerns
  • Code examples are production-grade and include proper error handling (exception raising, validation)
  • Strong emphasis on defense-in-depth: no single check is presented as sufficient
  • Pre-deploy checklist provides actionable verification steps
  • Clear guidance that spend limits must be enforced independently from model output
  • Practical specificity: e.g., max slippage BPS by asset volatility, min_amount_out as mandatory
  • Scope is well-defined: trading agents with transaction authority, not generic LLM security
  • Good balance of code examples and narrative guidance
Model: claude-haiku-4-5-20251001Analyzed: Sep 9, 2026

Reviews

Add this skill to your library to leave a review.

No reviews yet

Be the first to share your experience.

Version History

  1. v2.0

    Contract changed: description

    ✦ AIRefines activation scope in description to emphasize review of agent limits, simulation, and key handling.

    triggering2026-09-09

    LATEST
  2. v1.2

    Content updated

    ✦ AINo behavioral changes detected.

    2026-07-14

    View This Version
  3. v1.1

    Content updated

    ✦ AIAdds LICENSE file; SKILL.md content unchanged.

    2026-04-20

    View This Version
  4. v1.0

    2026-04-12

    View This VersionInitial version

Use affaan-m/llm-trading-agent-security in your dev environment

Command Palette

Search for a command to run...