Advertisement IC Markets

Fractals and Swing Points, Defining Highs and Lows Properly

Discuss 1-minute to 15-minute price action setups, fading intraday momentum, key support/resistance zones, and proven short-term trading methodologies.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

MQL5 Source Code

Copy and paste this code into the MetaEditor in MetaTrader 5 (press F4 in MT5 to open it), and compile it.

Code: Select all

//+------------------------------------------------------------------+
//|                                              EMA_Crossover_EA.mq5|
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "AI Assistant"
#property version   "1.00"

// Include the standard trade library for order execution
#include <Trade\Trade.mqh>

//--- Input Parameters (Adjustable from the MT5 interface)
input int      FastEMA_Period = 10;       // Fast EMA Period
input int      SlowEMA_Period = 50;       // Slow EMA Period
input double   LotSize        = 0.1;      // Trade Volume
input int      StopLossPoints = 500;      // Stop Loss in Points (500 pts = 50 pips on 5-digit broker)
input int      TakeProfitPts  = 1000;     // Take Profit in Points (1000 pts = 100 pips)
input ulong    MagicNumber    = 123456;   // EA Identification Number

//--- Global Variables
CTrade         trade;                     // Trade object for execution
int            fastEmaHandle;             // Handle for the fast EMA indicator
int            slowEmaHandle;             // Handle for the slow EMA indicator
double         fastEmaBuffer[];           // Array to store Fast EMA values
double         slowEmaBuffer[];           // Array to store Slow EMA values

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Set the Magic Number to identify trades opened by this EA
   trade.SetExpertMagicNumber(MagicNumber);
   
   // Initialize the indicator handles
   fastEmaHandle = iMA(_Symbol, _Period, FastEMA_Period, 0, MODE_EMA, PRICE_CLOSE);
   slowEmaHandle = iMA(_Symbol, _Period, SlowEMA_Period, 0, MODE_EMA, PRICE_CLOSE);
   
   // Check if indicators loaded successfully
   if(fastEmaHandle == INVALID_HANDLE || slowEmaHandle == INVALID_HANDLE)
     {
      Print("Error creating EMA indicators");
      return(INIT_FAILED);
     }
     
   // Set arrays as series (Index 0 is the current candle, 1 is previous, etc.)
   ArraySetAsSeries(fastEmaBuffer, true);
   ArraySetAsSeries(slowEmaBuffer, true);
   
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Release indicator handles from memory when EA is removed
   IndicatorRelease(fastEmaHandle);
   IndicatorRelease(slowEmaHandle);
  }

//+------------------------------------------------------------------+
//| Expert tick function (Executed on every price movement)          |
//+------------------------------------------------------------------+
void OnTick()
  {
   // 1. Check if we already have an open position for this EA
   if(CountOpenPositions() > 0) 
      return; 

   // 2. Copy the latest indicator values into our arrays
   // We copy 3 candles (Index 0, 1, and 2)
   if(CopyBuffer(fastEmaHandle, 0, 0, 3, fastEmaBuffer) <= 0) return;
   if(CopyBuffer(slowEmaHandle, 0, 0, 3, slowEmaBuffer) <= 0) return;

   // 3. Define pricing variables
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);

   // 4. BUY LOGIC: Fast EMA crossed ABOVE Slow EMA
   // We check candle [1] (closed) and candle [2] (previous) to confirm a completed crossover
   if(fastEmaBuffer[1] > slowEmaBuffer[1] && fastEmaBuffer[2] <= slowEmaBuffer[2])
     {
      double sl = ask - (StopLossPoints * point);
      double tp = ask + (TakeProfitPts * point);
      
      trade.Buy(LotSize, _Symbol, ask, sl, tp, "EMA Crossover BUY");
      Print("Buy Order Sent. SL: ", sl, " TP: ", tp);
     }
     
   // 5. SELL LOGIC: Fast EMA crossed BELOW Slow EMA
   else if(fastEmaBuffer[1] < slowEmaBuffer[1] && fastEmaBuffer[2] >= slowEmaBuffer[2])
     {
      double sl = bid + (StopLossPoints * point);
      double tp = bid - (TakeProfitPts * point);
      
      trade.Sell(LotSize, _Symbol, bid, sl, tp, "EMA Crossover SELL");
      Print("Sell Order Sent. SL: ", sl, " TP: ", tp);
     }
  }

//+------------------------------------------------------------------+
//| Helper Function: Count Open Positions for this EA                |
//+------------------------------------------------------------------+
int CountOpenPositions()
  {
   int count = 0;
   // Loop through all open positions on the account
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      // Only count positions that match this chart's symbol AND this EA's magic number
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == MagicNumber)
        {
         count++;
        }
     }
   return count;
  }
//+------------------------------------------------------------------+
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

How the Code Operates

#include <Trade\Trade.mqh>: This imports MT5's standard trade library, giving you access to the simplified CTrade class to execute trade.Buy() and trade.Sell() without manually configuring deep server requests.

ArraySetAsSeries(): This tells the arrays to index backwards. Index [0] becomes the current forming candle, index [1] is the last closed candle, and index [2] is the candle before that.

Crossover Confirmation: The logic specifically looks at index [1] and [2]. We never use index [0] for entry triggers because the current candle is still fluctuating, which can cause "repainting" (false signals). By waiting for candle [1] to close, the signal is permanently locked in.

CountOpenPositions(): This custom function ensures the EA doesn't open hundreds of trades at the same time. It checks the MagicNumber so that if you run this EA on EURUSD and GBPUSD simultaneously, they won't interfere with each other's trade counts.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

Deployment & Testing Protocol

Compile: Press F7 in MetaEditor. Ensure there are 0 errors in the log at the bottom.

Strategy Tester: Press Ctrl+R in MT5 to open the Strategy Tester. Run this EA on a 1-Hour (H1) timeframe using EURUSD or GBPUSD to see how it performs historically.

Optimize Parameters: The FastEMA_Period and SlowEMA_Period inputs are customizable. Use the MT5 Strategy Tester's "Optimization" mode to test thousands of variations (e.g., 20/200, 50/100) to find the most profitable moving average pair for your specific timeframe.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

This is the exact equivalent of the MQL5 Exponential Moving Average (EMA) Crossover strategy, translated into Pine Script (v5) for TradingView.

Pine Script is significantly more concise than MQL5 because order management, historical bar indexing, and chart overlays are handled natively by the engine.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

Pine Script Source Code

Open TradingView, click the Pine Editor tab at the bottom of your screen, paste this code, and click Add to Chart.

Code: Select all

//@version=5
strategy("EMA Crossover Strategy", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// --- Input Parameters ---
fastLength = input.int(10,   title="Fast EMA Period", group="Indicator Settings")
slowLength = input.int(50,   title="Slow EMA Period", group="Indicator Settings")
slPoints   = input.int(500,  title="Stop Loss (Points)", group="Risk Management")
tpPoints   = input.int(1000, title="Take Profit (Points)", group="Risk Management")

// --- Indicator Calculations ---
fastEma = ta.ema(close, fastLength)
slowEma = ta.ema(close, slowLength)

// Plot the EMAs directly on the price chart
plot(fastEma, color=color.new(color.blue, 0), title="Fast EMA", linewidth=2)
plot(slowEma, color=color.new(color.red, 0),  title="Slow EMA", linewidth=2)

// --- Entry Logic ---
// ta.crossover/crossunder automatically checks the previous closed candle
longCondition  = ta.crossover(fastEma, slowEma)
shortCondition = ta.crossunder(fastEma, slowEma)

if (longCondition)
    strategy.entry("Buy", strategy.long)

if (shortCondition)
    strategy.entry("Sell", strategy.short)

// --- Exit Logic (Stop Loss & Take Profit) ---
// syminfo.mintick converts points into the correct price fraction for the specific asset
if (strategy.position_size > 0)
    longSlPrice = strategy.position_avg_price - (slPoints * syminfo.mintick)
    longTpPrice = strategy.position_avg_price + (tpPoints * syminfo.mintick)
    strategy.exit("Exit Buy", from_entry="Buy", stop=longSlPrice, limit=longTpPrice)

if (strategy.position_size < 0)
    shortSlPrice = strategy.position_avg_price + (slPoints * syminfo.mintick)
    shortTpPrice = strategy.position_avg_price - (tpPoints * syminfo.mintick)
    strategy.exit("Exit Sell", from_entry="Sell", stop=shortSlPrice, limit=shortTpPrice)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

Key Differences from MQL5 to Pine Script

overlay=true: This command in the strategy() declaration forces the indicator lines and trade markers to plot directly over the candlesticks, rather than in a separate window below the chart.

ta.crossover(): You do not need to manually check array index [1] and [2] like in MQL5. Pine Script's built-in crossover function automatically evaluates historical series data and triggers precisely when a crossover completes on the candle close.

syminfo.mintick: This is TradingView's equivalent to MQL5's SymbolInfoDouble(_Symbol, SYMBOL_POINT). It dynamically calculates the minimum price movement (tick size) so your 500-point stop loss accurately translates to price, whether you are trading EURUSD, Gold, or Bitcoin.

Built-in Position Reversal: In MQL5, we explicitly checked CountOpenPositions(). In Pine Script, strategy.entry() handles this natively. If you are in a "Buy" position and a "Sell" signal triggers, Pine Script will automatically close the long trade and open the short trade in one seamless action.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

How to Backtest in TradingView

Apply to Chart: Once the script is saved and added, you will see the Blue and Red EMA lines appear on your chart, along with arrows showing historical entries and exits.

Strategy Tester: Click the Strategy Tester tab next to the Pine Editor. This displays a full breakdown of the strategy's historical performance, including Net Profit, Drawdown, Profit Factor, and a list of all executed trades.

Optimize: Click the gear icon (Settings) on the indicator's name in the top left corner of the chart. You can adjust the EMA lengths and SL/TP points in real-time, and the Strategy Tester will instantly recalculate the historical results based on your new parameters.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

Here is the exact Exponential Moving Average (EMA) Crossover strategy rewritten for MetaTrader 4 (MT4) using MQL4.

While MQL5 uses a more complex, object-oriented approach with indicator handles and trade libraries, MQL4 is more direct. You can call the indicators right on the current chart and execute trades using the built-in OrderSend() command.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

MQL4 Source Code

Open MetaTrader 4, press F4 to open the MetaEditor, create a new Expert Advisor, and paste this code:

Code: Select all

//+------------------------------------------------------------------+
//|                                              EMA_Crossover_EA.mq4|
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "AI Assistant"
#property version   "1.00"
#property strict    // Enforces modern MQL4 strict coding standards

//--- Input Parameters (Adjustable from the MT4 interface)
input int      FastEMA_Period = 10;       // Fast EMA Period
input int      SlowEMA_Period = 50;       // Slow EMA Period
input double   LotSize        = 0.1;      // Trade Volume
input int      StopLossPoints = 500;      // Stop Loss in Points (500 pts = 50 pips)
input int      TakeProfitPts  = 1000;     // Take Profit in Points (1000 pts = 100 pips)
input int      MagicNumber    = 123456;   // EA Identification Number

//+------------------------------------------------------------------+
//| Expert tick function (Executed on every price movement)          |
//+------------------------------------------------------------------+
void OnTick()
  {
   // 1. Check if we already have an open position for this EA
   if(CountOpenPositions() > 0) 
      return; 

   // 2. Calculate the EMA values directly using iMA()
   // Shift 1 = previous closed candle, Shift 2 = the candle before that
   double fastEma1 = iMA(Symbol(), 0, FastEMA_Period, 0, MODE_EMA, PRICE_CLOSE, 1);
   double fastEma2 = iMA(Symbol(), 0, FastEMA_Period, 0, MODE_EMA, PRICE_CLOSE, 2);
   
   double slowEma1 = iMA(Symbol(), 0, SlowEMA_Period, 0, MODE_EMA, PRICE_CLOSE, 1);
   double slowEma2 = iMA(Symbol(), 0, SlowEMA_Period, 0, MODE_EMA, PRICE_CLOSE, 2);

   // 3. Define variables for Stop Loss and Take Profit
   double sl = 0, tp = 0;
   
   // 4. BUY LOGIC: Fast EMA crossed ABOVE Slow EMA
   if(fastEma1 > slowEma1 && fastEma2 <= slowEma2)
     {
      sl = Ask - (StopLossPoints * Point);
      tp = Ask + (TakeProfitPts * Point);
      
      // Normalize prices to the broker's decimal digits to prevent errors
      sl = NormalizeDouble(sl, Digits);
      tp = NormalizeDouble(tp, Digits);
      
      // Execute the Buy Order
      int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "EMA Crossover BUY", MagicNumber, 0, clrBlue);
      if(ticket < 0) Print("OrderSend failed with error #", GetLastError());
     }
     
   // 5. SELL LOGIC: Fast EMA crossed BELOW Slow EMA
   else if(fastEma1 < slowEma1 && fastEma2 >= slowEma2)
     {
      sl = Bid + (StopLossPoints * Point);
      tp = Bid - (TakeProfitPts * Point);
      
      // Normalize prices to the broker's decimal digits to prevent errors
      sl = NormalizeDouble(sl, Digits);
      tp = NormalizeDouble(tp, Digits);
      
      // Execute the Sell Order
      int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "EMA Crossover SELL", MagicNumber, 0, clrRed);
      if(ticket < 0) Print("OrderSend failed with error #", GetLastError());
     }
  }

