Skip to content

A Python backtesting system for cryptocurrency trading strategies. Implements SMA crossover strategy on HYPE-USD using real market data from Hyperliquid API. Includes performance metrics, visualizations, and comprehensive analysis.

License

Notifications You must be signed in to change notification settings

puiusabin/algorithmic-trading-backtest

Repository files navigation

HYPE-USD SMA Strategy Backtester

A professional algorithmic trading backtesting system implementing a long-only Simple Moving Average (SMA) crossover strategy on HYPE-USD using real-time data from the Hyperliquid exchange API.

Python License Status


Overview

This project is a complete data science portfolio piece demonstrating:

  • Financial market data analysis with Python
  • RESTful API integration (Hyperliquid exchange)
  • Algorithmic trading strategy implementation
  • Statistical performance analysis
  • Professional data visualization
  • Clean, modular code architecture

Strategy Description

Type: Long-only SMA Crossover Strategy Asset: HYPE-USD (Hyperliquid cryptocurrency) Timeframe: 5-minute candles Indicator: 30-period Simple Moving Average (SMA) = 150 minutes

Entry Rules

  • Price crosses above the SMA after being below it
  • Opens a long position at the close price

Exit Rules

  • Minimum holding period: 12 candles (1 hour)
  • Exit when price touches the SMA again (within 0.2% threshold)
  • Closes position at the close price

Features

  • Real-time data fetching from Hyperliquid API
  • Automated SMA calculation and crossover detection
  • Comprehensive performance metrics (Sharpe ratio, win rate, max drawdown)
  • Professional multi-chart visualization
  • Trade log export to CSV
  • Configurable parameters via config.py
  • Fallback to synthetic data for testing
  • Interactive API testing utility
  • Clean terminal UI with progress indicators

Installation

Prerequisites

  • Python 3.8 or higher
  • pip package manager

Quick Start

  1. Clone the repository

    git clone https://github.com/yourusername/hype-sma-strategy.git
    cd hype-sma-strategy
  2. Install dependencies

    pip install -r requirements.txt
  3. Test API connection

    python api_test.py
  4. Run the backtest

    python hype_sma_strategy.py

Usage

Basic Usage

Run the strategy with default parameters:

python hype_sma_strategy.py

Testing API Connection

Verify Hyperliquid API connectivity and explore available markets:

python api_test.py

This utility will:

  • Test API connection
  • List all perpetual markets
  • List all spot markets
  • Fetch sample candle data for BTC and HYPE
  • Display formatted results with interactive prompts

Customizing Parameters

Edit config.py to adjust strategy settings:

# Asset and timeframe
COIN = "HYPE"          # Cryptocurrency symbol
INTERVAL = "5m"        # Candle interval
DAYS_LOOKBACK = 14     # Days of historical data

# Strategy parameters
SMA_PERIOD = 30        # SMA period (candles)
MIN_HOLD_CANDLES = 12  # Minimum hold time (candles)
SMA_TOUCH_THRESHOLD = 0.2  # Exit threshold (%)

# Display options
VERBOSE = True         # Detailed output
SAVE_PLOTS = True      # Save charts to file
SAVE_TRADE_LOG = True  # Export trades to CSV

View Current Configuration

python config.py

API Integration

Hyperliquid Exchange API

Endpoint: https://api.hyperliquid.xyz/info Method: POST Authentication: None required (public data)

Request Format

{
    "type": "candleSnapshot",
    "req": {
        "coin": "HYPE",           # Coin symbol
        "interval": "5m",          # Candle interval
        "startTime": 1234567890000,  # Unix timestamp (ms)
        "endTime": 1234567890000     # Unix timestamp (ms)
    }
}

Response Format

[
    {
        "t": 1234567890000,  # Timestamp (ms)
        "o": "20.5000",      # Open price
        "h": "20.7500",      # High price
        "l": "20.4000",      # Low price
        "c": "20.6000",      # Close price
        "v": "12345.67",     # Volume
        "n": 123             # Number of trades
    },
    ...
]

Important Notes

  • Candle Limit: API returns maximum of 5,000 most recent candles
  • Coin Format:
    • Perpetuals: Use coin name directly ("HYPE", "BTC", "ETH")
    • Spot: Use index format ("@107" for HYPE spot)
  • Time Format: Timestamps must be in milliseconds (multiply Unix timestamp by 1000)
  • Rate Limits: No official limits, but be respectful with request frequency

Sample Output

Performance Metrics

====================================================================
BACKTEST RESULTS
====================================================================

