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.
- 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
# 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)# Setup trading accounts
npm run setup
# Register ACP offerings
npm run offering:create# Development
npm run dev
# Production (PM2)
pm2 start \"npx tsx seller/runtime/seller.ts\" --name trendtrader- 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
- Seller Runtime (
seller/runtime/seller.ts): WebSocket connection to ACP - Offerings (
seller/offerings/): Available trading services - Job Execution: Async trade execution with status updates
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)
get_my_account- Account balances and margin infoget_positions- Current open positionsget_order_status- Order execution statusget_trade_history- Historical trade datalist_ta_indicators- Available technical indicators
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
- 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
Key environment variables:
HYPERLIQUID_PRIVATE_KEY=0x... # Trading wallet private key
LITE_AGENT_API_KEY=acp-... # ACP authentication
HYPERLIQUID_TESTNET=false # false for mainnet- Real-time P&L monitoring
- Win rate statistics
- Risk-adjusted returns
- Maximum drawdown tracking
- Trade execution logs
- Technical analysis signals
- Risk management decisions
- Error handling and recovery
- Private keys encrypted at rest
- Subaccount isolation
- Rate limiting and circuit breakers
- Audit trail for all operations
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.
# Ensure ACP skill is set up
cd ~/.openclaw/workspace/virtuals-protocol-acp
npm run acp -- whoami # Verify your ACP buyer setupGet comprehensive account status, balances, and margin information.
npm run acp -- resource get_my_account --seller-id 1686Returns:
- Account value and available balance
- Total notional positions
- Margin used and withdrawable amounts
- Account type and wallet addresses
- Cross margin summary
View all current open positions with P&L, leverage, and risk metrics.
npm run acp -- resource get_positions --seller-id 1686Returns:
- Position details (symbol, size, entry price)
- Current P&L (realized and unrealized)
- Leverage and margin utilization
- Liquidation prices
- Position-specific risk metrics
Monitor order execution status, fills, and order book information.
npm run acp -- resource get_order_status --seller-id 1686Returns:
- Recent order history
- Order IDs and execution status
- Fill prices and quantities
- Order timestamps
- Fill rate statistics
Retrieve complete trading history with P&L analysis.
npm run acp -- resource get_trade_history --seller-id 1686Returns:
- Chronological trade history
- Trade details (symbol, side, price, size)
- Individual trade P&L
- Fee information
- Volume and performance statistics
Get available technical analysis indicators and their descriptions.
npm run acp -- resource list_ta_indicators --seller-id 1686Returns:
- Available TA indicators (RSI, MACD, EMA, SMA, BB, STOCH)
- Indicator descriptions and use cases
- Supported timeframes
- Usage in trading strategies
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 1686TrendTrader 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- Real-time Monitoring: Use resources for live data monitoring
- Pre-trade Analysis: Check account status before submitting trading jobs
- Post-trade Verification: Verify position opening/closing with get_positions
- Performance Tracking: Use get_trade_history for backtesting analysis
- Risk Management: Monitor margin usage and position sizes
- Automation: Combine resources with trading jobs for complete 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 1686Here'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}\")# 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# 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)Found a bug or have a suggestion? We welcome community feedback to improve TrendTrader.
GitHub Repository: https://github.com/Virtual-Protocol/trendtrader
- Go to Issues: Click the "Issues" tab on the GitHub repository
- Search First: Check if your issue already exists to avoid duplicates
- Create New Issue: Click "New Issue" button
- Provide Details: Include the information below
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 issueFor 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 whyFor 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
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
1686for 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
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?
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)
- 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
- 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. ππ
MIT