본문으로 건너뛰기
Skillpedia
에이전트280k · #351

llm-trading-agent-security

하는 일

이 AI 에이전트는 자동화된 금융 거래를 안전하게 하도록 돕습니다. AI에 보내는 명령이 안전한지, 지출 한도가 지켜지는지 확인하여 금전 손실을 막습니다.

사용하는 경우

  • ✓거래를 실행하는 자동 트레이딩 봇을 만들 때.
  • ✓내 돈을 관리하는 에이전트의 보안을 검토할 때.
  • ✓에이전트가 쓸 수 있는 금액에 한도를 설정하고 싶을 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/skills/llm-trading-agent-security/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/skills/llm-trading-agent-security/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 거래 명령을 실행하기 전에 안전한지 확인해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

여러 겹의 보안을 추가해서 작동합니다. 여기에는 속임수를 막기 위해 명령을 확인하는 것, 지출 한도를 강제하는 것, 전송 전에 거래를 시뮬레이션하는 것이 포함됩니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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
자주 묻는 질문

'prompt injection'은 무엇인가요?

누군가 악의적인 명령으로 AI를 속여 원치 않는 행동을 하게 만드는 것입니다. 예를 들어 잘못된 주소로 돈을 보내게 하는 것이 있습니다.

'spend limits'는 무엇인가요?

AI 에이전트가 한 번의 거래나 하루에 쓸 수 있는 최대 금액을 정한 규칙입니다. 큰 손실을 막기 위한 것입니다.

거래를 보내기 전에 왜 시뮬레이션하나요?

시뮬레이션을 하면 실제로 일어나기 전에 거래 결과를 볼 수 있습니다. 결과가 예상대로인지 확인하고, 예기치 않은 시장 변동(슬리피지)으로 인한 손실을 피할 수 있습니다.

상세 정보

작성자의 원본 설명

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.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#351
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