Skip to content

milanp93/trading-agent

Repository files navigation

Trading Agent — Kraken CLI + ERC-8004

Autonomous trading agent built for the AI Trading Agents Hackathon (lablab.ai × Kraken, April 2026).

Live demo video:

Live.Demo.mp4

What It Does

A fully autonomous trading agent that:

  1. Follows the trend — EMA 20/50 crossover determines market direction, only buys in uptrends
  2. Manages exits first — stop-loss, trailing stop, take-profit, trend reversal exit before any new entries
  3. Enforces a Risk Firewall before any order — deterministic policy engine, EIP-712 signed intents
  4. Submits to RiskRouter — every trade intent goes through on-chain approval before execution
  5. Executes paper or live orders via Kraken CLI subprocess
  6. Posts on-chain checkpoints to ERC-8004 ValidationRegistry after every filled trade
  7. Displays everything in a live dashboard with real-time prices

Architecture

Market Data (Kraken CLI)
        │
        ▼
Strategy Engine v3 (EMA 20/50 trend + RSI + MACD)
        │ signal: buy / sell / hold
        ▼
Risk Firewall ◄─── deterministic policy (whitelist, sizing, loss limit, cooldown)
        │           EIP-712 TradeIntent signed before every order
        │ approved
        ▼
RiskRouter (on-chain) ──► Kraken CLI (paper/live order)
        │                          │
        ▼                          ▼
ValidationRegistry          Cost Basis Tracker
        │ checkpoint              │ position PnL + trailing stop
        ▼                          ▼
Dashboard (live prices, signals, trades, firewall blocks, on-chain events)

Key Features

Strategy v3 — Pro Trader Logic

Core philosophy: Trade WITH the trend, not against it.

PHASE 1 — Position Management (exits first, always):

  • Hard stop-loss at -1.5%
  • Take-profit at +2.0%
  • Trailing stop: locks profits at +0.8%, exits if drops 0.5% from peak
  • Trend reversal exit: downtrend + losing > 0.3% → cut immediately
  • RSI overbought exit: > 70

PHASE 2 — New Entries (only in favorable conditions):

  • UPTREND only (EMA20 > EMA50) — no buys in downtrends
  • RSI < 40 + MACD improving → dip buy
  • RSI < 30 in uptrend → strong mean reversion
  • Cash > 40% reserve, max 10% per asset
  • 5-minute sell cooldown per pair (prevents re-buy traps)
  • DOWNTREND: only extreme reversal (RSI < 25 + MACD crossed up)

Risk Firewall (deterministic)

Every order must pass all checks before execution:

  • Pair whitelist — only XBTUSD, ETHUSD, SOLUSD
  • Position sizing — max 6% of portfolio per trade (~$476, under $500 RiskRouter cap)
  • Rate limiting — min 60s between orders per pair
  • Daily loss circuit breaker — halts all trading at 2% drawdown
  • Sells exempt — closing positions is never blocked by sizing rules
  • EIP-712 signed intent — every approved trade produces a cryptographic proof
  • Stats: 1,319 blocks, 0 bypasses

ERC-8004 On-Chain Identity & Validation

  • Agent registered on Ethereum Sepolia: Agent ID #78
  • Validation score: 99/100
  • RiskRouter: 142 submissions, 77 approved on-chain
  • ValidationRegistry: 708 checkpoints posted
  • 5 shared hackathon contracts on Sepolia (AgentRegistry, HackathonVault, RiskRouter, ReputationRegistry, ValidationRegistry)
  • Dynamic gas pricing with receipt waiting and revert detection

Kraken CLI Integration

  • All market data and order execution via krakenfx/kraken-cli subprocess (-o json)
  • Paper trading: kraken paper buy/sell <PAIR> <AMOUNT> --type market
  • Live trading: kraken spot buy/sell <PAIR> <AMOUNT> --type market
  • Dead man's switch: cancels all open orders on process shutdown (SIGTERM/SIGINT)

Project Structure

trading-agent/
├── agent/
│   ├── main.py           # Agent loop: OHLC → signal → firewall → RiskRouter → execute
│   │                     # Position tracker: cost basis, peak PnL, sell cooldowns
│   ├── kraken_client.py  # Subprocess wrapper for kraken CLI (-o json)
│   ├── strategy.py       # Strategy v3: EMA trend + RSI/MACD + trailing stop
│   └── risk_firewall.py  # Deterministic policy engine + EIP-712 signing
├── erc8004/
│   ├── on_chain.py       # RiskRouter, ValidationRegistry, ReputationRegistry, Vault clients
│   │                     # Dynamic gas pricing, receipt waiting, revert detection
│   ├── abi/              # Contract ABIs (web3.py dict format)
│   └── scripts/
│       └── register.py   # One-time ERC-8004 registration
├── dashboard/
│   ├── server.py         # HTTP server — NDJSON log + live Kraken ticker prices
│   └── index.html        # Dark UI: prices, signals, trades, firewall, on-chain events
├── scripts/
│   └── demo_run.py       # Full pipeline demo (firewall block → buy → RiskRouter → checkpoint)
├── logs/
│   ├── trade_log.ndjson  # One JSON per event (5,000+ events)
│   └── cost_basis.json   # Persistent position tracking {pair: {qty, total_cost}}
├── checkpoints.jsonl     # Local copy of 708 on-chain checkpoints
├── .env
└── requirements.txt

On-Chain Proof

Agent deployed on Ethereum Sepolia (chain ID 11155111):

Item Value
Agent ID 78
Agent Wallet 0xcF5294f177EE5ee5765da44A5872B51db04524DF
Validation Score 99
AgentRegistry 0x97b07dDc405B0c28B17559aFFE63BdB3632d0ca3
HackathonVault 0x0E7CD8ef9743FEcf94f9103033a044caBD45fC90
RiskRouter 0xd6A6952545FF6E6E6681c2d15C59f9EB8F40FdBC
ReputationRegistry 0x423a9904e39537a9997fbaF0f220d79D7d545763
ValidationRegistry 0x92bF63E5C7Ac6980f237a7164Ab413BE226187F1
RiskRouter submissions 142 (77 approved)
On-chain checkpoints 708

Setup

Prerequisites

  • Python 3.11+
  • Kraken CLI installed (~/.cargo/bin/kraken)

Install

git clone https://github.com/milanp93/trading-agent
cd trading-agent
python -m venv venv && source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Fill in .env with your keys

Run (paper mode — no keys needed for trading)

# Start agent
source venv/bin/activate
nohup python agent/main.py >> logs/agent_stdout.log 2>&1 &
echo $! > logs/agent.pid

# Start dashboard
nohup python dashboard/server.py >> logs/dashboard.log 2>&1 &
# Open http://localhost:8765

# Stop agent (triggers dead man's switch)
kill $(cat logs/agent.pid)

Run demo script (shows full pipeline in one shot)

python scripts/demo_run.py

Safety Model

Control Implementation
Paper-first TRADING_MODE=paper default — no real money at risk
Signed intents Every order has EIP-712 TradeIntent before execution
RiskRouter On-chain approval required — max $500/trade, 10/hr, 5% drawdown
Least-privilege keys API key has only query + order permissions (no withdrawal)
Circuit breaker Halts all trading if daily loss > 2%
Dead man's switch Cancels open orders on SIGTERM/SIGINT
Trailing stop Locks profits at +0.8%, exits if drops 0.5% from peak
Sell cooldown 5-minute cooldown prevents immediate re-buy after selling
Trend filter EMA 20/50 — blocks buying in downtrends
Deterministic logs NDJSON audit trail of 5,000+ events
On-chain checkpoints 708 attestations on ValidationRegistry

Tech Stack

Layer Choice
Agent Python 3.14
Trading krakenfx/kraken-cli (subprocess, -o json)
EIP-712 signing eth-account
ERC-8004 web3.py
On-chain network Ethereum Sepolia (chain ID 11155111)
Dashboard Plain HTML + Chart.js (no build step)
Logging NDJSON

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages