An automated trading bot system for cryptocurrency trading, focusing on the Hyperliquid exchange with support for various trading strategies and a modern web-based frontend.
- Overview
- Project Structure
- Setup
- Running the Complete Application
- Trading Strategies
- Frontend Features
- API Endpoints
- Testing Guide
- Running the Bot
- Troubleshooting
- Contributing
TRbot is a flexible and extensible trading bot framework designed for algorithmic trading on the Hyperliquid cryptocurrency exchange. The system supports multiple strategies, risk management, and portfolio tracking, all accessible through a modern web-based user interface.
Key features:
- Modern React-based frontend for bot management
- FastAPI backend with comprehensive API for bot operations
- Multiple trading strategies with dynamic loading
- Comprehensive risk management
- Real-time portfolio tracking
- Test mode for strategy validation without risking real funds
- Modular design for easy extension
trbot/
├── backend/ - Backend API and core functionality
│ ├── hyperliquid_api_test.py - FastAPI backend endpoints
│ ├── strategy_implementations.py - Trading strategy implementations
│ ├── trading_bot_manager.py - Bot lifecycle management
│ ├── trading_bot_models.py - Data models for trading bots
│ └── requirements.txt - Backend dependencies
│
├── frontend/ - React-based frontend
│ ├── public/ - Static assets
│ ├── src/ - React source code
│ │ ├── components/ - React components
│ │ │ ├── Dashboard.js - Main dashboard view
│ │ │ ├── BotList.js - Trading bot list view
│ │ │ ├── BotDetail.js - Individual bot details
│ │ │ ├── CreateBot.js - Bot creation form
│ │ │ └── Navbar.js - Navigation component
│ │ ├── services/ - API services
│ │ │ └── api.js - API client code
│ │ ├── App.js - Main application component
│ │ └── index.js - Application entry point
│ └── package.json - Frontend dependencies
│
├── config/ - Configuration files
│ └── config.yaml - Main configuration file
├── trading_bot/ - Core trading bot code
│ ├── ai/ - AI-related components
│ ├── clients/ - Exchange client implementations
│ ├── market_data/ - Market data handling
│ ├── models/ - Core models (bot, orders, etc.)
│ ├── strategies/ - Trading strategies
│ │ ├── grid_strategy.py - Grid trading strategy
│ │ ├── bete_strategy.py - Behavioral analysis strategy
│ │ ├── ai_strategy.py - AI-powered strategy
│ │ └── momentum_strategy.py - Momentum-based strategy
│ ├── tests/ - Test files
│ ├── utils/ - Utility modules
│ └── main.py - Main entry point
├── .venv/ - Project-specific virtual environment
├── logs/ - Log files
├── cache/ - Cache directory
└── README.md - This file
Follow these steps to quickly set up and run TRbot:
TRbot uses a Python virtual environment called .venv that includes all the necessary dependencies. To set up this environment:
-
Create the virtual environment:
python -m venv .venv
-
Activate the virtual environment:
# On Windows .\.venv\Scripts\activate # On macOS/Linux source .venv/bin/activate
-
Install all required dependencies:
# Install requirements pip install -r requirements.txt pip install -r backend/requirements.txt # Install additional critical dependencies pip install bcrypt # Required for password hashing # Install hyperliquid-python-sdk from GitHub (required for proper imports) pip uninstall -y hyperliquid hyperliquid-python-sdk pip install git+https://github.com/hyperliquid-dex/hyperliquid-python-sdk.git
-
When working with the project, always ensure the
.venvis activated before running any commands or scripts.
-
Create and activate a Python virtual environment:
python -m venv newenv # On Windows newenv\Scripts\activate # On macOS/Linux source newenv/bin/activate
-
Install the required dependencies:
cd backend pip install -r requirements.txt pip install bcrypt # Required for password hashing # Install hyperliquid-python-sdk from GitHub (required for proper imports) pip uninstall -y hyperliquid hyperliquid-python-sdk pip install git+https://github.com/hyperliquid-dex/hyperliquid-python-sdk.git python -m pip install --upgrade pip
-
Initialize the database:
python initialize_db.py
-
Start the backend server:
uvicorn app.main:app --reload
The server will be available at http://127.0.0.1:8000. You can access the API documentation at http://127.0.0.1:8000/docs
-
Navigate to the frontend directory:
cd frontend -
Install dependencies:
npm install -
Start the development server:
npm startThe frontend will be available at http://localhost:3000
To run the complete TRbot application:
-
Start the backend server (in one terminal):
cd backend pip install --force-reinstall git+https://github.com/hyperliquid-dex/hyperliquid-python-sdk.git uvicorn app.main:app --reload -
Start the frontend development server (in another terminal):
cd frontend npm start -
Access the application:
- Frontend UI: http://localhost:3000
- API: http://localhost:8000
- Swagger documentation: http://localhost:8000/docs
-
For production deployment, consider using:
# Backend (production mode) cd backend uvicorn app.main:app --host 0.0.0.0 --port 8000 # Frontend (build for production) cd frontend npm run build # Then serve the build directory with a static file server
The system supports multiple trading strategies that can be used individually or in combination:
A grid trading strategy that places buy and sell orders at regular intervals around a central price. The grid automatically rebalances when the price moves significantly.
Features:
- Creates a grid of price levels around the current price
- Automatically rebalances when price moves outside the grid bounds
- Generates symmetric buy and sell orders
- Configurable grid levels and width
A strategy that analyzes market behavior patterns, social volume, and funding rates to identify trading opportunities.
Features:
- Uses array-based market data for comprehensive analysis
- Analyzes price patterns and social indicators
- Generates signals with confidence scores
- Adapts to changing market conditions
An AI-powered strategy that combines technical indicators with machine learning predictions and news sentiment analysis.
Features:
- Integrates with machine learning models for price prediction
- Uses news sentiment analysis to gauge market sentiment
- Combines technical indicators with AI predictions
- Weights different signals based on configurable parameters
A momentum-based strategy that uses RSI and MACD indicators to identify directional price movements.
Features:
- Uses RSI and MACD for momentum detection
- Implements take-profit and stop-loss mechanisms
- Adapts position sizing based on market volatility (ATR)
- Automatically exits positions when momentum weakens
The frontend provides a modern and intuitive interface for managing trading bots:
- Overview of all active bots
- Quick-view performance metrics
- Market overview with price data
- Action buttons for common operations
- Create new bots with custom parameters
- List view of all bots with filtering options
- Detailed view for individual bot monitoring
- Start, stop, pause, and delete bot operations
- Configure parameters for different strategy types:
- Trend Following
- Mean Reversion
- Breakout
- Market Making
- Set risk management parameters
- Customize timeframes and trading pairs
- Real-time position tracking
- P&L monitoring
- Error logging and notifications
- Trade history visualization
The backend provides a comprehensive API for managing trading bots:
GET /bots: Get all trading botsGET /bots/{bot_id}: Get a specific bot by IDPOST /bots: Create a new trading botPUT /bots/{bot_id}: Update an existing botDELETE /bots/{bot_id}: Delete a bot
POST /bots/{bot_id}/start: Start a botPOST /bots/{bot_id}/stop: Stop a botPOST /bots/{bot_id}/pause: Pause a bot
GET /market-data/coins: Get available trading coinsGET /market-data/ticker/{coin}: Get ticker data for a coinGET /market-data/order-book/{coin}: Get order book dataGET /market-data/trades/{coin}: Get recent tradesGET /available_coins: Get all available (non-delisted) coins with their properties from Hyperliquid
GET /strategy-types: Get available strategy typesGET /timeframes: Get available timeframes
- Python 3.9 or higher
- HyperLiquid API Key with test network access
- Dependencies installed from requirements.txt
For testing purposes, TRbot includes test frameworks that allow you to validate both individual components and the complete system.
TRbot includes standalone test scripts for each trading strategy that don't depend on external modules or live exchange connections:
-
BETEStrat Test:
backend/bete_strategy_standalone_test.py- Tests behavioral analysis trading signals across various market conditions
- Simulates normal, fear, and greed market scenarios
- Validates anomaly detection and smart money tracking
-
Momentum Strategy Test:
backend/momentum_strategy_standalone_test.py- Tests momentum signal generation and execution
- Simulates multiple trading days with different market conditions
- Validates stop-loss and take-profit functionality
-
Grid Strategy Test:
backend/grid_strategy_standalone_test.py- Tests grid creation and rebalancing
- Simulates range-bound and trending markets
- Validates order creation at grid levels
To run these standalone tests:
python backend/bete_strategy_standalone_test.py
python backend/momentum_strategy_standalone_test.py
python backend/grid_strategy_standalone_test.py
These tests provide a quick way to verify strategy logic without requiring an exchange connection or the full TRbot infrastructure.
The backend is built on the FastAPI framework and integrates with the Hyperliquid exchange using their official Python SDK. The main components include:
The system uses the hyperliquid-python-sdk to interact with the Hyperliquid exchange API. This SDK provides methods for:
- Retrieving market data (asset information, prices, order books)
- Managing orders (place, cancel, modify)
- Accessing user account information and trade history
- Managing positions and leverage
The backend collects and processes several types of data:
- Market Metadata: Information about available trading pairs, tick sizes, and other market parameters
- Price Data: Current and historical price information for trading decisions
- Order Book Data: Market depth information for advanced trading strategies
- Trade History: User and market trade history for analysis
- Funding Data: Funding rates for perpetual futures
Trading strategies are implemented as modules that can be configured and swapped out. Each strategy processes market data and generates trade signals according to its algorithm.
We've created testing scripts to validate connectivity and functionality with the Hyperliquid API. These tests ensure that all required data can be retrieved and processed properly.
This script tests various Hyperliquid SDK functions and saves the results for analysis. To run it:
python -m app.scripts.hyperliquid_testThe test script performs the following operations:
- Exchange Metadata: Retrieves information about all available assets
- Mid Prices: Gets current mid prices for all assets
- Order Book: Retrieves L2 order book data for specific assets
- Trade History: Tests trade history retrieval using user_fills methods
- Funding History: Gets funding rate history with proper time parameters
- Candle Data: Retrieves OHLCV candle data for technical analysis
- Trading Operations: Explores available trading methods in the SDK
Our tests confirm that the Hyperliquid SDK is functioning correctly for all key operations:
- Successfully retrieved exchange metadata (163 assets on testnet)
- Successfully retrieved mid prices for all assets
- Successfully retrieved order book data for BTC
- Successfully retrieved trade history using user_fills methods
- Successfully retrieved funding history with proper time parameters
- Successfully retrieved candle data for technical analysis
- Successfully identified 28 trading methods in the SDK, including market orders, limit orders, and position management
All test data is saved to the ./data directory for analysis.
The backend provides a framework for implementing various trading strategies. To test specific strategies:
python -m trading_bot.tests.test_multiple_strategiesThis will run tests for all implemented strategies.
Run the following to test the connection to the Hyperliquid exchange:
python -m app.scripts.simple_hl_testThis performs a basic connectivity test and prints the results.
To test retrieval of specific data types:
# Test retrieving market data
python -c "from app.services.hyperliquid_service import HyperliquidService; service = HyperliquidService(); print(service.get_market_data('BTC'))"
# Test retrieving candle data
python -c "from app.services.hyperliquid_service import HyperliquidService; service = HyperliquidService(); print(service.get_candles('BTC', '1h', limit=5))"Run the complete trading bot in test mode:
python -m trading_bot.main --config config/config.yaml --test-mode --log-level INFOThis will:
- Load all enabled strategies
- Connect to the exchange in test mode
- Process market data
- Generate trading signals
- Simulate order execution
To test a specific strategy end-to-end:
python -m trading_bot.main --config config/config.yaml --test-mode --strategy GridStrategy --log-level INFOWhile the bot is running:
- Check the logs for any errors or warnings
- Verify that orders are being processed correctly
- Confirm that the portfolio is being tracked accurately
- Ensure that risk management rules are being applied
python -m trading_bot.main --config config/config.yaml --test-modeWarning: Only proceed to production mode after thorough testing.
python -m trading_bot.main --config config/config.yaml--config: Path to configuration file (default: config/config.yaml)--log-level: Set logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)--test-mode: Run in test mode (no real trades)--strategy: Run a specific strategy only
-
API Connection Problems
- Check your API keys
- Ensure network connectivity
- Verify the API URL in your configuration
-
Strategy Not Running
- Check if the strategy is enabled in the configuration
- Verify that the strategy type is correct
- Look for import errors in the logs
-
Order Execution Issues
- Check exchange limits and minimums
- Verify account balance
- Look for execution errors in the logs
For more detailed information, run the bot with debug logging:
python -m trading_bot.main --config config/config.yaml --test-mode --log-level DEBUGLogs are stored in the logs directory. Review these for any errors or warnings.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request