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.
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.
- 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
- User → Sends natural command via Telegram (e.g., "Open a long on ETH with $200 at 2x leverage")
- n8n → Receives message, processes it, and queries ChatGPT to interpret intent
- ChatGPT → Analyzes the message and generates structured trading parameters
- n8n → Makes API calls to the Node.js service with interpreted parameters
- Node.js → Executes transactions on GMX v2 using user's encrypted wallets
- Blockchain → Transactions are executed on Arbitrum mainnet
-
Function: Conversational interface for users
-
Features:
- Natural language understanding
- Password-based authentication
- Sessions with expiration (1 hour inactivity)
- Support for multiple trading commands
-
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
- 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
- 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.)
- Function: Persistent database for users and wallets
- Features:
- AES-256-GCM encryption for private keys
- Telegram user management
- Operation history (future)
- Custom configurations
- Natural language commands in your own language
- Intelligent intent interpretation
- Contextual responses and confirmations, it has memory of previous interactions
- AES-256-GCM encrypted wallets
- Password authentication with scrypt
- Time-limited sessions
- Private keys never stored in plaintext
- Prices from 97+ tokens via GMX oracles
- 96+ available trading markets
- Position and balance information
- Continuous updates from Arbitrum mainnet
- Market, limit, stop-loss, take-profit orders
- Token swaps
- Configurable leverage
- Full position management
- Automatic EVM wallet creation
- Balances in multiple tokens (ETH, WETH, USDC, WBTC)
- Secure transfers
- Native GMX integration
- Node.js 18+
- Docker and Docker Compose
- Git
- Telegram Bot account (get token via @BotFather)
- Clone the repository:
git clone <repository-url>
cd gmxv2-ai-agent- Install dependencies:
npm install- Configure environment variables:
cp .env.example .envEdit .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- Start services with Docker:
docker-compose up -dThis 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
- Configure database:
# Generate Prisma client
npm run db:generate
# Run migrations
npm run db:migrate- Start the API service:
npm run dev- Configure n8n:
- Access
https://n8n.your-domain.com - Import workflow from
n8n/GMX_AI_Agent_n8n_workflow.json - Configure Telegram and OpenAI credentials
- Access
/create my_secure_password
/login my_secure_password
Note: Sessions expire after 1 hour of inactivity.
"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?"
"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"
"Cancel my ETH order"
"Show all my pending orders"
-
Initial registration:
- User:
/create my_password_123 - Bot: Confirms wallet creation and address
- User:
-
Price inquiry:
- User: "How much is BTC?"
- Bot: "Current BTC price is $43,250"
-
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
-
Monitoring:
- User: "How are my positions doing?"
- Bot: Shows P&L, size, leverage, etc.
GET /health- Service health checkGET /api/gmx/network- Network and connection info
GET /api/gmx/markets- List of all GMX v2 marketsGET /api/gmx/prices- Prices of all tokens (97+)POST /api/gmx/prices- Specific token prices by addressPOST /api/gmx/prices/ticker- Prices by ticker symbolsGET /api/gmx/tickers- Available ticker symbols
GET /api/gmx/positions?id=user_id- User's open positionsGET /api/gmx/orders- Active orders (optional account filter)
POST /api/gmx/orders- Create orders (market, limit, stop-loss, take-profit, swap)DELETE /api/gmx/orders- Cancel orders
POST /api/wallet/create- Create encrypted wallet for userPOST /api/wallet/login- Verify credentialsGET /api/wallet/:id- Public wallet informationGET /api/wallet/:id/balances- Balances in ETH, WETH, USDC, WBTC
- Users: Telegram user management
- Wallets: Encrypted EVM wallet storage
# 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- AES-256-GCM encryption with unique IV per wallet
- Scrypt key derivation
- Private keys never stored in plaintext
- Balance data is public on blockchain
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
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- Define types in
src/types/gmx.types.ts - Implement logic in
src/services/ - Create routes in
src/routes/ - Update documentation
- Mainnet: Operations on Arbitrum mainnet
- Real Funds: Handles real user funds
- Encryption: Military-grade wallet protection
- Authentication: Strict credential verification
- Implement rate limiting
- Set up monitoring and alerts
- HTTPS mandatory
- Regular database backups
- Thorough transaction validation
- 1-hour sessions (configurable)
- Limited token support for balances
- Manual n8n workflow configuration required
- Fork the repository
- Create feature branch (
git checkout -b feature/new-feature) - Commit changes (
git commit -m 'Add new feature') - Push to branch (
git push origin feature/new-feature) - Open Pull request
MIT License - see LICENSE file for details.
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
Built with ❤️ for the GMX v2 ecosystem | Powered by Arbitrum mainnet 🔥
- API Examples - Complete API usage examples
- Wallet API - Detailed wallet management documentation




