Basics of Trading Algorithms and Strategies in Algorithmic Trading

Algorithmic trading relies on automated strategies that identify profitable opportunities in the financial markets. These strategies, driven by mathematical models and historical data, allow traders to execute trades at high speeds with minimal human intervention. This article provides an overview of the most common trading algorithms and strategies, giving you a foundational understanding to start building your own.

What are Trading Algorithms?

A trading algorithm is a set of instructions that defines how and when to make trading decisions. By analysing data such as price, volume, and indicators, algorithms automatically execute trades based on predefined rules. These algorithms range from simple moving average crossovers to complex machine learning models, enabling traders to pursue diverse strategies.

Popular Types of Trading Algorithms

1. Trend-Following Algorithms

  • Overview: These algorithms detect market trends and generate buy/sell signals based on price direction.
  • Common Indicators: Moving Averages, MACD (Moving Average Convergence Divergence).
  • Example Strategy: A moving average crossover strategy that buys when the short-term average crosses above the long-term average.

2. Mean Reversion Algorithms

  • Overview: Mean reversion algorithms are based on the concept that asset prices revert to their historical averages over time.
  • Common Indicators: RSI (Relative Strength Index), Bollinger Bands.
  • Example Strategy: Buy when the price falls below the lower Bollinger Band, and sell when it exceeds the upper band.

3. Momentum-Based Algorithms

  • Overview: These algorithms seek to capture price momentum, buying when prices rise and selling when they fall.
  • Common Indicators: RSI, Momentum Oscillator.
  • Example Strategy: Buy when the RSI indicates strong upward momentum; sell when momentum weakens.

4. Statistical Arbitrage Algorithms

  • Overview: These strategies exploit price inefficiencies between correlated assets.
  • Common Indicators: Pair trading, regression models.
  • Example Strategy: Buy one asset and short another when their price divergence exceeds a certain threshold.

5. Market-Making Algorithms

  • Overview: Market-making algorithms aim to profit from the bid-ask spread by placing buy and sell orders simultaneously.
  • Common Indicators: Volume indicators, spread analysis.
  • Example Strategy: Set buy orders at the bid price and sell orders at the ask price.

6. High-Frequency Trading (HFT) Algorithms

  • Overview: HFT algorithms use extreme speed and volume to capture small profits from tiny price movements.
  • Common Indicators: Primarily rely on order book data and fast execution.
  • Example Strategy: Scalping to capture micro-profits within seconds or milliseconds.

Example Strategy: Mean Reversion with Bollinger Bands in MQL4

This MQL4 example demonstrates a mean reversion strategy using Bollinger Bands, an indicator that helps identify overbought and oversold conditions. The strategy buys when the price falls below the lower Bollinger Band and sells when it rises above the upper band.

Calculation for Bollinger Bands:

  • Middle Band (MA) = Simple Moving Average (SMA) of the price over a specified period.
  • Upper Band = Middle Band + (Standard Deviation * Multiplier).
  • Lower Band = Middle Band – (Standard Deviation * Multiplier).

In this example, we’ll use a 20-period SMA and a multiplier of 2 for the standard deviation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Mean Reversion Strategy Using Bollinger Bands in MQL4
input int BandPeriod = 20;          // Period for Bollinger Bands
input double BandMultiplier = 2.0;   // Multiplier for Standard Deviation
input double LotSize = 0.1;          // Lot size for orders
 
// Global variables to track trade status
bool buyTradeOpen = false;
bool sellTradeOpen = false;
 
void OnTick() {
   double upperBand = iBands(NULL, 0, BandPeriod, BandMultiplier, 0, PRICE_CLOSE, MODE_UPPER, 0);
   double lowerBand = iBands(NULL, 0, BandPeriod, BandMultiplier, 0, PRICE_CLOSE, MODE_LOWER, 0);
   double closePrice = iClose(NULL, 0, 0);
 
   // Check for a Buy Signal: Price is below the lower Bollinger Band
   if (closePrice < lowerBand && !buyTradeOpen) { // Close any open sell positions before buying if (sellTradeOpen) { CloseSell(); } // Open a Buy position OpenBuy(); } // Check for a Sell Signal: Price is above the upper Bollinger Band else if (closePrice > upperBand && !sellTradeOpen) {
       // Close any open buy positions before selling
       if (buyTradeOpen) {
           CloseBuy();
       }
       // Open a Sell position
       OpenSell();
   }
}
 
// Function to open a buy position
void OpenBuy() {
   int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, 0, 0, "Bollinger Buy", 0, 0, clrGreen);
   if (ticket > 0) {
       buyTradeOpen = true;
       sellTradeOpen = false;
       Print("Buy order opened successfully.");
   } else {
       Print("Error opening buy order: ", GetLastError());
   }
}
 
// Function to open a sell position
void OpenSell() {
   int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, 0, 0, "Bollinger Sell", 0, 0, clrRed);
   if (ticket > 0) {
       sellTradeOpen = true;
       buyTradeOpen = false;
       Print("Sell order opened successfully.");
   } else {
       Print("Error opening sell order: ", GetLastError());
   }
}
 
// Function to close any open buy position
void CloseBuy() {
   for (int i = OrdersTotal() - 1; i >= 0; i--) {
       if (OrderSelect(i, SELECT_BY_POS) && OrderType() == OP_BUY) {
           OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrGreen);
           buyTradeOpen = false;
           Print("Buy order closed.");
       }
   }
}
 
// Function to close any open sell position
void CloseSell() {
   for (int i = OrdersTotal() - 1; i >= 0; i--) {
       if (OrderSelect(i, SELECT_BY_POS) && OrderType() == OP_SELL) {
           OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrRed);
           sellTradeOpen = false;
           Print("Sell order closed.");
       }
   }
}

Explanation of the Strategy

1. Parameters

  • BandPeriod: Defines the period for calculating the SMA in the Bollinger Bands.
  • BandMultiplier: Multiplies the standard deviation, widening or narrowing the bands.
  • LotSize: The amount to trade per position.

2. Trade Execution:

  • A buy signal is triggered when the price falls below the lower Bollinger Band, indicating the asset is oversold.
  • A sell signal is triggered when the price rises above the upper Bollinger Band, suggesting the asset is overbought.

3. Trade Functions:

  • OpenBuy() and OpenSell() execute buy and sell trades respectively.
  • CloseBuy() and CloseSell() close open positions when an opposite signal is detected.

Conclusion

Understanding different algorithmic trading strategies is crucial for selecting and developing systems that align with your trading goals. The mean reversion strategy with Bollinger Bands is just one example, but each strategy type offers unique opportunities and requires its own set of indicators. In the next article, we’ll explore Technical Analysis vs. Fundamental Analysis in Algo Trading to determine when each is best suited for algorithmic strategies.