llm-trading-agent-security
affaan-m/everything-claude-code
Security patterns for autonomous trading agents: prompt injection defense, spend limits, pre-send simulation, circuit breakers, and key isolation.
What is llm-trading-agent-security?
Implements layered security controls for LLM agents with transaction signing authority. Use this when building AI trading bots, wallet assistants, or on-chain execution systems to prevent prompt injection attacks from turning into asset loss.
- Sanitize external data and detect prompt injection patterns before LLM processing
- Enforce hard spend limits (per-transaction and daily) independent of model output
- Simulate transactions before sending and validate slippage against expected minimums
- Implement circuit breakers that halt on consecutive losses or hourly drawdown thresholds
- Isolate agent wallets with session-only funds, never pointing to primary treasury
- Protect against MEV via private RPC endpoints and enforce deadline/slippage parameters
How to install llm-trading-agent-security
npx skills add https://github.com/affaan-m/everything-claude-code --skill llm-trading-agent-security- Python environment with eth_account and web3.py libraries
- Access to a blockchain RPC endpoint (private mempool recommended)
- Environment variables configured for wallet private keys (never hardcoded)
- Understanding of transaction simulation and slippage mechanics
How to use llm-trading-agent-security
- 1.Set up environment variables for your isolated trading wallet private key
- 2.Define spend limits (MAX_SINGLE_TX_USD, MAX_DAILY_SPEND_USD) appropriate to your use case
- 3.Implement the SpendLimitGuard class to track and enforce daily/per-transaction caps
- 4.Add sanitization regex patterns to detect and reject prompt injection attempts in external data
- 5.Implement pre-send simulation: call the transaction, decode output, validate against expected_min_out
- 6.Set up a TradingCircuitBreaker with loss thresholds and halt conditions
- 7.Configure private RPC endpoint and set slippage/deadline parameters per strategy
- 8.Log all agent decisions and transaction attempts for audit trail
Use cases
- Building an autonomous trading agent that signs and sends blockchain transactions
- Auditing an existing trading bot or on-chain execution assistant for security gaps
- Designing wallet key management and fund isolation for an LLM-controlled agent
- Giving an LLM access to order placement, token swaps, or treasury operations
- Preventing prompt injection attacks from draining funds via malicious input data
- AI/LLM engineers building trading bots or autonomous agents
- DeFi protocol teams deploying on-chain execution assistants
- Security auditors reviewing trading agent implementations
- Wallet and treasury managers integrating LLM automation
llm-trading-agent-security FAQ
Simulation reveals the actual output (slippage, revert conditions) without committing funds. It catches bad paths, insufficient liquidity, or MEV sandwich attacks before the transaction is irreversible.
Always use a dedicated hot wallet with only session funds. Never point the agent at a primary treasury wallet. This limits blast radius if the agent is compromised.
No. Treat prompt injection as one layer among many. Combine it with spend limits, simulation, circuit breakers, and wallet isolation. No single check is sufficient.
That is the intended behavior—the controls allow safe transactions through. If you want stricter approval, add a human-in-the-loop step or require explicit confirmation for large trades.
Set MAX_SLIPPAGE_BPS per strategy (e.g., 10 bps for stables, 50 bps for volatile). Require min_amount_out in every swap and reject if simulation output falls below it.
Full instructions (SKILL.md)
Source of truth, from affaan-m/everything-claude-code.
name: llm-trading-agent-security description: 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. metadata: origin: ECC direct-port adaptation version: "1.0.0"
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_outis 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
Related skills
More from affaan-m/everything-claude-code and the wider catalog.

security-review
Security checklist and patterns for authentication, input validation, secrets, and sensitive features.

golang-patterns
Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable applications.

coding-standards
Baseline coding conventions for naming, readability, immutability, and quality across projects.

frontend-patterns
React and Next.js patterns for components, state management, performance, and modern frontend practices.

backend-patterns
REST/GraphQL API design, database optimization, and server-side patterns for Node.js, Express, and Next.js.

golang-testing
Go testing patterns: table-driven tests, subtests, benchmarks, fuzzing, and TDD methodology.