Skip to content

Repository files navigation

AI Trading Agent Template

A complete, reusable AI trading agent with:

  • On-chain identity via ERC-8004 Agent Registry (Sepolia)
  • Trade execution via Kraken REST API (paper trading supported)
  • Capital management via Hackathon Vault + Risk Router contracts
  • Cryptographic explainability via EIP-712 signed checkpoints

Any team can pick this up, swap in their own model or strategy, and run it — the identity, risk, and audit layers stay the same.


Architecture

Your Strategy (TradingStrategy interface)
       ↓
  [On-chain] RiskRouter.validateTrade()
       ↓
  [Exchange] Kraken.placeOrder()
       ↓
  [Explainability] formatExplanation() + generateCheckpoint()
       ↓
  checkpoints.jsonl  (signed audit log)

Prerequisites

  • Node.js 20+
  • Sepolia ETH (sepoliafaucet.com)
  • Infura or Alchemy Sepolia RPC URL
  • Kraken Pro account with API keys (see below)

Setup

git clone <this-repo>
cd ai-trading-agent-tutorial
npm install
cp .env.example .env
# Fill in SEPOLIA_RPC_URL, PRIVATE_KEY, KRAKEN_API_KEY, KRAKEN_API_SECRET

Kraken API key

Use Kraken Pro (kraken.com → Go to Kraken Pro). Go to Settings → API and create a key with these permissions only:

  • Funds: Query
  • Orders and trades: Query open orders & trades, Create & modify orders, Cancel & close orders

Quickstart

1. Deploy contracts

npx hardhat run scripts/deploy.ts --network sepolia

Copy all 5 addresses printed to your .env:

AGENT_REGISTRY_ADDRESS=...
HACKATHON_VAULT_ADDRESS=...
RISK_ROUTER_ADDRESS=...
REPUTATION_REGISTRY_ADDRESS=...
VALIDATION_REGISTRY_ADDRESS=...

2. Register your agent

npm run register

Copy the printed AGENT_ID to your .env:

AGENT_ID=0

3. Run the agent + dashboard

In two separate terminals:

# Terminal 1 — agent loop
npm run run-agent

# Terminal 2 — live dashboard at http://localhost:3000
npm run dashboard

You'll see output like:

[agent] Starting agent loop
[agent] agentId:  0
[agent] Pair:     XBTUSD
[agent] Interval: 30s

[agent] XBTUSD @ $66,422.6
[2026-03-27T11:02:50.000Z] HOLD XBTUSD @ $66,422.60
  Confidence: 50%
  Reason: No clear momentum (0.09% change). Holding current position.
  Market: bid=66421, ask=66421.1, spread=0.0002%, vol=2764.35

────────────────────────────────────────────────────────────────────────
CHECKPOINT — HOLD XBTUSD
  Agent:     0
  Timestamp: 2026-03-27T11:02:50.000Z
  Amount:    $0
  Price:     $66422.6
  Confidence: 50%
  Sig:       0x4f93af3b...c66c3bb31c
  Signer:    0xYourAgentWallet
────────────────────────────────────────────────────────────────────────

[agent] Checkpoint posted to ValidationRegistry: 0xa6993f19...

The agent warms up for the first 5 ticks (collecting price samples), then starts evaluating momentum. It HOLDs when price change is below the threshold (~1%), and BUYs/SELLs on clear momentum. Every decision — including HOLDs — generates a signed checkpoint posted to the ValidationRegistry on Sepolia.

You'll see live market data, trade decisions, human-readable explanations, and signed checkpoints printed to the console. Every checkpoint is appended to checkpoints.jsonl.


Swap in your own strategy

Edit src/agent/index.ts:

// Replace this:
import { MomentumStrategy } from "./strategy.js";
const strategy = new MomentumStrategy(5, 100);

// With your own:
import { MyStrategy } from "./my-strategy.js";
const strategy = new MyStrategy();

Your strategy only needs to implement one method:

interface TradingStrategy {
  analyze(data: MarketData): Promise<TradeDecision>;
}

See src/agent/strategy.ts for examples including LLM strategy stubs.


Tutorial

Step-by-step walkthrough in the tutorial/ folder:

  1. What is ERC-8004 and why does it matter?
  2. Registering your agent on-chain
  3. Connecting to Kraken API
  4. The Vault and Risk Router
  5. Building the explanation layer
  6. EIP-712 signed checkpoints
  7. Using this as a reusable template

Project structure

contracts/
  AgentRegistry.sol      # ERC-8004 agent identity registry
  HackathonVault.sol     # Capital vault with per-agent allocation
  RiskRouter.sol         # On-chain risk validation

src/
  types/index.ts         # Shared TypeScript interfaces
  agent/
    index.ts             # Main agent loop
    identity.ts          # ERC-8004 registration
    strategy.ts          # TradingStrategy interface + example strategies
  exchange/
    kraken.ts            # Kraken CLI client (paper + live)
  onchain/
    vault.ts             # Vault contract interactions
    riskRouter.ts        # RiskRouter contract interactions
  explainability/
    reasoner.ts          # Human-readable explanation formatter
    checkpoint.ts        # EIP-712 checkpoint generation + verification

scripts/
  deploy.ts              # Deploy all contracts to Sepolia
  register-agent.ts      # Register agent on-chain
  run-agent.ts           # Run the agent
  dashboard.ts           # Live web dashboard (http://localhost:3000)

Verify a checkpoint

import { verifyCheckpoint } from "./src/explainability/checkpoint.js";

const valid = verifyCheckpoint(
  checkpoint,
  process.env.AGENT_REGISTRY_ADDRESS!,
  11155111,
  process.env.EXPECTED_SIGNER_ADDRESS!
);
console.log(valid); // true

License

MIT

About

A fully on-chain AI trading agent built on Ethereum Sepolia. Features ERC-721 agent identity (ERC-8004), a capital vault, EIP-712 signed trade intents, risk validation, reputation tracking, and cryptographic audit trails for every decision. Built with Solidity, TypeScript, and Hardhat.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages