Skip to content

Diedelaview/AJ_Traders

Repository files navigation

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

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

    COINGECKO_API_KEY=your_coingecko_api_key
    RECALL_API_KEY=your_recall_api_key
    GOOGLE_GENERATIVE_AI_API_KEY=your_google_ai_key
    HYPERLIQUID_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)

import { recallTradingAgent } from './src/mastra/agents/recall_trading_agent';

const response = await recallTradingAgent.stream([
  {
    role: 'user',
    content: `
      Portfolio State:
      - Available Balance: $50,000
      - Current Positions: BTC long $20,000, ETH short $15,000
      
      User Profile:
      - Risk Level: Moderate
      - Mission: Accumulate ETH
      - Experience: Intermediate
      
      Please provide Recall-specific trading recommendations.
    `
  }
]);

// Stream the response
for await (const chunk of response.textStream) {
  console.log(chunk);
}

Hyperliquid Trading Agent (DEX)

import { hyperliquidTradingAgent } from './src/mastra/agents/hyperliquid_trading_agent';

const response = await hyperliquidTradingAgent.stream([
  {
    role: 'user',
    content: `
      Wallet: 0x1234...
      Available Balance: $25,000
      
      User Profile:
      - Risk Level: High
      - DeFi Experience: Advanced
      - Self-custody preferred
      
      Please analyze and suggest Hyperliquid DEX positions.
    `
  }
]);

Trading Workflow (Platform Agnostic)

import { tradingWorkflow } from './src/mastra/workflows/trading-workflow';

// Execute workflow with user query
const result = await tradingWorkflow.execute({
  user_query: "Analyze my portfolio and suggest optimizations",
  user_wallet: "0x1234..." // Optional wallet address
});

console.log(result.formatted_recommendations);

Creating New Specialized Agents

// Use agent_template.ts as your starting point
import { createTemplateAgent } from './src/mastra/agents/agent_template';

// Follow the pattern established by recall_trading_agent.ts and hyperliquid_trading_agent.ts
// 1. Focus on single platform/domain
// 2. Import platform-specific tools only
// 3. Add platform-specific instructions
// 4. Register in src/mastra/index.ts

📊 Output Format

The agent returns structured JSON recommendations:

{
  "positions_to_maintain": [
    {
      "market": "BTC",
      "direction": "long",
      "size": 15000,
      "reasoning": ["Strong uptrend intact", "Portfolio diversification"],
      "leverage": 3
    }
  ],
  "positions_to_modify": [
    {
      "market": "ETH",
      "direction": "long",
      "size": 12000,
      "reasoning": ["Flip short to align with accumulation goal"],
      "leverage": 5
    }
  ],
  "positions_to_open": [
    {
      "market": "SOL",
      "direction": "long", 
      "size": 8000,
      "reasoning": ["Technical breakout", "Good risk-reward setup"],
      "leverage": 4
    }
  ]
}

🔧 Development

Running the Development Server

npm run dev

Building for Production

npm run build
npm start

Project Structure

src/mastra/
├── agents/
│   ├── agent_template.ts         # 📋 Blueprint for creating new agents
│   ├── recall_trading_agent.ts   # 🏦 CEX trading specialist (Recall)
│   └── hyperliquid_trading_agent.ts # 🔗 DEX trading specialist (Hyperliquid)
├── workflows/
│   └── trading-workflow.ts       # Trading workflow orchestration
├── tools/
│   ├── coingecko-API_tool.ts     # Shared market data integration
│   ├── recall_tool.ts            # Recall CEX-specific tools
│   ├── hyperliquid-tool.ts       # Hyperliquid DEX-specific tools
│   └── plan-validation-tool.ts   # Shared risk validation
├── index.ts                      # Mastra configuration and agent registration
└── 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

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

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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors