MQL4/MQL5 Medium Level: 30 Examples with Explanations
👉 Bonus: Exclusive pine-script strategy — See How It Works
#ExampleDescription
1 Moving Average Crossover Strategy Implements a simple moving average crossover strategy for buy/sell signals.
2 Calculating RSI Indicator Demonstrates how to calculate and use the Relative Strength Index (RSI) to make trading decisions.
3 Bollinger Bands Strategy Shows how to retrieve Bollinger Bands data and use it for trading decisions.
4 ATR-based Trailing Stop Implements an Average True Range (ATR)-based trailing stop to adjust stop-loss levels based on market volatility.
5 Setting Take Profit and Stop Loss Demonstrates setting take profit and stop-loss levels dynamically for each trade.
6 Multi-timeframe Analysis Shows how to retrieve and use indicator data from multiple timeframes for analysis.
7 Risk Management with Lot Sizing Calculates lot sizes based on account balance and risk percentage.
8 Order History Analysis Retrieves and analyzes closed orders to calculate profit, loss, and win rate.
9 Trailing Stop Function Implements a reusable function to handle trailing stops for open trades.
10 Trendline Drawing on Chart Draws trendlines on the chart based on recent highs and lows.
11 Event-Driven Trading (OnTimer) Sets up event-driven trading logic with OnTimer() for executing trades at fixed intervals.
12 Fibonacci Retracement Levels Calculates and draws Fibonacci retracement levels based on recent high and low prices.
13 Trade Panel Interface Creates a simple graphical trade panel on the chart for easier manual trading.
14 Multi-Currency Strategy Shows how to place orders and analyze multiple currency pairs in a single script.
15 Pending Buy/Sell Stop Orders Places pending stop orders above/below the current price for breakout strategies.
16 Market Sessions Identification Detects the current market session (e.g., London, New York) based on time and adjusts strategy accordingly.
17 Trailing Re-Order Function Implements a “trailing reorder” system that reorders when price hits certain levels.
18 Partial Close Function Shows how to close a portion of an open position while leaving the remaining lot size active.
19 Heiken Ashi Candle Calculation Calculates Heiken Ashi candles and uses them as filters for entries and exits.
20 Event-Driven Notifications Sends notifications when specific events (e.g., order closure, threshold breach) occur using SendNotification().
21 Detecting Support and Resistance Identifies support and resistance levels based on recent highs and lows.
22 Pivot Point Calculation Calculates daily pivot points and displays them on the chart.
23 Equity Drawdown Limit Monitors equity drawdown and pauses trading if a defined threshold is reached.
24 Money Flow Index (MFI) Uses the Money Flow Index to assess market pressure and make trading decisions.
25 Moving Average Slope Calculation Calculates the slope of a moving average to determine trend strength.
26 Risk/Reward Ratio Calculation Calculates the risk/reward ratio for each trade based on stop loss and take profit levels.
27 Daily Profit/Loss Calculation Calculates the profit or loss achieved each trading day.
28 Custom Indicator Integration Shows how to integrate custom indicators and use their values in trading logic.
29 Trading with Spread Control Monitors the current spread and disables trading when it exceeds a defined threshold.
30 Moving Stop Loss to Break-Even Implements a function to move stop loss to break-even after a certain profit level is achieved.
Detailed Examples and Explanations
- Moving Average Crossover Strategy:
double fastMA = iMA(Symbol(), 0, 10, 0, MODE_SMA, PRICE_CLOSE, 0);
double slowMA = iMA(Symbol(), 0, 20, 0, MODE_SMA, PRICE_CLOSE, 0);
if (fastMA > slowMA) {
// Buy Signal
} else if (fastMA < slowMA) {
// Sell Signal
}Explanation: Uses a fast and slow moving average to generate buy/sell signals based on crossovers.
Calculating RSI Indicator:
double rsi = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);
if (rsi < 30) {
// Oversold - Buy Signal
} else if (rsi > 70) {
// Overbought - Sell Signal
}Explanation: Uses RSI to identify overbought or oversold conditions, triggering buy/sell actions accordingly.
Bollinger Bands Strategy:
double upperBand = iBands(Symbol(), 0, 20, 2, 0, PRICE_CLOSE, MODE_UPPER, 0);
double lowerBand = iBands(Symbol(), 0, 20, 2, 0, PRICE_CLOSE, MODE_LOWER, 0);if (Ask < lowerBand) {
// Buy Signal
} else if (Bid > upperBand) {
// Sell Signal
}Explanation: Uses Bollinger Bands to detect price breakouts and reversions.
ATR-based Trailing Stop:
double atr = iATR(Symbol(), 0, 14, 0);
double trailingStop = atr * 1.5;Explanation: Uses the ATR to adjust trailing stops based on market volatility.
Setting Take Profit and Stop Loss:
double tp = Ask + 50 * Point;
double sl = Ask - 50 * Point;
int ticket = OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, sl, tp, "Buy Order with TP/SL", 0, 0, Blue);Explanation: Places a buy order with take profit and stop loss levels set at a fixed distance.
Multi-timeframe Analysis:
double maH1 = iMA(Symbol(), PERIOD_H1, 20, 0, MODE_SMA, PRICE_CLOSE, 0);
double maD1 = iMA(Symbol(), PERIOD_D1, 20, 0, MODE_SMA, PRICE_CLOSE, 0);Explanation: Uses moving averages from different timeframes to make trading decisions.
Risk Management with Lot Sizing:
double riskPercent = 0.01;
double lotSize = (AccountBalance() * riskPercent) / 100;Explanation: Calculates lot size based on risk percentage to manage exposure.
Order History Analysis:
double totalProfit = 0;
for (int i = OrdersHistoryTotal() - 1; i >= 0; i-- ) {
if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
totalProfit += OrderProfit();
}
}Explanation: Summarizes profit from all historical orders for performance analysis.
Trailing Stop Function:
void ApplyTrailingStop(double trailPoints) {
if (OrderSelect(ticket, SELECT_BY_TICKET)) {
if (OrderType() == OP_BUY) {
double newSL = Bid - trailPoints * Point;
if (OrderStopLoss() < newSL) {
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrRed);
}
}
}
}Explanation: Adjusts stop loss dynamically for open positions.
Trendline Drawing on Chart:
ObjectCreate("Trendline", OBJ_TREND, 0, Time[0], High[0], Time[10], Low[10]);
ObjectSetInteger(0, "Trendline", OBJPROP_COLOR, clrBlue);Explanation: Draws a trendline on the chart between two points based on recent highs and lows.
👉 Bonus: Exclusive pine-script strategy — See How It Works
Stay Tuned…
