5 min read
Deriv MT5 Bot

Deriv MT5 Bot

An advanced automated trading bot designed for Deriv’s synthetic markets using MetaTrader 5 (MT5) integration. This bot implements sophisticated trading strategies with risk management, backtesting capabilities, and real-time market analysis.

Features

  • Automated Trading - Fully automated trading execution on Deriv synthetic markets
  • Multiple Strategies - Implementation of various trading strategies (trend following, mean reversion, breakout)
  • Risk Management - Advanced risk management with position sizing and stop-loss
  • Backtesting Engine - Comprehensive backtesting with historical data analysis
  • Real-time Monitoring - Live monitoring of trades and performance metrics
  • MT5 Integration - Seamless integration with MetaTrader 5 platform
  • Performance Analytics - Detailed performance analysis and reporting
  • Custom Indicators - Support for custom technical indicators

Trading Strategies

Trend Following Strategy

  • Moving Average Crossover - Uses multiple moving averages for trend identification
  • MACD Strategy - MACD indicator-based trend following
  • Bollinger Bands - Volatility-based trend trading
  • RSI Divergence - RSI divergence for trend reversal detection

Mean Reversion Strategy

  • Bollinger Bands Reversion - Trading at band extremes
  • RSI Overbought/Oversold - RSI-based mean reversion
  • Stochastic Oscillator - Stochastic-based reversal trading
  • Support/Resistance - Price level-based mean reversion

Breakout Strategy

  • Channel Breakouts - Trading breakouts from price channels
  • Volatility Breakouts - Volatility expansion-based trading
  • News-Based Breakouts - Economic news impact trading
  • Pattern Breakouts - Technical pattern breakout trading

Tech Stack

  • Language: Python 3.8+
  • Trading Platform: MetaTrader 5 API
  • Data Analysis: Pandas, NumPy, TA-Lib
  • Backtesting: Custom backtesting engine
  • Database: SQLite for trade logging
  • Web Interface: Flask for monitoring dashboard

Installation & Setup

  1. Clone the repository:

    git clone https://github.com/1cbyc/deriv-mt5-bot.git
    cd deriv-mt5-bot
    
  2. Install dependencies:

    pip install -r requirements.txt
    
  3. Configure MT5 connection:

    cp config.example.yaml config.yaml
    # Edit configuration with your MT5 credentials
    
  4. Run the bot:

    python main.py
    

Configuration

Strategy Configuration

strategies:
  trend_following:
    enabled: true
    parameters:
      fast_ma: 10
      slow_ma: 20
      stop_loss: 0.02
      take_profit: 0.04
  
  mean_reversion:
    enabled: true
    parameters:
      rsi_period: 14
      oversold: 30
      overbought: 70
      stop_loss: 0.015

Risk Management

risk_management:
  max_position_size: 0.02  # 2% of account
  max_daily_loss: 0.05    # 5% daily loss limit
  max_open_trades: 3
  correlation_limit: 0.7

Usage Examples

Basic Trading Bot

from deriv_bot import DerivBot

# Initialize bot
bot = DerivBot(config_file='config.yaml')

# Start trading
bot.start_trading()

Custom Strategy Implementation

class CustomStrategy:
    def __init__(self, parameters):
        self.rsi_period = parameters['rsi_period']
        self.oversold = parameters['oversold']
        self.overbought = parameters['overbought']
    
    def generate_signal(self, data):
        rsi = calculate_rsi(data, self.rsi_period)
        
        if rsi < self.oversold:
            return 'BUY'
        elif rsi > self.overbought:
            return 'SELL'
        return 'HOLD'

Backtesting

# Run backtest
results = bot.backtest(
    strategy='trend_following',
    start_date='2024-01-01',
    end_date='2024-12-31',
    initial_capital=10000
)

# Analyze results
print(f"Total Return: {results['total_return']:.2%}")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {results['max_drawdown']:.2%}")

Performance Metrics

Key Performance Indicators

  • Total Return - Overall portfolio performance
  • Sharpe Ratio - Risk-adjusted returns
  • Maximum Drawdown - Largest peak-to-trough decline
  • Win Rate - Percentage of profitable trades
  • Profit Factor - Ratio of gross profit to gross loss
  • Average Trade - Average profit/loss per trade

Risk Metrics

  • Value at Risk (VaR) - Potential loss at confidence level
  • Expected Shortfall - Average loss beyond VaR
  • Volatility - Standard deviation of returns
  • Beta - Market correlation measure

Monitoring Dashboard

Real-time Monitoring

  • Live Trade Status - Current open positions and P&L
  • Performance Charts - Real-time performance visualization
  • Risk Metrics - Current risk exposure and limits
  • Strategy Performance - Individual strategy performance

Historical Analysis

  • Trade History - Complete trade log with analysis
  • Performance Reports - Monthly/quarterly performance reports
  • Strategy Comparison - Performance comparison across strategies
  • Risk Analysis - Historical risk metrics and analysis

Security Features

Account Protection

  • API Key Security - Secure storage of API credentials
  • Trade Limits - Maximum trade size and frequency limits
  • Emergency Stop - Immediate trading halt functionality
  • Audit Logging - Complete audit trail of all actions

Risk Controls

  • Position Limits - Maximum position size controls
  • Loss Limits - Daily and total loss limits
  • Correlation Limits - Maximum correlation between positions
  • Volatility Limits - Maximum volatility exposure

Project Impact

This trading bot has been used for:

  • Personal Trading - Automated personal trading strategies
  • Educational Purposes - Learning algorithmic trading concepts
  • Strategy Development - Testing and refining trading strategies
  • Risk Management - Implementing systematic risk controls

Future Enhancements

  • Machine Learning - ML-powered strategy optimization
  • Multi-Asset Trading - Support for multiple asset classes
  • Advanced Analytics - Enhanced performance analytics
  • Mobile App - Mobile monitoring and control
  • Social Trading - Copy trading and social features