Building Autonomous Crypto Trading Bots with ElizaOS: A Complete Technical Guide

Justin Olivier

How we built a fully autonomous AI trading agent that analyzes market data, processes news sentiment, and executes trades automatically—all while running in a secure trusted execution environment.

The Challenge: From Manual Trading to Autonomous Intelligence

Cryptocurrency markets never sleep. While traditional traders struggle with 24/7 monitoring, emotional decision-making, and information overload, the future belongs to autonomous agents that can process vast amounts of data and execute trades with machine precision.

At Etherwave Labs, we've been exploring how AI agents can revolutionize decentralized finance (DeFAI). Our latest proof of concept demonstrates something remarkable: a fully autonomous trading bot powered by ElizaOS that combines large language models with real-time market analysis.

This isn't just another trading script—it's an intelligent agent that reads crypto news, analyzes technical indicators, makes strategic decisions, and executes trades automatically. Here's how we built it.

What is ElizaOS? The Foundation of Autonomous Agents

ElizaOS represents a breakthrough in AI agent development. Incubated by a16z, this open-source framework enables developers to build AI-powered autonomous agents that can analyze, plan, and act in complex environments.

The framework's power lies in its modular architecture:

  • LLM Integration: Supports GPT-4, Claude, LLaMA, and other models via Ollama
  • Plugin System: Extensible Actions and Providers for custom functionality
  • Multi-Environment: Can operate across web, blockchain, and third-party APIs
  • Autonomous Decision Making: Agents can process context and make independent choices

Our Trading Bot: Intelligence Meets Execution

Our proof of concept demonstrates an ElizaOS agent that operates as a complete trading system:

  • Market Data Analysis: Fetches real-time prices, technical indicators (MACD, RSI), and sentiment data
  • News Processing: Analyzes crypto news from CoinDesk to gauge market sentiment
  • Strategic Decision Making: Uses LLM reasoning to determine long, short, or wait positions
  • Automated Execution: Places orders automatically on Hyperliquid exchange
  • Risk Management: Monitors portfolio balance and open positions

The entire system operates autonomously, with the LLM serving as the "brain" that processes all inputs and makes trading decisions.

Technical Implementation: Building the Trading Agent

Prerequisites and Environment Setup

Before diving into development, ensure you have the required tools:

environment setup
Required tools before starting development

Essential Environment Variables:

.env
# Trading platform credentials
HYPERLIQUID_PRIVKEY=your_private_key_here

# AI model configuration  
OLLAMA_EMBEDDING_MODEL=nomic-embed-text

# Market data APIs
COINGECKO_API_KEY=your_coingecko_api_key
COINDESK_API_KEY=your_coindesk_api_key
TAAPI_API_KEY=your_taapi_api_key

Quick Start Installation:

# Step 1: Initialize the embedding server ollama pull nomic-embed-text && ollama serve # Step 2: Clone and setup the project git clone https://github.com/etherwave-labs/ai-agent-playground.git cd ai-agent-playground/trading-ai bun install && bun run dev # Step 3: Start the trading scheduler (executes every 15 minutes) cd ../workflowTradingAi bun run workflow.ts

Plugin Architecture: The Building Blocks

ElizaOS's plugin system allows us to extend the agent's capabilities through two types of components:

project architecture
ElizaOS project architecture

1. Actions: What the Agent Can Do

Market Operations:

  • placeOrder.ts: Executes trades via Hyperliquid API with proper risk management
  • log.ts: Records all LLM decision-making processes for audit trails
  • rag.ts: Maintains historical trade records (legacy implementation)

2. Providers: Information Sources

Market Data Providers:

  • fetchBTCPrice.ts: Real-time Bitcoin spot prices and 7-day historical data via CoinGecko
  • getDataMarket.ts: Technical analysis indicators (RSI, MACD) from TAAPI.io
  • fetchNewsCoindesk.ts: Cryptocurrency news sentiment analysis from CoinDesk

Portfolio Management Providers:

  • getBalanceHyperLiquid.ts: Real-time wallet balance using EIP-712 signatures
  • getOpenOrder.ts: Active trading positions monitoring
  • getPnL.ts: Profit/loss tracking across multiple timeframes (1d, 1w, 1m, all-time)

Creating Custom Plugins: Extending Agent Capabilities

The modular design makes it straightforward to add new functionality. Here's how to build custom components:

Example Provider - Market Data:

bitcoinPriceProvider.ts
import { Provider } from 'elizaos'

export const btcPriceProvider: Provider = {
  name: 'btc-price',
  description: 'Fetches current BTC spot price from CoinGecko',
  position: 2, // Execution priority
  get: async () => {
    const apiKey = process.env.COINGECKO_API_KEY
    const response = await fetch(
      `https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&x_cg_pro_api_key=${apiKey}`
    )
    const { bitcoin } = await response.json()
    
    return { 
      price: bitcoin.usd,
      timestamp: Date.now(),
      source: 'coingecko'
    }
  },
}

Example Action - Order Execution:

placeOrderAction.ts
import { Action } from 'elizaos'

export const placeOrderAction: Action = {
  name: 'PLACE_ORDER',
  description: 'Executes trading orders on Hyperliquid exchange',
  handler: async (runtime, message, state, parameters, callback) => {
    try {
      // Validate order parameters
      const { side, size, price, symbol } = parameters
      
      // Execute trade via Hyperliquid API
      const transactionId = await hyperLiquid.placeOrder({
        side,
        size, 
        price,
        symbol,
        timestamp: Date.now()
      })
      
      // Confirm execution
      await callback({ 
        text: `Order executed successfully. Transaction ID: ${transactionId}`, 
        actions: ['PLACE_ORDER'] 
      })
      
      return true
    } catch (error) {
      console.error('Order execution failed:', error)
      return false
    }
  }
}

Integration Steps:

  • Create your plugin file in the src/plugins/ directory
  • Export the Provider or Action object with proper typing
  • Register the plugin in index.ts configuration

The Decision Engine: How AI Makes Trading Choices

The agent's decision-making process combines multiple data sources into a coherent trading strategy:

Data Synthesis Process

  • Market Technical Analysis: RSI and MACD indicators provide momentum and trend signals
  • News Sentiment Analysis: CoinDesk articles are processed for bullish/bearish sentiment
  • Price Action Context: Current price compared to recent highs/lows and support/resistance levels
  • Risk Assessment: Portfolio balance, open positions, and historical performance

Sentiment Scoring Algorithm

The agent converts all inputs into a unified sentiment score (0-100%):

sentiment algo
Decision making process with market sentiment score

LLM Decision Process

The language model receives structured context including:

  • Current market sentiment score
  • Technical indicator readings
  • Recent news analysis summary
  • Portfolio status and risk metrics
  • Historical performance data

The LLM then reasons through the data and makes a strategic decision, which gets passed to the PLACE_ORDER action for execution.

Advanced Security: Trusted Execution Environment (TEE) Integration

For production trading bots handling real funds, security becomes paramount. We've explored Trusted Execution Environment (TEE) protection using Intel SGX to ensure code and data remain secure even in compromised environments.

Why TEE Matters for Trading Bots

  • Hardware-level isolation: Code runs in encrypted enclaves
  • Tamper resistance: Even kernel-level attacks cannot access secrets
  • Confidential computing: Private keys and trading logic remain encrypted
  • Remote attestation: Cryptographic proof of code integrity

Implementation with Gramine and Azure

Step 1: Containerization

dockerfile
FROM ubuntu:22.04

# Install system dependencies
RUN apt-get update && apt-get install -y curl git build-essential

# Install Bun runtime
RUN curl -fsSL https://bun.sh/install | bash

# Install Ollama for local LLM inference
RUN curl -L https://ollama.com/download/linux | tar -xz && \
    mv ollama /usr/local/bin

WORKDIR /app
COPY . .
RUN bun install --production

# Entry point for the trading agent
CMD ["bun", "run", "workflow.ts"]

Step 2: SGX Enclave Generation

# Create manifest for Gramine SGX gramine-manifest -Dlog_level=error Dockerfile.manifest # Sign the enclave with your SGX key gramine-sgx-sign \ --manifest Dockerfile.manifest \ --output Dockerfile.sig \ --key sgx.key # Extract MRENCLAVE and MRSIGNER for attestation gramine-sgx-get-token --output enclave.token

Step 3: Azure Confidential Computing Deployment

# Create SGX-enabled VM on Azure az vm create \ --resource-group rg-trading-bot \ --name trading-bot-sgx \ --image Canonical:0001-com-ubuntu-confidential-vm-focal:22_04-lts-cvm:latest \ --size Standard_DC4s_v3 \ --admin-username azureuser \ --generate-ssh-keys \ --enable-sgx

Step 4: Secure Key Management

# Encrypt sensitive environment variables az keyvault secret set \ --vault-name trading-bot-vault \ --name hyperliquid-privkey \ --value "encrypted_private_key" # Keys are only decrypted inside the verified enclave gramine-sgx-get-quote -m Dockerfile.manifest -o attestation.bin

Alternative: Zero-Knowledge Proofs with Risc0

For scenarios requiring cryptographic proof of execution without hardware dependencies, consider Risc0 zkVM:

guest_main
#[no_mangle] 
pub extern "C" fn guest_main() {
    let market_data: MarketData = env::read();
    let trading_decision = analyze_market(market_data);
    env::commit(&trading_decision);
}

This approach generates zero-knowledge proofs of correct execution, providing cryptographic guarantees that trades were made according to predetermined logic.

Key Learnings

What Worked Well:

  • LLM reasoning provided nuanced market interpretation
  • Multi-source data fusion improved decision accuracy
  • Automated execution eliminated emotional trading
  • TEE implementation ensured security compliance

Areas for Improvement:

  • Market volatility occasionally triggered false signals
  • News sentiment analysis needs refinement for crypto-specific terminology
  • Risk management could be more sophisticated

Conclusion

This project demonstrates that the convergence of AI and blockchain technology can create truly autonomous financial agents. By combining ElizaOS's flexible framework with advanced security measures like TEE, we've built a system that can:

  • Process Information faster than human traders
  • Make Decisions based on comprehensive data analysis
  • Execute Trades with machine precision
  • Operate Securely in production environments
  • Scale Efficiently across multiple markets and assets

Key Takeaways for Developers

  • Start Simple: Begin with basic market data and simple strategies
  • Security First: Implement proper key management and execution environment security
  • Test Extensively: Backtest thoroughly before deploying real capital
  • Monitor Continuously: Automated doesn't mean unmonitored
  • Iterate Rapidly: The crypto market evolves quickly—so should your strategies

The Broader Impact

Autonomous trading agents represent just the beginning of DeFAI, AI-powered DeFi. As these systems mature, we'll likely see:

  • Democratized Access: Sophisticated trading strategies available to retail users
  • Reduced Market Inefficiencies: AI agents will quickly arbitrage price differences
  • New Financial Products: Hybrid AI-DeFi protocols we haven't yet imagined
  • Enhanced Market Stability: Reduced emotional trading and improved price discovery

The tools and techniques demonstrated here provide a foundation for the next generation of decentralized financial applications. At Etherwave Labs, we're excited to continue pushing the boundaries of what's possible when AI meets blockchain technology.

References

ElizaOS – GitHub: https://github.com/elizaOS/eliza

Bun Runtime: https://bun.com

Ollama – nomic‑embed‑text: https://ollama.com/library/nomic-embed-text

Hyperliquid API: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api

CoinGecko API: https://docs.coingecko.com/reference/introduction

CoinDesk News API: https://developers.coindesk.com/documentation/data-api/news

TAAPI.io: https://taapi.io

Gramine SGX: https://gramine.readthedocs.io

Risc0 zkVM: https://github.com/risc0/risc0

About Etherwave Labs

Etherwave Labs is a blockchain development agency and venture building company specializing in Web3 innovations. We help businesses leverage cutting-edge technologies like AI agents, DeFi protocols, and zero-knowledge proofs to build the future of decentralized applications.

Connect with us:

  • Website: etherwavelabs.com
  • Follow our latest research and development updates
  • Explore partnership opportunities for your Web3 projects

Ready to build your own autonomous trading system? Contact our team for consultation and custom development services.

More articles

Secure Ethereum Sign-In with Next.js: A Step-by-Step Guide Using WalletConnect's AppKit

Discover how to implement Sign In With Ethereum (SIWE) in your Next.js app using WalletConnect's AppKit. Learn to secure API routes with next-auth tokens, enhancing user authentication and control over digital identity. Boost your dApp's security and user experience today!

Read more

Building Autonomous Crypto Trading Bots with ElizaOS: A Complete Technical Guide

Learn how to build autonomous AI trading bots using ElizaOS framework. Complete guide covering market analysis, decision algorithms, secure deployment with TEE, and real-world implementation. Built by blockchain experts at Etherwave Labs.

Read more

Ready to take your project to the next level?

Contact us today to discuss how we can help you achieve your goals in the blockchain space.