Trade Statistics:
   Total Trades:        24
   Winning Trades:      15
   Losing Trades:       9
   Win Rate:            62.50%

Returns:
   Average Return:      +1.45%
   Total Return:        +34.80%
   Best Trade:          +5.67%
   Worst Trade:         -2.34%

Risk Metrics:
   Sharpe Ratio:        1.82
   Maximum Drawdown:    -8.45%

Time Metrics:
   Avg Hold Time:       87 minutes

====================================================================

Generated Files

  • strategy_results.png - Multi-chart visualization
  • trade_log.csv - Detailed trade history

Project Structure

hype-sma-strategy/
│
├── hype_sma_strategy.py    # Main strategy implementation
├── api_test.py              # API testing utility
├── config.py                # Configuration parameters
├── requirements.txt         # Python dependencies
├── README.md                # This file
├── .gitignore               # Git ignore rules
│
└── (generated files)
    ├── strategy_results.png # Backtest visualization
    └── trade_log.csv        # Trade history export

Customization Guide

1. Change Trading Pair

Edit config.py:

COIN = "BTC"  # Trade Bitcoin instead

2. Adjust Timeframe

INTERVAL = "15m"     # Use 15-minute candles
SMA_PERIOD = 20      # Adjust SMA accordingly
MIN_HOLD_CANDLES = 8 # Adjust minimum hold time

3. Use Preset Configurations

Uncomment preset configurations in config.py:

# PRESET 2: Aggressive - Shorter SMA, shorter hold time
SMA_PERIOD = 20
MIN_HOLD_CANDLES = 6  # 30 minutes
SMA_TOUCH_THRESHOLD = 0.3

4. Enable Advanced Features

# Add trading fees and slippage
USE_FEES = True
TRADING_FEE = 0.05  # 0.05% per trade

USE_SLIPPAGE = True
SLIPPAGE = 0.1  # 0.1% slippage

Troubleshooting

Issue: "No candles returned from API"

Possible causes:

  • Coin symbol not found (check with api_test.py)
  • Too many days requested (max ~17 days for 5m candles)
  • API temporarily unavailable

Solutions:

  1. Run python api_test.py to verify coin exists
  2. Reduce DAYS_LOOKBACK in config.py
  3. Check Hyperliquid status: https://status.hyperliquid.xyz/

Issue: "ModuleNotFoundError"

Solution:

pip install -r requirements.txt

Issue: Charts not displaying

Solution: Check your matplotlib backend. Add to config.py:

import matplotlib
matplotlib.use('TkAgg')  # or 'Qt5Agg'

Issue: Slow performance

Solution:

  • Reduce DAYS_LOOKBACK to fetch less data
  • Increase INTERVAL to use larger candles
  • Disable verbose output: VERBOSE = False

Learning Objectives

This project demonstrates proficiency in:

  1. Python Programming

    • Object-oriented design (class-based architecture)
    • Type hints and documentation
    • Error handling and validation
  2. Data Science & Analysis

    • Pandas DataFrame manipulation
    • NumPy numerical computations
    • Statistical calculations (Sharpe ratio, drawdown)
  3. Financial Markets

    • Technical indicators (SMA)
    • Trading strategy logic
    • Risk management concepts
  4. API Integration

    • RESTful API communication
    • JSON data parsing
    • Error handling for network requests
  5. Data Visualization

    • Matplotlib multi-chart layouts
    • Time series plotting
    • Trade signal visualization
  6. Software Engineering

    • Modular code organization
    • Configuration management
    • Documentation and README creation

Disclaimer

EDUCATIONAL PURPOSE ONLY

This project is for educational and demonstration purposes only. It is NOT financial advice.

  • No Guarantees: Past performance does not guarantee future results
  • Risk Warning: Cryptocurrency trading carries significant risk of loss
  • Paper Trading: This is a backtesting tool, not a live trading system
  • Do Your Research: Always conduct your own research before trading
  • Consult Professionals: Seek advice from licensed financial advisors

The authors assume no liability for any losses incurred from using this software.


Resources

Documentation

Learning Resources

Related Projects


License

MIT License - See LICENSE file for details


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/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Acknowledgments

  • Hyperliquid team for providing free API access
  • Python community for excellent open-source libraries
  • Quantitative finance community for strategy inspiration

Built with Python | Made for learning and exploration

About

A Python backtesting system for cryptocurrency trading strategies. Implements SMA crossover strategy on HYPE-USD using real market data from Hyperliquid API. Includes performance metrics, visualizations, and comprehensive analysis.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages