make the same code double top as well , and add them on one code
- User
make the same code double top as well , and add them on one code
Assistant
Below is the combined MQL4 code for both Double Top and Double Bottom patterns based on EMA. The code includes a pattern type selector (Double Bottom or Double Top) and handles both cases within a single script. The logic is extended to detect tops/bottoms symmetrically, with clear visualization and alerts for both patterns.
//+------------------------------------------------------------------+ //| EMA Double Pattern.mq4 | //| Detects Double Tops and Double Bottoms | //| Based on EMA Touch Conditions | //+------------------------------------------------------------------+ #property copyright "Your Name" #property link "Your Website" #property version "1.00" #property strict #property indicator_chart_window // Overlay on price chart // ———— Configurable Inputs ———— enum PatternType { DOUBLE_BOTTOM = 0, DOUBLE_TOP = 1 }; input PatternType patternType = DOUBLE_BOTTOM; // Select Pattern Type input int emaPeriod = 20; // EMA Period input int swingLookback = 1; // Swing Lookback (N Bars) input double priceTolerance = 0.5; // Price Tolerance (%) input double necklineTouchThreshold = 0.1; // Neckline Touch Threshold (%) input double patternFailureThreshold = 1.0; // Pattern Failure Threshold (%) input color emaColor = clrBlue;// EMA Color input color necklineColor = clrRed; // Neckline Color input color markerColor = clrLimeGreen; // Marker Color input color alertColor = clrRed; // Alert Color // ———— Global Variables (State Management) ———— static int state = 0; // 0: Idle | 1: 1st Peak/Trough Confirmed | 2: Below/Above EMA | 3: 2nd Peak/Trough Confirmed | 4: Alert Triggered static double firstPrice = 0.0; // 1st Top/Bottom Price static double necklineCandidate = 0.0; // Neckline Candidate (Between Peaks/Troughs) static double secondPrice = 0.0; // 2nd Top/Bottom Price static double neckline = 0.0; // Confirmed Neckline Price static datetime lastBarTime = 0; // Track last bar time // ———— Helper Function: Check if New Bar Has Formed ———— bool IsNewBar() { if (Time[0] != lastBarTime) { lastBarTime = Time[0]; return true; } return false; } // ———— Helper Function: Calculate Percentage Difference ———— double PercentDiff(double price1, double price2) { return MathAbs((price1 - price2) / price2) * 100; } // ———— Helper Function: Confirm Swing (Low for Bottom, High for Top) ———— bool IsConfirmedSwing(int shift, bool isTop) { if (shift < swingLookback) return false; // Check if price[shift] is lower/higher than previous N bars bool isExtreme = true; for (int i = 1; i <= swingLookback; i++) { if ((isTop && High[shift] <= High[shift + i]) || (!isTop && Low[shift] >= Low[shift + i])) { isExtreme = false; break; } } // Check if price[shift] is lower/higher than next N bars (confirmed by closed bars) for (int i = 1; i <= swingLookback; i++) { if (shift - i < 0) break; if ((isTop && High[shift] <= High[shift - i]) || (!isTop && Low[shift] >= Low[shift - i])) { isExtreme = false; break; } } return isExtreme; } // ———— Helper Function: Draw Text Marker ———— void DrawTextMarker(datetime barTime, double price, string text, color markerColor, bool belowBar) { string objName = StringConcatenate("Marker_", barTime); if (ObjectFind(objName) != -1) ObjectDelete(objName); double yOffset = belowBar ? -0.0005 * price : 0.0005 * price; // Adjust offset ObjectCreate(objName, OBJ_TEXT, 0, barTime, price + yOffset); ObjectSetString(0, objName, OBJPROP_TEXT, text); ObjectSetInteger(0, objName, OBJPROP_COLOR, markerColor); ObjectSetInteger(0, objName, OBJPROP_FONT_SIZE, 8); ObjectSetInteger(0, objName, OBJPROP_ALIGN, ALIGN_CENTER); } // ———— Helper Function: Draw Neckline ———— void DrawNeckline(double price, bool isConfirmed) { string objName = isConfirmed ? "Neckline_Confirmed" : "Neckline_Temp"; if (ObjectFind(objName) != -1) ObjectDelete(objName); datetime startTime = Time[0]; datetime endTime = startTime + (Period() * 60) * 20; // Extend 20 bars ahead ObjectCreate(objName, OBJ_TREND, 0, startTime, price, endTime, price); ObjectSetInteger(0, objName, OBJPROP_COLOR, isConfirmed ? necklineColor : clrOrange); ObjectSetInteger(0, objName, OBJPROP_STYLE, isConfirmed ? STYLE_DASH : STYLE_DOT); ObjectSetInteger(0, objName, OBJPROP_WIDTH, isConfirmed ? 2 : 1); if (isConfirmed) { string labelName = StringConcatenate("Neckline_Label_", Time[0]); ObjectCreate(labelName, OBJ_TEXT, 0, startTime, price + 0.0005 * price); ObjectSetString(0, labelName, OBJPROP_TEXT, StringFormat("Neckline: %.2f", price)); ObjectSetInteger(0, labelName, OBJPROP_COLOR, necklineColor); } } //+------------------------------------------------------------------+ //| Expert Advisor tick function | //+------------------------------------------------------------------+ void OnTick() { if (!IsNewBar()) return; // Execute only on new bar close // Calculate EMA double ema = iMA(_Symbol, _Period, emaPeriod, 0, MODE_EMA, PRICE_CLOSE, 1); // Plot EMA static string emaLineName = "EMA_Line"; if (ObjectFind(emaLineName) == -1) { ObjectCreate(emaLineName, OBJ_TREND, 0, Time[1], ema, Time[0], ema); } else { ObjectMove(emaLineName, 0, Time[1], ema); ObjectMove(emaLineName, 1, Time[0], ema); } ObjectSetInteger(0, emaLineName, OBJPROP_COLOR, emaColor); ObjectSetInteger(0, emaLineName, OBJPROP_WIDTH, 2); // Determine Pattern Parameters (Top or Bottom) bool isTop = (patternType == DOUBLE_TOP); double extremePrice = isTop ? High[1] : Low[1]; // Use previous bar (shift=1) double closePrice = Close[1]; double emaPrev = iMA(_Symbol, _Period, emaPeriod, 0, MODE_EMA, PRICE_CLOSE, 2); // EMA for close[2] // ———— State 0: Idle → Look for 1st Peak/Trough ———— if (state == 0) { bool isTouchEma = isTop ? (closePrice > emaPrev && extremePrice >= ema && closePrice < ema) : // Top: Close above EMA → Touch EMA → Close below EMA (closePrice < emaPrev && extremePrice <= ema && closePrice > ema); // Bottom: Close below EMA → Touch EMA → Close above EMA if (isTouchEma && IsConfirmedSwing(1, isTop)) { state = 1; firstPrice = extremePrice; necklineCandidate = isTop ? Low[1] : High[1]; // Neckline candidate (between peaks/troughs) string markerText = isTop ? "1" : "1"; DrawTextMarker(Time[1], extremePrice, markerText, markerColor, !isTop); Print("State 0 → 1: 1st ", isTop ? "Top" : "Bottom", " Confirmed at ", firstPrice); } } // ———— State 1: 1st Peak/Trough Confirmed → Track Neckline ———— else if (state == 1) { double updatePrice = isTop ? Low[0] : High[0]; // Update neckline candidate if ((isTop && updatePrice < necklineCandidate) || (!isTop && updatePrice > necklineCandidate)) { necklineCandidate = updatePrice; DrawNeckline(necklineCandidate, false); // Temp neckline } // Transition to State 2: Price crosses EMA (opposite direction) bool isCrossEma = isTop ? (closePrice > ema) : (closePrice < ema); if (isCrossEma) { state = 2; Print("State 1 → 2: Price Crossed EMA"); } // Pattern Failure: Price moves too far (opposite direction) double failurePrice = isTop ? High[1] : Low[1]; if ((isTop && PercentDiff(failurePrice, firstPrice) > patternFailureThreshold) || (!isTop && PercentDiff(firstPrice, failurePrice) > patternFailureThreshold)) { state = 0; firstPrice = 0.0; necklineCandidate = 0.0; Print("State 1 → 0: Pattern Failed (Price Moved Too Far)"); } } // ———— State 2: Below/Above EMA → Look for 2nd Peak/Trough ———— else if (state == 2) { bool isSecondExtreme = IsConfirmedSwing(1, isTop) && ((isTop && closePrice < ema) || (!isTop && closePrice > ema)) && (PercentDiff(extremePrice, firstPrice) <= priceTolerance); if (isSecondExtreme) { state = 3; secondPrice = extremePrice; neckline = isTop ? ta.lowest(Low, 1, 0) : ta.highest(High, 1, 0); // Confirm neckline string markerText = isTop ? "2" : "2"; DrawTextMarker(Time[1], extremePrice, markerText, markerColor, !isTop); DrawNeckline(neckline, true); // Confirmed neckline Print("State 2 → 3: 2nd ", isTop ? "Top" : "Bottom", " Confirmed at ", secondPrice, ". Neckline: ", neckline); } // Pattern Failure: Price moves too far (opposite direction) double failurePrice = isTop ? High[1] : Low[1]; if ((isTop && PercentDiff(failurePrice, firstPrice) > patternFailureThreshold) || (!isTop && PercentDiff(firstPrice, failurePrice) > patternFailureThreshold)) { state = 0; firstPrice = 0.0; necklineCandidate = 0.0; Print("State 2 → 0: Pattern Failed (Price Moved Too Far)"); } } // ———— State 3: 2nd Peak/Trough Confirmed → Wait for Neckline Touch ———— else if (state == 3) { double touchThreshold = neckline * (isTop ? (1 + (necklineTouchThreshold / 100)) : (1 - (necklineTouchThreshold / 100))); bool isTouch = isTop ? (Low[1] <= touchThreshold) : (High[1] >= touchThreshold); if (isTouch) { state = 4; Alert(StringFormat("Double ", isTop ? "Top" : "Bottom", ": Neckline Touched!\nSymbol: %s\nTimeframe: %s\nNeckline: %.2f\nPrice: %.2f", _Symbol, EnumToString(_Period), neckline, isTop ? Low[1] : High[1])); DrawTextMarker(Time[1], isTop ? Low[1] : High[1], "⚠", alertColor, isTop); Print("State 3 → 4: Neckline Touched at ", isTop ? Low[1] : High[1]); } // Pattern Failure: Price moves too far (opposite direction) double failurePrice = isTop ? High[1] : Low[1]; if ((isTop && PercentDiff(failurePrice, secondPrice) > patternFailureThreshold) || (!isTop && PercentDiff(secondPrice, failurePrice) > patternFailureThreshold)) { state = 0; firstPrice = 0.0; necklineCandidate = 0.0; secondPrice = 0.0; neckline = 0.0; Print("State 3 → 0: Pattern Failed (Price Moved Too Far)"); } } // ———— State 4: Alert Triggered → Reset ———— else if (state == 4) { state = 0; firstPrice = 0.0; necklineCandidate = 0.0; secondPrice = 0.0; neckline = 0.0; Print("State 4 → 0: Alert Triggered → Reset"); } }Key Features of the Combined Code
-
Pattern Type Selector
- Use the
patternTypeinput to switch between Double Top and Double Bottom detection. - Logic dynamically adjusts for highs/lows, EMA touch direction, and neckline calculation.
- Use the
-
Symmetric Logic
- Double Top:
- 1st top: Price touches EMA from above → closes below EMA.
- 2nd top: Within tolerance of 1st top → neckline = lowest low between tops.
- Alert: Price touches neckline (downside).
- Double Bottom:
- 1st bottom: Price touches EMA from below → closes above EMA.
- 2nd bottom: Within tolerance of 1st bottom → neckline = highest high between bottoms.
- Alert: Price touches neckline (upside).
- Double Top:
-
Visualization
- EMA line (blue).
- "1" and "2" markers for tops/bottoms (green).
- Neckline (red dashed line with price label).
- Alert marker ("⚠" in red).
-
Alert System
- MetaTrader alert with pattern type, neckline price, and current price.
- Configure email/SMS alerts via Tools → Options → Alerts.
-
Failure Protection
- Resets if price moves too far beyond the 1st or 2nd top/bottom (configurable threshold).
How to Use
- Attach the script to a chart in MetaTrader 4.
- Select the pattern type (Double Top or Double Bottom) via inputs.
- Adjust EMA period, tolerance, and thresholds for your asset/timeframe.
- Watch for:
- Double Top: Short on neckline touch (downside breakout).
- Double Bottom: Long on neckline touch (upside breakout).
Example Input Settings
- Double Bottom:
patternType = DOUBLE_BOTTOMemaPeriod = 20priceTolerance = 0.5(0.5% price similarity between bottoms)
- Double Top:
patternType = DOUBLE_TOPemaPeriod = 50priceTolerance = 0.3(0.3% price similarity between tops)
Let me know if you need further enhancements (e.g., volume confirmation, multi-timeframe EMA, or additional filters)!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.