Skip to content

kahwaipd/trendtrader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

25 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

TrendTrader - Hyperliquid Trading Agent with Technical Analysis

A sophisticated ACP (Agent Communication Protocol) seller that provides AI-powered trading services on Hyperliquid. TrendTrader combines technical analysis with risk management to execute optimal trades.

Features

  • Technical Analysis Integration: RSI, MACD, EMA, SMA, Bollinger Bands, Stochastic Oscillator
  • Automated Position Management: Smart entry and exit based on TA signals
  • Risk Management: Configurable leverage, position sizing, and stop-loss mechanisms
  • Multi-timeframe Analysis: 1m to 1d chart analysis
  • Real-time Market Data: Live Hyperliquid price feeds and order book
  • ACP Integration: Seamless job execution through Virtuals Protocol ACP
  • Audit Trail: Complete trade logging and performance tracking

Quick Start

1. Setup Environment

# Clone repository
git clone <repository-url>
cd trendtrader

# Install dependencies
npm install

# Configure environment
cp .env.example .env
# Edit .env with your keys:
# - HYPERLIQUID_PRIVATE_KEY
# - LITE_AGENT_API_KEY (from ACP setup)

2. Initialize

# Setup trading accounts
npm run setup

# Register ACP offerings
npm run offering:create

3. Start Services

# Development
npm run dev

# Production (PM2)
pm2 start \"npx tsx seller/runtime/seller.ts\" --name trendtrader

Architecture

Core Components

  • Trading Engine (src/hyperliquid/): Direct Hyperliquid API integration
  • Technical Analysis (src/indicators/): Multi-indicator signal generation
  • User Management (src/users/): Subaccount creation and management
  • Risk Management: Position sizing, leverage limits, drawdown protection
  • Audit System (src/audit/): Trade logging and performance metrics

ACP Integration

  • Seller Runtime (seller/runtime/seller.ts): WebSocket connection to ACP
  • Offerings (seller/offerings/): Available trading services
  • Job Execution: Async trade execution with status updates

Trading Services

Available Offerings (Jobs)

  • open_position_ta - Open leveraged positions with TA analysis ($0.03)
  • close_position_ta - Close positions with optimal timing ($0.03)
  • cancel_order - Cancel pending orders ($0.01)
  • set_order_price - Modify order prices ($0.01)
  • transfer_to_perps - Move funds to perpetuals account ($0.01)
  • check_deposit_status - Check deposit confirmations ($0.01)
  • withdraw - Withdraw funds from account ($0.01)

Data Resources (Free)

  • get_my_account - Account balances and margin info
  • get_positions - Current open positions
  • get_order_status - Order execution status
  • get_trade_history - Historical trade data
  • list_ta_indicators - Available technical indicators

Technical Analysis

TrendTrader employs multiple indicators for signal generation:

  • RSI: Identifies overbought/oversold conditions
  • MACD: Trend momentum and crossover signals
  • EMA/SMA: Moving average trend detection
  • Bollinger Bands: Volatility and mean reversion
  • Stochastic: Price momentum within ranges

Risk Management

  • Position Sizing: Automatic sizing based on account balance
  • Leverage Limits: Configurable maximum leverage (default 20x)
  • Stop Loss: Dynamic stops based on volatility
  • Drawdown Protection: Account preservation mechanisms

Configuration

Key environment variables:

HYPERLIQUID_PRIVATE_KEY=0x...        # Trading wallet private key
LITE_AGENT_API_KEY=acp-...           # ACP authentication
HYPERLIQUID_TESTNET=false            # false for mainnet

Monitoring

Performance Tracking

  • Real-time P&L monitoring
  • Win rate statistics
  • Risk-adjusted returns
  • Maximum drawdown tracking

Logging

  • Trade execution logs
  • Technical analysis signals
  • Risk management decisions
  • Error handling and recovery

Security

  • Private keys encrypted at rest
  • Subaccount isolation
  • Rate limiting and circuit breakers
  • Audit trail for all operations

πŸ“Š ACP Resources Usage Guide

TrendTrader exposes 5 data resources through the ACP system for retrieving trading data and account information. These resources are free to use and provide real-time data.

πŸ”§ Prerequisites

# Ensure ACP skill is set up
cd ~/.openclaw/workspace/virtuals-protocol-acp
npm run acp -- whoami  # Verify your ACP buyer setup

Available Resources

1. πŸ“‹ get_my_account - Account Information

Get comprehensive account status, balances, and margin information.

npm run acp -- resource get_my_account --seller-id 1686

Returns:

  • Account value and available balance
  • Total notional positions
  • Margin used and withdrawable amounts
  • Account type and wallet addresses
  • Cross margin summary

2. πŸ“ˆ get_positions - Current Open Positions

View all current open positions with P&L, leverage, and risk metrics.

npm run acp -- resource get_positions --seller-id 1686

Returns:

  • Position details (symbol, size, entry price)
  • Current P&L (realized and unrealized)
  • Leverage and margin utilization
  • Liquidation prices
  • Position-specific risk metrics

3. πŸ“‹ get_order_status - Check Order Status

Monitor order execution status, fills, and order book information.

npm run acp -- resource get_order_status --seller-id 1686

Returns:

  • Recent order history
  • Order IDs and execution status
  • Fill prices and quantities
  • Order timestamps
  • Fill rate statistics

4. πŸ“Š get_trade_history - Historical Trades

Retrieve complete trading history with P&L analysis.

npm run acp -- resource get_trade_history --seller-id 1686

Returns:

  • Chronological trade history
  • Trade details (symbol, side, price, size)
  • Individual trade P&L
  • Fee information
  • Volume and performance statistics

5. πŸ“‰ list_ta_indicators - Technical Analysis Tools

Get available technical analysis indicators and their descriptions.

npm run acp -- resource list_ta_indicators --seller-id 1686

Returns:

  • Available TA indicators (RSI, MACD, EMA, SMA, BB, STOCH)
  • Indicator descriptions and use cases
  • Supported timeframes
  • Usage in trading strategies

πŸ”§ Command Reference

Basic Syntax:

npm run acp -- resource <resource_name> --seller-id 1686 [--params '{\"key\":\"value\"}']

TrendTrader Seller ID: 1686

Example Usage:

# Get account information
npm run acp -- resource get_my_account --seller-id 1686

# Check current positions
npm run acp -- resource get_positions --seller-id 1686

# View recent orders
npm run acp -- resource get_order_status --seller-id 1686

# Get trade history
npm run acp -- resource get_trade_history --seller-id 1686

# List available indicators
npm run acp -- resource list_ta_indicators --seller-id 1686

πŸ“‘ HTTP API Access

TrendTrader also provides HTTP endpoints for direct API access:

# Health check
curl https://trendtrader.ts.net/health

# Service status
curl https://trendtrader.ts.net/status

# Account info (requires wallet address)
curl \"https://trendtrader.ts.net/account?walletAddress=0x...\"

# Current positions
curl \"https://trendtrader.ts.net/positions?walletAddress=0x...\"

# Trade history
curl \"https://trendtrader.ts.net/trades?walletAddress=0x...&limit=50\"

# Available indicators
curl https://trendtrader.ts.net/indicators

πŸ’‘ Integration Tips

  1. Real-time Monitoring: Use resources for live data monitoring
  2. Pre-trade Analysis: Check account status before submitting trading jobs
  3. Post-trade Verification: Verify position opening/closing with get_positions
  4. Performance Tracking: Use get_trade_history for backtesting analysis
  5. Risk Management: Monitor margin usage and position sizes
  6. Automation: Combine resources with trading jobs for complete workflow

πŸ€– Example Trading Workflow

# 1. Check account status
npm run acp -- resource get_my_account --seller-id 1686

# 2. Verify no conflicting positions
npm run acp -- resource get_positions --seller-id 1686

# 3. Submit trading job
npm run acp -- buy open_position_ta --seller-id 1686 --params '{\"symbol\":\"ETH\",\"side\":\"long\",\"leverage\":2,\"amount_usd\":100}'

# 4. Monitor execution
npm run acp -- resource get_order_status --seller-id 1686

# 5. Check new position
npm run acp -- resource get_positions --seller-id 1686

# 6. Review trade history
npm run acp -- resource get_trade_history --seller-id 1686

🐍 Python Client Example

Here's a simple Python client for interacting with TrendTrader's HTTP API:

import requests
import json
from typing import Dict, List, Optional

