인셔셔RSS 관심 있는 블로그, 뉴스, 기술 정보를 효율적으로 추적하고 읽으세요
원문 읽기 InertiaRSS에서 열기

추천 피드

小众软件
小众软件
博客园 - 叶小钗
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
T
Tailwind CSS Blog
Jina AI
Jina AI
量子位
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
J
Java Code Geeks
V
Visual Studio Blog
月光博客
月光博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
내가 Hermes Agent를 트레이딩 파트너로 삼아 멀티체인 DEX 트레이딩 봇을 구축한 방법
semi · 2026-05-28 · via DEV Community

이것은 Hermes Agent Challenge: Build With Hermes Agent

에 제출하는 글입니다. 제가 만든 것

IYOP Trading Bot은 Solana(Jupiter), Ethereum(Uniswap V3), BSC(PancakeSwap V2) 전반에서 거래를 실행하는 AI 기반 멀티체인 DEX 트레이딩 봇입니다. 시장 분석에 MiMo v2를 사용하고, 여러 기술 지표를 기반으로 신호를 생성하며, 포지션 사이징과 손실 방어를 통해 리스크를 관리합니다.

내가 해결하려던 문제는: 분산형 거래가 파편화되어 있다는 점이었다. 각 체인은 자체 DEX, 자체 특성, 자체 유동성 풀을 가지고 있다. 이를 수동으로 모니터링하는 것은 불가능하다. 체인 간 거래를 실행하려면 서로 다른 SDK, 서로 다른 가스 관리, 서로 다른 지갑 처리가 필요하다.

나는 다음과 같은 기능을 갖춘 통합 계층이 필요했다:

  • 여러 DEX를 동시에 스캔
  • 기술적 지표와 AI 분석으로 신호 생성
  • 적절한 리스크 관리로 거래 실행
  • 체인 간 포지션 추적
  • 손절매와 이익실현 자동 처리

그리고 실제로 출시할 수 있을 만큼 개발 과정을 빠르게 만들기 위해 Hermes Agent가 필요했습니다.

데모

라이브 데모: iyop-trading-terminal.vercel.app

출처: github.com/iyop666/iyop-trading-bot

이 봇은 웹 대시보드가 있는 FastAPI 백엔드로 실행됩니다. 주요 기능:

  • 멀티체인 DEX 스캐닝 (Jupiter, Uniswap V3, PancakeSwap)
  • IYOP v2 API를 통한 AI 기반 시장 분석
  • 신뢰도 점수를 포함한 신호 생성
  • 포지션 크기 조정과 하락 제한을 통한 리스크 관리
  • 손절매/이익실현을 포함한 거래 실행
  • 실시간 WebSocket 가격 피드

코드

다음은 Hermes Agent가 구축을 도운 핵심 모듈입니다:

AI 시장 분석기 (AI Market Analyzer)

분석기는 IYOP v2에 연결하여 빠른 시장 분석, 신호 생성 및 감정 분석을 수행합니다:

import httpx
from dataclasses import dataclass
from enum import Enum

MIMO_API_URL = "http://127.0.0.1:19911/v1/chat/completions"
MIMO_MODEL = "gitlawb/mimo-v2-flash"

class Signal(Enum):
    BUY = "buy"
    SELL = "sell"
    HOLD = "hold"

@dataclass
class MarketAnalysis:
    signal: Signal
    confidence: float
    reasoning: str
    risk_level: str

async def analyze_market(pair: str, timeframe: str) -> MarketAnalysis:
    """Send market data to MiMo v2 for analysis."""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            MIMO_API_URL,
            json={
                "model": MIMO_MODEL,
                "messages": [
                    {"role": "system", "content": "Analyze this trading pair..."},
                    {"role": "user", "content": f"Pair: {pair}, Timeframe: {timeframe}"}
                ],
                "temperature": 0.1
            },
            timeout=30
        )
        result = response.json()
        return parse_analysis(result)

전체 화면 모드 전체 화면 모드 종료

신호 생성

가중치 점수를 사용하여 여러 기술적 지표를 결합합니다:

from dataclasses import dataclass
from enum import Enum

class SignalType(Enum):
    STRONG_BUY = "strong_buy"
    BUY = "buy"
    WEAK_BUY = "weak_buy"
    HOLD = "hold"
    WEAK_SELL = "weak_sell"
    SELL = "sell"
    STRONG_SELL = "strong_sell"

@dataclass
class TradeSignal:
    signal_type: SignalType
    confidence: float  # 0.0 to 1.0
    pair: str
    price: float
    indicators: dict
    reasoning: str

def generate_signal(indicators: dict, ai_analysis: dict) -> TradeSignal:
    """Combine technical indicators with AI analysis."""
    weights = {
        "rsi": 0.25,
        "macd": 0.20,
        "bollinger": 0.15,
        "volume": 0.15,
        "ai_analysis": 0.25
    }

    score = 0.0
    for indicator, weight in weights.items():
        score += normalize(indicators.get(indicator, 0)) * weight

    signal_type = classify_signal(score)
    return TradeSignal(
        signal_type=signal_type,
        confidence=abs(score),
        pair=indicators["pair"],
        price=indicators["price"],
        indicators=indicators,
        reasoning=build_reasoning(indicators, ai_analysis)
    )

