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.
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
Type: Long-only SMA Crossover Strategy Asset: HYPE-USD (Hyperliquid cryptocurrency) Timeframe: 5-minute candles Indicator: 30-period Simple Moving Average (SMA) = 150 minutes
- Price crosses above the SMA after being below it
- Opens a long position at the close price
- Minimum holding period: 12 candles (1 hour)
- Exit when price touches the SMA again (within 0.2% threshold)
- Closes position at the close price
- 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
- Python 3.8 or higher
- pip package manager
-
Clone the repository
git clone https://github.com/yourusername/hype-sma-strategy.git cd hype-sma-strategy -
Install dependencies
pip install -r requirements.txt
-
Test API connection
python api_test.py
-
Run the backtest
python hype_sma_strategy.py
Run the strategy with default parameters:
python hype_sma_strategy.pyVerify Hyperliquid API connectivity and explore available markets:
python api_test.pyThis 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
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 CSVpython config.pyEndpoint: https://api.hyperliquid.xyz/info
Method: POST
Authentication: None required (public data)
{
"type": "candleSnapshot",
"req": {
"coin": "HYPE", # Coin symbol
"interval": "5m", # Candle interval
"startTime": 1234567890000, # Unix timestamp (ms)
"endTime": 1234567890000 # Unix timestamp (ms)
}
}[
{
"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
},
...
]- 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)
- Perpetuals: Use coin name directly (
- Time Format: Timestamps must be in milliseconds (multiply Unix timestamp by 1000)
- Rate Limits: No official limits, but be respectful with request frequency
====================================================================
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
====================================================================
strategy_results.png- Multi-chart visualizationtrade_log.csv- Detailed trade history
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
Edit config.py:
COIN = "BTC" # Trade Bitcoin insteadINTERVAL = "15m" # Use 15-minute candles
SMA_PERIOD = 20 # Adjust SMA accordingly
MIN_HOLD_CANDLES = 8 # Adjust minimum hold timeUncomment 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# Add trading fees and slippage
USE_FEES = True
TRADING_FEE = 0.05 # 0.05% per trade
USE_SLIPPAGE = True
SLIPPAGE = 0.1 # 0.1% slippagePossible causes:
- Coin symbol not found (check with
api_test.py) - Too many days requested (max ~17 days for 5m candles)
- API temporarily unavailable
Solutions:
- Run
python api_test.pyto verify coin exists - Reduce
DAYS_LOOKBACKinconfig.py - Check Hyperliquid status: https://status.hyperliquid.xyz/
Solution:
pip install -r requirements.txtSolution:
Check your matplotlib backend. Add to config.py:
import matplotlib
matplotlib.use('TkAgg') # or 'Qt5Agg'Solution:
- Reduce
DAYS_LOOKBACKto fetch less data - Increase
INTERVALto use larger candles - Disable verbose output:
VERBOSE = False
This project demonstrates proficiency in:
-
Python Programming
- Object-oriented design (class-based architecture)
- Type hints and documentation
- Error handling and validation
-
Data Science & Analysis
- Pandas DataFrame manipulation
- NumPy numerical computations
- Statistical calculations (Sharpe ratio, drawdown)
-
Financial Markets
- Technical indicators (SMA)
- Trading strategy logic
- Risk management concepts
-
API Integration
- RESTful API communication
- JSON data parsing
- Error handling for network requests
-
Data Visualization
- Matplotlib multi-chart layouts
- Time series plotting
- Trade signal visualization
-
Software Engineering
- Modular code organization
- Configuration management
- Documentation and README creation
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.
- Backtrader - Python backtesting framework
- QuantConnect - Cloud-based backtesting platform
- Zipline - Algorithmic trading library
MIT License - See LICENSE file for details
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- 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