Skip to content

deepload/trBot_pl

Repository files navigation

TRbot Trading Bot

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.

Table of Contents

Overview

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

Project Structure

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

Setup

Quick Installation Guide

Follow these steps to quickly set up and run TRbot:

Using .venv

TRbot uses a Python virtual environment called .venv that includes all the necessary dependencies. To set up this environment:

  1. Create the virtual environment:

    python -m venv .venv
  2. Activate the virtual environment:

    # On Windows
    .\.venv\Scripts\activate
    
    # On macOS/Linux
    source .venv/bin/activate
  3. 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
  4. When working with the project, always ensure the .venv is activated before running any commands or scripts.

Backend Setup

  1. Create and activate a Python virtual environment:

    python -m venv newenv
    # On Windows
    newenv\Scripts\activate
    # On macOS/Linux
    source newenv/bin/activate
  2. 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
  3. Initialize the database:

    python initialize_db.py
  4. 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

Frontend Setup

  1. Navigate to the frontend directory:

    cd frontend
    
  2. Install dependencies:

    npm install
    
  3. Start the development server:

    npm start
    

    The frontend will be available at http://localhost:3000

Running the Complete Application

To run the complete TRbot application:

  1. 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
    
  2. Start the frontend development server (in another terminal):

    cd frontend
    npm start
    
  3. Access the application:

  4. 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
    

Trading Strategies

The system supports multiple trading strategies that can be used individually or in combination:

Grid Strategy

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

BETEStrat (Behavioral Analysis Strategy)

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

AI Strategy

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

Momentum Strategy

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

Frontend Features

The frontend provides a modern and intuitive interface for managing trading bots:

Dashboard

  • Overview of all active bots
  • Quick-view performance metrics
  • Market overview with price data
  • Action buttons for common operations

Bot Management

  • 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

Strategy Configuration

  • Configure parameters for different strategy types:
    • Trend Following
    • Mean Reversion
    • Breakout
    • Market Making
  • Set risk management parameters
  • Customize timeframes and trading pairs

Bot Monitoring

  • Real-time position tracking
  • P&L monitoring
  • Error logging and notifications
  • Trade history visualization

API Endpoints

The backend provides a comprehensive API for managing trading bots:

Bot Management

  • GET /bots: Get all trading bots
  • GET /bots/{bot_id}: Get a specific bot by ID
  • POST /bots: Create a new trading bot
  • PUT /bots/{bot_id}: Update an existing bot
  • DELETE /bots/{bot_id}: Delete a bot

Bot Control

  • POST /bots/{bot_id}/start: Start a bot
  • POST /bots/{bot_id}/stop: Stop a bot
  • POST /bots/{bot_id}/pause: Pause a bot

Market Data

  • GET /market-data/coins: Get available trading coins
  • GET /market-data/ticker/{coin}: Get ticker data for a coin
  • GET /market-data/order-book/{coin}: Get order book data
  • GET /market-data/trades/{coin}: Get recent trades
  • GET /available_coins: Get all available (non-delisted) coins with their properties from Hyperliquid

Strategy Information

  • GET /strategy-types: Get available strategy types
  • GET /timeframes: Get available timeframes

Testing Guide

Prerequisites

  • Python 3.9 or higher
  • HyperLiquid API Key with test network access
  • Dependencies installed from requirements.txt

Testing Environment Setup

For testing purposes, TRbot includes test frameworks that allow you to validate both individual components and the complete system.

Standalone Strategy Tests

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.

Backend Components

The backend is built on the FastAPI framework and integrates with the Hyperliquid exchange using their official Python SDK. The main components include:

1. Hyperliquid SDK Integration

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

2. Data Collection and Processing

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

3. Strategy Implementation

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.

Testing Backend with Hyperliquid SDK

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.

Testing with hyperliquid_test.py

This script tests various Hyperliquid SDK functions and saves the results for analysis. To run it:

python -m app.scripts.hyperliquid_test

The test script performs the following operations:

  1. Exchange Metadata: Retrieves information about all available assets
  2. Mid Prices: Gets current mid prices for all assets
  3. Order Book: Retrieves L2 order book data for specific assets
  4. Trade History: Tests trade history retrieval using user_fills methods
  5. Funding History: Gets funding rate history with proper time parameters
  6. Candle Data: Retrieves OHLCV candle data for technical analysis
  7. Trading Operations: Explores available trading methods in the SDK

Test Results

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.

Implementing Trading Strategies

The backend provides a framework for implementing various trading strategies. To test specific strategies:

python -m trading_bot.tests.test_multiple_strategies

This will run tests for all implemented strategies.

Testing Individual Components

1. Test Hyperliquid API Connection

Run the following to test the connection to the Hyperliquid exchange:

python -m app.scripts.simple_hl_test

This performs a basic connectivity test and prints the results.

2. Test Data Retrieval

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))"

End-to-End Testing

1. Full Bot Test in Test Mode

Run the complete trading bot in test mode:

python -m trading_bot.main --config config/config.yaml --test-mode --log-level INFO

This will:

  • Load all enabled strategies
  • Connect to the exchange in test mode
  • Process market data
  • Generate trading signals
  • Simulate order execution

2. Test a Specific Strategy

To test a specific strategy end-to-end:

python -m trading_bot.main --config config/config.yaml --test-mode --strategy GridStrategy --log-level INFO

3. Monitor and Validate

While 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

Running the Bot

Test Mode (Recommended for Initial Setup)

python -m trading_bot.main --config config/config.yaml --test-mode

Production Mode

Warning: Only proceed to production mode after thorough testing.

python -m trading_bot.main --config config/config.yaml

Command Line Options

  • --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

Troubleshooting

Common Issues

  1. API Connection Problems

    • Check your API keys
    • Ensure network connectivity
    • Verify the API URL in your configuration
  2. 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
  3. Order Execution Issues

    • Check exchange limits and minimums
    • Verify account balance
    • Look for execution errors in the logs

Debug Mode

For more detailed information, run the bot with debug logging:

python -m trading_bot.main --config config/config.yaml --test-mode --log-level DEBUG

Log Analysis

Logs are stored in the logs directory. Review these for any errors or warnings.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published