Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

i want an metatrader 5 ea that detect and mark Swing lines. horizontal lines drawn on…

  1. User

    i want an metatrader 5 ea that detect and mark Swing lines. horizontal lines drawn on the chart at price levels representing recent swing highs and swing lows — significant peaks (highs) and troughs (lows) within a certain lookback period. Your Swing Lines Implementation Overview Data Structure: You use a struct SwingLine to store each swing line’s data:

    struct SwingLine { double price; // Swing high or low price level datetime startTime; // Candle open time where swing was detected datetime endTime; // Time when price touched the swing line (0 if not yet touched) bool isHigh; // True if swing high, False if swing low string objName; // Unique name for the horizontal line chart object }; SwingLine swings[MAX_SWINGS]; // Fixed max number of swings to track int swingCount = 0; // Number of currently tracked swing lines Detecting and Adding New Swing Lines: Every new bar on the swingTF timeframe triggers detection. You find the highest high and lowest low over the last swingLookback bars excluding the last closed bar (offset by 1). Compare which happened most recently (higher bar time or lower bar time) to decide whether to add a swing high line or a swing low line. If maximum allowed swings (MAX_SWINGS, 5 here) is reached, you remove the oldest swing line before adding a new one. Drawing Swing Lines on Chart: Each swing line is drawn as a horizontal line (OBJ_HLINE) with properties: Color: green for highs, red for lows. Width: 2 pixels. Not extended indefinitely (OBJPROP_RAY_RIGHT = false). Starts from the candle time of swing detection. The line is extended forward in time (OBJPROP_TIME2) every new bar until price touches it. Price Touch Detection: If price crosses or touches the swing line level (bid ≥ swing high price or ask ≤ swing low price) The swing line's end time is set to current candle time. The line style changes to dashed (STYLE_DASH) to indicate it was "hit". The line then stops extending forward (OBJPROP_TIME2 is fixed to the touch candle time). Maintaining Swing Lines: On each new swingTF bar, the ProcessSwings() function updates all swing lines: Extends lines forward if not touched. Checks for price interactions. Adds new swing lines based on lookback. Deleting Swing Lines on Deinit: When the EA stops, all swing lines and helper lines (swingHighLineName, swingLowLineName) are deleted to clean the chart. Purpose & Benefits in the EA These swing lines visually mark key swing highs and lows on your chosen timeframe. Can be used to: Identify breakout points (price moving beyond swing high/low). Set potential stop-loss or take-profit levels. Serve as filters or confirmation for entry signals. The lines update dynamically and "expire" (are removed) as new swings develop or price interacts with them.

  2. Assistant

    Certainly! Below is a complete MQL5 Expert Advisor source code that implements your described Swing Lines indicator on a specified swing timeframe (swingTF), detecting swing highs and lows using a lookback period, marking them as horizontal lines on the chart, and managing their lifecycle as per your specifications.

    //+------------------------------------------------------------------+
    //|                                                SwingLinesEA.mq5  |
    //|                              Swing High/Low lines on chart       |
    //+------------------------------------------------------------------+
    #property copyright "ChatGPT"
    #property link      ""
    #property version   "1.00"
    #property strict
    
    #include <Trade\Trade.mqh>
    
    #define MAX_SWINGS 5
    
    input ENUM_TIMEFRAMES swingTF = PERIOD_M15;      // Timeframe to detect swings on
    input int          swingLookback = 20;            // Number of bars to look back for swing high/low
    
    struct SwingLine
    {
       double    price;          // Swing high or low price level
       datetime  startTime;      // Candle open time where swing was detected
       datetime  endTime;        // Time when price touched the swing line (0 if not touched yet)
       bool      isHigh;         // True if swing high, False if swing low
       string    objName;        // Unique name for the horizontal line chart object
    };
    
    SwingLine swings[MAX_SWINGS];                       // Array to hold swing lines
    int swingCount = 0;                                 // Currently tracked swings count
    
    // Helper function: Generate a unique object name for swing line
    string GenerateSwingLineName(bool isHigh, datetime time)
    {
       return StringFormat("SwingLine_%c_%d", (isHigh ? 'H' : 'L'), (int)time);
    }
    
    // Helper function: Delete swing line object from the chart
    void DeleteSwingLine(int index)
    {
       if(swings[index].objName!="")
       {
          if(ObjectFind(0, swings[index].objName) != -1)
             ObjectDelete(0, swings[index].objName);
       }
       
       // Shift array elements left
       for(int i=index; i<swingCount-1; i++)
          swings[i] = swings[i+1];
       
       swingCount--;
    }
    
    // Find/high or low highest/lowest over lookback bars on swingTF excluding last closed bar (offset by 1)
    bool FindSwingHighLow(datetime &highTime, double &highPrice, datetime &lowTime, double &lowPrice)
    {
       // Get number of bars on swingTF
       int bars = iBars(_Symbol, swingTF);
       
       // Validate we have enough bars
       if(bars < swingLookback + 2) // +2 for offset and indexing from 0
          return false;
       
       highPrice = -DBL_MAX;
       lowPrice = DBL_MAX;
       highTime = 0;
       lowTime = 0;
       
       // We exclude the last closed bar (offset=1)
       int startBar = 1;      // bar index 1 = last closed bar to exclude
       int endBar = swingLookback + 1; // to lookback bars excluding last closed bar
       
       for(int i=startBar+1; i<=endBar; i++) 
       {
          double h = iHigh(_Symbol, swingTF, i);
          double l = iLow(_Symbol, swingTF, i);
          datetime t = iTime(_Symbol, swingTF, i);
          
          if(h > highPrice)
          {
             highPrice = h;
             highTime = t;
          }
          if(l < lowPrice)
          {
             lowPrice = l;
             lowTime = t;
          }
       }
       
       if(highTime == 0 || lowTime==0) return false;
       
       return true;
    }
    
    // Add new swing line to array and draw it on chart
    void AddSwingLine(bool isHigh, double price, datetime time)
    {
       // If max swings reached, delete oldest swing (index 0 is oldest)
       if(swingCount == MAX_SWINGS)
          DeleteSwingLine(0);
       
       SwingLine newSwing;
       newSwing.price = price;
       newSwing.startTime = time;
       newSwing.endTime = 0;      // Not touched yet
       newSwing.isHigh = isHigh;
       newSwing.objName = GenerateSwingLineName(isHigh, time);
       
       swings[swingCount] = newSwing;
       swingCount++;
       
       // Draw horizontal line on chart
       if(ObjectFind(0, newSwing.objName) == -1)
       {
          ObjectCreate(0, newSwing.objName, OBJ_HLINE, 0, time, price);
          
          Color lineColor = isHigh ? clrGreen : clrRed;
          ObjectSetInteger(0, newSwing.objName, OBJPROP_COLOR, lineColor);
          ObjectSetInteger(0, newSwing.objName, OBJPROP_WIDTH, 2);
          ObjectSetInteger(0, newSwing.objName, OBJPROP_RAY_RIGHT, false);
         
          // Left time for the line is the startTime
          ObjectSetInteger(0, newSwing.objName, OBJPROP_TIME, newSwing.startTime);
          
          // Set end time to a time in future, for extending line
          datetime endTime = TimeCurrent() + PeriodSeconds(_Period);
          ObjectSetInteger(0, newSwing.objName, OBJPROP_TIME2, endTime);
          
          ObjectSetInteger(0, newSwing.objName, OBJPROP_STYLE, STYLE_SOLID);
          // Depth level so it is above most other charts
          ObjectSetInteger(0, newSwing.objName, OBJPROP_BACK, false);
       }
    }
    
    // Update (extend/end) swing line on chart
    void UpdateSwingLine(int index, datetime newEndTime)
    {
       string obj = swings[index].objName;
       
       if(newEndTime != 0)
       {
          swings[index].endTime = newEndTime;
          // Stop extending line
          ObjectSetInteger(0, obj, OBJPROP_TIME2, newEndTime);
          // Change style to dashed (hit)
          ObjectSetInteger(0, obj, OBJPROP_STYLE, STYLE_DASH);
       }
       else
       {
          // Extend line to current time + 1 bar period
          datetime extendTime = TimeCurrent() + PeriodSeconds(_Period);
          ObjectSetInteger(0, obj, OBJPROP_TIME2, extendTime);
       }
    }
    
    // Check if price touched or crossed swing line
    bool PriceTouchedSwingLine(int index)
    {
       SwingLine &s = swings[index];
       if(s.endTime != 0) return true; // already touched
       
       double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
       double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
       
       if(s.isHigh)
       {
          // Swing high: price touches if bid >= swing price
          if(bid >= s.price)
             return true;
       }
       else
       {
          // Swing low: price touches if ask <= swing price
          if(ask <= s.price)
             return true;
       }
       return false;
    }
    
    // Process all existing swings: extend or mark touched ones
    void ProcessExistingSwings()
    {
       datetime openTimeCurrentBar = iTime(_Symbol, swingTF, 0);
       
       for(int i=0; i<swingCount; i++)
       {
          if(swings[i].endTime == 0)
          {
             // Not touched yet, check price touch
             if(PriceTouchedSwingLine(i))
             {
                // Mark touched: end time is current bar open time
                UpdateSwingLine(i, openTimeCurrentBar);
             }
             else
             {
                // Still extending line to future time
                UpdateSwingLine(i, 0);
             }
          }
       }
    }
    
    // Detect and add new swing line if applicable (called every new swingTF bar)
    void DetectAndAddSwingLine()
    {
       datetime highTime; double highPrice;
       datetime lowTime; double lowPrice;
       
       if(!FindSwingHighLow(highTime, highPrice, lowTime, lowPrice))
          return;  // Not enough data to detect swings
       
       // Decide which came more recently; add that swing line
       if(highTime > lowTime)
       {
          // High more recent — add swing high
          // Prevent duplicates: don't add if swing line at that time already exists
          bool exists = false;
          for(int i=0; i<swingCount; i++)
          {
             if(swings[i].isHigh && swings[i].startTime == highTime)
             {
                exists = true;
                break;
             }
          }
          if(!exists)
             AddSwingLine(true, highPrice, highTime);
       }
       else
       {
          // Low more recent — add swing low
          bool exists = false;
          for(int i=0; i<swingCount; i++)
          {
             if(!swings[i].isHigh && swings[i].startTime == lowTime)
             {
                exists = true;
                break;
             }
          }
          if(!exists)
             AddSwingLine(false, lowPrice, lowTime);
       }
    }
    
    // Check if we are on a new bar on the swingTF
    datetime lastProcessedTime = 0;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
       // Clear any previous swing lines before start
       for(int i=0; i<MAX_SWINGS; i++)
          DeleteSwingLine(i);
       swingCount = 0;
       lastProcessedTime = 0;
       
       Print("SwingLinesEA initialized.");
       return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
       // Delete all swing lines on deinit
       for(int i=swingCount-1; i>=0; i--)
       {
          DeleteSwingLine(i);
       }
       swingCount = 0;
       Print("SwingLinesEA deinitialized - all lines removed.");
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
       // We'll process swings on new bar of swingTF only
       datetime currentBarTime = iTime(_Symbol, swingTF, 0);
       if(currentBarTime == 0)
          return; // no bar loaded yet
       
       if(currentBarTime != lastProcessedTime)
       {
          lastProcessedTime = currentBarTime;
          
          // 1. Process existing swing lines (extend or mark touched)
          ProcessExistingSwings();
          
          // 2. Detect and add new swings
          DetectAndAddSwingLine();
       }
    }
    //+------------------------------------------------------------------+
    

    Explanation & How to Use

    1. Inputs:

      • swingTF — timeframe the EA analyzes bars on (default 15 min)
      • swingLookback — how many bars in that timeframe are checked for swing highs/lows (default 20)
    2. Swing Detection:

      • On every new bar of the swingTF timeframe, the EA:
        • Finds the highest high and lowest low over the past swingLookback bars (offset by 1 bar to exclude the last closed bar).
        • Determines which of these swing points occurred most recently.
        • Adds a horizontal line at the swing high or low and stores it in the swings array.
      • Maintains a maximum of 5 swing lines; removes the oldest when adding a new one.
    3. Swing Lines on Chart:

      • Swing highs lines are green, swing lows are red.
      • Lines start at the candle open time when swing was detected.
      • Lines extend forward in time until price "touches" them.
      • When price touches/crosses a swing line (bid ≥ swing high price, ask ≤ swing low price):
        • The line’s endTime is set to current candle time.
        • The line style changes to dashed.
        • The line stops extending forward.
    4. Cleanup:

      • When the EA is removed, all swing lines are deleted.

    Notes:

    • Attach this EA to any chart (any symbol and timeframe). It draws swing lines based on the swingTF you specify.
    • Swing detection is based purely on the bar data of swingTF, it does not trade.
    • The EA dynamically updates and removes swing lines as new swing points appear and price interacts with them.
    • You can modify MAX_SWINGS if you want to track more or fewer swing lines.

    If you want me to extend this code to provide alerts or integrate with trading logic, just let me know!

  3. User

    'Color' - undeclared identifier aaaaa.mq5 115 7 'lineColor' - undeclared identifier aaaaa.mq5 115 13 'lineColor' - some operator expected aaaaa.mq5 115 13 'OBJPROP_TIME2' - undeclared identifier aaaaa.mq5 125 45 'ObjectSetInteger' - no one of the overloads can be applied to the function call aaaaa.mq5 125 7 '&' - reference cannot used aaaaa.mq5 157 14

  4. Assistant

    Thank you for providing the error messages. They indicate some issues with:

    • The Color type undefined — in MQL5 the color type is color (lowercase).
    • OBJPROP_TIME2 is missing — it's not a standard property for horizontal line objects in MQL5.
    • ObjectSetInteger usage incorrect for certain properties.
    • & reference on struct element not allowed in MQL5.

    I'll correct the code accordingly and provide explanations.


    Corrected Code:

    //+------------------------------------------------------------------+
    //|                                              SwingLinesEA.mq5    |
    //|                        Swing High/Low lines on chart             |
    //+------------------------------------------------------------------+
    #property copyright "ChatGPT"
    #property link      ""
    #property version   "1.01"
    #property strict
    
    #include <Trade\Trade.mqh>
    
    #define MAX_SWINGS 5
    
    input ENUM_TIMEFRAMES swingTF = PERIOD_M15;      // Timeframe to detect swings on
    input int          swingLookback = 20;            // Number of bars to look back for swing high/low
    
    struct SwingLine
    {
       double    price;          // Swing high or low price level
       datetime  startTime;      // Candle open time where swing was detected
       datetime  endTime;        // Time when price touched the swing line (0 if not touched yet)
       bool      isHigh;         // True if swing high, False if swing low
       string    objName;        // Unique name for the horizontal line chart object
    };
    
    SwingLine swings[MAX_SWINGS];                       // Array to hold swing lines
    int swingCount = 0;                                 // Currently tracked swings count
    
    // Helper function: Generate a unique object name for swing line
    string GenerateSwingLineName(bool isHigh, datetime time)
    {
       return StringFormat("SwingLine_%c_%d", (isHigh ? 'H' : 'L'), (int)time);
    }
    
    // Helper function: Delete swing line object from the chart
    void DeleteSwingLine(int index)
    {
       if(swings[index].objName!="")
       {
          if(ObjectFind(0, swings[index].objName) != -1)
             ObjectDelete(0, swings[index].objName);
       }
       
       // Shift array elements left
       for(int i=index; i<swingCount-1; i++)
          swings[i] = swings[i+1];
       
       swingCount--;
    }
    
    // Find/high or low highest/lowest over lookback bars on swingTF excluding last closed bar (offset by 1)
    bool FindSwingHighLow(datetime &highTime, double &highPrice, datetime &lowTime, double &lowPrice)
    {
       // Get number of bars on swingTF
       int bars = iBars(_Symbol, swingTF);
       
       // Validate we have enough bars
       if(bars < swingLookback + 2) // +2 for offset and indexing from 0
          return false;
       
       highPrice = -DBL_MAX;
       lowPrice = DBL_MAX;
       highTime = 0;
       lowTime = 0;
       
       // We exclude the last closed bar (offset=1)
       int startBar = 1;      // bar index 1 = last closed bar to exclude
       int endBar = swingLookback + 1; // to lookback bars excluding last closed bar
       
       for(int i=startBar+1; i<=endBar; i++) 
       {
          double h = iHigh(_Symbol, swingTF, i);
          double l = iLow(_Symbol, swingTF, i);
          datetime t = iTime(_Symbol, swingTF, i);
          
          if(h > highPrice)
          {
             highPrice = h;
             highTime = t;
          }
          if(l < lowPrice)
          {
             lowPrice = l;
             lowTime = t;
          }
       }
       
       if(highTime == 0 || lowTime==0) return false;
       
       return true;
    }
    
    // Add new swing line to array and draw it on chart
    void AddSwingLine(bool isHigh, double price, datetime time)
    {
       // If max swings reached, delete oldest swing (index 0 is oldest)
       if(swingCount == MAX_SWINGS)
          DeleteSwingLine(0);
       
       SwingLine newSwing;
       newSwing.price = price;
       newSwing.startTime = time;
       newSwing.endTime = 0;      // Not touched yet
       newSwing.isHigh = isHigh;
       newSwing.objName = GenerateSwingLineName(isHigh, time);
       
       swings[swingCount] = newSwing;
       swingCount++;
       
       // Draw horizontal line on chart
       if(ObjectFind(0, newSwing.objName) == -1)
       {
          ObjectCreate(0, newSwing.objName, OBJ_HLINE, 0, 0, price);
          
          color lineColor = isHigh ? clrGreen : clrRed;
          ObjectSetInteger(0, newSwing.objName, OBJPROP_COLOR, lineColor);
          ObjectSetInteger(0, newSwing.objName, OBJPROP_WIDTH, 2);
          ObjectSetInteger(0, newSwing.objName, OBJPROP_RAY_RIGHT, false);
         
          // Note: horizontal line doesn't support time properties like OBJPROP_TIME and OBJPROP_TIME2
          
          ObjectSetInteger(0, newSwing.objName, OBJPROP_STYLE, STYLE_SOLID);
          ObjectSetInteger(0, newSwing.objName, OBJPROP_BACK, false);
       }
    }
    
    // Update (extend/end) swing line on chart
    void UpdateSwingLine(int index, datetime newEndTime)
    {
       string obj = swings[index].objName;
       
       if(newEndTime != 0)
       {
          swings[index].endTime = newEndTime;
          // Cannot change OBJPROP_TIME2 because horizontal line doesn't have that property
          // We indicate line hit by changing style to dashed
          
          ObjectSetInteger(0, obj, OBJPROP_STYLE, STYLE_DASH);
       }
       else
       {
          // Nothing to do here to extend line because horizontal line in MQL5 extends fully by default
          // Just make sure style is solid if not touched
          ObjectSetInteger(0, obj, OBJPROP_STYLE, STYLE_SOLID);
       }
    }
    
    // Check if price touched or crossed swing line
    bool PriceTouchedSwingLine(int index)
    {
       SwingLine swingsRef = swings[index];  // Copy, references ( &) not allowed in MQL5
       
       if(swingsRef.endTime != 0) return true; // already touched
       
       double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
       double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
       
       if(swingsRef.isHigh)
       {
          // Swing high: price touches if bid >= swing price
          if(bid >= swingsRef.price)
             return true;
       }
       else
       {
          // Swing low: price touches if ask <= swing price
          if(ask <= swingsRef.price)
             return true;
       }
       return false;
    }
    
    // Process all existing swings: extend or mark touched ones
    void ProcessExistingSwings()
    {
       datetime openTimeCurrentBar = iTime(_Symbol, swingTF, 0);
       
       for(int i=0; i<swingCount; i++)
       {
          if(swings[i].endTime == 0)
          {
             // Not touched yet, check price touch
             if(PriceTouchedSwingLine(i))
             {
                // Mark touched: end time is current bar open time
                UpdateSwingLine(i, openTimeCurrentBar);
             }
             else
             {
                // Still not touched, style solid
                UpdateSwingLine(i, 0);
             }
          }
       }
    }
    
    // Detect and add new swing line if applicable (called every new swingTF bar)
    void DetectAndAddSwingLine()
    {
       datetime highTime; double highPrice;
       datetime lowTime; double lowPrice;
       
       if(!FindSwingHighLow(highTime, highPrice, lowTime, lowPrice))
          return;  // Not enough data to detect swings
       
       // Decide which came more recently; add that swing line
       if(highTime > lowTime)
       {
          // High more recent — add swing high
          // Prevent duplicates: don't add if swing line at that time already exists
          bool exists = false;
          for(int i=0; i<swingCount; i++)
          {
             if(swings[i].isHigh && swings[i].startTime == highTime)
             {
                exists = true;
                break;
             }
          }
          if(!exists)
             AddSwingLine(true, highPrice, highTime);
       }
       else
       {
          // Low more recent — add swing low
          bool exists = false;
          for(int i=0; i<swingCount; i++)
          {
             if(!swings[i].isHigh && swings[i].startTime == lowTime)
             {
                exists = true;
                break;
             }
          }
          if(!exists)
             AddSwingLine(false, lowPrice, lowTime);
       }
    }
    
    // Check if we are on a new bar on the swingTF
    datetime lastProcessedTime = 0;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
       // Clear any previous swing lines before start
       for(int i=0; i<swingCount; i++)
          DeleteSwingLine(i);
       swingCount = 0;
       lastProcessedTime = 0;
       
       Print("SwingLinesEA initialized.");
       return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
       // Delete all swing lines on deinit
       for(int i=swingCount-1; i>=0; i--)
       {
          DeleteSwingLine(i);
       }
       swingCount = 0;
       Print("SwingLinesEA deinitialized - all lines removed.");
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
       // We'll process swings on new bar of swingTF only
       datetime currentBarTime = iTime(_Symbol, swingTF, 0);
       if(currentBarTime == 0)
          return; // no bar loaded yet
       
       if(currentBarTime != lastProcessedTime)
       {
          lastProcessedTime = currentBarTime;
          
          // 1. Process existing swing lines (extend or mark touched)
          ProcessExistingSwings();
          
          // 2. Detect and add new swings
          DetectAndAddSwingLine();
       }
    }
    //+------------------------------------------------------------------+
    

    Key Fixes

    1. 'Color' → 'color':
      The MQL5 type is lowercase color, not Color.

    2. OBJPROP_TIME2 unsupported for OBJ_HLINE:
      Horizontal lines in MQL5 do not have OBJPROP_TIME or OBJPROP_TIME2 properties. They extend infinitely to the left and right by default. So I removed code that sets those properties.

    3. No reference (&) for struct elements:
      MQL5 doesn’t support references (&) for struct array elements, so I copied struct values instead when needed.

    4. Object creation parameters:
      The ObjectCreate call for OBJ_HLINE ignores the time parameter. It requires three parameters: chart ID, object name, object type, subwindow (0), time (ignored for HLINE), price.

    5. Extending lines:
      Since MQL5 horizontal lines are infinite, line extension handled via properties isn’t needed; style changes (solid/dashed) indicate state.


    How to compile and use

    • Copy this code into a new Expert Advisor in MetaEditor.
    • Save and compile.
    • Attach to any chart.
    • It will plot swing highs in green, swing lows in red on the chart.
    • Lines will change style to dashed if price crosses/touches them.

    If you want improved dynamic time-limited lines, you'd need to use OBJ_TREND with two points, but this complicates tracking extension and line touch detection.


    If you want me to help with such two-point line approach or alerts, let me know!