AJ Traders - Mastra Trading Agent System

A comprehensive multi-platform cryptocurrency trading system built with the Mastra framework, featuring specialized agents for centralized and decentralized exchanges, intelligent portfolio management, risk assessment, and automated trading recommendations.

šŸš€ Overview

This project demonstrates advanced Mastra agent architecture with specialized trading agents for different platforms. Each agent is optimized for its specific trading environment while sharing common risk management and validation tools.

šŸ—ļø Architecture

Specialized Trading Agents

  1. Recall Trading Agent (src/mastra/agents/recall_trading_agent.ts)

    • Specialized for Recall centralized exchange (CEX)
    • Advanced order types and margin trading
    • High liquidity and tight spreads
    • Professional trading interface integration
  2. Hyperliquid Trading Agent (src/mastra/agents/hyperliquid_trading_agent.ts)

    • Specialized for Hyperliquid decentralized exchange (DEX)
    • Non-custodial trading and on-chain settlement
    • DeFi-native features and composability
    • Transparent orderbook and MEV protection
  3. Agent Template (src/mastra/agents/agent_template.ts)

    • Blueprint for creating new specialized agents
    • Best practices and architectural patterns
    • Applied examples: recall_trading_agent.ts, hyperliquid_trading_agent.ts

Core Workflow & Tools

  1. Trading Workflow (src/mastra/workflows/trading-workflow.ts)

    • Multi-step workflow orchestration
    • Context gathering → Plan generation → Validation → Formatting
    • Comprehensive risk assessment and validation
    • Platform-agnostic workflow design
  2. Validation Tools (src/mastra/tools/plan-validation-tool.ts)

    • Portfolio plan validation against risk constraints
    • Position sizing and leverage checks
    • Safety buffer enforcement
    • Cross-platform risk management
  3. Platform-Specific Tools

    • Recall Tool (src/mastra/tools/recall_tool.ts): CEX portfolio management and execution
    • Hyperliquid Tool (src/mastra/tools/hyperliquid-tool.ts): DEX trading and on-chain operations
    • CoinGecko API Tool (src/mastra/tools/coingecko-API_tool.ts): Shared market data across platforms

šŸ“‹ Features

Multi-Platform Trading System

  • Platform Specialization: Dedicated agents for CEX and DEX environments
  • Clean Architecture: No platform mixing - each agent focuses on its strengths
  • Template-Based Development: Easy to extend with new platform agents
  • Shared Risk Management: Consistent validation across all platforms

Recall Trading Agent (CEX)

  • Professional Trading: Advanced order types, margin, and leverage
  • High Liquidity: Access to deep orderbooks and tight spreads
  • Fiat Integration: On/off ramps and traditional banking features
  • Institutional Features: Portfolio analytics and advanced charting

Hyperliquid Trading Agent (DEX)

  • Self-Custody: Non-custodial trading with full control of assets
  • On-Chain Transparency: All trades visible and verifiable on-chain
  • DeFi Composability: Integration with broader DeFi ecosystem
  • MEV Protection: Advanced protection against front-running

Shared Agent Capabilities

  • Structured Output: Returns validated JSON with positions to maintain, modify, or open
  • Risk Management: Enforces safety buffers, position limits, and leverage constraints
  • User Personalization: Adapts to user risk profile, preferences, and trading experience
  • Market Analysis: Integrates current prices, historical data, and market sentiment
  • Portfolio Assessment: Analyzes existing positions and suggests optimizations
  • Platform-Specific Optimization: Each agent leverages its platform's unique features

Workflow Features

  • Context Gathering: Collects user profile, portfolio state, and market conditions
  • AI-Powered Recommendations: Uses advanced LLM for trading strategy generation
  • Validation Pipeline: Multi-layer validation for risk management
  • Formatted Output: User-friendly recommendations with risk assessment

Risk Management

  • Safety Buffers: Maintains minimum 10% balance buffer
  • Position Limits: Respects user-defined maximum position sizes
  • Leverage Controls: Validates leverage against user preferences
  • Concentration Checks: Warns about over-concentration in single assets

