Communitygithub.com

llm-trading-agent-security

Sicherheitsmuster für autonome Handelsagenten mit Wallet- oder Transaktionshoheit. Behandelt Prompt-Injection, Ausgabenlimits, Pre-Send-Simulation, Schutzschalter, MEV-Schutz und Schlüsselverwaltung. Verwenden, wenn ein autonomer Agent Wallet- oder Transaktionshoheit besitzt und seine Limits, Simulation oder Schlüsselverwaltung überprüft werden müssen.

Was ist llm-trading-agent-security?

Dieses Skill definiert ein mehrschichtiges Sicherheitsframework für autonome KI-Handelsagenten, die Transaktionen signieren und senden. Der Schlüsselgedanke ist, dass für LLM-gesteuerte Handelsagenten ein strengeres Bedrohungsmodell gilt als für normale LLM-Anwendungen: Eine einzige Injection oder ein fehlerhafter Tool-Pfad kann direkt zu Vermögensverlusten führen. Das Skill behandelt Prompt-Injection als finanziellen Angriff und bietet konkrete Python-Implementierungen für zentrale Sicherheitskontrollen: harte Ausgabenlimits pro Transaktion und pro Tag, Transaktionssimulation vor dem Senden mit erzwungenem minimalen Ausgabebetrag, einen Schutzschalter, der bei zu vielen aufeinanderfolgenden Verlusten oder Überschreitung stündlicher Verlustschwellen auslöst, Wallet-Isolation durch dedizierte heiße Wallets mit Sitzungsgeldern und MEV-Schutz durch private Mempools, Slippage-Grenzen und Deadline-Setzung. Es ist plattformunabhängig und kann in beliebige KI-Agenten-Frameworks (Claude Code, Cursor, Codex, etc.) integriert werden. Die bereitgestellten Codebeispiele sind in Python unter Verwendung von eth_account, web3.py und grundlegender Standardbibliotheken gehalten. Das Skill enthält zudem eine Pre-Deploy-Checkliste, die sicherstellt, dass alle Entscheidungen des Agenten überwacht, begrenzt und protokolliert werden.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/llm-trading-agent-security

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Sicherheit für LLM-Handelsagenten

Autonome Handelsagenten haben ein härteres Bedrohungsmodell als normale LLM-Apps: Eine Injection oder ein schlechter Tool-Pfad kann direkt in einen Vermögensverlust münden.

Wann verwenden

  • Erstellen eines KI-Agenten, der Transaktionen signiert und sendet
  • Auditieren eines Handelsbots oder eines On-Chain-Ausführungsassistenten
  • Entwerfen der Wallet-Schlüsselverwaltung für einen Agenten
  • Gewähren eines LLM-Zugriffs auf Order-Platzierung, Swaps oder Treasury-Operationen

Wie es funktioniert

Schichten Sie die Verteidigung. Keine einzelne Prüfung ist ausreichend. Behandeln Sie Prompt-Hygiene, Ausgabenrichtlinie, Simulation, Ausführungslimits und Wallet-Isolation als unabhängige Kontrollen.

Beispiele

Prompt-Injection als finanziellen Angriff behandeln

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"Potenzielle Prompt-Injection: {text[:100]}")
    return text

Token-Namen, Paar-Labels, Webhooks oder soziale Feeds nicht blind in einen ausführungsfähigen Prompt einfügen.

Harte Ausgabenlimits

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"Einzel-Tx ${usd_amount} überschreitet Maximum ${MAX_SINGLE_TX_USD}")

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

        self._record_spend(usd_amount)

Vor dem Senden simulieren

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 ist vor dem Senden erforderlich")

    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)

Schutzschalter

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("Zu viele aufeinanderfolgende Verluste")

        if self.hour_start_value <= 0:
            self.halt("Ungültiger 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"Stündlicher PnL {hourly_pnl:.1%} unter Schwellwert")

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 nicht gesetzt")

account = Account.from_key(private_key)

Verwenden Sie ein dediziertes Hot-Wallet mit nur den erforderlichen Sitzungsgeldern. Richten Sie den Agenten niemals auf ein primäres Treasury-Wallet.

MEV- und Deadline-Schutz

import time

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

Pre-Deploy-Checkliste

  • Externe Daten werden bereinigt, bevor sie in den LLM-Kontext gelangen
  • Ausgabenlimits werden unabhängig von der Modellausgabe durchgesetzt
  • Transaktionen werden vor dem Senden simuliert
  • min_amount_out ist obligatorisch
  • Schutzschalter stoppen bei Drawdown oder ungültigem Zustand
  • Schlüssel stammen aus der Umgebung oder einem Secret Manager, niemals aus Code oder Logs
  • Bei Bedarf wird ein privater Mempool oder geschütztes Routing verwendet
  • Slippage und Deadlines werden pro Strategie festgelegt
  • Alle Agentenentscheidungen werden audit-loggt, nicht nur erfolgreiche Sendungen

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Verwandte Skills