A sophisticated trading system that implements a multi-timeframe strategy using Python, with both backtesting and live trading capabilities on Binance Testnet.
This project implements a trading strategy that combines multiple timeframes (15-minute entries with 1-hour confirmations) to make trading decisions. The system includes both backtesting capabilities using backtesting.py and live trading functionality through Binance Testnet API.
- Multi-timeframe strategy implementation (15m entries, 1h confirmations)
- Comprehensive backtesting system with detailed trade logging
- Live trading integration with Binance Testnet
- Trade comparison and analysis tools
- Modular, class-based architecture for maintainability and extensibility
├── README.md
├── requirements.txt
├── .env.example # Template for API credentials
├── run_backtest.py # Run backtesting
├── run_live.py # Run live trading
├── config/
│ └── config.py # Configuration settings and API keys
├── src/
│ ├── strategy/
│ │ ├── base.py # Base strategy class
│ │ └── multi_tf.py # Multi-timeframe strategy implementation
│ ├── backtesting/
│ │ ├── backtest.py # Backtesting engine
│ │ └── analyzer.py # Backtest results analysis
│ ├── trading/
│ │ ├── exchange.py # Binance API wrapper
│ │ └── executor.py # Trade execution logic
│ └── utils/
│ ├── logger.py # Logging utilities
│ ├── indicator.py # Technical indicators
│ └── data.py # Data handling utilities
└── data/
├── historical_data.csv # Historical price data for backtesting
├── backtest_trades.csv # Backtest trade logs
└── live_trades.csv # Live trading logs
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtThe backtesting system is ready to use with the included historical data:
python run_backtest.pyExpected output:
==================================================
BACKTEST RESULTS
==================================================
Total Trades: 1
Win Rate: 0.00%
Equity Final: $99,680.59
Return: -0.32%
Max Drawdown: -0.32%
Sharpe Ratio: N/A
==================================================
Trades are automatically saved to data/backtest_trades.csv.
- Visit Binance Testnet
- Create an account or log in
- Generate API Key and Secret
# Copy the example environment file
cp .env.example .env
# Edit .env and add your testnet credentials
nano .env # or use your preferred editorUpdate .env with your credentials:
BINANCE_API_KEY=your_testnet_api_key_here
BINANCE_API_SECRET=your_testnet_api_secret_here
python run_live.pyThis will verify your API connection and display current balance without executing trades.
The strategy combines signals from two timeframes:
- 15-minute timeframe for entry signals
- 1-hour timeframe for trade confirmation (simulated by checking every 4th bar)
- Long Entry: RSI < 40 (oversold) on a confirmation bar (every 4 bars)
- Short Entry: RSI > 60 (overbought) on a confirmation bar
- Long Exit: RSI > 70 (overbought) OR price drops 0.5% below SMA50
- Short Exit: RSI < 30 (oversold) OR price rises 0.5% above SMA50
- Position sizing: 95% of available equity per trade
- Commission: 0.2% per trade (backtesting)
- Live trading: Uses
RISK_PER_TRADEfrom config (default 1% of balance)
Edit config/config.py to customize:
SYMBOL = "BTCUSDT" # Trading pair
ENTRY_TIMEFRAME = "15m" # Entry signal timeframe
CONFIRM_TIMEFRAME = "1h" # Confirmation timeframe
RISK_PER_TRADE = 0.01 # Risk 1% per trade (live trading)Logged automatically during backtesting with columns:
- Size, Entry/Exit Bar, Entry/Exit Price
- PnL, Commission, Return %
- Entry/Exit Time, Duration
- Indicator values at entry and exit
Logged when executing live trades with columns:
- Timestamp, Side (BUY/SELL)
- Quantity, Price
- Order ID, Status
Add indicator functions to src/utils/indicator.py:
def add_macd(df, fast=12, slow=26, signal=9):
"""Add MACD indicator to dataframe."""
# Implementation here
return dfExtend or modify src/strategy/multi_tf.py:
- Override
init()to add custom indicators - Modify
next()to implement your entry/exit logic - Adjust parameters like
rsi_period,sma_period,confirm_interval
Always test thoroughly:
- Backtest first: Validate strategy logic with historical data
- Paper trade: Use Binance Testnet before real trading
- Monitor logs: Check
trading.logfor live trading activity
"Broker canceled order due to insufficient margin"
- Solution: Increase
cashparameter inbacktest.pyor reduce position size
"Failed to connect to Binance Testnet"
- Verify API keys in
.envfile - Check that keys are from testnet.binance.vision (not regular Binance)
- Ensure internet connection is active
"No trades executed in backtest"
- Check if historical data has enough rows (needs 50+ for SMA calculation)
- Adjust RSI thresholds if market conditions don't trigger signals
- Verify
confirm_intervalaligns with data frequency
Key packages used:
- backtesting - Backtesting framework
- python-binance - Binance API wrapper
- pandas - Data manipulation
- numpy - Numerical computations
- ta - Technical Analysis library
- python-dotenv - Environment variable management
Install all dependencies:
pip install -r requirements.txtThe analyzer displays:
- Total Trades: Number of completed trades
- Win Rate: Percentage of profitable trades
- Equity Final: Final portfolio value
- Return: Total return percentage
- Max Drawdown: Largest peak-to-trough decline
- Sharpe Ratio: Risk-adjusted return metric
⚠️ NEVER commit.envfile or API keys to version control⚠️ Always test on Testnet before using real funds⚠️ Monitor live trades actively; automated trading carries risk⚠️ Start with small position sizes
- Real-time data streaming for live trading
- Multiple symbol support
- Advanced order types (limit, stop-loss)
- Telegram/Discord notifications
- Performance dashboard with charts
- Parameter optimization using
.optimize()
Implementation by: Devansh
- Binance for providing the Testnet API
- backtesting.py library contributors
- Technical Analysis library contributors
This project is for educational purposes. Use at your own risk.