class TrendTraderClient:
    \"\"\"Simple Python client for TrendTrader HTTP API\"\"\"
    
    def __init__(self, base_url: str = \"https://trendtrader.ts.net\"):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json',
            'User-Agent': 'TrendTrader-Python-Client/1.0'
        })
    
    def health_check(self) -> Dict:
        \"\"\"Check if TrendTrader service is healthy\"\"\"
        response = self.session.get(f\"{self.base_url}/health\")
        response.raise_for_status()
        return response.json()
    
    def get_status(self) -> Dict:
        \"\"\"Get TrendTrader service status and configuration\"\"\"
        response = self.session.get(f\"{self.base_url}/status\")
        response.raise_for_status()
        return response.json()
    
    def get_account(self, wallet_address: str) -> Dict:
        \"\"\"Get account information for a wallet address\"\"\"
        params = {'walletAddress': wallet_address}
        response = self.session.get(f\"{self.base_url}/account\", params=params)
        response.raise_for_status()
        return response.json()
    
    def get_positions(self, wallet_address: str) -> List[Dict]:
        \"\"\"Get current open positions for a wallet address\"\"\"
        params = {'walletAddress': wallet_address}
        response = self.session.get(f\"{self.base_url}/positions\", params=params)
        response.raise_for_status()
        return response.json()['data']
    
    def get_trades(self, wallet_address: str, limit: int = 50) -> List[Dict]:
        \"\"\"Get trade history for a wallet address\"\"\"
        params = {'walletAddress': wallet_address, 'limit': limit}
        response = self.session.get(f\"{self.base_url}/trades\", params=params)
        response.raise_for_status()
        return response.json()['data']
    
    def get_indicators(self) -> List[Dict]:
        \"\"\"Get available technical indicators\"\"\"
        response = self.session.get(f\"{self.base_url}/indicators\")
        response.raise_for_status()
        return response.json()['data']
    
    def print_account_summary(self, wallet_address: str):
        \"\"\"Print a formatted account summary\"\"\"
        try:
            account = self.get_account(wallet_address)
            positions = self.get_positions(wallet_address)
            
            print(\"\\nπŸ“Š TrendTrader Account Summary\")
            print(\"=\" * 40)
            print(f\"πŸ’° Account Value: ${account['data']['marginSummary']['accountValue']}\")
            print(f\"πŸ’Έ Available: ${account['data']['withdrawable']}\")
            print(f\"πŸ”’ Margin Used: ${account['data']['marginUsed']}\")
            print(f\"πŸ“ˆ Open Positions: {len(positions)}\")
            
            if positions:
                print(\"\\nπŸ“ˆ Current Positions:\")
                for pos in positions:
                    pnl_color = \"🟒\" if float(pos['pnl']) >= 0 else \"πŸ”΄\"
                    print(f\"  {pnl_color} {pos['coin']} {pos['side']}: {pos['szi']} @ ${pos['entryPx']} (P&L: ${pos['pnl']})\")
            else:
                print(\"\\nπŸ“ˆ No open positions\")
                
        except requests.RequestException as e:
            print(f\"❌ Error fetching account data: {e}\")

# Usage Examples
if __name__ == \"__main__\":
    # Initialize client
    client = TrendTraderClient()
    
    # Health check
    try:
        health = client.health_check()
        print(f\"βœ… TrendTrader Status: {health['status']}\")
        print(f\"⏰ Uptime: {health['uptime']} seconds\")
    except requests.RequestException as e:
        print(f\"❌ Health check failed: {e}\")
        exit(1)
    
    # Example wallet address (replace with actual address)
    wallet_address = \"0x742d35Cc6645C0532Cfb0d3D6BB3a5Be8Cc5a7E4\"
    
    # Get account summary
    client.print_account_summary(wallet_address)
    
    # Get available indicators
    try:
        indicators = client.get_indicators()
        print(f\"\\nπŸ“Š Available Indicators: {len(indicators)}\")
        for indicator in indicators:
            print(f\"  πŸ“ˆ {indicator['name']}: {indicator['description']}\")
    except requests.RequestException as e:
        print(f\"❌ Error fetching indicators: {e}\")
    
    # Get recent trades
    try:
        trades = client.get_trades(wallet_address, limit=5)
        if trades:
            print(f\"\\nπŸ“Š Recent Trades ({len(trades)}):\")
            for trade in trades:
                side_emoji = \"πŸ“ˆ\" if trade['side'] == 'B' else \"πŸ“‰\"
                print(f\"  {side_emoji} {trade['coin']}: {trade['sz']} @ ${trade['px']} (Fee: ${trade['fee']})\")
        else:
            print(\"\\nπŸ“Š No recent trades found\")
    except requests.RequestException as e:
        print(f\"❌ Error fetching trades: {e}\")

πŸ“¦ Installation & Setup

# Install required Python packages
pip install requests

# Save the client code as trendtrader_client.py
# Update the wallet_address with your actual address

# Run the example
python trendtrader_client.py

πŸ”§ Advanced Usage

# Monitor positions with automatic refresh
import time

client = TrendTraderClient()
wallet = \"0x742d35Cc6645C0532Cfb0d3D6BB3a5Be8Cc5a7E4\"

while True:
    try:
        positions = client.get_positions(wallet)
        if positions:
            total_pnl = sum(float(pos['pnl']) for pos in positions)
            print(f\"πŸ’° Total P&L: ${total_pnl:.2f} ({len(positions)} positions)\")
        time.sleep(30)  # Check every 30 seconds
    except KeyboardInterrupt:
        break
    except Exception as e:
        print(f\"❌ Error: {e}\")
        time.sleep(5)

πŸ› Bug Reports & Issues

Found a bug or have a suggestion? We welcome community feedback to improve TrendTrader.

πŸ“‹ How to Report Issues

GitHub Repository: https://github.com/Virtual-Protocol/trendtrader

Steps to Submit:

  1. Go to Issues: Click the "Issues" tab on the GitHub repository
  2. Search First: Check if your issue already exists to avoid duplicates
  3. Create New Issue: Click "New Issue" button
  4. Provide Details: Include the information below

πŸ“ Bug Report Template

When reporting bugs, please include:

**Bug Description**
Brief summary of the issue

**Environment**
- TrendTrader API: HTTP API / ACP Resources / Trading Jobs
- URL/Endpoint: https://trendtrader.ts.net/... or ACP command
- Browser/Client: Chrome, curl, Python client, etc.
- Device: Desktop, Mobile, Server

**Steps to Reproduce**
1. Step 1
2. Step 2
3. Step 3
4. Observed issue

**Expected Behavior**
What should have happened

**Actual Behavior**
What actually happened

**Error Messages/Logs**
- HTTP response codes/messages
- Console errors
- ACP job status
- Python client exceptions

**Additional Context**
- Wallet address (if relevant): 0x...
- Trading symbol: ETH, BTC, etc.
- Position size/leverage used
- Account balance/status
- Timestamp of issue

πŸš€ Feature Request Template

For new feature suggestions:

**Feature Summary**
Brief description of the proposed feature

**Problem/Use Case**
What problem would this solve? Why is it needed?

**Proposed Solution**
How should this feature work?

**Category**
- [ ] Trading functionality (new indicators, position types)
- [ ] API endpoints (new data, better responses)
- [ ] Performance (speed, reliability)  
- [ ] Documentation (guides, examples)
- [ ] Integration (new clients, tools)
- [ ] Risk management (safety features)
- [ ] Other: ________________

**Examples**
Similar features from other platforms or detailed mockups

**Priority**
Low / Medium / High - and why

πŸ”’ Security Issues

For security vulnerabilities:

  • DO NOT create public GitHub issues for sensitive security bugs
  • Email directly: security@virtuals.io
  • Include: "TrendTrader Security" in the subject line
  • Provide: Detailed steps, impact assessment, suggested fixes
  • Allow time: For responsible disclosure and fix deployment

⚑ Common Issues & Solutions

HTTP API Issues:

  • 503/Connection errors: Check if https://trendtrader.ts.net/health returns online
  • Wallet address required: Most endpoints need ?walletAddress=0x... parameter
  • Empty responses: Verify wallet has trading history/positions
  • CORS errors: Use server-side requests, not browser fetch

ACP Resource Issues:

  • "Unknown seller ID": Use seller ID 1686 for TrendTrader
  • Authentication errors: Verify ACP buyer setup with npm run acp -- whoami
  • Timeout errors: Resources may take 10-30 seconds for complex queries
  • Empty results: Normal if no trading activity exists

Trading Job Issues:

  • Job stuck pending: Check pm2 logs with pm2 logs trendtrader
  • Insufficient balance: Verify account has enough USDC for position size
  • Invalid parameters: Check offering.json files for required params
  • Order rejections: May be due to market conditions or Hyperliquid limits

πŸ“Š Performance Issues

Include these details for performance problems:

  • Response times: How long did the request take?
  • Payload size: Large trading history requests may be slow
  • Concurrent requests: Are you making multiple simultaneous calls?
  • Network location: Geographic distance from servers
  • Rate limiting: Are you hitting API limits?

πŸ’‘ Enhancement Ideas

We're interested in suggestions for:

  • New technical indicators (VWAP, Ichimoku, custom signals)
  • Additional trading pairs beyond current offerings
  • Risk management features (stop-loss, take-profit automation)
  • Portfolio analytics (performance tracking, drawdown analysis)
  • Integration helpers (SDKs for other languages, webhook support)
  • Documentation improvements (tutorials, advanced examples)

🀝 Community Support

  • General Discussion: OpenClaw Discord
  • Live Trading Chat: Join the #trendtrader channel
  • Documentation: Check this README and inline code comments
  • Examples: See Python client and workflow examples above

⏰ Response Expectations

  • Critical trading issues: Within 24-48 hours
  • API bugs: Within 1 week
  • Feature requests: Reviewed monthly
  • Documentation: Updated as needed

Thank you for helping improve TrendTrader! Your feedback makes the trading experience better for everyone. πŸš€πŸ“ˆ


License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors