Strategy · Pine Script v6 · Own pane

MS+MACD Enhanced Tests

by iamrichardD

This script implements an enhanced testing framework for the Market Structure MACD 4H strategy.

View on GitHub

GitHub stars57on the repository
Pine versionv6current
Lines of code191
Settings0inputs
LicenceApache-2.0
Last update1 year ago19 Aug 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

191 lines of Pine Script v6 from production/4h-swing-trading/test-suite-enhanced.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

test-suite-enhanced.pine
// Market Structure MACD 4H Strategy - Enhanced Test Suite
// Comprehensive testing for streamlined MS+MACD+Trailing system
// Performance validation and stress testing

//@version=6
strategy("MS+MACD Enhanced Tests", overlay=false, max_labels_count=300)

//=====================================================================================================================
// ENHANCED PINEUNIT TESTING FRAMEWORK
//=====================================================================================================================

type TestCase
    string name
    bool passed
    string message
    float expected
    float actual
    string category
    
type TestSuite
    string name
    array<TestCase> tests
    int totalTests
    int passedTests
    int failedTests
    
    method addTest(string testName, bool condition, string message = "", float expected = na, float actual = na, string category = "General") =>
        test = TestCase.new(testName, condition, message, expected, actual, category)
        array.push(this.tests, test)
        this.totalTests += 1
        if condition
            this.passedTests += 1
        else
            this.failedTests += 1
    
    method getResults() =>
        passRate = this.totalTests > 0 ? (this.passedTests / this.totalTests) * 100 : 0
        [this.passedTests, this.failedTests, this.totalTests, passRate]

//=====================================================================================================================
// ADVANCED MOCK FUNCTIONS FOR ENHANCED TESTING
//=====================================================================================================================

// Enhanced Market Structure with Period Sensitivity
mockAdvancedMarketStructure(price, lookback, sensitivity) =>
    // Simulate different detection periods (20 vs 50)
    detectionRate = sensitivity <= 20 ? 0.8 : 0.6  // Shorter periods = more signals
    noiseLevel = sensitivity <= 20 ? 0.15 : 0.1    // Shorter periods = more noise
    
    baseSignal = price > 100.5 or price < 99.5  // Basic structure break
    adjustedSignal = baseSignal and math.random() > noiseLevel
    
    [adjustedSignal, detectionRate, noiseLevel]

// MACD Parameter Sensitivity Testing
mockMACDSensitivity(fast, slow, signal, marketCondition) =>
    // Test different MACD settings in various markets
    if marketCondition == "trending"
        effectiveness = fast <= 12 and slow >= 26 ? 0.85 : 0.65
    else if marketCondition == "choppy"
        effectiveness = fast >= 12 and slow <= 26 ? 0.55 : 0.35
    else
        effectiveness = 0.7
    
    signalQuality = effectiveness > 0.7
    [signalQuality, effectiveness]

// Advanced Trailing Stop Simulation
mockAdvancedTrailing(entryPrice, priceHistory, atrValue, marketVolatility) =>
    // Simulate trailing in different market conditions
    var float maxProfit = 0.0
    var float trailValue = na
    var bool wasTriggered = false
    
    for i = 0 to array.size(priceHistory) - 1
        currentPrice = array.get(priceHistory, i)
        currentProfit = currentPrice - entryPrice
        
        if currentProfit > maxProfit
            maxProfit := currentProfit
            
        if maxProfit >= atrValue * 1.0  // Trail trigger
            newTrail = currentPrice - (atrValue * 1.5)
            if na(trailValue) or newTrail > trailValue
                trailValue := newTrail
                
        // Check if trail was hit
        if not na(trailValue) and currentPrice <= trailValue
            wasTriggered := true
            break
    
    profitCaptured = wasTriggered ? trailValue - entryPrice : maxProfit
    [profitCaptured, maxProfit, wasTriggered]

// Risk Management Stress Testing
mockRiskStress(accountSize, riskPercent, volatilityMultiplier, drawdownLevel) =>
    baseRisk = accountSize * (riskPercent / 100)
    adjustedRisk = baseRisk * volatilityMultiplier
    
    // Stress test scenarios
    normalMarket = adjustedRisk / accountSize <= 0.03  // ≤3% per trade
    stressedMarket = adjustedRisk / accountSize <= 0.05  // ≤5% per trade
    extremeMarket = adjustedRisk / accountSize <= 0.08   // ≤8% per trade
    
    maxDrawdownExpected = riskPercent * 5  // Rough estimate
    drawdownOk = drawdownLevel <= maxDrawdownExpected
    
    [normalMarket, stressedMarket, extremeMarket, drawdownOk]

// Performance Simulation
mockPerformanceScenario(winRate, avgWin, avgLoss, tradeCount) =>
    wins = math.floor(tradeCount * (winRate / 100))
    losses = tradeCount - wins
    
    grossProfit = wins * avgWin
    grossLoss = losses * avgLoss
    netProfit = grossProfit - grossLoss
    profitFactor = grossLoss > 0 ? grossProfit / grossLoss : na
    
    expectancy = (winRate / 100 * avgWin) - ((100 - winRate) / 100 * avgLoss)
    
    [netProfit, profitFactor, expectancy, wins, losses]

//=====================================================================================================================
// TEST SUITES INITIALIZATION
//=====================================================================================================================

var testSuiteAdvanced = TestSuite.new("Advanced Market Structure", array.new<TestCase>(), 0, 0, 0)
var testSuiteMACD = TestSuite.new("MACD Optimization", array.new<TestCase>(), 0, 0, 0)
var testSuiteRisk = TestSuite.new("Risk Management Stress", array.new<TestCase>(), 0, 0, 0)
var testSuiteTrailing = TestSuite.new("Advanced Trailing", array.new<TestCase>(), 0, 0, 0)
var testSuitePerformance = TestSuite.new("Performance Validation", array.new<TestCase>(), 0, 0, 0)
var testSuiteIntegration = TestSuite.new("System Integration", array.new<TestCase>(), 0, 0, 0)

//=====================================================================================================================
// ADVANCED MARKET STRUCTURE TESTS
//=====================================================================================================================

if bar_index == 100
    // Test period sensitivity (20 vs 50)
    [signal20, rate20, noise20] = mockAdvancedMarketStructure(105.0, 20, 20)
    [signal50, rate50, noise50] = mockAdvancedMarketStructure(105.0, 50, 50)
    
    testSuiteAdvanced.addTest("Period 20 Sensitivity", signal20 and rate20 > 0.7, 
                             "CHoCH period 20 should provide good sensitivity", rate20, rate20, "Detection")
    
    testSuiteAdvanced.addTest("Period 20 vs 50 Trade-off", rate20 > rate50 and noise20 > noise50, 
                             "Period 20 should have higher detection but more noise", na, na, "Detection")
    
    // Test IDM period optimization (5 vs 8)
    [signalIDM5, rateIDM5, noiseIDM5] = mockAdvancedMarketStructure(102.0, 5, 5)
    [signalIDM8, rateIDM8, noiseIDM8] = mockAdvancedMarketStructure(102.0, 8, 8)
    
    testSuiteAdvanced.addTest("IDM Period 5 Responsiveness", rateIDM5 > 0.75, 
                             "IDM period 5 should be highly responsive", 0.75, rateIDM5, "IDM")
    
    testSuiteAdvanced.addTest("IDM Period Balance", signalIDM5 and noiseIDM5 < 0.2, 
                             "IDM period 5 should balance signal and noise", na, noiseIDM5, "IDM")
    
    // Test structure break validation
    priceSequence = array.from(100.0, 101.0, 102.0, 103.0, 105.0)  // Strong trend
    strongBreak = array.get(priceSequence, 4) > array.get(priceSequence, 0) * 1.03
    testSuiteAdvanced.addTest("Strong Structure Break", strongBreak, 
                             "Should detect significant structure breaks", na, na, "Structure")
    
    // Test weak signal filtering
    weakSequence = array.from(100.0, 100.2, 100.1, 100.3, 100.4)  // Weak movement
    weakBreak = array.get(weakSequence, 4) > array.get(weakSequence, 0) * 1.005
    testSuiteAdvanced.addTest("Weak Signal Filtering", not weakBreak, 
                             "Should filter out weak/false signals", na, na, "Structure")

//=====================================================================================================================
// MACD OPTIMIZATION TESTS
//=====================================================================================================================

if bar_index == 200
    // Test MACD in trending markets
    [trendSignal, trendEffect] = mockMACDSensitivity(12, 26, 9, "trending")
    testSuiteMACD.addTest("MACD Trending Market", trendSignal and trendEffect > 0.8, 
                         "MACD should perform well in trending markets", 0.8, trendEffect, "Trending")
    
    // Test MACD in choppy markets
    [choppySignal, choppyEffect] = mockMACDSensitivity(12, 26, 9, "choppy")
    testSuiteMACD.addTest("MACD Choppy Market", trendEffect > choppyEffect, 
                         "MACD should perform better in trending vs choppy", trendEffect, choppyEffect, "Choppy")
    
    // Test alternative MACD settings
    [fastSignal, fastEffect] = mockMACDSensitivity(8, 21, 7, "trending")
    [slowSignal, slowEffect] = mockMACDSensitivity(16, 35, 12, "trending")
    
    testSuiteMACD.addTest("MACD Settings Comparison", trendEffect >= fastEffect and trendEffect >= slowEffect,

Overview

MS+MACD Enhanced Tests defines test cases with pass rates and includes mock functions simulating advanced market structure detection, MACD sensitivity analysis across trending and choppy conditions, and advanced trailing stop calculations based on ATR. The strategy draws test results and signals in a separate pane with no inputs. It performs performance validation and stress testing of the MS+MACD+Trailing system. The code uses mock logic and does not implement real trading entries or exits.

Details

Published by

iamrichardD on GitHub

Type

Strategy, Pine Script v6

Draws

Separate pane below the chart

Category

Trend, Oscillators & momentum, SMC / ICT / price action, Volatility & bands

Markets

Any symbol

Timeframes

H4 and above

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

TnS_ICT_V20

by raybird
1 stars

TnS_ICT_V20 is a Pine Script v6 strategy that identifies institutional trading opportunities using ICT concepts. It calculates pivot swings as support and resistance levels, OTE zones, and a thermodynamic audit based on free energy and fractal entropy to filte

Strategy v6 SMC / ICT / price actionTrend
Updated 2 months ago · None stated GitHub repository of TnS_ICT_V20
106 stars

This strategy captures strong bullish momentum by combining a 200-period SMA baseline, a custom Bollinger Band, the True Strength Index (TSI) smoothed with WMAs, and the ADX trend strength indicator. It initiates long positions when price is above the 200 SMA,

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of ADX_TSI_Bol Band Trend Chaser

Combines an upgraded WaveTrend oscillator engine with market structure swing pivots, volume profile point of control (POC), and multi-timeframe trend alignment scoring. Trades are triggered by WaveTrend reversal or pullback continuation signals that pass conte

Strategy v6 Oscillators & momentumTrend
Updated yesterday · MIT GitHub repository of WaveTrend v3 [WavesUnchained] — Strategy
6 stars

This strategy identifies high-volatility expansion bars by comparing the high-low range to a moving average plus standard deviation threshold. When range expansion occurs, it checks momentum over a specified lookback period. It opens a long position if the cur

Strategy v5 Volatility & bandsOscillators & momentum
Updated 1 year ago · None stated GitHub repository of TradersPost High-Low Range Strategy

Alpy Kazan

by avatar-lavventura
2 stars

This strategy tracks market direction using an ATR-based trailing envelope similar to Supertrend, combined with Bollinger Bands, Keltner Channels, and momentum filters. Long and short entry signals trigger on trend direction shifts within a specified backtest

Strategy v4 TrendVolatility & bands
Updated 7 months ago · None stated GitHub repository of Alpy Kazan

Alt Coin BB SMA Strategy

by samliu0206
1 stars

Alt Coin BB SMA Strategy calculates custom MACD delta histogram values, Bollinger Bands, and middle band slopes to generate trading signals in a separate pane. It triggers long entry orders when the price crosses above the Bollinger middle band, provided the M

Strategy v4 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Alt Coin BB SMA Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers