Developing a Bollinger Bands-Based Trading Bot for Bybit Using Python

This article presents a comprehensive guide to building a cryptocurrency trading bot in Python, designed to operate on the Bybit exchange. The bot utilizes Bollinger Bands as its primary strategy, supplemented by additional indicators to improve signal accuracy. It includes both backtesting and live trading components.
Strategy Overview: Bollinger Bands
Bollinger Bands are a technical analysis tool based on a moving average and standard deviation. The bot uses the following components:
- Middle Band: Simple Moving Average (SMA), typically over 20 periods.
- Upper Band: SMA + 2 × standard deviation.
- Lower Band: SMA − 2 × standard deviation.
The basic trading logic is:
- Buy when the price touches the lower band.
- Sell when the price touches the upper band.
However, relying solely on Bollinger Bands yields poor results. Additional indicators are integrated to refine entry conditions.
Supplementary Indicators
To enhance signal precision, the following indicators are used:
- RSI (Relative Strength Index): Detects overbought (>70) and oversold (<30) conditions.
- EMA (Exponential Moving Average): Filters trend direction; price above EMA favors long positions.
- ATR (Average True Range): Measures volatility; used for adaptive stop-loss.
- CSI/CSC (Cluster Strength Index / Cluster Signal Confirmation): Custom indicators based on candle clustering and signal density.
🛠️ Tools and Libraries
The bot uses the following Python libraries:
requests,pybit: API accesspandas,numpy: Data manipulation and indicator calculationsdatetime,time: Time controlthreading: Multithreadingtelebot: Telegram notifications (optional)
📁 Project Structure
bollinger_bot/
├── main.py # Live trading logic
├── back.py # Backtesting logic
├── config.cfg # Configuration file (optional)
⚙️ Configuration
The bot configuration includes symbol, interval, Bollinger Band parameters, stop-loss percentage, and cluster thresholds:
symbol = "ETHUSDT"
interval = "5m"
bb_period = 40
bb_std = 1
STOP_LOSS_PCT = 0.004
config = {
'min_cluster': 3,
'bull_quant': 0.75,
'bear_quant': 0.25,
'rsi': 60
}
📈 Historical Data Fetching
To perform backtesting and indicator calculations, historical candlestick data is retrieved:
def fetch_klines_paged(symbol, interval, total_bars, client):
...
return df
This function bypasses API limits by paginating requests and assembling a full dataset.
📊 Indicator Calculations
The bot computes several indicators:
RSI
def compute_rsi(df, period=450):
...
return df
Uses a long period (450) for smoothing, optimized for ATR-adjusted performance.
Bollinger Bands
def compute_bollinger(df):
...
return df
Calculates SMA and standard deviation to derive upper and lower bands.
CSI
def get_csi(df):
...
return df
Combines candle body ratio, volume score, and normalized range to assess price movement strength.
CSC (Cluster Signal Confirmation)
def compute_csc(df, min_cluster, bull_quant, bear_quant):
...
return df
Identifies clusters of bullish or bearish candles based on CSI quantiles.
📌 Signal Logic
Entry signals are determined by combining Bollinger Band touches with RSI and CSI conditions:
def check_signal_row(row, prev_row):
...
return 'buy' or 'sell' or None
Conditions include:
- Price crossing Bollinger Bands
- CSI momentum
- RSI thresholds
- Cluster confirmation
🧪 Backtesting
The backtesting script simulates trades and logs results:
if __name__ == '__main__':
...
trades_df.to_csv('trades_complete.csv', sep=';', index=False)
Trades are closed either by stop-loss or after a fixed time interval. The script outputs total profit/loss and recent trades.
🤖 Live Bot Implementation
The live bot mirrors the backtest logic, with real-time candle fetching and Telegram alerts. It includes:
- Real-time candle validation
- Indicator recalculation
- Signal detection
- Position management via Bybit API
Key Functions
Candle Fetching
def get_last_closed_candle():
...
return last_candle
Ensures only closed candles are used for signal evaluation.
CSC Calculation (Live)
def compute_csc(df):
sub = df.tail(min(50000, len(df)))
...
return df
Limits cluster analysis to recent candles to match backtest behavior.
Order Execution
def place_order(symbol, side, qty_eth, stop_price):
...
Places market orders with stop-loss and sends Telegram notifications.
Position Closure
def close_position(symbol, position_type, qty_eth):
...
Closes positions based on stop-loss or time expiration.
Entry Cooldown
def can_enter_again(signal_type):
...
Prevents multiple entries within the same candle.
Main Loop
while True:
...
time.sleep(3)
Runs continuously, checking for new signals every 5 minutes and managing open positions.
Full text code file available here.
Performance
Backtesting over 100,000 5-minute candles yielded a net profit of 173.86% over one year. With 10× leverage, this translates to 1738% return on margin. After accounting for Bybit fees (0.1%) and slippage (~0.02%), the net profit remains substantial.
Conclusion
This bot demonstrates a robust framework for algorithmic trading using Bollinger Bands and supplementary indicators. It includes historical testing and live deployment with real-time data and notifications. While the strategy is profitable in backtests, live trading requires careful monitoring, risk management, and consideration of market conditions.