전체 화면 모드 전체 화면 모드 종료

멀티체인 DEX 통합

Jupiter, Uniswap V3 및 PancakeSwap을 위한 통합 인터페이스:

from enum import Enum
import httpx

class DEX(Enum):
    JUPITER = "jupiter"      # Solana
    UNISWAP = "uniswap"      # Ethereum
    PANCAKESWAP = "pancakeswap"  # BSC

class Chain(Enum):
    SOLANA = "solana"
    ETHEREUM = "ethereum"
    BSC = "bsc"

@dataclass
class SwapResult:
    success: bool
    tx_hash: str
    input_amount: float
    output_amount: float
    chain: Chain
    dex: DEX
    gas_used: float

async def execute_swap(
    dex: DEX,
    chain: Chain,
    token_in: str,
    token_out: str,
    amount: float,
    slippage: float = 0.5
) -> SwapResult:
    """Execute a swap on the specified DEX."""
    if dex == DEX.JUPITER:
        return await jupiter_swap(token_in, token_out, amount, slippage)
    elif dex == DEX.UNISWAP:
        return await uniswap_swap(token_in, token_out, amount, slippage)
    elif dex == DEX.PANCAKESWAP:
        return await pancakeswap_swap(token_in, token_out, amount, slippage)

전체 화면 모드 전체 화면 모드 종료

위험 관리

포지션 규모 설정 및 손실 보호:

@dataclass
class RiskManager:
    max_position_pct: float = 0.1  # 10% max per position
    max_daily_loss: float = 0.05   # 5% max daily loss
    max_drawdown: float = 0.15     # 15% max drawdown
    current_drawdown: float = 0.0
    daily_pnl: float = 0.0

    def can_open_position(self, portfolio_value: float, position_size: float) -> bool:
        """Check if a new position is within risk limits."""
        # Check position size limit
        if position_size / portfolio_value > self.max_position_pct:
            return False

        # Check daily loss limit
        if self.daily_pnl < -(portfolio_value * self.max_daily_loss):
            return False

        # Check drawdown limit
        if self.current_drawdown > self.max_drawdown:
            return False

        return True

    def calculate_position_size(
        self,
        portfolio_value: float,
        entry_price: float,
        stop_loss: float
    ) -> float:
        """Calculate optimal position size based on risk parameters."""
        risk_per_trade = portfolio_value * self.max_position_pct
        price_risk = abs(entry_price - stop_loss) / entry_price
        return risk_per_trade / price_risk if price_risk > 0 else 0

전체 화면 모드 시작 전체 화면 모드 종료

거래 실행 엔진

가격 손절과 이익 실현을 포함한 주문 생애 주기 처리:

class Side(str, Enum):
    BUY = "buy"
    SELL = "sell"

class OrderStatus(str, Enum):
    PENDING = "pending"
    FILLED = "filled"
    CANCELLED = "cancelled"
    SL_HIT = "stop_loss_hit"
    TP_HIT = "take_profit_hit"

@dataclass
class Position:
    id: str
    pair: str
    side: Side
    entry_price: float
    current_price: float
    size: float
    stop_loss: float
    take_profit: float
    pnl: float
    chain: Chain
    dex: DEX

class Trader:
    def __init__(self, risk_manager: RiskManager):
        self.positions: dict[str, Position] = {}
        self.risk_manager = risk_manager
        self.trade_history: list[dict] = []

    async def open_position(
        self,
        pair: str,
        side: Side,
        size: float,
        stop_loss: float,
        take_profit: float,
        chain: Chain,
        dex: DEX
    ) -> Position:
        """Open a new position with risk checks."""
        if not self.risk_manager.can_open_position(self.portfolio_value, size):
            raise RiskLimitExceeded("Position exceeds risk limits")

        # Execute the swap
        result = await execute_swap(dex, chain, pair, size)

        position = Position(
            id=str(uuid.uuid4()),
            pair=pair,
            side=side,
            entry_price=result.price,
            current_price=result.price,
            size=size,
            stop_loss=stop_loss,
            take_profit=take_profit,
            pnl=0.0,
            chain=chain,
            dex=dex
        )

        self.positions[position.id] = position
        return position

전체 화면 모드 시작 전체 화면 모드 종료

내 기술 스택

  • 백엔드: Python, FastAPI, Pydantic
  • AI 엔진: MiMo v2 (로컬 API)
  • DEX 통합: Jupiter (Solana), Uniswap V3 (Ethereum), PancakeSwap V2 (BSC)
  • 데이터: WebSocket 가격 피드, 비동기 HTTP용 httpx
  • 프론트엔드: HTML 대시보드
  • AI 어시스턴트: Hermes Agent (개발, 디버깅, 배포용)

내가 Hermes Agent를 사용한 방법

1. 아키텍처 설계

트레이딩 봇을 구축하기 시작했을 때, 나는 요구사항을 Hermes에 설명했다:

"AI 분석, 신호 생성, 리스크 관리 및 거래 실행이 가능한 멀티체인 DEX 트레이딩 봇이 필요합니다. Jupiter(주피터), Uniswap V3(유니스왑 V3), PancakeSwap(팬케이크스왑)을 지원해야 합니다."

Hermes(헤르메스)가 모듈 구조를 설계했습니다:

  • backend/ai/ AI 분석 및 신호 생성용
  • backend/core/ DEX 통합, 리스크 관리 및 거래 실행용
  • 분석과 실행 간의 관심사 분리

그 아키텍처는 나중에 리팩토링하는 데 몇 시간을 절약해 주었습니다.

2. DEX 통합 코드

각 DEX는 서로 다른 API, 서로 다른 트랜잭션 형식, 서로 다른 가스 추정치를 가지고 있습니다. 각각의 문서를 읽는 대신, 나는 Hermes에게 말했습니다:

"Jupiter, Uniswap V3, PancakeSwap용 비동기 스왑 함수를 작성하세요. httpx를 사용하고, 오류를 처리하며, 트랜잭션 해시를 반환하세요."

Hermes는 세 개의 DEX 모두에 대한 통합 코드를 생성했습니다. 오류 처리를 검토하고, 슬리피지 매개변수를 조정하고, 테스트까지 마쳤습니다. 원래 문서를 읽고 상용구를 작성하는 데 하루 종일 걸렸을 작업을 30분 만에 완료했습니다.

3. 리스크 관리 로직

리스크 관리자는 포지션 사이징, 손실 제한, 일일 손실 상한을 처리해야 했습니다. 규칙을 설명했습니다:

"포지션당 최대 10%, 일일 손실 최대 5%, 최대 하락률 15%. 손절 거리를 기준으로 포지션 크기를 계산하세요."

Hermes는 적절한 예외 처리를 포함하여 로직을 구현했습니다. 극단적인 값(100% 손실 시나리오)으로 테스트했을 때, 거래를 올바르게 거부했습니다.

4. 신호 가중치 시스템

여러 지표를 단일 신호로 결합하려면 가중치 시스템이 필요했습니다. 나는 Hermes에게 물었다:

"RSI(25%), MACD(20%), 볼린저 밴드(Bollinger, 15%), 거래량(15%), AI 분석(15%)에 가중치를 부여하는 신호 생성기를 만듭니다. 각 지표를 -1에서 +1 범위로 정규화합니다."

헤르메스(Hermes)는 가중치를 조정 가능한 가중 점수 시스템을 구축했습니다. 이후 테스트 결과 AI 분석이 가장 예측력이 높은 것으로 나타나 가중치를 30%로 조정했습니다.

5. 테스트 및 디버깅

봇이 거래를 올바르게 실행하지 않을 때, 나는 Hermes에게 문제를 추적해 달라고 요청했다:

"거래가 실행되지 않습니다. 스왑 함수, 리스크 관리자, 거래 실행자를 확인하십시오. 병목 지점을 찾으십시오."

Hermes는 코드를 살펴본 후, 포트폴리오 가치가 각 거래 후에 업데이트되지 않아 리스크 관리자가 거래를 거부하고 있음을 발견했다. 한 줄 수정이었지만, 수동으로 찾았다면 디버깅에 한 시간이 걸렸을 것이다.

왜 헤르메스 에이전트(Hermes Agent)가 필수적이었는가

트레이딩 봇을 구축하려면 다음이 필요합니다.

  • 빠른 반복(시장이 움직이므로 코드가 따라가야 함)
  • 크로스 모듈 인식(리스크 매니저가 트레이더에 영향을 미치고, 트레이더가 포트폴리오에 영향을 미침)
  • 비동기 프로그래밍 패턴(모든 DEX 호출은 비동기적임)
  • 에러 핸들링 엣지 케이스(네트워크 실패, 가스 부족, 슬리피지)

Hermes는 전체 코드베이스에 걸쳐 컨텍스트를 유지했기 때문에 이 모든 것을 처리했습니다. 리스크 매니저를 변경했을 때, Hermes가 자동으로 트레이더에 대한 업데이트를 제안했습니다. 새로운 DEX를 추가했을 때는 시그널 생성기를 업데이트하여 새로운 체인을 포함시켰습니다.

이러한 교차 모듈 인식이 프로토타입과 작동하는 봇의 차이를 만들었습니다.


프로젝트 통계:

  • ~2,000줄의 Python 코드
  • 3개의 DEX 통합 (Jupiter, Uniswap V3, PancakeSwap)
  • 5가지 거래 전략 (모멘텀, 평균 회귀, AI 기반, 스캘핑, 하이브리드)
  • 3중 안전 계층을 갖춘 리스크 관리
  • 실시간 WebSocket 가격 피드
  • MiMo v2를 통한 AI 기반 시장 분석

링크: