{"id":47936653,"url":"https://github.com/tangle-network/ai-trading-blueprint","last_synced_at":"2026-05-29T11:00:40.519Z","repository":{"id":338758886,"uuid":"1159021875","full_name":"tangle-network/ai-trading-blueprint","owner":"tangle-network","description":null,"archived":false,"fork":false,"pushed_at":"2026-05-28T14:19:50.000Z","size":5736,"stargazers_count":1,"open_issues_count":13,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-28T16:13:26.369Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tangle-network.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":"audit.toml","citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-16T08:04:51.000Z","updated_at":"2026-05-28T14:22:31.000Z","dependencies_parsed_at":null,"dependency_job_id":"3cc4f89f-025f-4aa8-9ef2-5e15da8874f7","html_url":"https://github.com/tangle-network/ai-trading-blueprint","commit_stats":null,"previous_names":["tangle-network/ai-trading-blueprint"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/tangle-network/ai-trading-blueprint","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangle-network%2Fai-trading-blueprint","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangle-network%2Fai-trading-blueprint/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangle-network%2Fai-trading-blueprint/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangle-network%2Fai-trading-blueprint/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tangle-network","download_url":"https://codeload.github.com/tangle-network/ai-trading-blueprint/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangle-network%2Fai-trading-blueprint/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33648534,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-05-29T02:00:06.066Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-04T07:44:32.185Z","updated_at":"2026-05-29T11:00:40.512Z","avatar_url":"https://github.com/tangle-network.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AI Trading Blueprints\n\nSelf-improving autonomous trading agents with decentralized risk validation, built on [Tangle Network](https://tangle.tools).\n\nAgents trade across 10 DeFi protocols (Hyperliquid perps, Uniswap, Polymarket, Aave, GMX, etc.) with a three-tier security model: per-trade validator signatures for untrusted operators, pre-approved trading envelopes for instant execution, and self-operated mode for trusted operators. The same strategy config drives backtesting, paper trading, and live execution.\n\n## Architecture\n\n```\n                    ┌─────────────────────────────────────┐\n                    │         SELF-IMPROVING LOOP          │\n                    │                                       │\n  Candle data ──→ StrategyRunner ──→ TradeSignal           │\n                       │                 │                  │\n               ┌───────┴──────┐    ┌─────┴──────┐         │\n               │ Advisory     │    │ Auto-exec   │         │\n               │ (agent       │    │ (bracket    │         │\n               │  decides)    │    │  orders)    │         │\n               └───────┬──────┘    └─────┬──────┘         │\n                       │                 │                  │\n                Trade records + execution quality           │\n                       │                                    │\n              evolve-strategy.js ──→ mutate HarnessConfig  │\n                       │                                    │\n              POST /strategy/config ──→ runner updates     │\n                       └────────────────────────────────────┘\n\n  Validation trust:\n    PerTrade    → validator EIP-712 sigs per trade (5-30s)\n    Envelope    → pre-approved bounds, instant execution\n    SelfOperated → local policy only, no external validation\n```\n\nSee [ARCHITECTURE.md](./ARCHITECTURE.md) for full system diagrams.\n\n## Deployment Models\n\n| Model | Binary | Bots | Vault Creation | Use Case |\n|-------|--------|------|----------------|----------|\n| **Cloud Fleet** | `trading-blueprint-bin` | Multi-bot, shared HTTP API | On-chain `JOB_PROVISION` | Scalable operator fleets |\n| **Instance** | `trading-instance-blueprint-bin` | Single dedicated bot | Service init vault + operator API provision | Per-subscription bots |\n| **TEE Instance** | `trading-tee-instance-blueprint-bin` | Single bot + hardware isolation | Service init vault + operator API provision | Sensitive strategies in enclave |\n\n## Runtime Backend Selection\n\nTrading provision requests can select runtime backend via:\n\n- `strategy_config_json.runtime_backend = \"docker\" | \"firecracker\" | \"tee\"`\n\nOperator mapping:\n\n- The provision handler maps this to sandbox metadata (`metadata_json.runtime_backend`).\n- `firecracker` currently follows the sandbox-runtime Firecracker gate:\n  it returns a clear validation error until provider wiring is enabled.\n- `tee` is intended for confidential runtime selection; TEE instance blueprints pin this mode by default.\n\n## Supported Protocols\n\n| Adapter | Type | Operations |\n|---------|------|------------|\n| **Hyperliquid** | Perpetuals | Native L1 API: market/limit/stop-loss/take-profit/bracket orders, leverage, positions |\n| **Uniswap V3** | DEX | Token swaps (exact in/out) |\n| **Aave V3** | Lending | Supply, borrow, repay, withdraw |\n| **GMX v2** | Perpetuals | Leveraged long/short |\n| **Morpho** | Lending | Optimized lending rates |\n| **Vertex** | Perpetuals | Perp trading |\n| **Polymarket** | Prediction | On-chain CTF + off-chain CLOB orders |\n| **Aerodrome** | DEX | Base L2 swaps |\n| **TWAP** | Execution | Time-weighted average price |\n| **Stat Arb** | Execution | Cross-venue statistical arbitrage |\n\n## Strategy Packs\n\nModular AI prompt packs compose protocol adapters into trading strategies:\n\n| Pack | Providers | Default Cron | Max Turns |\n|------|-----------|-------------|-----------|\n| `prediction` | Polymarket, Coingecko | Every 15 min | 20 |\n| `dex` | Uniswap V3, Coingecko | Every 5 min | 12 |\n| `yield` | Aave V3, Morpho, Coingecko | Every 15 min | 10 |\n| `perp` | GMX v2, Hyperliquid, Vertex, Coingecko | Every 2 min | 15 |\n| `volatility` | 6 providers | Every 10 min | 12 |\n| `mm` | Polymarket, Hyperliquid, Uniswap V3, Coingecko | Every 1 min | 15 |\n| `multi` | All 8 providers | Every 5 min | 20 |\n\n## Security Model\n\nThree-tier validation trust, set per bot at provision time:\n\n| Trust Level | Who | Validation | Latency |\n|-------------|-----|-----------|---------|\n| **PerTrade** | Untrusted operators | Validator EIP-712 signatures per trade | 5-30s |\n| **Envelope** | Depositor-approved strategy | Pre-approved bounds, instant within | ~0ms |\n| **SelfOperated** | Self-hosted operators | Local policy only (envelope still enforced) | ~0ms |\n\n**Trading Envelope** — operators approve a policy surface (allowed assets, max position size, leverage cap, total exposure limit, drawdown threshold, SL distance range). Trades within the envelope execute instantly. Cancels always instant. The exact entry/exit within the envelope is unpredictable — prevents front-running.\n\n**On-Chain Guards** — `PolicyEngine` enforces token whitelists, position caps, leverage limits, rate limiting. `TradeValidator` verifies m-of-n EIP-712 signatures (minimum 2-of-2 floor). Intent deduplication prevents replay.\n\n**Fund Safety** — position ledger survives restarts, startup reconciliation detects orphaned positions, SIGTERM handler emergency-closes all open positions, retry with exponential backoff on API failures.\n\n**Security Audit** — 3 harden rounds, 12 CRITICALs + 8 HIGHs fixed, 429 Forge fuzz tests including adversarial scenarios (donation attacks, cross-vault NAV manipulation, score averaging, lockup bypass).\n\n## Project Structure\n\n### Rust Workspace (10 crates)\n\n| Crate | Role |\n|-------|------|\n| `trading-runtime` | Core types, protocol adapters, trade executor, validator client, market data |\n| `trading-http-api` | REST API consumed by AI agent sidecars (port 9100) |\n| `trading-blueprint-lib` | Tangle blueprint jobs, workflow orchestration, sidecar lifecycle |\n| `trading-blueprint-bin` | Operator binary — processes Tangle jobs, manages sidecars, runs HTTP API |\n| `trading-validator-lib` | Validator server, policy evaluation, AI scoring, EIP-712 signing |\n| `trading-validator-bin` | Validator binary — runs standalone validator nodes |\n| `trading-instance-blueprint-lib` | Single-bot-per-service variant (simplified, no multi-bot routing) |\n| `trading-instance-blueprint-bin` | Instance operator binary |\n| `trading-tee-instance-blueprint-lib` | TEE-secured instance variant (Phala/Nitro/GCP/Azure enclaves) |\n| `trading-tee-instance-blueprint-bin` | TEE instance operator binary |\n\n### Solidity Contracts\n\n| Contract | Purpose |\n|----------|---------|\n| `TradingBlueprint.sol` | Tangle blueprint — vault deployment, job handlers, operator roles |\n| `TradingVault.sol` | ERC-7575 vault — trade execution with policy + signature checks |\n| `VaultFactory.sol` | Deploys vault instances with configured policies and validators |\n| `PolicyEngine.sol` | Per-vault risk policies (whitelists, limits, rate limiting) |\n| `TradeValidator.sol` | EIP-712 signature verification, m-of-n multisig enforcement |\n| `FeeDistributor.sol` | Fee collection and distribution (30% validators, 70% operators) |\n| `VaultShare.sol` | ERC-20 share token for vault depositors |\n\n### Arena Frontend\n\nReact 19 + React Router v7 + UnoCSS web app for managing bots, vaults, and provisioning.\n\n- Bot dashboard with real-time metrics and trade history\n- Multi-step provisioning workflow\n- Vault deposit/withdrawal interface with collateral management\n- Terminal integration for sidecar logs\n- Web3 wallet connection (wagmi + ConnectKit)\n\n## Getting Started\n\n### Prerequisites\n\n- **Rust** 1.80+\n- **Foundry** (forge, anvil, cast)\n- **Docker** with `blueprint-sidecar:all-harness` image\n- **Node.js** 20+ with pnpm\n\n### Build\n\n```bash\n# Rust workspace\ncargo build --workspace\n\n# Solidity contracts\ncd contracts \u0026\u0026 forge build\n\n# Arena frontend\ncd arena \u0026\u0026 pnpm install\n```\n\n### Local Development\n\n```bash\n# Option A: cargo tangle harness (recommended)\ncargo tangle harness up   # boots anvil, deploys contracts, runs operator\n\n# Option B: manual\nanvil --host 0.0.0.0\n./scripts/deploy-local.sh\ncargo run --release -p trading-blueprint-bin\n\n# Validator nodes (separate terminals)\ncargo run --release -p trading-validator-bin\n\n# Frontend\ncd arena \u0026\u0026 pnpm dev\n```\n\n### Deploy to Hetzner (production)\n\n```bash\n./deploy/go-live-base-sepolia.sh \u003cserver-ip\u003e \u003coperator-private-key\u003e\n```\n\nUses the Blueprint Manager (`cargo tangle blueprint run`), not the raw binary. Supports N service instances per BPM.\nThe default Base Sepolia `tnt-core` manifest is committed at\n`deploy/manifests/base-sepolia/tnt-core.latest.json`, so operators do not need a\nmatching sibling checkout. Override with `TNT_CORE_DEPLOYMENT_MANIFEST=/path/to/manifest.json`\nwhen targeting a different deployment snapshot.\n\n### Base Sepolia Operator Prep\n\nFresh protocol deploys come from `tnt-core`, not this repo. This repo carries a\ncommitted Base Sepolia manifest snapshot for the latest known-good deployment.\nLoad protocol addresses from that file by default, or point at another manifest\nexplicitly:\n\n```bash\nsource ./scripts/load-base-sepolia-env.sh\n\n# or\nsource ./scripts/load-base-sepolia-env.sh /path/to/tnt-core-manifest.json\n```\n\nThat exports the current:\n\n- `TANGLE_CONTRACT`\n- `STAKING_CONTRACT` for the staking or `MultiAssetDelegation` contract\n- `STATUS_REGISTRY_CONTRACT`\n- `STATUS_REGISTRY_ADDRESS` for the operator heartbeat path\n- `HTTP_RPC_URL=https://sepolia.base.org`\n- `WS_RPC_URL=wss://base-sepolia-rpc.publicnode.com`\n- `CHAIN_ID=84532`\n\nThen set the blueprint-specific IDs from your own service deployment:\n\n```bash\nexport BLUEPRINT_ID=\u003ctrading blueprint id\u003e\nexport SERVICE_ID=\u003cservice instance id\u003e\n```\n\nFor local operator runs, keep secrets in an untracked root `settings.env` and use the tracked template as the starting point:\n\n```bash\ncp settings.env.example settings.env\n```\n\nFill in only the local-only values you need, such as AI API keys, operator identity, or a custom `SESSION_AUTH_SECRET`. The repo ignores `settings.env`; only `settings.env.example` is meant to be committed.\n\nPricing engine launch:\n\n```bash\n./scripts/run-pricing-engine.sh --config scripts/operator1.toml\n```\n\nUse `STAKING_CONTRACT` as the contract name throughout the operator and deployment flow.\n\n### Testing\n\n```bash\n# Solidity (429 tests including adversarial fuzz)\ncd contracts \u0026\u0026 forge test\n\n# Rust unit tests (481 tests)\ncargo test -p trading-runtime --lib          # 310 tests\ncargo test -p trading-http-api --lib         # 16 tests\ncargo test -p trading-blueprint-lib --lib    # 99 tests\ncargo test -p trading-validator-lib --lib    # 56 tests\n\n# Integration tests\ncargo test -p trading-runtime --test new_signals_integration      # 9 signal type tests\ncargo test -p trading-runtime --test backtest_runner_equivalence  # backtest↔live equivalence\n\n# Hyperliquid E2E (requires funded testnet account)\nHYPERLIQUID_E2E=1 EXECUTOR_PRIVATE_KEY=0x... \\\n  cargo test -p trading-runtime --test hyperliquid_e2e -- --nocapture\n\n# Full E2E with Docker sidecars\nSIDECAR_E2E=1 cargo test -p trading-blueprint-lib --test tangle_e2e_full\n```\n\n**Total: 928 tests (429 Forge + 499 Rust), 0 failures.**\n\n## Operator API\n\nOperators authenticate via EIP-191 challenge-response to receive PASETO session tokens.\n\n```\nPOST /api/auth/challenge    → { message, nonce, expires_at }\nPOST /api/auth/session      → { token }  (sign message, submit signature)\n```\n\nProtected endpoints (require `Authorization: Bearer \u003ctoken\u003e`):\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| GET | `/api/bots` | List all bots |\n| GET | `/api/bots/{id}` | Bot details |\n| GET | `/api/bots/{id}/trades` | Trade history |\n| GET | `/api/bots/{id}/metrics` | Performance metrics |\n| POST | `/api/bots/{id}/secrets` | Inject secrets (two-phase activation) |\n| POST | `/api/bots/{id}/start` | Start trading |\n| POST | `/api/bots/{id}/stop` | Stop trading |\n| POST | `/api/bots/{id}/run-now` | Trigger immediate tick |\n| PATCH | `/api/bots/{id}/config` | Update configuration |\n| DELETE | `/api/bots/{id}/secrets` | Clear secrets |\n\n## Trading HTTP API\n\nREST API on port 9100, consumed by AI agents running inside sidecars:\n\n| Endpoint | Purpose |\n|----------|---------|\n| `POST /market-data/prices` | Aggregated price feeds |\n| `POST /portfolio/state` | Current holdings and positions |\n| `POST /circuit-breaker/check` | Risk limit enforcement |\n| `POST /validate` | Trade intent validation (fans out to validator committee) |\n| `POST /execute` | Trade execution (routes to vault, HL, or CLOB based on target_protocol) |\n| **Hyperliquid** | |\n| `POST /hyperliquid/order` | Place any order type (market/limit/stop/TP) |\n| `POST /hyperliquid/bracket` | Entry + stop-loss + take-profit grouped |\n| `POST /hyperliquid/cancel` | Cancel order |\n| `POST /hyperliquid/leverage` | Set leverage (cross/isolated) |\n| `GET /hyperliquid/account` | Positions, margin, open orders |\n| `GET /hyperliquid/prices` | Mid prices for all HL perp markets |\n| `GET/PUT /hyperliquid/envelope` | View/update trading envelope |\n| **Strategy Runner** | |\n| `POST /strategy/tick` | Feed candle, get entry/exit signals (optional auto-execute) |\n| `POST /strategy/config` | Update harness config (from evolve-strategy.js) |\n| `GET /strategy/state` | Current runner state (harness version, rules) |\n| **Collateral** | |\n| `GET /collateral/status` | CLOB collateral status |\n| `POST /collateral/release` | Release vault funds for off-chain CLOB trading |\n| `POST /collateral/return` | Return CLOB funds to vault |\n\n## Self-Improving Strategy Loop\n\nThe meta-harness automatically evolves trading strategies through backtesting:\n\n1. **Backtest** — `HarnessConfig` defines entry/exit rules evaluated against historical candles\n2. **Paper trade** — same config drives the `StrategyRunner` against live market data\n3. **Live trade** — same config, real money, via `/strategy/tick` with `target_protocol`\n4. **Evaluate** — execution quality metrics (slippage, fill time) + decision traces\n5. **Evolve** — `evolve-strategy.js` mutates config, backtests variants, promotes winners\n6. **Guard** — walk-forward validation blocks configs that overfit in-sample data\n\n### Signal Types (13)\n\n| Category | Signals |\n|----------|---------|\n| Momentum | RSI, MACD, PriceMomentum |\n| Trend | EMA Cross, SMA Cross |\n| Volatility | Bollinger Bands, ATR Breakout |\n| Volume | Volume Surge, OBV, VWAP |\n| Market Structure | FundingRate, FundingRateSpread, MeanReversion |\n\nThe agent can combine any signals with weighted conditions. The meta-harness discovers which combinations work.\n\n## License\n\nSee [LICENSE](./LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftangle-network%2Fai-trading-blueprint","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftangle-network%2Fai-trading-blueprint","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftangle-network%2Fai-trading-blueprint/lists"}