šŸ› ļø Installation

  1. Clone and Install Dependencies

     1git clone <your-repo>
     2cd AJ_Traders
     3npm install
  2. Environment Setup Create a .env file with required API keys:

     1COINGECKO_API_KEY=your_coingecko_api_key
     2RECALL_API_KEY=your_recall_api_key
     3GOOGLE_GENERATIVE_AI_API_KEY=your_google_ai_key
     4HYPERLIQUID_PRIVATE_KEY=your_wallet_private_key_for_hyperliquid
  3. Database Setup The agent uses LibSQL for memory storage. The database file will be created automatically.

šŸŽÆ Usage

Recall Trading Agent (CEX)

 1import { recallTradingAgent } from './src/mastra/agents/recall_trading_agent';
 2
 3const response = await recallTradingAgent.stream([
 4  {
 5    role: 'user',
 6    content: `
 7      Portfolio State:
 8      - Available Balance: $50,000
 9      - Current Positions: BTC long $20,000, ETH short $15,000
10      
11      User Profile:
12      - Risk Level: Moderate
13      - Mission: Accumulate ETH
14      - Experience: Intermediate
15      
16      Please provide Recall-specific trading recommendations.
17    `
18  }
19]);
20
21// Stream the response
22for await (const chunk of response.textStream) {
23  console.log(chunk);
24}

Hyperliquid Trading Agent (DEX)

 1import { hyperliquidTradingAgent } from './src/mastra/agents/hyperliquid_trading_agent';
 2
 3const response = await hyperliquidTradingAgent.stream([
 4  {
 5    role: 'user',
 6    content: `
 7      Wallet: 0x1234...
 8      Available Balance: $25,000
 9      
10      User Profile:
11      - Risk Level: High
12      - DeFi Experience: Advanced
13      - Self-custody preferred
14      
15      Please analyze and suggest Hyperliquid DEX positions.
16    `
17  }
18]);

Trading Workflow (Platform Agnostic)

 1import { tradingWorkflow } from './src/mastra/workflows/trading-workflow';
 2
 3// Execute workflow with user query
 4const result = await tradingWorkflow.execute({
 5  user_query: "Analyze my portfolio and suggest optimizations",
 6  user_wallet: "0x1234..." // Optional wallet address
 7});
 8
 9console.log(result.formatted_recommendations);

Creating New Specialized Agents

 1// Use agent_template.ts as your starting point
 2import { createTemplateAgent } from './src/mastra/agents/agent_template';
 3
 4// Follow the pattern established by recall_trading_agent.ts and hyperliquid_trading_agent.ts
 5// 1. Focus on single platform/domain
 6// 2. Import platform-specific tools only
 7// 3. Add platform-specific instructions
 8// 4. Register in src/mastra/index.ts

šŸ“Š Output Format

The agent returns structured JSON recommendations:

 1{
 2  "positions_to_maintain": [
 3    {
 4      "market": "BTC",
 5      "direction": "long",
 6      "size": 15000,
 7      "reasoning": ["Strong uptrend intact", "Portfolio diversification"],
 8      "leverage": 3
 9    }
10  ],
11  "positions_to_modify": [
12    {
13      "market": "ETH",
14      "direction": "long",
15      "size": 12000,
16      "reasoning": ["Flip short to align with accumulation goal"],
17      "leverage": 5
18    }
19  ],
20  "positions_to_open": [
21    {
22      "market": "SOL",
23      "direction": "long", 
24      "size": 8000,
25      "reasoning": ["Technical breakout", "Good risk-reward setup"],
26      "leverage": 4
27    }
28  ]
29}

šŸ”§ Development

Running the Development Server

npm run dev

Building for Production

 1npm run build
 2npm start

Project Structure

 1src/mastra/
 2ā”œā”€ā”€ agents/
 3│   ā”œā”€ā”€ agent_template.ts         # šŸ“‹ Blueprint for creating new agents
 4│   ā”œā”€ā”€ recall_trading_agent.ts   # šŸ¦ CEX trading specialist (Recall)
 5│   └── hyperliquid_trading_agent.ts # šŸ”— DEX trading specialist (Hyperliquid)
 6ā”œā”€ā”€ workflows/
 7│   └── trading-workflow.ts       # Trading workflow orchestration
 8ā”œā”€ā”€ tools/
 9│   ā”œā”€ā”€ coingecko-API_tool.ts     # Shared market data integration
10│   ā”œā”€ā”€ recall_tool.ts            # Recall CEX-specific tools
11│   ā”œā”€ā”€ hyperliquid-tool.ts       # Hyperliquid DEX-specific tools
12│   └── plan-validation-tool.ts   # Shared risk validation
13ā”œā”€ā”€ index.ts                      # Mastra configuration and agent registration
14└── mcp.ts                       # Model Context Protocol setup

šŸ›ļø Agent Architecture Principles

Template-Based Development

  • agent_template.ts: Comprehensive blueprint showing best practices
  • Applied Examples: Each specialized agent demonstrates focused implementation
  • Clean Separation: No platform mixing - each agent has clear boundaries
  • Extensible Design: Easy to add new platforms following established patterns

Platform Specialization Benefits

  • Optimized Instructions: Each agent speaks the language of its platform
  • Focused Tools: Platform-specific tools without unnecessary complexity
  • User Clarity: Users know exactly which agent handles their preferred platform
  • Maintainable Code: Changes to one platform don't affect others

šŸŽ›ļø Configuration

User Profile Schema

 1{
 2  risk_level: string,              // Risk tolerance description
 3  token_preferences: string,       // Preferred cryptocurrencies
 4  mission_statement: string,       // Trading objectives
 5  trading_experience: "beginner" | "intermediate" | "advanced",
 6  max_position_size_pct: number,   // Max position size (% of portfolio)
 7  preferred_leverage: number       // Preferred leverage multiplier
 8}

Risk Management Parameters

  • Minimum Order Size: $10 USD
  • Safety Buffer: 10-15% of available balance
  • Maximum Leverage: Configurable per user
  • Concentration Limits: Warns at >40% single asset exposure

šŸ” Advanced Features

Validation Pipeline

The plan-validation-tool provides comprehensive validation:

  • Size Validation: Ensures positions meet minimum thresholds
  • Buffer Enforcement: Maintains required safety margins
  • Leverage Checks: Validates against user preferences
  • Concentration Analysis: Identifies portfolio risks

Market Data Integration

  • Real-time Prices: CoinGecko API for current market data across platforms
  • Platform-Specific APIs: Direct integration with Recall and Hyperliquid
  • Historical Analysis: Multi-timeframe price analysis for context
  • Cross-Platform Data: Shared market intelligence across specialized agents
  • Trade Execution: Platform-specific quote and execution capabilities

Memory and Context

  • Persistent Memory: LibSQL storage for conversation history across agents
  • Context Awareness: Each agent maintains platform-specific preferences
  • Shared Validation: Common risk management across all platforms
  • Adaptive Learning: Improves recommendations based on platform-specific feedback

🚨 Risk Disclaimers

  • This is a multi-platform trading system template for educational purposes
  • Cryptocurrency trading involves substantial risk of loss on all platforms
  • CEX and DEX trading have different risk profiles - understand each platform
  • Always conduct your own research before making trading decisions
  • The agents' recommendations should not be considered financial advice
  • Self-custody (DEX) requires additional security considerations

šŸ¤ Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Implement your changes
  4. Add tests for new functionality
  5. Submit a pull request

šŸ“„ License

This project is licensed under the ISC License - see the LICENSE file for details.

šŸ†˜ Support

For questions about Mastra framework:

For issues with this template:

  • Open an issue in this repository
  • Check existing issues for solutions

šŸ”® Future Enhancements

Platform Expansion

  • Additional CEX integrations (Binance, Coinbase Pro, Kraken)
  • More DEX protocols (Uniswap, dYdX, GMX)
  • Cross-chain DEX support
  • Arbitrage agents between platforms

Advanced Features

  • Multi-exchange portfolio aggregation
  • Advanced technical analysis indicators
  • Backtesting capabilities across platforms
  • Real-time market notifications
  • Social sentiment analysis integration

DeFi & Yield

  • Yield farming agent
  • Liquidity provision strategies
  • DeFi protocol integration beyond trading
  • Cross-platform yield optimization

AI & ML

  • Portfolio optimization algorithms
  • Machine learning-based predictions
  • Pattern recognition across platforms
  • Adaptive risk management

Built with ā¤ļø using Mastra - The TypeScript AI Framework

šŸŽ­ Agent Examples

This repository showcases two distinct agent implementation patterns:

1. Platform-Specific Trading Agents

  • recallTradingAgent: CEX specialist with advanced order management
  • hyperliquidTradingAgent: DEX specialist with on-chain focus

2. Template Blueprint

  • agent_template.ts: Complete guide for building new agents

Each demonstrates different aspects of Mastra agent development, from template blueprints to complex financial decision-making systems.