//+------------------------------------------------------------------+
//| Helper Function: Count Open Positions for this EA                |
//+------------------------------------------------------------------+
int CountOpenPositions()
  {
   int count = 0;
   // Loop through all open orders in the MT4 terminal
   for(int i = OrdersTotal() - 1; i >= 0; i--)
     {
      // Select the order to check its properties
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         // Only count orders matching our Symbol and Magic Number
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            count++;
           }
        }
     }
   return count;
  }
//+------------------------------------------------------------------+
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7821
Joined: Mon Jul 20, 2026 1:28 pm

Re: Fractals and Swing Points, Defining Highs and Lows Properly

Post by PTScalper »

Key Differences from MQL5 to MQL4

Direct Indicator Calls (iMA): In MQL5, we had to initialize an indicator "handle" in OnInit() and copy data into arrays using CopyBuffer. MQL4 is much simpler; you call iMA() right in the OnTick() function and use the last parameter (1 or 2) to tell MT4 which historical candle to look at.

Predefined Variables: MT4 automatically provides variables like Ask, Bid, Point, and Digits. You don't have to define them using SymbolInfoDouble() like you do in MT5.

OrderSend() function: MT4 manages trades through the native OrderSend() function instead of relying on an included <Trade\Trade.mqh> library.

NormalizeDouble(): MQL4 is very strict about order prices. If your Stop Loss isn't rounded precisely to your broker's decimal digits (e.g., 5 decimal places for EURUSD), the broker will reject the order with an "Invalid Price" error. The NormalizeDouble() step prevents this.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply