Skip to content

Repository files navigation

GMX v2 AI Agent 🚀

This project was developed for GMX and Cyfrin Updraft GMX Perpetuals Trading Curriculum

A conversational interface for trading on the GMX v2 protocol on Arbitrum mainnet. This platform allows users to interact with GMX through an intelligent Telegram bot, using natural language processing to execute complex trading operations intuitively.

📋 Overview

The GMX v2 AI Agent project provides a natural language interface for trading on GMX v2 that combines multiple technologies to provide a seamless and secure user experience. Users can execute complex trading operations simply by writing natural language commands through Telegram.

Technology Stack

  • Telegram: Chat-based user interface for natural interactions
  • n8n: Orchestration layer that handles Telegram messages and integrates with ChatGPT
  • ChatGPT: Natural language understanding and command interpretation engine
  • Node.js + TypeScript + GMX SDK: Execution layer that directly interacts with the blockchain
  • PostgreSQL: Database for user and encrypted wallet management
  • Docker & Docker Compose: Containerization and orchestration for complete environment setup

Workflow

  1. User → Sends natural command via Telegram (e.g., "Open a long on ETH with $200 at 2x leverage")
  2. n8n → Receives message, processes it, and queries ChatGPT to interpret intent
  3. ChatGPT → Analyzes the message and generates structured trading parameters
  4. n8n → Makes API calls to the Node.js service with interpreted parameters
  5. Node.js → Executes transactions on GMX v2 using user's encrypted wallets
  6. Blockchain → Transactions are executed on Arbitrum mainnet

🏗️ System Architecture

Component Details

Telegram Bot

  • Function: Conversational interface for users

  • Features:

    • Natural language understanding
    • Password-based authentication
    • Sessions with expiration (1 hour inactivity)
    • Support for multiple trading commands

    Chatbot Example 1

    Chatbot Example 2

n8n (Orchestrator)

  • Function: Central coordinator of data flow

  • Features:

    • Telegram message processing
    • ChatGPT API integration
    • RESTful calls to Node.js service
    • Error handling and retries
    • Temporary state storage

    n8n Full Workflow n8n AI Agent n8n Authentication

ChatGPT (Decision Engine)

  • Function: AI for interpreting user intentions
  • Features:
    • Semantic analysis of natural language commands
    • Generation of structured trading parameters
    • Syntax and logic validation of operations
    • Contextual responses to users

Node.js API Service (Executor)

  • Function: Direct interface with GMX v2 and blockchain
  • Features:
    • RESTful API with TypeScript
    • Official GMX v2 SDK integration
    • Secure encrypted wallet management
    • Real-time price and market data
    • Multiple order execution (market, limit, stop-loss, etc.)

PostgreSQL (Storage)

  • Function: Persistent database for users and wallets
  • Features:
    • AES-256-GCM encryption for private keys
    • Telegram user management
    • Operation history (future)
    • Custom configurations

✨ Key Features

🤖 Conversational Interface

  • Natural language commands in your own language
  • Intelligent intent interpretation
  • Contextual responses and confirmations, it has memory of previous interactions

🔐 Advanced Security

  • AES-256-GCM encrypted wallets
  • Password authentication with scrypt
  • Time-limited sessions
  • Private keys never stored in plaintext

📊 Real-time Data

  • Prices from 97+ tokens via GMX oracles
  • 96+ available trading markets
  • Position and balance information
  • Continuous updates from Arbitrum mainnet

🎯 Complete Trading

  • Market, limit, stop-loss, take-profit orders
  • Token swaps
  • Configurable leverage
  • Full position management

💰 Wallet Management

  • Automatic EVM wallet creation
  • Balances in multiple tokens (ETH, WETH, USDC, WBTC)
  • Secure transfers
  • Native GMX integration

🚀 Installation and Setup

Prerequisites

  • Node.js 18+
  • Docker and Docker Compose
  • Git
  • Telegram Bot account (get token via @BotFather)

Environment Configuration

  1. Clone the repository:
git clone <repository-url>
cd gmxv2-ai-agent
  1. Install dependencies:
npm install
  1. Configure environment variables:
cp .env.example .env

Edit .env with:

# Environment Configuration for GMX v2 API Service

# Server Configuration
NODE_ENV=development
PORT=3000

# Database Configuration (PostgreSQL)
DB_HOST=localhost
DB_PORT=5432
DB_NAME=gmxv2_agent
DB_USER=gmx_user
DB_PASSWORD=your_secure_password_here
DATABASE_URL=postgresql://gmx_user:your_secure_password_here@localhost:5432/gmxv2_agent

# Docker Database Configuration (same as above for compose)
POSTGRES_DB=gmxv2_agent
POSTGRES_USER=gmx_user
POSTGRES_PASSWORD=your_secure_password_here

# Arbitrum Mainnet Network Configuration
RPC_URL=https://arb1.arbitrum.io/rpc

# Docker/Traefik Configuration (optional for local development)
SSL_EMAIL=your-email@example.com
SUBDOMAIN=gmx
DOMAIN_NAME=localhost
GENERIC_TIMEZONE=America/New_York
WEBHOOK_URL=https://your-webhook-url-here.ngrok-free.dev
  1. Start services with Docker:
docker-compose up -d

This command starts all the required infrastructure services:

  • PostgreSQL: Database for user and wallet data
  • Redis: Caching and session storage for n8n
  • n8n: Workflow automation platform
  • Traefik: Reverse proxy and SSL termination
  1. Configure database:
# Generate Prisma client
npm run db:generate

# Run migrations
npm run db:migrate
  1. Start the API service:
