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
-
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
-
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
-
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
-
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
-
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
-
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
- Recall Tool (
š 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
-
Clone and Install Dependencies
1git clone <your-repo> 2cd AJ_Traders 3npm install
-
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
-
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
- Fork the repository
- Create a feature branch
- Implement your changes
- Add tests for new functionality
- 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 managementhyperliquidTradingAgent
: 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.