Communitygithub.com

llm-trading-agent-security

자율 트레이딩 에이전트의 보안 패턴을 다룹니다. 지갑이나 트랜잭션 권한을 가진 에이전트의 프롬프트 인젝션, 지출 한도, 사전 전송 시뮬레이션, 서킷 브레이커, MEV 보호 및 키 관리 방법을 제시합니다. 자율 에이전트가 지갑 또는 트랜잭션 권한을 보유하고 있으며, 그 한도, 시뮬레이션 또는 키 관리에 대한 검토가 필요할 때 사용하세요.

llm-trading-agent-security란 무엇인가요?

이 스킬은 자율 트레이딩 에이전트의 보안 위협 모델을 다루며, 특히 프롬프트 인젝션, 지출 한도, 사전 전송 시뮬레이션, 서킷 브레이커, MEV 보호, 키 관리 등 핵심 방어 계층을 제공합니다. 일반 LLM 앱보다 훨씬 엄격한 보안이 요구되는 자율 트레이딩 에이전트에서 인젝션 또는 잘못된 도구 사용이 자산 손실로 직결될 수 있으므로, 여러 독립적인 방어 메커니즘을 계층화하는 것이 중요합니다. Python 코드 예제와 함께 실제 구현 가능한 패턴을 제공하며, Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 적용할 수 있습니다. 배포 전 체크리스트를 통해 외부 데이터 정제, 지출 한도 적용, 트랜잭션 시뮬레이션, 서킷 브레이커 설정, 키 관리, 감사 로깅 등 필수 보안 조치를 확인할 수 있습니다.

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

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

LLM 트레이딩 에이전트 보안

자율 트레이딩 에이전트는 일반 LLM 앱보다 더 엄격한 위협 모델을 가집니다. 인젝션이나 잘못된 도구 경로는 직접 자산 손실로 이어질 수 있습니다.

사용 시기

  • 트랜잭션에 서명하고 전송하는 AI 에이전트를 구축할 때
  • 트레이딩 봇 또는 온체인 실행 도우미를 감사할 때
  • 에이전트의 지갑 키 관리를 설계할 때
  • LLM에 주문 배치, 스왑 또는 재무 작업 접근 권한을 부여할 때

작동 방식

방어 계층을 구성하세요. 단일 검사만으로는 충분하지 않습니다. 프롬프트 위생, 지출 정책, 시뮬레이션, 실행 한도, 지갑 격리를 독립적인 제어 체계로 취급하세요.

예제

프롬프트 인젝션을 금전적 공격으로 취급

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

토큰 이름, 페어 레이블, 웹훅 또는 소셜 피드를 실행 가능한 프롬프트에 무분별하게 주입하지 마세요.

엄격한 지출 한도

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)

전송 전 시뮬레이션

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)

서킷 브레이커

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

지갑 격리

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)

필요한 세션 자금만 보유한 전용 핫월렛을 사용하세요. 절대 기본 재무 지갑을 에이전트가 가리키게 하지 마세요.

MEV 및 마감 시간 보호

import time

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

배포 전 체크리스트

  • 외부 데이터는 LLM 컨텍스트에 들어가기 전에 정제됨
  • 지출 한도는 모델 출력과 독립적으로 적용됨
  • 트랜잭션은 전송 전에 시뮬레이션됨
  • min_amount_out은 필수
  • 서킷 브레이커는 손실 또는 유효하지 않은 상태에서 정지됨
  • 키는 환경 변수 또는 비밀 관리자에서 가져오며, 코드나 로그에 절대 노출되지 않음
  • 필요에 따라 비공개 멤풀 또는 보호된 라우팅 사용
  • 슬리피지 및 마감 시간은 전략별로 설정됨
  • 모든 에이전트 결정은 성공 전송뿐만 아니라 감사 로그에 기록됨

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.

관련 스킬