npm run dev
  1. Configure n8n:
    • Access https://n8n.your-domain.com
    • Import workflow from n8n/GMX_AI_Agent_n8n_workflow.json
    • Configure Telegram and OpenAI credentials

💬 Bot Usage

Authentication

/create my_secure_password
/login my_secure_password

Note: Sessions expire after 1 hour of inactivity.

Trading Commands

Information Queries

"What are my open positions?"
"What's the price of BTC?"
"What are the prices of ETH and SOL?"
"What's my balance?"
"What are my open orders?"
"What's my wallet address?"
"What's the private key of my wallet?"

Trading Operations

"Open a long on ETH with $200 at 2x leverage"
"Close my BTC short"
"Place a limit order: buy ETH at $2500"
"Swap 24 USDC for BTC"
"Swap 24 USDC for BTC at 95000"

Order Management

"Cancel my ETH order"
"Show all my pending orders"

Complete Flow Examples

  1. Initial registration:

    • User: /create my_password_123
    • Bot: Confirms wallet creation and address
  2. Price inquiry:

    • User: "How much is BTC?"
    • Bot: "Current BTC price is $43,250"
  3. Position opening:

    • User: "I want to open a long on ETH with 100 dollars at 2x"
    • Bot: Confirms parameters and executes order
    • System: Creates order on GMX v2 using encrypted wallet
  4. Monitoring:

    • User: "How are my positions doing?"
    • Bot: Shows P&L, size, leverage, etc.

📡 API Endpoints

System Information

  • GET /health - Service health check
  • GET /api/gmx/network - Network and connection info

Market Data

  • GET /api/gmx/markets - List of all GMX v2 markets
  • GET /api/gmx/prices - Prices of all tokens (97+)
  • POST /api/gmx/prices - Specific token prices by address
  • POST /api/gmx/prices/ticker - Prices by ticker symbols
  • GET /api/gmx/tickers - Available ticker symbols

Position Management

  • GET /api/gmx/positions?id=user_id - User's open positions
  • GET /api/gmx/orders - Active orders (optional account filter)

Trading Orders

  • POST /api/gmx/orders - Create orders (market, limit, stop-loss, take-profit, swap)
  • DELETE /api/gmx/orders - Cancel orders

Wallet Management

  • POST /api/wallet/create - Create encrypted wallet for user
  • POST /api/wallet/login - Verify credentials
  • GET /api/wallet/:id - Public wallet information
  • GET /api/wallet/:id/balances - Balances in ETH, WETH, USDC, WBTC

🗄️ Database

Data Model

  • Users: Telegram user management
  • Wallets: Encrypted EVM wallet storage

Management Commands

# Generate Prisma client
npm run db:generate

# Create and apply migrations
npm run db:migrate

# Open Prisma Studio (GUI)
npm run db:studio

# Reset database (⚠️ deletes all data)
npm run db:reset

Data Security

  • AES-256-GCM encryption with unique IV per wallet
  • Scrypt key derivation
  • Private keys never stored in plaintext
  • Balance data is public on blockchain

🛠️ Development

Project Structure

src/
├── index.ts              # 🚀 Main entry point
├── routes/
│   ├── gmx.routes.ts     # 🛣️ GMX endpoints
│   └── wallet.routes.ts  # 🔐 Wallet endpoints
├── services/
│   ├── gmx.service.ts    # ⚙️ GMX SDK logic
│   ├── wallet.service.ts # 🔐 Wallet management
│   └── data.service.ts   # 🗄️ Prisma operations
├── types/
│   └── gmx.types.ts      # 📝 TypeScript definitions
├── middleware/
│   └── errorHandler.ts   # 🛡️ Error handling
├── utils/
│   ├── logger.ts         # 📊 Winston logging
│   ├── database.ts       # 🗄️ DB connection
│   └── gmx.ts           # 🔧 GMX utilities
└── prisma/
    ├── schema.prisma     # 📋 Database schema
    └── migrations/       # 🔄 DB migrations

Available Scripts

npm run dev      # Development with hot reload
npm run build    # Compile for production
npm run start    # Run production build
npm run test     # Run tests
npm run lint     # Code linting

Adding New Features

  1. Define types in src/types/gmx.types.ts
  2. Implement logic in src/services/
  3. Create routes in src/routes/
  4. Update documentation

🚨 Important Considerations

Security

  • Mainnet: Operations on Arbitrum mainnet
  • Real Funds: Handles real user funds
  • Encryption: Military-grade wallet protection
  • Authentication: Strict credential verification

Production

  • Implement rate limiting
  • Set up monitoring and alerts
  • HTTPS mandatory
  • Regular database backups
  • Thorough transaction validation

Current Limitations

  • 1-hour sessions (configurable)
  • Limited token support for balances
  • Manual n8n workflow configuration required

🤝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/new-feature)
  3. Commit changes (git commit -m 'Add new feature')
  4. Push to branch (git push origin feature/new-feature)
  5. Open Pull request

📄 License

MIT License - see LICENSE file for details.

🎓 Educational Purpose

This project has been developed for educational purposes to demonstrate:

  • Integration with DeFi protocols (GMX v2)
  • Natural language processing for trading interfaces
  • Secure wallet management and encryption
  • Full-stack development with modern technologies
  • Blockchain interaction and smart contract integration

⚠️ Disclaimer: This is an educational project. Use at your own risk. Always conduct proper security audits and testing before using in production environments.


Built with ❤️ for the GMX v2 ecosystem | Powered by Arbitrum mainnet 🔥

Additional Documentation

About

🤖 AI-powered conversational trading agent for GMX v2 protocol on Arbitrum mainnet. Execute complex trades using natural language commands via Telegram bot, powered by Node.js, TypeScript, and ChatGPT.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages