Zeal Terminal Open Zeal Terminal

Pine Script v4 · Strategy

Webhook Starter Kit [HullBuster]

A Pine Script v4 strategy built on EMA (seriesData, ncMALength), Stoch (close[indexClosedBar], high[indexClosedBar]) and SMA (htf_seriesFastAlma, ncNormalizeLen). It has 14 order rules, 6 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade is one contract and pays no commission. 47 settings; defaults include Build Number 101, Trading Mode BiDir and Minimum Profit 0.50.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Webhook Starter Kit [HullBuster] repaint?
No
No repainting patterns were found in the source.
Can Webhook Starter Kit [HullBuster] be converted to Pine Script v5?
Not tested
The steps are shown below, but the original does not run in Zeal Terminal's engine, so they could not be checked.
Does Webhook Starter Kit [HullBuster] use a stop loss?
Yes
strategy.exit sets a stop on line 552, 562, 629, 633.
Does Webhook Starter Kit [HullBuster] run in Zeal Terminal?
No
Not yet: Pine Script v4 Error at @L703:C69: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.
Does not run in Zeal Terminal yetPine Script v4 Error at @L703:C69: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • Check

    1 setting does nothing

    “Build Number” is declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

  • Note

    Uses an argument v6 removed

    when = on line 571, 576. The upgraded version below moves each call inside an if block.

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames ema → ta.ema, linreg → ta.linreg, alma → ta.alma, stoch → ta.stoch, security → request.security, sma → ta.sma, stdev → ta.stdev, abs → math.abs, crossover → ta.crossover, crossunder → ta.crossunder, tostring → str.tostring.
  • 2 strategy calls use the when = argument (line 571, 576). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Not verified

The v4 script does not run in Zeal Terminal's engine (Pine Script v4 Error at @L703:C69: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.), so this step could not be checked.

  • Line 3: //@version=4 → //@version=5
  • Line 8: input(type = input.integer) → input.int()
  • Line 10: input(type = input.float) → input.float()
  • Line 11: input(type = input.float) → input.float()
  • Line 12: input(type = input.float) → input.float()
  • Line 13: input(type = input.float) → input.float()
93 more edits
  • Line 14: input(type = input.float) → input.float()
  • Line 15: input(type = input.bool) → input.bool()
  • Line 16: input(type = input.integer) → input.int()
  • Line 19: input(type = input.integer) → input.int()
  • Line 20: input(type = input.integer) → input.int()
  • Line 21: input(type = input.integer) → input.int()
  • Line 22: input(type = input.integer) → input.int()
  • Line 23: input(type = input.integer) → input.int()
  • Line 24: input(type = input.integer) → input.int()
  • Line 25: input(type = input.integer) → input.int()
  • Line 26: input(type = input.integer) → input.int()
  • Line 27: input(type = input.float) → input.float()
  • Line 28: input(type = input.float) → input.float()
  • Line 29: input(type = input.float) → input.float()
  • Line 30: input(type = input.float) → input.float()
  • Line 31: input(type = input.bool) → input.bool()
  • Line 32: input(type = input.bool) → input.bool()
  • Line 33: input(type = input.bool) → input.bool()
  • Line 34: input(type = input.bool) → input.bool()
  • Line 35: input(type = input.bool) → input.bool()
  • Line 36: input(type = input.bool) → input.bool()
  • Line 37: input(type = input.bool) → input.bool()
  • Line 38: input(type = input.bool) → input.bool()
  • Line 39: input(type = input.bool) → input.bool()
  • Line 40: input(type = input.bool) → input.bool()
  • Line 41: input(type = input.float) → input.float()
  • Line 42: input(type = input.float) → input.float()
  • Line 43: input(type = input.float) → input.float()
  • Line 44: input(type = input.float) → input.float()
  • Line 45: input(type = input.float) → input.float()
  • Line 46: input(type = input.float) → input.float()
  • Line 47: input(type = input.bool) → input.bool()
  • Line 48: input(type = input.bool) → input.bool()
  • Line 49: input(type = input.bool) → input.bool()
  • Line 50: input(type = input.bool) → input.bool()
  • Line 51: input(type = input.bool) → input.bool()
  • Line 52: input(type = input.bool) → input.bool()
  • Line 53: input(type = input.bool) → input.bool()
  • Line 54: input(type = input.bool) → input.bool()
  • Line 106: ema → ta.ema
  • Line 107: ema → ta.ema
  • Line 112: linreg → ta.linreg
  • Line 114: linreg → ta.linreg
  • Line 116: alma → ta.alma
  • Line 118: stoch → ta.stoch
  • Line 127: security → request.security
  • Line 128: security → request.security
  • Line 130: security → request.security
  • Line 132: security → request.security
  • Line 134: sma → ta.sma
  • Line 137: stdev → ta.stdev
  • Line 139: security → request.security
  • Line 140: sma → ta.sma
  • Line 141: sma → ta.sma
  • Line 144: sma → ta.sma
  • Line 146: sma → ta.sma
  • Line 148: ema → ta.ema
  • Line 150: stoch → ta.stoch
  • Line 151: sma → ta.sma
  • Line 152: sma → ta.sma
  • Line 411: abs → math.abs
  • Line 432: crossover → ta.crossover
  • Line 444: crossunder → ta.crossunder
  • Line 547: tostring → str.tostring
  • Line 549: tostring → str.tostring
  • Line 550: abs → math.abs
  • Line 552: tostring → str.tostring
  • Line 557: tostring → str.tostring
  • Line 559: tostring → str.tostring
  • Line 560: abs → math.abs
  • Line 562: tostring → str.tostring
  • Line 564: abs → math.abs
  • Line 571: tostring → str.tostring
  • Line 576: tostring → str.tostring
  • Line 592: tostring → str.tostring
  • Line 592: tostring → str.tostring
  • Line 592: tostring → str.tostring
  • Line 592: tostring → str.tostring
  • Line 592: tostring → str.tostring
  • Line 628: tostring → str.tostring
  • Line 629: tostring → str.tostring
  • Line 632: tostring → str.tostring
  • Line 633: tostring → str.tostring
  • Line 687: tostring → str.tostring
  • Line 688: tostring → str.tostring
  • Line 689: tostring → str.tostring
  • Line 690: tostring → str.tostring
  • Line 691: tostring → str.tostring
  • Line 699: tostring → str.tostring
  • Line 700: tostring → str.tostring
  • Line 701: tostring → str.tostring
  • Line 703: tostring → str.tostring
  • Line 704: tostring → str.tostring
⋯// © tradingtudi-//@version=4+//@version=5strategy(title = "WebhookDrive-V1", overlay = true, pyramiding = 0, initial_capital = 10000, currency = currency.USD)⋯// ------------------------------inputBuild           = input(defval = 101,    type = input.integer,  minval = 0.0,  title = "Build Number",           group = "[ SECTION 1 ]", tooltip = "This is a trend follow script that enters the market long above the purple line and short below. It is prone to losses on ranging markets where the trend line bisects the price stream")+inputBuild           = input.int(defval = 101,  minval = 0.0,  title = "Build Number",           group = "[ SECTION 1 ]", tooltip = "This is a trend follow script that enters the market long above the purple line and short below. It is prone to losses on ranging markets where the trend line bisects the price stream")inputTradingMode     = input(defval = "BiDir", options = ["Long","Short","BiDir","Flip Flop","Crypto","Range","No Trade"], title = "Trading Mode", group = "[ SECTION 1 ]", tooltip = "BiDir is for margin trading with a stop. Flip Flop will alter direction on trend line cross. Crypto is long only with downward pyramids. Range only enters on a counter-trend")-inputMinProfit       = input(defval = 0.50,   type = input.float,    minval = 0.0,  title = "Minimum Profit",         group = "[ SECTION 1 ]", tooltip = "Smallest take profit offset to permit a close order. This is a conditional exit not a limit (quote currency units)")+inputMinProfit       = input.float(defval = 0.50,    minval = 0.0,  title = "Minimum Profit",         group = "[ SECTION 1 ]", tooltip = "Smallest take profit offset to permit a close order. This is a conditional exit not a limit (quote currency units)")-inputStopOffset      = input(defval = 0.50,   type = input.float,    minval = 0.0,  title = "Stop Offset",            group = "[ SECTION 1 ]", tooltip = "Hard stop offset from the trade open price (quote currency units)")+inputStopOffset      = input.float(defval = 0.50,    minval = 0.0,  title = "Stop Offset",            group = "[ SECTION 1 ]", tooltip = "Hard stop offset from the trade open price (quote currency units)")-inputTickScaler      = input(defval = 10.0,   type = input.float,    minval = 1.0,  title = "Tick Scalar",            group = "[ SECTION 1 ]", tooltip = "Value used to remove the pipette from quote currency calculations. See the Summary Report to determine this value")+inputTickScaler      = input.float(defval = 10.0,    minval = 1.0,  title = "Tick Scalar",            group = "[ SECTION 1 ]", tooltip = "Value used to remove the pipette from quote currency calculations. See the Summary Report to determine this value")-inputChgDivisor      = input(defval = 1000.0, type = input.float,    minval = 1.0,  title = "Price Normalizer",       group = "[ SECTION 1 ]", tooltip = "Value used to normalize bar prices for differential calculations. Serves to increase the magnitude of significant digits. Applied to all inputs specifying net change and roc")+inputChgDivisor      = input.float(defval = 1000.0,    minval = 1.0,  title = "Price Normalizer",       group = "[ SECTION 1 ]", tooltip = "Value used to normalize bar prices for differential calculations. Serves to increase the magnitude of significant digits. Applied to all inputs specifying net change and roc")-inputPryramidSpan    = input(defval = 0.0,    type = input.float,    minval = 0.0,  title = "Pyramid Minimum Span",   group = "[ SECTION 1 ]", tooltip = "Minimum spacing between downward pyramid levels (quote currency units). Set to zero to disable downward pyramiding. To fully disable pyramiding zero the value in the Properties tab")+inputPryramidSpan    = input.float(defval = 0.0,    minval = 0.0,  title = "Pyramid Minimum Span",   group = "[ SECTION 1 ]", tooltip = "Minimum spacing between downward pyramid levels (quote currency units). Set to zero to disable downward pyramiding. To fully disable pyramiding zero the value in the Properties tab")-inputPyramidBaleOut  = input(defval = true,   type = input.bool,                    title = "Position Bale Out",      group = "[ SECTION 1 ]", tooltip = "Enable to exit positions early. The algorithm ensures the position exits at a profit but not at the amount specified in the Minimum Profit input. Reduces the risk when pyramiding")+inputPyramidBaleOut  = input.bool(defval = true,                    title = "Position Bale Out",      group = "[ SECTION 1 ]", tooltip = "Enable to exit positions early. The algorithm ensures the position exits at a profit but not at the amount specified in the Minimum Profit input. Reduces the risk when pyramiding")-inputMaxAddOns       = input(defval = 0,      type = input.integer,  minval = 0,    maxval = 20, title  = "Maximum DCA Increments", group = "[ SECTION 1 ]", tooltip = "Sets a whole number limit on the number of times a losing position can be averaged down")+inputMaxAddOns       = input.int(defval = 0,  minval = 0,    maxval = 20, title  = "Maximum DCA Increments", group = "[ SECTION 1 ]", tooltip = "Sets a whole number limit on the number of times a losing position can be averaged down")inputSignalPeriod    = input(defval = "60",   options = ["60","240","1440"],        title = "Signal Line Period",     group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Blue, Green, Orange signal lines and the ZScore oscillator not visible")inputTrendPeriod     = input(defval = "240",  options = ["60","240","1440"],        title = "Trend Line Period",      group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Purple trend line and Stochastic indicator")-inputFastAlmaLen     = input(defval = 10,     type = input.integer,  minval = 1,    title = "Fast Alma Length",       group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Blue line (Arnaud Legoux Moving Average indicator)")+inputFastAlmaLen     = input.int(defval = 10,  minval = 1,    title = "Fast Alma Length",       group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Blue line (Arnaud Legoux Moving Average indicator)")-inputFastLinRegLen   = input(defval = 30,     type = input.integer,  minval = 1,    title = "Fast LinReg Length",     group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Green line (Linear Regression indicator)")+inputFastLinRegLen   = input.int(defval = 30,  minval = 1,    title = "Fast LinReg Length",     group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Green line (Linear Regression indicator)")-inputSlowLinRegLen   = input(defval = 100,    type = input.integer,  minval = 1,    title = "Slow LinReg Length",     group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Orange line (Linear Regression indicator)")+inputSlowLinRegLen   = input.int(defval = 100,  minval = 1,    title = "Slow LinReg Length",     group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Orange line (Linear Regression indicator)")-inputTrendDEMALen    = input(defval = 200,    type = input.integer,  minval = 1,    title = "Trend Line Length",      group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Purple line (Double Smoothed Moving Average indicator)")+inputTrendDEMALen    = input.int(defval = 200,  minval = 1,    title = "Trend Line Length",      group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Purple line (Double Smoothed Moving Average indicator)")-inputStochastLen     = input(defval = 14,     type = input.integer,  minval = 1,    title = "Stochastic Length",      group = "[ SECTION 2 ]", tooltip = "Sets the period length of two Stochastic indicators. One at the Purple line. Second at the chart interval")+inputStochastLen     = input.int(defval = 14,  minval = 1,    title = "Stochastic Length",      group = "[ SECTION 2 ]", tooltip = "Sets the period length of two Stochastic indicators. One at the Purple line. Second at the chart interval")-inputFastCrossLen    = input(defval = 9,      type = input.integer,  minval = 1,    title = "Fast Cross Length",      group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")+inputFastCrossLen    = input.int(defval = 9,  minval = 1,    title = "Fast Cross Length",      group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")-inputSlowCrossLen    = input(defval = 24,     type = input.integer,  minval = 1,    title = "Slow Cross Length",      group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")+inputSlowCrossLen    = input.int(defval = 24,  minval = 1,    title = "Slow Cross Length",      group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")-inputFastEMALen      = input(defval = 8,      type = input.integer,  minval = 1,    title = "Fast EMA Length",        group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Yellow line (Exponential Moving Average indicator). This is a chart interval indicator")+inputFastEMALen      = input.int(defval = 8,  minval = 1,    title = "Fast EMA Length",        group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Yellow line (Exponential Moving Average indicator). This is a chart interval indicator")-inputFastEMARiseNet  = input(defval = 3.0,    type = input.float,    minval = 0.00, title = "Fast EMA Rise NetChg",   group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the upward cross of the Yellow over the Blue line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")+inputFastEMARiseNet  = input.float(defval = 3.0,    minval = 0.00, title = "Fast EMA Rise NetChg",   group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the upward cross of the Yellow over the Blue line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")-inputFastEMARiseROC  = input(defval = 0.8,    type = input.float,    minval = 0.00, title = "Fast EMA Rise ROC",      group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the upward cross of the Yellow over the Blue line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")+inputFastEMARiseROC  = input.float(defval = 0.8,    minval = 0.00, title = "Fast EMA Rise ROC",      group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the upward cross of the Yellow over the Blue line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")-inputFastEMAFallNet  = input(defval = 4.0,    type = input.float,    minval = 0.00, title = "Fast EMA Fall NetChg",   group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the downward cross of the Yellow under the Blue line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")+inputFastEMAFallNet  = input.float(defval = 4.0,    minval = 0.00, title = "Fast EMA Fall NetChg",   group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the downward cross of the Yellow under the Blue line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")-inputFastEMAFallROC  = input(defval = 0.8,    type = input.float,    minval = 0.00, title = "Fast EMA Fall ROC",      group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the downward cross of the Yellow under the Blue line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")+inputFastEMAFallROC  = input.float(defval = 0.8,    minval = 0.00, title = "Fast EMA Fall ROC",      group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the downward cross of the Yellow under the Blue line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")-inputLongNascent     = input(defval = false,  type = input.bool,                    title = "Enter Long On Nascent",  group = "[ SECTION 4 ]", tooltip = "Enables rudimentary counter-trend trading. If checked long trades will signal below the Purple trend line and will exit above. The strategy will perform poorly in trending markets")+inputLongNascent     = input.bool(defval = false,                    title = "Enter Long On Nascent",  group = "[ SECTION 4 ]", tooltip = "Enables rudimentary counter-trend trading. If checked long trades will signal below the Purple trend line and will exit above. The strategy will perform poorly in trending markets")-inputLongCrossExit   = input(defval = true,   type = input.bool,                    title = "Long Natural Exit",      group = "[ SECTION 4 ]", tooltip = "A natural long exit is when the Blue line crosses under the Green Line (downward). The position must be profitable to exit")+inputLongCrossExit   = input.bool(defval = true,                    title = "Long Natural Exit",      group = "[ SECTION 4 ]", tooltip = "A natural long exit is when the Blue line crosses under the Green Line (downward). The position must be profitable to exit")-inputLongSignalExit  = input(defval = true,   type = input.bool,                    title = "Long Signal Exit",       group = "[ SECTION 4 ]", tooltip = "A signal event is when the Blue crosses over the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the positive value specified in section #6. The position must be profitable to exit")+inputLongSignalExit  = input.bool(defval = true,                    title = "Long Signal Exit",       group = "[ SECTION 4 ]", tooltip = "A signal event is when the Blue crosses over the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the positive value specified in section #6. The position must be profitable to exit")-inputLongEventExit   = input(defval = true,   type = input.bool,                    title = "Long Price Event Exit",  group = "[ SECTION 4 ]", tooltip = "A price event is when the Yellow crosses over the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")+inputLongEventExit   = input.bool(defval = true,                    title = "Long Price Event Exit",  group = "[ SECTION 4 ]", tooltip = "A price event is when the Yellow crosses over the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")-inputLongStochExit   = input(defval = true,   type = input.bool,                    title = "Long Stochastic Exit",   group = "[ SECTION 4 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the overbought threshold (80). The position must be profitable to exit")+inputLongStochExit   = input.bool(defval = true,                    title = "Long Stochastic Exit",   group = "[ SECTION 4 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the overbought threshold (80). The position must be profitable to exit")-inputShortNascent    = input(defval = false,  type = input.bool,                    title = "Enter Short On Nascent", group = "[ SECTION 5 ]", tooltip = "Enables rudimentary counter-trend trading. If checked short trades will signal above the Purple trend line and will exit below. The strategy will perform poorly in trending markets")+inputShortNascent    = input.bool(defval = false,                    title = "Enter Short On Nascent", group = "[ SECTION 5 ]", tooltip = "Enables rudimentary counter-trend trading. If checked short trades will signal above the Purple trend line and will exit below. The strategy will perform poorly in trending markets")-inputShortCrossExit  = input(defval = true,   type = input.bool,                    title = "Short Natural Exit",     group = "[ SECTION 5 ]", tooltip = "A natural short exit is when the Blue line crosses over the Green Line. (upward) The position must be profitable to exit")+inputShortCrossExit  = input.bool(defval = true,                    title = "Short Natural Exit",     group = "[ SECTION 5 ]", tooltip = "A natural short exit is when the Blue line crosses over the Green Line. (upward) The position must be profitable to exit")-inputShortSignalExit = input(defval = true,   type = input.bool,                    title = "Short Signal Exit",      group = "[ SECTION 5 ]", tooltip = "A signal event is when the Blue crosses under the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the negative value specified in section #6. The position must be profitable to exit")+inputShortSignalExit = input.bool(defval = true,                    title = "Short Signal Exit",      group = "[ SECTION 5 ]", tooltip = "A signal event is when the Blue crosses under the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the negative value specified in section #6. The position must be profitable to exit")-inputShortEventExit  = input(defval = true,   type = input.bool,                    title = "Short Price Event Exit", group = "[ SECTION 5 ]", tooltip = "A price event is when the Yellow crosses under the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")+inputShortEventExit  = input.bool(defval = true,                    title = "Short Price Event Exit", group = "[ SECTION 5 ]", tooltip = "A price event is when the Yellow crosses under the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")-inputShortStochExit  = input(defval = true,   type = input.bool,                    title = "Short Stochastic Exit",  group = "[ SECTION 5 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the oversold threshold (20). The position must be profitable to exit")+inputShortStochExit  = input.bool(defval = true,                    title = "Short Stochastic Exit",  group = "[ SECTION 5 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the oversold threshold (20). The position must be profitable to exit")-inputRiseEventNet    = input(defval = 10.0,   type = input.float,    minval = 0.00, title = "Rise Event Net Change",  group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the upward cross of the Blue over the Green line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")+inputRiseEventNet    = input.float(defval = 10.0,    minval = 0.00, title = "Rise Event Net Change",  group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the upward cross of the Blue over the Green line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")-inputRiseEventROC    = input(defval = 0.1,    type = input.float,    minval = 0.00, title = "Rise Event ROC",         group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the upward cross of the Blue over the Green line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")+inputRiseEventROC    = input.float(defval = 0.1,    minval = 0.00, title = "Rise Event ROC",         group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the upward cross of the Blue over the Green line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")-inputMinZScoreABZ    = input(defval = 5.0,    type = input.float,    minval = 0.00, title = "Min Above Zero ZScore",  group = "[ SECTION 6 ]", tooltip = "Specifies the overbought threshold of the ZScore oscillator. If the [Long Signal Exit] option in Section #4 is enabled a high value here will cause the long trade to stay in the market longer")+inputMinZScoreABZ    = input.float(defval = 5.0,    minval = 0.00, title = "Min Above Zero ZScore",  group = "[ SECTION 6 ]", tooltip = "Specifies the overbought threshold of the ZScore oscillator. If the [Long Signal Exit] option in Section #4 is enabled a high value here will cause the long trade to stay in the market longer")-inputFallEventNet    = input(defval = 10.0,   type = input.float,    minval = 0.00, title = "Fall Event Net Change",  group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the downward cross of the Blue under the Green line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")+inputFallEventNet    = input.float(defval = 10.0,    minval = 0.00, title = "Fall Event Net Change",  group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the downward cross of the Blue under the Green line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")-inputFallEventROC    = input(defval = 0.1,    type = input.float,    minval = 0.00, title = "Fall Event ROC",         group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the downward cross of the Blue under the Green line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")+inputFallEventROC    = input.float(defval = 0.1,    minval = 0.00, title = "Fall Event ROC",         group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the downward cross of the Blue under the Green line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")-inputMinZScoreBLZ    = input(defval = 5.0,    type = input.float,    minval = 0.00, title = "Min Below Zero ZScore",  group = "[ SECTION 6 ]", tooltip = "Specifies the oversold threshold of the ZScore oscillator. If the [Short Signal Exit] option in Section #5 is enabled a high value here will cause the short trade to stay in the market longer")+inputMinZScoreBLZ    = input.float(defval = 5.0,    minval = 0.00, title = "Min Below Zero ZScore",  group = "[ SECTION 6 ]", tooltip = "Specifies the oversold threshold of the ZScore oscillator. If the [Short Signal Exit] option in Section #5 is enabled a high value here will cause the short trade to stay in the market longer")-inputShowLines       = input(defval = true,   type = input.bool,                    title = "Show Trend Lines",       group = "[ SECTION 7 ]", tooltip = "Display the Yellow, Blue, Green, Orange and Purple trend lines. They are rendered at a width of 2")+inputShowLines       = input.bool(defval = true,                    title = "Show Trend Lines",       group = "[ SECTION 7 ]", tooltip = "Display the Yellow, Blue, Green, Orange and Purple trend lines. They are rendered at a width of 2")-inputShowCrosses     = input(defval = false,  type = input.bool,                    title = "Show Entry Regions",     group = "[ SECTION 7 ]", tooltip = "Background fill for the SMA crossovers specified in Section #3. The SMA is on the chart time frame so will display frequent transitions. Blue is an upward cross. Red is downward")+inputShowCrosses     = input.bool(defval = false,                    title = "Show Entry Regions",     group = "[ SECTION 7 ]", tooltip = "Background fill for the SMA crossovers specified in Section #3. The SMA is on the chart time frame so will display frequent transitions. Blue is an upward cross. Red is downward")-inputShowEvents      = input(defval = false,  type = input.bool,                    title = "Display Event Regions",  group = "[ SECTION 7 ]", tooltip = "Background fill for signal events specified in Section #6. The Blue crossing the Green lines. Use it to configure Section #6. Blue is exceeding rise values. Red is is exceeding fall values")+inputShowEvents      = input.bool(defval = false,                    title = "Display Event Regions",  group = "[ SECTION 7 ]", tooltip = "Background fill for signal events specified in Section #6. The Blue crossing the Green lines. Use it to configure Section #6. Blue is exceeding rise values. Red is is exceeding fall values")-inputShowEMPeaks     = input(defval = false,  type = input.bool,                    title = "Display EMA Peaks",      group = "[ SECTION 7 ]", tooltip = "Background fill for price events specified in Section #3. The Yellow crossing the Blue lines. Use it to configure Section #3. Blue is exceeding rise values. Red is is exceeding fall values")+inputShowEMPeaks     = input.bool(defval = false,                    title = "Display EMA Peaks",      group = "[ SECTION 7 ]", tooltip = "Background fill for price events specified in Section #3. The Yellow crossing the Blue lines. Use it to configure Section #3. Blue is exceeding rise values. Red is is exceeding fall values")-inputShowStochEvent  = input(defval = false,  type = input.bool,                    title = "Show Stochastic Events", group = "[ SECTION 7 ]", tooltip = "Background fill for Stochastic events occurring on the Purple line. Use it verify selected exits in Section #4 and #5. Blue is exceeding overbought levels. Red is is exceeding oversold levels")+inputShowStochEvent  = input.bool(defval = false,                    title = "Show Stochastic Events", group = "[ SECTION 7 ]", tooltip = "Background fill for Stochastic events occurring on the Purple line. Use it verify selected exits in Section #4 and #5. Blue is exceeding overbought levels. Red is is exceeding oversold levels")-inputShowConsecLoss  = input(defval = false,  type = input.bool,                    title = "Show Consecutive Losses",group = "[ SECTION 7 ]", tooltip = "Background fill for periods when consecutive losses are occurring. Red areas mean stops where hit and have not encountered a profitable exit. Use it to make adjustments to the values in Section #1")+inputShowConsecLoss  = input.bool(defval = false,                    title = "Show Consecutive Losses",group = "[ SECTION 7 ]", tooltip = "Background fill for periods when consecutive losses are occurring. Red areas mean stops where hit and have not encountered a profitable exit. Use it to make adjustments to the values in Section #1")-inputShowBaleOuts    = input(defval = false,  type = input.bool,                    title = "Show Bale Outs",         group = "[ SECTION 7 ]", tooltip = "Displays red labels under the bars where a position was exited prematurely. Each box contains information about the state of the trade at exit time. Use it when [Position Bale Out] in Section #1 is enabled")+inputShowBaleOuts    = input.bool(defval = false,                    title = "Show Bale Outs",         group = "[ SECTION 7 ]", tooltip = "Displays red labels under the bars where a position was exited prematurely. Each box contains information about the state of the trade at exit time. Use it when [Position Bale Out] in Section #1 is enabled")-inputReport          = input(defval = false,  type = input.bool,                    title = "Show Summary Report",    group = "[ SECTION 7 ]", tooltip = "Displays a blue label at the live end of the chart. Contains useful strategy metrics which can aid in the development of the script. Relevant information should be added here as the script logic evolves. Happy Trading!")+inputReport          = input.bool(defval = false,                    title = "Show Summary Report",    group = "[ SECTION 7 ]", tooltip = "Displays a blue label at the live end of the chart. Contains useful strategy metrics which can aid in the development of the script. Relevant information should be added here as the script logic evolves. Happy Trading!")int  inputNormalizeLen    = 100⋯calcDEMA(seriesData, ncMALength) =>-    float emaAlpha   = ema(seriesData, ncMALength)+    float emaAlpha   = ta.ema(seriesData, ncMALength)-    float emaOfEma   = ema(emaAlpha,   ncMALength)+    float emaOfEma   = ta.ema(emaAlpha,   ncMALength)    float seriesDema = (2 * emaAlpha) - emaOfEma⋯calcSlowLinReg() =>-    float seriesOut = linreg(fltBarPrice[indexClosedBar], ncSlowLinRegLen, ncLinRegOffset)+    float seriesOut = ta.linreg(fltBarPrice[indexClosedBar], ncSlowLinRegLen, ncLinRegOffset)calcFastLinReg() =>-    float seriesOut = linreg(fltBarPrice[indexClosedBar], ncFastLinRegLen, ncLinRegOffset)+    float seriesOut = ta.linreg(fltBarPrice[indexClosedBar], ncFastLinRegLen, ncLinRegOffset)calcFastAlma() =>-    float seriesOut = alma(fltBarPrice[indexClosedBar], ncFastAlmaLen, 0.85, 6)+    float seriesOut = ta.alma(fltBarPrice[indexClosedBar], ncFastAlmaLen, 0.85, 6)calcStochastic() =>-    float seriesOut = stoch(close[indexClosedBar], high[indexClosedBar], low[indexClosedBar], ncStochasLen)+    float seriesOut = ta.stoch(close[indexClosedBar], high[indexClosedBar], low[indexClosedBar], ncStochasLen)// ----------------------------⋯// Linear Regression-float htf_seriesSlowLinReg = security(syminfo.tickerid, inputSignalPeriod, calcSlowLinReg())[indexReadBar]+float htf_seriesSlowLinReg = request.security(syminfo.tickerid, inputSignalPeriod, calcSlowLinReg())[indexReadBar]-float htf_seriesFastLinReg = security(syminfo.tickerid, inputSignalPeriod, calcFastLinReg())[indexReadBar]+float htf_seriesFastLinReg = request.security(syminfo.tickerid, inputSignalPeriod, calcFastLinReg())[indexReadBar]// Arnaud Legoux Moving Average-float htf_seriesFastAlma   = security(syminfo.tickerid, inputSignalPeriod, calcFastAlma())[indexReadBar]+float htf_seriesFastAlma   = request.security(syminfo.tickerid, inputSignalPeriod, calcFastAlma())[indexReadBar]// Double Exponential Moving Average-float htf_seriesTrendDEMA  = security(syminfo.tickerid, inputTrendPeriod,  calcTrendDEMA())[indexReadBar]+float htf_seriesTrendDEMA  = request.security(syminfo.tickerid, inputTrendPeriod,  calcTrendDEMA())[indexReadBar]// ZScore Simple Moving Average-float htf_seriesAlmaMean   = sma(htf_seriesFastAlma, ncNormalizeLen)+float htf_seriesAlmaMean   = ta.sma(htf_seriesFastAlma, ncNormalizeLen)// ZScore Seriesfloat htf_seriesMarks      = htf_seriesFastAlma - htf_seriesAlmaMean-float htf_seriesZScore     = htf_seriesMarks / stdev(htf_seriesMarks, ncNormalizeLen)+float htf_seriesZScore     = htf_seriesMarks / ta.stdev(htf_seriesMarks, ncNormalizeLen)// Stochastic Oscillator-float htf_seriesFastK      = security(syminfo.tickerid, inputTrendPeriod,  calcStochastic())[indexReadBar]+float htf_seriesFastK      = request.security(syminfo.tickerid, inputTrendPeriod,  calcStochastic())[indexReadBar]-float htf_seriesDLine      = sma(htf_seriesFastK, ncKn2Period)+float htf_seriesDLine      = ta.sma(htf_seriesFastK, ncKn2Period)-float htf_seriesSlowD      = sma(htf_seriesDLine, ncDn3Period)+float htf_seriesSlowD      = ta.sma(htf_seriesDLine, ncDn3Period)// ---- [ CHART TIME FRAME ] ----// Fast Cross Simple Moving Average-float seriesFastCross = sma(fltBarPrice, ncFastCrossLen)+float seriesFastCross = ta.sma(fltBarPrice, ncFastCrossLen)// Slow Cross Simple Moving Average-float seriesSlowCross = sma(fltBarPrice, ncSlowCrossLen)+float seriesSlowCross = ta.sma(fltBarPrice, ncSlowCrossLen)// Fast Exponential Moving Average-float seriesFastEMA   = ema(fltBarPrice, ncFastEMALen)+float seriesFastEMA   = ta.ema(fltBarPrice, ncFastEMALen)// Stochastic Oscillator-float seriesFastK     = stoch(seriesClose, seriesHigh, seriesLow, ncStochasLen)+float seriesFastK     = ta.stoch(seriesClose, seriesHigh, seriesLow, ncStochasLen)-float seriesDLine     = sma(seriesFastK, ncKn2Period)+float seriesDLine     = ta.sma(seriesFastK, ncKn2Period)-float seriesSlowD     = sma(seriesDLine, ncDn3Period)+float seriesSlowD     = ta.sma(seriesDLine, ncDn3Period)// ----------------------------⋯nPositionDir := (strategy.position_size < 0) ? -1 : (strategy.position_size > 0) ? 1 : 0-fltNumShares := abs(strategy.position_size)+fltNumShares := math.abs(strategy.position_size)fltNetProfit := strategy.openprofit⋯// -----------------------------bCrossRise := crossover(seriesFastCross, seriesSlowCross)+bCrossRise := ta.crossover(seriesFastCross, seriesSlowCross)if ((bAlreadyIn == false) and (strTradingMode != "No Trade"))⋯// -----------------------------bCrossFall := crossunder(seriesFastCross, seriesSlowCross)+bCrossFall := ta.crossunder(seriesFastCross, seriesSlowCross)if ((bAlreadyIn == false) and (bOpenLong == false) and (strTradingMode != "No Trade"))⋯    if (fltQuantity  > 0.0)-        strategy.entry(strLongName,  strategy.long,  qty = fltQuantity, alert_message = "entry stop = " + tostring(fltStopPrice))+        strategy.entry(strLongName,  strategy.long,  qty = fltQuantity, alert_message = "entry stop = " + str.tostring(fltStopPrice))    if (fltQuantity == 0.0)-        strategy.entry(strLongName,  strategy.long,  alert_message = "entry stop = " + tostring(fltStopPrice))+        strategy.entry(strLongName,  strategy.long,  alert_message = "entry stop = " + str.tostring(fltStopPrice))-        fltCurrentSize := abs(strategy.position_size)+        fltCurrentSize := math.abs(strategy.position_size)    if (fltStopPrice > 0.0)-        strategy.exit(strLongStop, strLongName, stop = fltStopPrice, alert_message = "stop = " + tostring(fltStopPrice))+        strategy.exit(strLongStop, strLongName, stop = fltStopPrice, alert_message = "stop = " + str.tostring(fltStopPrice))if (bOpenShort == true)⋯    if (fltQuantity  > 0.0)-        strategy.entry(strShortName, strategy.short, qty = fltQuantity, alert_message = "entry stop = " + tostring(fltStopPrice))+        strategy.entry(strShortName, strategy.short, qty = fltQuantity, alert_message = "entry stop = " + str.tostring(fltStopPrice))    if (fltQuantity == 0.0)-        strategy.entry(strShortName, strategy.short, alert_message = "entry stop = " + tostring(fltStopPrice))+        strategy.entry(strShortName, strategy.short, alert_message = "entry stop = " + str.tostring(fltStopPrice))-        fltCurrentSize := abs(strategy.position_size)+        fltCurrentSize := math.abs(strategy.position_size)    if (fltStopPrice > 0.0)-        strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message = "stop = " + tostring(fltStopPrice))+        strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message = "stop = " + str.tostring(fltStopPrice))if (fltDefaultSize == 0.0)-    fltDefaultSize := abs(strategy.position_size)+    fltDefaultSize := math.abs(strategy.position_size)// ----------------------------⋯    fltExitPrice := seriesClose-    strategy.close( strLongName, when = true, alert_message = "exit profit = " + tostring(fltExitPrice - fltEntryPrice))+    strategy.close( strLongName, when = true, alert_message = "exit profit = " + str.tostring(fltExitPrice - fltEntryPrice))    strategy.cancel(strLongName)⋯    fltExitPrice := seriesClose-    strategy.close( strShortName, when = true, alert_message = "exit profit = " + tostring(fltEntryPrice - fltExitPrice))+    strategy.close( strShortName, when = true, alert_message = "exit profit = " + str.tostring(fltEntryPrice - fltExitPrice))    strategy.cancel(strShortName)⋯    ncMaxConsecs  := ncConsecLosses-    strBadRunDate := tostring(year) + "-" + tostring(month, "##") + "-" + tostring(dayofmonth, "##") + " [" + tostring(hour, "##") + ":" + tostring(minute, "##") + ":00]"+    strBadRunDate := str.tostring(year) + "-" + str.tostring(month, "##") + "-" + str.tostring(dayofmonth, "##") + " [" + str.tostring(hour, "##") + ":" + str.tostring(minute, "##") + ":00]"// ----------------------------⋯        bNewPyramidLevel := true-        strategy.entry(strLongName,  strategy.long,  alert_message="pyramid level = " + tostring(ncPyramidCount + 1))+        strategy.entry(strLongName,  strategy.long,  alert_message="pyramid level = " + str.tostring(ncPyramidCount + 1))-        strategy.exit(strLongStop, strLongName, stop = fltStopPrice,   alert_message="scale out level = " + tostring(ncPyramidCount + 1))+        strategy.exit(strLongStop, strLongName, stop = fltStopPrice,   alert_message="scale out level = " + str.tostring(ncPyramidCount + 1))    if ((nPositionDir == -1) and (bPyramidRise == true))        bNewPyramidLevel := true-        strategy.entry(strShortName, strategy.short, alert_message="pyramid level = " + tostring(ncPyramidCount + 1))+        strategy.entry(strShortName, strategy.short, alert_message="pyramid level = " + str.tostring(ncPyramidCount + 1))-        strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message="scale out level = " + tostring(ncPyramidCount + 1))+        strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message="scale out level = " + str.tostring(ncPyramidCount + 1))if (bNewPyramidLevel == true)⋯    string txtReport = " Bale Out Exit"-    txtReport := txtReport + "\n" + " Net Profit: "    + tostring(fltNetProfit, "#.####")+    txtReport := txtReport + "\n" + " Net Profit: "    + str.tostring(fltNetProfit, "#.####")-    txtReport := txtReport + "\n" + " Position Size: " + tostring(fltNumShares, "#.####")+    txtReport := txtReport + "\n" + " Position Size: " + str.tostring(fltNumShares, "#.####")-    txtReport := txtReport + "\n" + " Pyramid Count: " + tostring(ncPyramidCount)+    txtReport := txtReport + "\n" + " Pyramid Count: " + str.tostring(ncPyramidCount)-    txtReport := txtReport + "\n" + " MAE Level: "     + tostring(fltMAELevel,  "#.####")+    txtReport := txtReport + "\n" + " MAE Level: "     + str.tostring(fltMAELevel,  "#.####")-    txtReport := txtReport + "\n" + " Consec Losses: " + tostring(ncLastConsecs)+    txtReport := txtReport + "\n" + " Consec Losses: " + str.tostring(ncLastConsecs)    label.new(bar_index, high, txtReport, xloc=xloc.bar_index, yloc=yloc.belowbar, style=label.style_labelup, color=#FF0000, textcolor=color.white, size=size.normal, textalign=text.align_left)⋯txtReport := txtReport +        "╒═════════════════╕"-txtReport := txtReport + "\n" + "   Minimum Tick Size: "  + tostring(syminfo.mintick)+txtReport := txtReport + "\n" + "   Minimum Tick Size: "  + str.tostring(syminfo.mintick)-txtReport := txtReport + "\n" + "   Maximum Pyramids: "   + tostring(ncHighestLevel + 1)+txtReport := txtReport + "\n" + "   Maximum Pyramids: "   + str.tostring(ncHighestLevel + 1)-txtReport := txtReport + "\n" + "   Consecutive Losses: " + tostring(ncMaxConsecs)+txtReport := txtReport + "\n" + "   Consecutive Losses: " + str.tostring(ncMaxConsecs)txtReport := txtReport + "\n" + "   Date: "               + strBadRunDate-txtReport := txtReport + "\n" + "   Max TV Drawdown: "    + tostring(strategy.max_drawdown, "#.####")+txtReport := txtReport + "\n" + "   Max TV Drawdown: "    + str.tostring(strategy.max_drawdown, "#.####")-txtReport := txtReport + "\n" + "   Max TV Contracts: "   + tostring(strategy.max_contracts_held_all, "#.####")+txtReport := txtReport + "\n" + "   Max TV Contracts: "   + str.tostring(strategy.max_contracts_held_all, "#.####")txtReport := txtReport + "\n" + "╘═════════════════╛"⋯

Clean v5

Not verified

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L692:C89: 'label.style_labelup' is not available in Pine Script v5. It was added in a later version.), so this step could not be checked.

  • Line 9: input() → input.string()
  • Line 17: input() → input.string()
  • Line 18: input() → input.string()
  • Line 571: when = true → if block
  • Line 576: when = true → if block
⋯inputBuild           = input.int(defval = 101,  minval = 0.0,  title = "Build Number",           group = "[ SECTION 1 ]", tooltip = "This is a trend follow script that enters the market long above the purple line and short below. It is prone to losses on ranging markets where the trend line bisects the price stream")-inputTradingMode     = input(defval = "BiDir", options = ["Long","Short","BiDir","Flip Flop","Crypto","Range","No Trade"], title = "Trading Mode", group = "[ SECTION 1 ]", tooltip = "BiDir is for margin trading with a stop. Flip Flop will alter direction on trend line cross. Crypto is long only with downward pyramids. Range only enters on a counter-trend")+inputTradingMode     = input.string(defval = "BiDir", options = ["Long","Short","BiDir","Flip Flop","Crypto","Range","No Trade"], title = "Trading Mode", group = "[ SECTION 1 ]", tooltip = "BiDir is for margin trading with a stop. Flip Flop will alter direction on trend line cross. Crypto is long only with downward pyramids. Range only enters on a counter-trend")inputMinProfit       = input.float(defval = 0.50,    minval = 0.0,  title = "Minimum Profit",         group = "[ SECTION 1 ]", tooltip = "Smallest take profit offset to permit a close order. This is a conditional exit not a limit (quote currency units)")⋯inputMaxAddOns       = input.int(defval = 0,  minval = 0,    maxval = 20, title  = "Maximum DCA Increments", group = "[ SECTION 1 ]", tooltip = "Sets a whole number limit on the number of times a losing position can be averaged down")-inputSignalPeriod    = input(defval = "60",   options = ["60","240","1440"],        title = "Signal Line Period",     group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Blue, Green, Orange signal lines and the ZScore oscillator not visible")+inputSignalPeriod    = input.string(defval = "60",   options = ["60","240","1440"],        title = "Signal Line Period",     group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Blue, Green, Orange signal lines and the ZScore oscillator not visible")-inputTrendPeriod     = input(defval = "240",  options = ["60","240","1440"],        title = "Trend Line Period",      group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Purple trend line and Stochastic indicator")+inputTrendPeriod     = input.string(defval = "240",  options = ["60","240","1440"],        title = "Trend Line Period",      group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Purple trend line and Stochastic indicator")inputFastAlmaLen     = input.int(defval = 10,  minval = 1,    title = "Fast Alma Length",       group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Blue line (Arnaud Legoux Moving Average indicator)")⋯    fltExitPrice := seriesClose-    strategy.close( strLongName, when = true, alert_message = "exit profit = " + str.tostring(fltExitPrice - fltEntryPrice))+    if true+        strategy.close( strLongName, alert_message = "exit profit = " + str.tostring(fltExitPrice - fltEntryPrice))    strategy.cancel(strLongName)⋯    fltExitPrice := seriesClose-    strategy.close( strShortName, when = true, alert_message = "exit profit = " + str.tostring(fltEntryPrice - fltExitPrice))+    if true+        strategy.close( strShortName, alert_message = "exit profit = " + str.tostring(fltEntryPrice - fltExitPrice))    strategy.cancel(strShortName)⋯

Does it run in Pine Script v6?

Not tested

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L694:C89: 'label.style_labelup' is not available in Pine Script v5. It was added in a later version.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © tradingtudi-//@version=5+//@version=6strategy(title = "WebhookDrive-V1", overlay = true, pyramiding = 0, initial_capital = 10000, currency = currency.USD)⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
[ SECTION 1 ]
Build NumberThis is a trend follow script that enters the market long above the purple line and short below. It is prone to losses on ranging markets where the trend line bisects the price stream101int (written input.integer) · min 0.0unused
Trading ModeBiDir is for margin trading with a stop. Flip Flop will alter direction on trend line cross. Crypto is long only with downward pyramids. Range only enters on a counter-trendBiDirstring · options ["Long","Short","BiDir","Flip Flop","Crypto","Range","No Trade"]strTradingMode line 60 line 62 line 64 line 68 line 73 line 74
Minimum ProfitSmallest take profit offset to permit a close order. This is a conditional exit not a limit (quote currency units)0.50float · min 0.0fltMinProfit
Stop OffsetHard stop offset from the trade open price (quote currency units)0.50float · min 0.0fltStopOffset
Tick ScalarValue used to remove the pipette from quote currency calculations. See the Summary Report to determine this value10.0float · min 1.0fltFXMinTick
Price NormalizerValue used to normalize bar prices for differential calculations. Serves to increase the magnitude of significant digits. Applied to all inputs specifying net change and roc1000.0float · min 1.0fltChgDivisor
Pyramid Minimum SpanMinimum spacing between downward pyramid levels (quote currency units). Set to zero to disable downward pyramiding. To fully disable pyramiding zero the value in the Properties tab0.0float · min 0.0fltPryramidSpan
Position Bale OutEnable to exit positions early. The algorithm ensures the position exits at a profit but not at the amount specified in the Minimum Profit input. Reduces the risk when pyramidingtrueboolbPyramidBaleOut
Maximum DCA IncrementsSets a whole number limit on the number of times a losing position can be averaged down0int (written input.integer) · min 0 · max 20ncMaxAddOns
[ SECTION 2 ]
Signal Line PeriodSets the bar interval for the Blue, Green, Orange signal lines and the ZScore oscillator not visible60string · options ["60","240","1440"]htf_seriesSlowLinReg htf_seriesFastLinReg htf_seriesFastAlma
Trend Line PeriodSets the bar interval for the Purple trend line and Stochastic indicator240string · options ["60","240","1440"]htf_seriesTrendDEMA htf_seriesFastK
Fast Alma LengthSets the period length of the Blue line (Arnaud Legoux Moving Average indicator)10int (written input.integer) · min 1ncFastAlmaLen
Fast LinReg LengthSets the period length of the Green line (Linear Regression indicator)30int (written input.integer) · min 1ncFastLinRegLen
Slow LinReg LengthSets the period length of the Orange line (Linear Regression indicator)100int (written input.integer) · min 1ncSlowLinRegLen
Trend Line LengthSets the period length of the Purple line (Double Smoothed Moving Average indicator)200int (written input.integer) · min 1ncTrendDEMALen
Stochastic LengthSets the period length of two Stochastic indicators. One at the Purple line. Second at the chart interval14int (written input.integer) · min 1ncStochasLen
[ SECTION 3 ]
Fast Cross LengthSets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short9int (written input.integer) · min 1ncFastCrossLen
Slow Cross LengthSets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short24int (written input.integer) · min 1ncSlowCrossLen
Fast EMA LengthSets the period length of the Yellow line (Exponential Moving Average indicator). This is a chart interval indicator8int (written input.integer) · min 1ncFastEMALen
Fast EMA Rise NetChgMeasures the delta percentage from the upward cross of the Yellow over the Blue line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer3.0float · min 0.00fltFastEMARiseNet
Fast EMA Rise ROCMeasures the rate of change from the upward cross of the Yellow over the Blue line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer0.8float · min 0.00fltFastEMARiseROC
Fast EMA Fall NetChgMeasures the delta percentage from the downward cross of the Yellow under the Blue line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer4.0float · min 0.00fltFastEMAFallNet
Fast EMA Fall ROCMeasures the rate of change from the downward cross of the Yellow under the Blue line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer0.8float · min 0.00fltFastEMAFallROC
[ SECTION 4 ]
Enter Long On NascentEnables rudimentary counter-trend trading. If checked long trades will signal below the Purple trend line and will exit above. The strategy will perform poorly in trending marketsfalseboolbLongNascent
Long Natural ExitA natural long exit is when the Blue line crosses under the Green Line (downward). The position must be profitable to exittrueboolbLongCrossExit
Long Signal ExitA signal event is when the Blue crosses over the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the positive value specified in section #6. The position must be profitable to exittrueboolbLongSignalExit
Long Price Event ExitA price event is when the Yellow crosses over the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exittrueboolbLongEventExit
Long Stochastic ExitThis exit occurs when the Stochastic oscillator measuring the Purple line exceeds the overbought threshold (80). The position must be profitable to exittrueboolbLongStochExit
[ SECTION 5 ]
Enter Short On NascentEnables rudimentary counter-trend trading. If checked short trades will signal above the Purple trend line and will exit below. The strategy will perform poorly in trending marketsfalseboolbShortNascent
Short Natural ExitA natural short exit is when the Blue line crosses over the Green Line. (upward) The position must be profitable to exittrueboolbShortCrossExit
Short Signal ExitA signal event is when the Blue crosses under the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the negative value specified in section #6. The position must be profitable to exittrueboolbShortSignalExit
Short Price Event ExitA price event is when the Yellow crosses under the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exittrueboolbShortEventExit
Short Stochastic ExitThis exit occurs when the Stochastic oscillator measuring the Purple line exceeds the oversold threshold (20). The position must be profitable to exittrueboolbShortStochExit
[ SECTION 6 ]
Rise Event Net ChangeMeasures the delta percentage from the upward cross of the Blue over the Green line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer10.0float · min 0.00fltRiseEventNet
Rise Event ROCMeasures the rate of change from the upward cross of the Blue over the Green line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer0.1float · min 0.00fltRiseEventROC
Min Above Zero ZScoreSpecifies the overbought threshold of the ZScore oscillator. If the [Long Signal Exit] option in Section #4 is enabled a high value here will cause the long trade to stay in the market longer5.0float · min 0.00fltMinZScoreABZ
Fall Event Net ChangeMeasures the delta percentage from the downward cross of the Blue under the Green line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer10.0float · min 0.00fltFallEventNet
Fall Event ROCMeasures the rate of change from the downward cross of the Blue under the Green line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer0.1float · min 0.00fltFallEventROC
Min Below Zero ZScoreSpecifies the oversold threshold of the ZScore oscillator. If the [Short Signal Exit] option in Section #5 is enabled a high value here will cause the short trade to stay in the market longer5.0float · min 0.00fltMinZScoreBLZ
[ SECTION 7 ]
Show Trend LinesDisplay the Yellow, Blue, Green, Orange and Purple trend lines. They are rendered at a width of 2trueboolline 657
Show Entry RegionsBackground fill for the SMA crossovers specified in Section #3. The SMA is on the chart time frame so will display frequent transitions. Blue is an upward cross. Red is downwardfalseboolbgcolor
Display Event RegionsBackground fill for signal events specified in Section #6. The Blue crossing the Green lines. Use it to configure Section #6. Blue is exceeding rise values. Red is is exceeding fall valuesfalseboolbgcolor
Display EMA PeaksBackground fill for price events specified in Section #3. The Yellow crossing the Blue lines. Use it to configure Section #3. Blue is exceeding rise values. Red is is exceeding fall valuesfalseboolbgcolor
Show Stochastic EventsBackground fill for Stochastic events occurring on the Purple line. Use it verify selected exits in Section #4 and #5. Blue is exceeding overbought levels. Red is is exceeding oversold levelsfalseboolbgcolor
Show Consecutive LossesBackground fill for periods when consecutive losses are occurring. Red areas mean stops where hit and have not encountered a profitable exit. Use it to make adjustments to the values in Section #1falseboolbgcolor
Show Bale OutsDisplays red labels under the bars where a position was exited prematurely. Each box contains information about the state of the trade at exit time. Use it when [Position Bale Out] in Section #1 is enabledfalseboolline 685
Show Summary ReportDisplays a blue label at the live end of the chart. Contains useful strategy metrics which can aid in the development of the script. Relevant information should be added here as the script logic evolves. Happy Trading!falseboolline 706

What it calculates

  • EMA (ema, ta.ema in v5)seriesData, ncMALengthemaAlpha · line 106
  • EMA (ema, ta.ema in v5)emaAlpha, ncMALengthemaOfEma · line 107
  • Stoch (stoch, ta.stoch in v5)close[indexClosedBar], high[indexClosedBar], low[indexClosedBar], ncStochasLenseriesOut · line 118
  • SMA (sma, ta.sma in v5)htf_seriesFastAlma, ncNormalizeLenhtf_seriesAlmaMean · line 134
  • Stdev (stdev, ta.stdev in v5)htf_seriesMarks, ncNormalizeLenhtf_seriesZScore · line 137
  • SMA (sma, ta.sma in v5)htf_seriesFastK, ncKn2Periodhtf_seriesDLine · line 140
  • SMA (sma, ta.sma in v5)htf_seriesDLine, ncDn3Periodhtf_seriesSlowD · line 141
  • SMA (sma, ta.sma in v5)fltBarPrice, ncFastCrossLenseriesFastCross · line 144
  • SMA (sma, ta.sma in v5)fltBarPrice, ncSlowCrossLenseriesSlowCross · line 146
  • EMA (ema, ta.ema in v5)fltBarPrice, ncFastEMALenseriesFastEMA · line 148
  • Stoch (stoch, ta.stoch in v5)seriesClose, seriesHigh, seriesLow, ncStochasLenseriesFastK · line 150
  • SMA (sma, ta.sma in v5)seriesFastK, ncKn2PeriodseriesDLine · line 151
  • SMA (sma, ta.sma in v5)seriesDLine, ncDn3PeriodseriesSlowD · line 152
  • Crossover (crossover, ta.crossover in v5)seriesFastCross, seriesSlowCrossbCrossRise · line 432
  • Crossunder (crossunder, ta.crossunder in v5)seriesFastCross, seriesSlowCrossbCrossFall · line 444

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

The script has 154 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open WBHDrive-L long(fltQuantity > 0.0)On547
Open WBHDrive-L long(fltQuantity == 0.0)On549
Exit WBHD-L-Stop stop(fltStopPrice > 0.0)On552
Open WBHDrive-S short(fltQuantity > 0.0)On557
Open WBHDrive-S short(fltQuantity == 0.0)On559
Exit WBHD-S-Stop stop(fltStopPrice > 0.0)On562
Close WBHDrive-LtrueOn571
cancel WBHDrive-L(bCloseLong == true)On572
Close WBHDrive-StrueOn576
cancel WBHDrive-S(bCloseShort == true)On577
Open WBHDrive-L long((nPositionDir == 1) and (bPyramidFall == true))On628
Exit WBHD-L-Stop stop((nPositionDir == 1) and (bPyramidFall == true))On629
Open WBHDrive-S short((nPositionDir == -1) and (bPyramidRise == true))On632
Exit WBHD-S-Stop stop((nPositionDir == -1) and (bPyramidRise == true))On633

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

No

No repainting patterns in the source.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe data5 security call(s), none with lookahead on.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
Volume Weighted Bollinger Bands Strategy by Ankit_1618ema sma stdevv4 strategy+10.0%1527.5%
BB21_MA200_Strategy by mohaneeema sma stdevv4 strategyNo trades on this market
Super Breakout day trading by beststockalertstdev sma emav4 strategyNo trades on this market
Super Auto Breakout Day Trade Volatile stocks by beststockalertstdev sma emav4 strategy−6.1%5129.1%
VFI strategy [based on VFI indicator published by UTS] by mohaneesma stdev emav4 strategy+181.4%8154.2%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No Pine Script v4 Error at @L703:C69: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.Not measured
PineTSNo v5 and v6 only—Not measured

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © tradingtudi//@version=4strategy(title = "WebhookDrive-V1", overlay = true, pyramiding = 0, initial_capital = 10000, currency = currency.USD)// -----------------------------// ---- Strategy Inputs// -----------------------------inputBuild           = input(defval = 101,    type = input.integer,  minval = 0.0,  title = "Build Number",           group = "[ SECTION 1 ]", tooltip = "This is a trend follow script that enters the market long above the purple line and short below. It is prone to losses on ranging markets where the trend line bisects the price stream")inputTradingMode     = input(defval = "BiDir", options = ["Long","Short","BiDir","Flip Flop","Crypto","Range","No Trade"], title = "Trading Mode", group = "[ SECTION 1 ]", tooltip = "BiDir is for margin trading with a stop. Flip Flop will alter direction on trend line cross. Crypto is long only with downward pyramids. Range only enters on a counter-trend")inputMinProfit       = input(defval = 0.50,   type = input.float,    minval = 0.0,  title = "Minimum Profit",         group = "[ SECTION 1 ]", tooltip = "Smallest take profit offset to permit a close order. This is a conditional exit not a limit (quote currency units)")inputStopOffset      = input(defval = 0.50,   type = input.float,    minval = 0.0,  title = "Stop Offset",            group = "[ SECTION 1 ]", tooltip = "Hard stop offset from the trade open price (quote currency units)")inputTickScaler      = input(defval = 10.0,   type = input.float,    minval = 1.0,  title = "Tick Scalar",            group = "[ SECTION 1 ]", tooltip = "Value used to remove the pipette from quote currency calculations. See the Summary Report to determine this value")inputChgDivisor      = input(defval = 1000.0, type = input.float,    minval = 1.0,  title = "Price Normalizer",       group = "[ SECTION 1 ]", tooltip = "Value used to normalize bar prices for differential calculations. Serves to increase the magnitude of significant digits. Applied to all inputs specifying net change and roc")inputPryramidSpan    = input(defval = 0.0,    type = input.float,    minval = 0.0,  title = "Pyramid Minimum Span",   group = "[ SECTION 1 ]", tooltip = "Minimum spacing between downward pyramid levels (quote currency units). Set to zero to disable downward pyramiding. To fully disable pyramiding zero the value in the Properties tab")inputPyramidBaleOut  = input(defval = true,   type = input.bool,                    title = "Position Bale Out",      group = "[ SECTION 1 ]", tooltip = "Enable to exit positions early. The algorithm ensures the position exits at a profit but not at the amount specified in the Minimum Profit input. Reduces the risk when pyramiding")inputMaxAddOns       = input(defval = 0,      type = input.integer,  minval = 0,    maxval = 20, title  = "Maximum DCA Increments", group = "[ SECTION 1 ]", tooltip = "Sets a whole number limit on the number of times a losing position can be averaged down")inputSignalPeriod    = input(defval = "60",   options = ["60","240","1440"],        title = "Signal Line Period",     group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Blue, Green, Orange signal lines and the ZScore oscillator not visible")inputTrendPeriod     = input(defval = "240",  options = ["60","240","1440"],        title = "Trend Line Period",      group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Purple trend line and Stochastic indicator")inputFastAlmaLen     = input(defval = 10,     type = input.integer,  minval = 1,    title = "Fast Alma Length",       group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Blue line (Arnaud Legoux Moving Average indicator)")inputFastLinRegLen   = input(defval = 30,     type = input.integer,  minval = 1,    title = "Fast LinReg Length",     group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Green line (Linear Regression indicator)")inputSlowLinRegLen   = input(defval = 100,    type = input.integer,  minval = 1,    title = "Slow LinReg Length",     group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Orange line (Linear Regression indicator)")inputTrendDEMALen    = input(defval = 200,    type = input.integer,  minval = 1,    title = "Trend Line Length",      group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Purple line (Double Smoothed Moving Average indicator)")inputStochastLen     = input(defval = 14,     type = input.integer,  minval = 1,    title = "Stochastic Length",      group = "[ SECTION 2 ]", tooltip = "Sets the period length of two Stochastic indicators. One at the Purple line. Second at the chart interval")inputFastCrossLen    = input(defval = 9,      type = input.integer,  minval = 1,    title = "Fast Cross Length",      group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")inputSlowCrossLen    = input(defval = 24,     type = input.integer,  minval = 1,    title = "Slow Cross Length",      group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")inputFastEMALen      = input(defval = 8,      type = input.integer,  minval = 1,    title = "Fast EMA Length",        group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Yellow line (Exponential Moving Average indicator). This is a chart interval indicator")inputFastEMARiseNet  = input(defval = 3.0,    type = input.float,    minval = 0.00, title = "Fast EMA Rise NetChg",   group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the upward cross of the Yellow over the Blue line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")inputFastEMARiseROC  = input(defval = 0.8,    type = input.float,    minval = 0.00, title = "Fast EMA Rise ROC",      group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the upward cross of the Yellow over the Blue line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")inputFastEMAFallNet  = input(defval = 4.0,    type = input.float,    minval = 0.00, title = "Fast EMA Fall NetChg",   group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the downward cross of the Yellow under the Blue line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")inputFastEMAFallROC  = input(defval = 0.8,    type = input.float,    minval = 0.00, title = "Fast EMA Fall ROC",      group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the downward cross of the Yellow under the Blue line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")inputLongNascent     = input(defval = false,  type = input.bool,                    title = "Enter Long On Nascent",  group = "[ SECTION 4 ]", tooltip = "Enables rudimentary counter-trend trading. If checked long trades will signal below the Purple trend line and will exit above. The strategy will perform poorly in trending markets")inputLongCrossExit   = input(defval = true,   type = input.bool,                    title = "Long Natural Exit",      group = "[ SECTION 4 ]", tooltip = "A natural long exit is when the Blue line crosses under the Green Line (downward). The position must be profitable to exit")inputLongSignalExit  = input(defval = true,   type = input.bool,                    title = "Long Signal Exit",       group = "[ SECTION 4 ]", tooltip = "A signal event is when the Blue crosses over the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the positive value specified in section #6. The position must be profitable to exit")inputLongEventExit   = input(defval = true,   type = input.bool,                    title = "Long Price Event Exit",  group = "[ SECTION 4 ]", tooltip = "A price event is when the Yellow crosses over the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")inputLongStochExit   = input(defval = true,   type = input.bool,                    title = "Long Stochastic Exit",   group = "[ SECTION 4 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the overbought threshold (80). The position must be profitable to exit")inputShortNascent    = input(defval = false,  type = input.bool,                    title = "Enter Short On Nascent", group = "[ SECTION 5 ]", tooltip = "Enables rudimentary counter-trend trading. If checked short trades will signal above the Purple trend line and will exit below. The strategy will perform poorly in trending markets")inputShortCrossExit  = input(defval = true,   type = input.bool,                    title = "Short Natural Exit",     group = "[ SECTION 5 ]", tooltip = "A natural short exit is when the Blue line crosses over the Green Line. (upward) The position must be profitable to exit")inputShortSignalExit = input(defval = true,   type = input.bool,                    title = "Short Signal Exit",      group = "[ SECTION 5 ]", tooltip = "A signal event is when the Blue crosses under the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the negative value specified in section #6. The position must be profitable to exit")inputShortEventExit  = input(defval = true,   type = input.bool,                    title = "Short Price Event Exit", group = "[ SECTION 5 ]", tooltip = "A price event is when the Yellow crosses under the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")inputShortStochExit  = input(defval = true,   type = input.bool,                    title = "Short Stochastic Exit",  group = "[ SECTION 5 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the oversold threshold (20). The position must be profitable to exit")inputRiseEventNet    = input(defval = 10.0,   type = input.float,    minval = 0.00, title = "Rise Event Net Change",  group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the upward cross of the Blue over the Green line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")inputRiseEventROC    = input(defval = 0.1,    type = input.float,    minval = 0.00, title = "Rise Event ROC",         group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the upward cross of the Blue over the Green line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")inputMinZScoreABZ    = input(defval = 5.0,    type = input.float,    minval = 0.00, title = "Min Above Zero ZScore",  group = "[ SECTION 6 ]", tooltip = "Specifies the overbought threshold of the ZScore oscillator. If the [Long Signal Exit] option in Section #4 is enabled a high value here will cause the long trade to stay in the market longer")inputFallEventNet    = input(defval = 10.0,   type = input.float,    minval = 0.00, title = "Fall Event Net Change",  group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the downward cross of the Blue under the Green line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")inputFallEventROC    = input(defval = 0.1,    type = input.float,    minval = 0.00, title = "Fall Event ROC",         group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the downward cross of the Blue under the Green line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")inputMinZScoreBLZ    = input(defval = 5.0,    type = input.float,    minval = 0.00, title = "Min Below Zero ZScore",  group = "[ SECTION 6 ]", tooltip = "Specifies the oversold threshold of the ZScore oscillator. If the [Short Signal Exit] option in Section #5 is enabled a high value here will cause the short trade to stay in the market longer")inputShowLines       = input(defval = true,   type = input.bool,                    title = "Show Trend Lines",       group = "[ SECTION 7 ]", tooltip = "Display the Yellow, Blue, Green, Orange and Purple trend lines. They are rendered at a width of 2")inputShowCrosses     = input(defval = false,  type = input.bool,                    title = "Show Entry Regions",     group = "[ SECTION 7 ]", tooltip = "Background fill for the SMA crossovers specified in Section #3. The SMA is on the chart time frame so will display frequent transitions. Blue is an upward cross. Red is downward")inputShowEvents      = input(defval = false,  type = input.bool,                    title = "Display Event Regions",  group = "[ SECTION 7 ]", tooltip = "Background fill for signal events specified in Section #6. The Blue crossing the Green lines. Use it to configure Section #6. Blue is exceeding rise values. Red is is exceeding fall values")inputShowEMPeaks     = input(defval = false,  type = input.bool,                    title = "Display EMA Peaks",      group = "[ SECTION 7 ]", tooltip = "Background fill for price events specified in Section #3. The Yellow crossing the Blue lines. Use it to configure Section #3. Blue is exceeding rise values. Red is is exceeding fall values")inputShowStochEvent  = input(defval = false,  type = input.bool,                    title = "Show Stochastic Events", group = "[ SECTION 7 ]", tooltip = "Background fill for Stochastic events occurring on the Purple line. Use it verify selected exits in Section #4 and #5. Blue is exceeding overbought levels. Red is is exceeding oversold levels")inputShowConsecLoss  = input(defval = false,  type = input.bool,                    title = "Show Consecutive Losses",group = "[ SECTION 7 ]", tooltip = "Background fill for periods when consecutive losses are occurring. Red areas mean stops where hit and have not encountered a profitable exit. Use it to make adjustments to the values in Section #1")inputShowBaleOuts    = input(defval = false,  type = input.bool,                    title = "Show Bale Outs",         group = "[ SECTION 7 ]", tooltip = "Displays red labels under the bars where a position was exited prematurely. Each box contains information about the state of the trade at exit time. Use it when [Position Bale Out] in Section #1 is enabled")inputReport          = input(defval = false,  type = input.bool,                    title = "Show Summary Report",    group = "[ SECTION 7 ]", tooltip = "Displays a blue label at the live end of the chart. Contains useful strategy metrics which can aid in the development of the script. Relevant information should be added here as the script logic evolves. Happy Trading!")int  inputNormalizeLen    = 100bool inputAccumulateLong  = falsebool inputAccumulateShort = falsebool inputExclusiveLong   = falsebool inputExclusiveShort  = falseif (inputTradingMode == "Long")    inputExclusiveLong   := trueif (inputTradingMode == "Short")    inputExclusiveShort  := trueif (inputTradingMode == "Crypto")    inputAccumulateLong  := true    inputLongNascent     := true    inputExclusiveLong   := trueif (inputTradingMode == "Range")    inputAccumulateLong  := true    inputAccumulateShort := true    inputLongNascent     := true    inputShortNascent    := truestrategy.risk.allow_entry_in((inputTradingMode == "Long") ? strategy.direction.long : (inputTradingMode == "Short") ? strategy.direction.short : (inputTradingMode == "Crypto") ? strategy.direction.long : strategy.direction.all)if (inputTradingMode == "Crypto")    inputTradingMode := "Flip Flop"// -----------------------------// ---- Indicator Configurations// -----------------------------float fltBarPrice = close// Linear Regressionint ncSlowLinRegLen = inputSlowLinRegLenint ncFastLinRegLen = inputFastLinRegLenint ncLinRegOffset  = 0// Arnaud Legoux Moving Averageint ncFastAlmaLen = inputFastAlmaLen// Double Exponential Moving Averageint ncTrendDEMALen = inputTrendDEMALen// ZScore Simple Moving Averageint ncNormalizeLen = inputNormalizeLen// Fast Cross Simple Moving Averageint ncFastCrossLen = inputFastCrossLen// Slow Cross Simple Moving Averageint ncSlowCrossLen = inputSlowCrossLen// Fast Exponential Moving Averageint ncFastEMALen   = inputFastEMALen// Stochastic Oscillatorint ncStochasLen   = inputStochastLenint ncKn2Period    = 3int ncDn3Period    = 3// -----------------------------// ---- Series Utilities// -----------------------------int indexClosedBar = barstate.isrealtime ? 1 : 0int indexReadBar   = barstate.isrealtime ? 0 : 1calcDEMA(seriesData, ncMALength) =>    float emaAlpha   = ema(seriesData, ncMALength)    float emaOfEma   = ema(emaAlpha,   ncMALength)    float seriesDema = (2 * emaAlpha) - emaOfEmacalcTrendDEMA() =>    float seriesOut = calcDEMA(fltBarPrice[indexClosedBar], ncTrendDEMALen)calcSlowLinReg() =>    float seriesOut = linreg(fltBarPrice[indexClosedBar], ncSlowLinRegLen, ncLinRegOffset)calcFastLinReg() =>    float seriesOut = linreg(fltBarPrice[indexClosedBar], ncFastLinRegLen, ncLinRegOffset)calcFastAlma() =>    float seriesOut = alma(fltBarPrice[indexClosedBar], ncFastAlmaLen, 0.85, 6)calcStochastic() =>    float seriesOut = stoch(close[indexClosedBar], high[indexClosedBar], low[indexClosedBar], ncStochasLen)// ----------------------------// ---- Series Creation// ----------------------------float seriesClose = close[indexClosedBar]float seriesHigh  = high[indexClosedBar]float seriesLow   = low[indexClosedBar]// ---- [ HIGHER TIME FRAME ] ----// Linear Regressionfloat htf_seriesSlowLinReg = security(syminfo.tickerid, inputSignalPeriod, calcSlowLinReg())[indexReadBar]float htf_seriesFastLinReg = security(syminfo.tickerid, inputSignalPeriod, calcFastLinReg())[indexReadBar]// Arnaud Legoux Moving Averagefloat htf_seriesFastAlma   = security(syminfo.tickerid, inputSignalPeriod, calcFastAlma())[indexReadBar]// Double Exponential Moving Averagefloat htf_seriesTrendDEMA  = security(syminfo.tickerid, inputTrendPeriod,  calcTrendDEMA())[indexReadBar]// ZScore Simple Moving Averagefloat htf_seriesAlmaMean   = sma(htf_seriesFastAlma, ncNormalizeLen)// ZScore Seriesfloat htf_seriesMarks      = htf_seriesFastAlma - htf_seriesAlmaMeanfloat htf_seriesZScore     = htf_seriesMarks / stdev(htf_seriesMarks, ncNormalizeLen)// Stochastic Oscillatorfloat htf_seriesFastK      = security(syminfo.tickerid, inputTrendPeriod,  calcStochastic())[indexReadBar]float htf_seriesDLine      = sma(htf_seriesFastK, ncKn2Period)float htf_seriesSlowD      = sma(htf_seriesDLine, ncDn3Period)// ---- [ CHART TIME FRAME ] ----// Fast Cross Simple Moving Averagefloat seriesFastCross = sma(fltBarPrice, ncFastCrossLen)// Slow Cross Simple Moving Averagefloat seriesSlowCross = sma(fltBarPrice, ncSlowCrossLen)// Fast Exponential Moving Averagefloat seriesFastEMA   = ema(fltBarPrice, ncFastEMALen)// Stochastic Oscillatorfloat seriesFastK     = stoch(seriesClose, seriesHigh, seriesLow, ncStochasLen)float seriesDLine     = sma(seriesFastK, ncKn2Period)float seriesSlowD     = sma(seriesDLine, ncDn3Period)// ----------------------------// ---- Indicator Conditions// ----------------------------bool bHTFSignalRise     = (htf_seriesFastAlma > htf_seriesFastLinReg)bool bHTFSignalFall     = (htf_seriesFastAlma < htf_seriesFastLinReg)bool bHTFFastAboveTrend = ((htf_seriesFastAlma > htf_seriesTrendDEMA) and (htf_seriesFastLinReg > htf_seriesTrendDEMA))bool bHTFFastBelowTrend = ((htf_seriesFastAlma < htf_seriesTrendDEMA) and (htf_seriesFastLinReg < htf_seriesTrendDEMA))bool bFastAboveSignal   = ((seriesFastEMA > htf_seriesFastAlma) and (htf_seriesFastAlma > htf_seriesFastLinReg))bool bFastBelowSignal   = ((seriesFastEMA < htf_seriesFastAlma) and (htf_seriesFastAlma < htf_seriesFastLinReg))bool bFullFanCone       = ((bFastAboveSignal == true) and (htf_seriesFastLinReg > htf_seriesSlowLinReg))bool bDownFanCone       = ((bFastBelowSignal == true) and (htf_seriesFastLinReg < htf_seriesSlowLinReg))bool bPartialTrendRise  = ((seriesFastEMA > htf_seriesFastAlma) and (htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg))bool bPartialTrendFall  = ((seriesFastEMA < htf_seriesFastAlma) and (htf_seriesFastAlma < htf_seriesSlowLinReg) and (htf_seriesFastLinReg < htf_seriesSlowLinReg))bool bDurableTrendRise  = ((bPartialTrendRise == true) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))bool bDurableTrendFall  = ((bPartialTrendFall == true) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))bool bHTFNascentRise    = ((htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))bool bHTFNascentFall    = ((htf_seriesFastAlma < htf_seriesSlowLinReg) and (htf_seriesFastLinReg < htf_seriesSlowLinReg) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))// -------------------------------// ---- Event Utilities// -------------------------------float fltFXMinTick = syminfo.mintick * inputTickScalercalcRiseNetChg(fltFastPrice, fltSlowPrice) =>    float fltPercentChg = 0.0    float fltChgDivisor = (inputChgDivisor > 1.0) ? inputChgDivisor : fltSlowPrice    if (((na(fltSlowPrice) == false) and (fltSlowPrice > 0.0) and (fltFastPrice > fltSlowPrice)) == true)        fltPercentChg := (((fltFastPrice - fltSlowPrice) / fltFXMinTick) / fltChgDivisor) * 100.0    float fltResult = fltPercentChgcalcFallNetChg(fltFastPrice, fltSlowPrice) =>    float fltPercentChg = 0.0    float fltChgDivisor = (inputChgDivisor > 1.0) ? inputChgDivisor : fltSlowPrice    if (((na(fltSlowPrice) == false) and (fltSlowPrice > 0.0) and (fltFastPrice < fltSlowPrice)) == true)        fltPercentChg := (((fltSlowPrice - fltFastPrice) / fltFXMinTick) / fltChgDivisor) * 100.0    float fltResult = fltPercentChg// -------------------------------// ---- HTF Fast Alma Crosses HTF Fast LinReg// -------------------------------// Alma Above and Below LinReg (AL)var float fltRiseALCrossPrice = 0.0var float fltRiseALNetChg     = 0.0var float fltFallALCrossPrice = 0.0var float fltFallALNetChg     = 0.0var int   ncRiseALBarsSince   = 0var int   ncFallALBarsSince   = 0if (htf_seriesFastAlma > htf_seriesFastLinReg)    if (ncFallALBarsSince > 0)     // We were previously falling        ncFallALBarsSince   := 0   // Zero means not in that direction        fltFallALCrossPrice := 0.0        ncRiseALBarsSince   := 1   // Non-zero means currently rising        fltRiseALCrossPrice := seriesClose        fltRiseALNetChg     := 0.0    else        ncRiseALBarsSince := ncRiseALBarsSince + 1 // Rise continues        fltRiseALNetChg   := calcRiseNetChg(seriesClose, fltRiseALCrossPrice) // Risingif (htf_seriesFastAlma < htf_seriesFastLinReg)    if (ncRiseALBarsSince > 0)     // We were previously rising        ncRiseALBarsSince   := 0   // Zero means not in that direction        fltRiseALCrossPrice := 0.0        ncFallALBarsSince   := 1   // Non-zero means currently falling        fltFallALCrossPrice := seriesClose        fltFallALNetChg     := 0.0    else        ncFallALBarsSince := ncFallALBarsSince + 1 // Fall continues        fltFallALNetChg   := calcFallNetChg(seriesClose, fltFallALCrossPrice) // FallingisMinimumNetChgROC(ncTypeBarsSince, fltTypeNetChg, fltMinNetChg, fltMinROC) =>    bool bPassed = false    bPassed := (((ncTypeBarsSince > 0) and (fltTypeNetChg > 0.0)) and (fltTypeNetChg >= fltMinNetChg) and ((fltTypeNetChg / ncTypeBarsSince) >= fltMinROC))// -------------------------------// ---- Fast EMA Crosses HTF Alma// -------------------------------// LTF EMA Above and Below HTF Alma (EM)var float fltRiseEMCrossPrice = 0.0var float fltRiseEMNetChg     = 0.0var float fltFallEMCrossPrice = 0.0var float fltFallEMNetChg     = 0.0var int   ncRiseEMBarsSince   = 0var int   ncFallEMBarsSince   = 0if (seriesFastEMA > htf_seriesFastAlma)    if (ncFallEMBarsSince > 0)     // We were previously falling        ncFallEMBarsSince   := 0   // Zero means not in that direction        fltFallEMCrossPrice := 0.0        ncRiseEMBarsSince   := 1   // Non-zero means currently rising        fltRiseEMCrossPrice := seriesClose        fltRiseEMNetChg     := 0.0    else        ncRiseEMBarsSince := ncRiseEMBarsSince + 1 // Rise continues        fltRiseEMNetChg   := calcRiseNetChg(seriesClose, fltRiseEMCrossPrice) // Risingif (seriesFastEMA < htf_seriesFastAlma)    if (ncRiseEMBarsSince > 0)     // We were previously rising        ncRiseEMBarsSince   := 0   // Zero means not in that direction        fltRiseEMCrossPrice := 0.0        ncFallEMBarsSince   := 1   // Non-zero means currently falling        fltFallEMCrossPrice := seriesClose        fltFallEMNetChg     := 0.0    else        ncFallEMBarsSince := ncFallEMBarsSince + 1 // Fall continues        fltFallEMNetChg   := calcFallNetChg(seriesClose, fltFallEMCrossPrice) // Falling// ----------------------------// ---- ZScore Histogram Tracking// ----------------------------// ZScore Above and Below Zero Line (ZS)bool bNewRiseZSHigh = falsebool bNewFallZSLow  = falsevar int   ncRiseZSSince  = 0var int   ncFallZSSince  = 0var int   ncRiseZSCount  = 0var int   ncFallZSCount  = 0var float fltRiseZSValue = 0.0var float fltFallZSValue = 0.0var float fltRiseZSHigh  = 0.0var float fltFallZSLow   = 0.0var int   ncAboveZSCount = 0var int   ncBelowZSCount = 0var int   ncAboveZSSince = 0var int   ncBelowZSSince = 0ncRiseZSSince  := ncRiseZSSince  + 1ncFallZSSince  := ncFallZSSince  + 1ncAboveZSSince := ncAboveZSSince + 1ncBelowZSCount := ncBelowZSCount + 1if (htf_seriesZScore > htf_seriesZScore[1])    fltRiseZSValue := htf_seriesZScore[0]    fltRiseZSHigh  := seriesClose[0] // High    bNewRiseZSHigh := true    if (ncRiseZSSince > 0) // We were previously falling        ncRiseZSSince := 0        ncRiseZSCount := 1    else        ncRiseZSSince := 0        ncRiseZSCount := ncRiseZSCount + 1 // Rise continuesif (htf_seriesZScore > 0.0)    if (ncAboveZSSince > 0) // We were previously below zero        ncAboveZSSince := 0        ncAboveZSCount := 1    else        ncAboveZSSince := 0        ncAboveZSCount := ncAboveZSCount + 1 // Above zero continuesif (htf_seriesZScore < htf_seriesZScore[1])    fltFallZSValue := htf_seriesZScore[0]    fltFallZSLow   := seriesClose[0] // Low    bNewFallZSLow := true    if (ncFallZSSince > 0) // We were previously rising        ncFallZSSince := 0        ncFallZSCount := 1    else        ncFallZSSince := 0        ncFallZSCount := ncFallZSCount + 1 // Fall continuesif (htf_seriesZScore < 0.0)    if (ncBelowZSSince > 0) // We were previously above zero        ncBelowZSSince := 0        ncBelowZSCount := 1    else        ncBelowZSSince := 0        ncBelowZSCount := ncBelowZSCount + 1 // Below zero continues// ----------------------------// ---- Strategy Variables// ----------------------------var float fltEntryPrice  = 0.0var float fltExitPrice   = 0.0var float fltStopPrice   = 0.0var float fltEntryHigh   = 0.0var float fltEntryLow    = 0.0var float fltDefaultSize = 0.0var float fltCurrentSize = 0.0var bool  bPullback      = falsevar bool  bFEERise       = falsevar bool  bFEEFall       = falsevar int   ncPyramidCount = 0var int   nPyramidWaveID = 0var int   nEntryTrendDir = 0var int   ncConsecLosses = 0var bool  bNascentEntry  = falsevar bool  bHemiTransit   = falsevar float fltLastLevel   = 0.0var float fltMAELevel    = 0.0string strLongName       = "WBHDrive-L"string strShortName      = "WBHDrive-S"string strLongStop       = "WBHD-L-Stop"string strShortStop      = "WBHD-S-Stop"string strTradingMode    = inputTradingModefloat  fltMinProfit      = inputMinProfitfloat  fltStopOffset     = inputStopOffsetfloat  fltPryramidSpan   = inputPryramidSpanfloat  fltRiseEventNet   = inputRiseEventNetfloat  fltRiseEventROC   = inputRiseEventROCfloat  fltMinZScoreABZ   = inputMinZScoreABZfloat  fltFallEventNet   = inputFallEventNetfloat  fltFallEventROC   = inputFallEventROCfloat  fltMinZScoreBLZ   = inputMinZScoreBLZfloat  fltFastEMARiseNet = inputFastEMARiseNetfloat  fltFastEMARiseROC = inputFastEMARiseROCfloat  fltFastEMAFallNet = inputFastEMAFallNetfloat  fltFastEMAFallROC = inputFastEMAFallROCint    ncMaxAddOns       = inputMaxAddOnsbool   bPyramidBaleOut   = inputPyramidBaleOutbool   bAccumulateLong   = inputAccumulateLongbool   bAccumulateShort  = inputAccumulateShortbool   bLongNascent      = inputLongNascentbool   bLongCrossExit    = inputLongCrossExitbool   bLongSignalExit   = inputLongSignalExitbool   bLongEventExit    = inputLongEventExitbool   bLongStochExit    = inputLongStochExitbool   bShortNascent     = inputShortNascentbool   bShortCrossExit   = inputShortCrossExitbool   bShortSignalExit  = inputShortSignalExitbool   bShortEventExit   = inputShortEventExitbool   bShortStochExit   = inputShortStochExitfloat  fltNetProfit      = 0.0float  fltNumShares      = 0.0float  fltExpected       = 0.0bool   bAlreadyIn        = falsebool   bProfitable       = falseint    nPositionDir      = 0bool   bCrossRise        = falsebool   bCrossFall        = falsebool   bOpenLong         = falsebool   bOpenShort        = falsebool   bOpenTrade        = falsebool   bCloseLong        = falsebool   bCloseShort       = falsebool   bCloseTrade       = falsecalcPipsProfit(nTradeDir, fltPriceNow, fltOpenPrice) =>    float fltProfit = 0.0    if (nTradeDir == 1)        fltProfit := fltPriceNow - fltOpenPrice    if (nTradeDir == -1)        fltProfit := fltOpenPrice - fltPriceNow    float fltResult = fltProfit// ---------------------------------// --- Statistical Event Calculation// ---------------------------------bool bRiseALEvent = (((fltRiseEventNet   > 0.0) and (fltRiseEventROC   > 0.0)) and (isMinimumNetChgROC(ncRiseALBarsSince, fltRiseALNetChg, fltRiseEventNet,   fltRiseEventROC)   == true))bool bFallALEvent = (((fltFallEventNet   > 0.0) and (fltFallEventROC   > 0.0)) and (isMinimumNetChgROC(ncFallALBarsSince, fltFallALNetChg, fltFallEventNet,   fltFallEventROC)   == true))bool bRiseEMEvent = (((fltFastEMARiseNet > 0.0) and (fltFastEMARiseROC > 0.0)) and (isMinimumNetChgROC(ncRiseEMBarsSince, fltRiseEMNetChg, fltFastEMARiseNet, fltFastEMARiseROC) == true))bool bFallEMEvent = (((fltFastEMAFallNet > 0.0) and (fltFastEMAFallROC > 0.0)) and (isMinimumNetChgROC(ncFallEMBarsSince, fltFallEMNetChg, fltFastEMAFallNet, fltFastEMAFallROC) == true))var float fltHTFEventHigh = 0.0var float fltHTFEventLow  = 0.0var int   nLastHTFEvent   = 0if (bRiseALEvent == true)    fltHTFEventHigh := seriesClose    nLastHTFEvent := 1if (bFallALEvent == true)    fltHTFEventLow  := seriesClose    nLastHTFEvent := -1bool bRiseStochas = (((htf_seriesDLine > 80) and (bFullFanCone == true)) or ((htf_seriesSlowD > 90) and (bDurableTrendRise == true)) or ((htf_seriesDLine > 90) and (bPartialTrendRise == true) and (fltHTFEventHigh > 0.0) and (seriesClose > fltHTFEventHigh)))bool bFallStochas = (((htf_seriesDLine < 20) and (bDownFanCone == true)) or ((htf_seriesSlowD < 10) and (bDurableTrendFall == true)) or ((htf_seriesDLine < 10) and (bPartialTrendFall == true) and (fltHTFEventLow  > 0.0) and (seriesClose < fltHTFEventLow)))var int nImpulseWaveDir = 0var int nImpulseWaveID  = 0int nWaveDirNow = 0if (htf_seriesFastLinReg > htf_seriesSlowLinReg)    nWaveDirNow :=  1if (htf_seriesFastLinReg < htf_seriesSlowLinReg)    nWaveDirNow := -1if (nWaveDirNow != nImpulseWaveDir)    nImpulseWaveDir := nWaveDirNow    nImpulseWaveID  := nImpulseWaveID + 1// ----------------------------// ---- Actual Strategy// ----------------------------nPositionDir := (strategy.position_size < 0) ? -1 : (strategy.position_size > 0) ? 1 : 0fltNumShares := abs(strategy.position_size)fltNetProfit := strategy.openprofitfltExpected  := (fltMinProfit * fltNumShares)bProfitable  := (fltNetProfit >= fltExpected)if ((strategy.position_entry_name == strLongName) or (strategy.position_entry_name == strShortName))    bAlreadyIn := trueif (bProfitable == true)    bProfitable := (calcPipsProfit(nPositionDir, seriesClose, fltEntryPrice) >= fltMinProfit)if (bAlreadyIn == false)    if (fltEntryPrice > 0.0)        ncConsecLosses := ncConsecLosses + 1        ncPyramidCount := 0        fltLastLevel   := 0.0        fltEntryPrice  := 0.0        fltStopPrice   := 0.0        bPullback      := false        bFEERise       := false        bFEEFall       := false// ----------------------------// ---- Entry Condition - Long// ----------------------------bCrossRise := crossover(seriesFastCross, seriesSlowCross)if ((bAlreadyIn == false) and (strTradingMode != "No Trade"))    if (bCrossRise == true)        if ((seriesClose > htf_seriesTrendDEMA) and (strTradingMode != "Range"))            bOpenLong     := true            bNascentEntry := false        else if ((bLongNascent == true) and (bHTFNascentRise == true))            bOpenLong     := true            bNascentEntry := true// ----------------------------// ---- Entry Condition - Short// ----------------------------bCrossFall := crossunder(seriesFastCross, seriesSlowCross)if ((bAlreadyIn == false) and (bOpenLong == false) and (strTradingMode != "No Trade"))    if (bCrossFall == true)        if ((seriesClose < htf_seriesTrendDEMA) and (strTradingMode != "Range"))            bOpenShort    := true            bNascentEntry := false        else if ((bShortNascent == true) and (bHTFNascentFall == true))            bOpenShort    := true            bNascentEntry := true// ----------------------------// ---- Conditional Close// ----------------------------if (bAlreadyIn == true)    if (htf_seriesZScore > fltMinZScoreABZ)        bFEERise := true    if (htf_seriesZScore < (fltMinZScoreBLZ * (-1)))        bFEEFall := trueif (bAlreadyIn == true)    if ((nPositionDir == 1) and (bProfitable == true))        if ((bLongCrossExit  == true)  and (bHTFSignalFall == true))            bCloseLong  := true        if ((bLongSignalExit == true)  and (bHTFSignalRise == true) and (bRiseALEvent == true) and (bFEERise == true))            bCloseLong  := true        if ((bLongEventExit  == true)  and (bRiseEMEvent == true) and (bFastAboveSignal == true) and (bHTFFastAboveTrend == true))            bCloseLong  := true        if ((bLongStochExit  == true)  and (bRiseStochas == true))            bCloseLong  := true    if ((nPositionDir == -1) and (bProfitable == true))        if ((bShortCrossExit  == true) and (bHTFSignalRise == true))            bCloseShort := true        if ((bShortSignalExit == true) and (bHTFSignalFall == true) and (bFallALEvent == true)  and (bFEEFall == true))            bCloseShort := true        if ((bShortEventExit  == true) and (bFallEMEvent == true) and (bFastBelowSignal == true) and (bHTFFastBelowTrend == true))            bCloseShort := true        if ((bShortStochExit  == true) and (bFallStochas == true))            bCloseShort  := true// ----------------------------// ---- Flip Flop Condition// ----------------------------if (bAlreadyIn == true)    if ((nPositionDir ==  1) and (seriesClose > htf_seriesTrendDEMA) and (bNascentEntry == true))        bHemiTransit := true    if ((nPositionDir == -1) and (seriesClose < htf_seriesTrendDEMA) and (bNascentEntry == true))        bHemiTransit := trueif ((bAlreadyIn == true) and (strTradingMode == "Flip Flop"))    if (nPositionDir ==  1)        if ((seriesClose < fltEntryPrice) and (bFallEMEvent == true) and (bFastBelowSignal == true) and (bHTFFastBelowTrend == true) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))            if ((bNascentEntry == true) and (bHemiTransit == true))                bCloseLong  := true            if ((bNascentEntry == true) and (htf_seriesFastAlma < htf_seriesSlowLinReg) and (htf_seriesFastLinReg < htf_seriesSlowLinReg) and (bFallALEvent == true) and (bAccumulateLong == false))                bCloseLong  := true            if ((nEntryTrendDir ==  1)  and (bNascentEntry == false) and (inputExclusiveLong == false))                bCloseLong  := true    if (nPositionDir == -1)        if ((seriesClose > fltEntryPrice) and (bRiseEMEvent == true) and (bFastAboveSignal == true) and (bHTFFastAboveTrend == true) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))            if ((bNascentEntry == true) and (bHemiTransit == true))                bCloseShort := true            if ((bNascentEntry == true) and (htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg) and (bRiseALEvent == true) and (bAccumulateShort == false))                bCloseShort := true            if ((nEntryTrendDir == -1)  and (bNascentEntry == false) and (inputExclusiveShort == false))                bCloseShort := true// ----------------------------// ---- Bale Out Condition// ----------------------------bool bBailingOut = falseif (nPositionDir ==  1)    if ((bPyramidBaleOut == true) and (seriesClose > htf_seriesTrendDEMA) and (bRiseStochas == true) and (htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))        if (fltNetProfit > (fltExpected * 2.0))            bCloseLong  := true            bBailingOut := trueif (nPositionDir == -1)    if ((bPyramidBaleOut == true) and (seriesClose < htf_seriesTrendDEMA) and (bFallEMEvent == true) and (bFastBelowSignal == true) and (bHTFFastBelowTrend == true) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))        if (fltNetProfit > (fltExpected * 2.0))            bCloseShort := true            bBailingOut := true// ----------------------------// ---- Open Trade// ----------------------------calcQuantity() =>    float fltTradeSize = fltCurrentSize    if (fltDefaultSize > 0.0)        fltTradeSize := ((ncMaxAddOns > 0) and (fltDefaultSize > 0.0) and (ncConsecLosses > 0) and (ncConsecLosses < ncMaxAddOns)) ? (fltDefaultSize * (ncConsecLosses + 1)) : fltDefaultSize    float fltResult = fltTradeSizefloat fltQuantity = 0.0if ((bOpenLong == true) or (bOpenShort == true))    fltQuantity    := calcQuantity()    fltEntryPrice  := seriesClose    fltEntryHigh   := seriesHigh    fltEntryLow    := seriesLow    fltLastLevel   := fltEntryPrice    fltMAELevel    := 0.0    fltStopPrice   := 0.0    bOpenTrade     := true    bFEERise       := false    bFEEFall       := false    bPullback      := false    bHemiTransit   := false    ncPyramidCount := 0    nEntryTrendDir := (seriesClose > htf_seriesTrendDEMA) ? 1 : -1if (bOpenLong == true)    if (fltStopOffset > 0.0)        fltStopPrice := (seriesLow - fltStopOffset)    if (fltQuantity  > 0.0)        strategy.entry(strLongName,  strategy.long,  qty = fltQuantity, alert_message = "entry stop = " + tostring(fltStopPrice))    if (fltQuantity == 0.0)        strategy.entry(strLongName,  strategy.long,  alert_message = "entry stop = " + tostring(fltStopPrice))        fltCurrentSize := abs(strategy.position_size)    if (fltStopPrice > 0.0)        strategy.exit(strLongStop, strLongName, stop = fltStopPrice, alert_message = "stop = " + tostring(fltStopPrice))if (bOpenShort == true)    if (fltStopOffset > 0.0)        fltStopPrice := (seriesHigh + fltStopOffset)    if (fltQuantity  > 0.0)        strategy.entry(strShortName, strategy.short, qty = fltQuantity, alert_message = "entry stop = " + tostring(fltStopPrice))    if (fltQuantity == 0.0)        strategy.entry(strShortName, strategy.short, alert_message = "entry stop = " + tostring(fltStopPrice))        fltCurrentSize := abs(strategy.position_size)    if (fltStopPrice > 0.0)        strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message = "stop = " + tostring(fltStopPrice))if (fltDefaultSize == 0.0)    fltDefaultSize := abs(strategy.position_size)// ----------------------------// ---- Close Trade// ----------------------------var int ncLastConsecs = 0if (bCloseLong == true)    fltExitPrice := seriesClose    strategy.close( strLongName, when = true, alert_message = "exit profit = " + tostring(fltExitPrice - fltEntryPrice))    strategy.cancel(strLongName)    bCloseTrade  := trueif (bCloseShort == true)    fltExitPrice := seriesClose    strategy.close( strShortName, when = true, alert_message = "exit profit = " + tostring(fltEntryPrice - fltExitPrice))    strategy.cancel(strShortName)    bCloseTrade  := trueif (bCloseTrade == true)    ncLastConsecs  := ncConsecLosses    ncConsecLosses := (bProfitable == true) ? 0 : ncConsecLosses + 1    fltLastLevel   := 0.0    fltEntryPrice  := 0.0    fltStopPrice   := 0.0    bPullback      := false    bFEERise       := false    bFEEFall       := falsevar string strBadRunDate = ""var int    ncMaxConsecs  = 0if (ncConsecLosses > ncMaxConsecs)    ncMaxConsecs  := ncConsecLosses    strBadRunDate := tostring(year) + "-" + tostring(month, "##") + "-" + tostring(dayofmonth, "##") + " [" + tostring(hour, "##") + ":" + tostring(minute, "##") + ":00]"// ----------------------------// ---- Pyramid Technology// ----------------------------if ((nPositionDir ==  1) and (seriesSlowD < 20) and ((bFallALEvent == true) or (bFallStochas == true)))    bPullback := trueif ((nPositionDir == -1) and (seriesSlowD > 80) and ((bRiseALEvent == true) or (bRiseStochas == true)))    bPullback := trueIsPyramidFall() =>    bool bResult = false    bool bPassed = false    bool bExceedingSpan = ((fltPryramidSpan > 0.0) and ((fltLastLevel - seriesClose) > fltPryramidSpan))    if ((bCrossRise == true) and (seriesClose > htf_seriesTrendDEMA) and (bHTFFastAboveTrend == true) and (seriesClose > fltLastLevel) and (bPullback == true))        bPassed := true    else if ((seriesClose < fltLastLevel) and (bExceedingSpan == true) and (seriesClose > fltEntryPrice) and ((bFallALEvent == true) or (bFallEMEvent == true) or (bFallStochas == true)))        bPassed := true    else if ((seriesClose < fltLastLevel) and (bExceedingSpan == true) and (seriesClose < fltEntryPrice) and (bFallALEvent == true) and (bFallStochas == true) and (bAccumulateLong == true) and (nImpulseWaveID > nPyramidWaveID))        bPassed := true    bResult := bPassedIsPyramidRise() =>    bool bResult = false    bool bPassed = false    bool bExceedingSpan = ((fltPryramidSpan > 0.0) and ((seriesClose - fltLastLevel) > fltPryramidSpan))    if ((bCrossFall == true) and (seriesClose < htf_seriesTrendDEMA) and (bHTFFastBelowTrend == true) and (seriesClose < fltLastLevel) and (bPullback == true))        bPassed := true    else if ((seriesClose > fltLastLevel) and (bExceedingSpan == true) and (seriesClose < fltEntryPrice) and ((bRiseALEvent == true) or (bRiseEMEvent == true) or (bRiseStochas == true)))        bPassed := true    else if ((seriesClose > fltLastLevel) and (bExceedingSpan == true) and (seriesClose > fltEntryPrice) and (bRiseALEvent == true) and (bRiseStochas == true) and (bAccumulateShort == true) and (nImpulseWaveID > nPyramidWaveID))        bPassed := true    bResult := bPassedbool bNewPyramidLevel = falsebool bPyramidFall = IsPyramidFall()bool bPyramidRise = IsPyramidRise()if (bAlreadyIn == true)    if ((nPositionDir ==  1) and (bPyramidFall == true))        bNewPyramidLevel := true        strategy.entry(strLongName,  strategy.long,  alert_message="pyramid level = " + tostring(ncPyramidCount + 1))        strategy.exit(strLongStop, strLongName, stop = fltStopPrice,   alert_message="scale out level = " + tostring(ncPyramidCount + 1))    if ((nPositionDir == -1) and (bPyramidRise == true))        bNewPyramidLevel := true        strategy.entry(strShortName, strategy.short, alert_message="pyramid level = " + tostring(ncPyramidCount + 1))        strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message="scale out level = " + tostring(ncPyramidCount + 1))if (bNewPyramidLevel == true)    ncPyramidCount := ncPyramidCount + 1    nPyramidWaveID := nImpulseWaveID    fltLastLevel   := seriesClose    bPullback      := false    if (ncPyramidCount == 1)        fltMAELevel := seriesClose    if ((nPositionDir ==  1) and (seriesClose < fltMAELevel))        fltMAELevel := seriesClose    if ((nPositionDir == -1) and (seriesClose > fltMAELevel))        fltMAELevel := seriesClosevar int ncHighestLevel = 0if (ncPyramidCount > ncHighestLevel)    ncHighestLevel := ncPyramidCount// ----------------------------// ---- Strategy Plots// ----------------------------// HTF Trend Linesfloat plotSlowLinReg = nafloat plotFastLinReg = nafloat plotTrendDEMA  = nafloat plotFastAlma   = nafloat plotFastEMA    = naif (inputShowLines == true)    plotSlowLinReg := htf_seriesSlowLinReg    plotFastLinReg := htf_seriesFastLinReg    plotTrendDEMA  := htf_seriesTrendDEMA    plotFastAlma   := htf_seriesFastAlma    plotFastEMA    := seriesFastEMAplot(plotSlowLinReg, color = color.orange, linewidth = 2, title = "SlowLinReg")plot(plotFastLinReg, color = color.green,  linewidth = 2, title = "FastLinReg")plot(plotTrendDEMA,  color = color.purple, linewidth = 2, title = "TrendDEMA")plot(plotFastAlma,   color = color.blue,   linewidth = 2, title = "FastAlma")plot(plotFastEMA,    color = color.yellow, linewidth = 2, title = "FastEMA")// Entry Crossover Background Fillbgcolor(((inputShowCrosses == true) and (bCrossRise == true)) ? color.blue : na)bgcolor(((inputShowCrosses == true) and (bCrossFall == true)) ? color.red  : na)// HTF Event Background Fillbgcolor(((inputShowEvents == true) and (bRiseALEvent == true)) ? color.blue : na)bgcolor(((inputShowEvents == true) and (bFallALEvent == true)) ? color.red  : na)// Entry EMA Event Background Fillbgcolor(((inputShowEMPeaks == true) and (bRiseEMEvent == true)) ? color.blue : na)bgcolor(((inputShowEMPeaks == true) and (bFallEMEvent == true)) ? color.red  : na)// Stochastic Event Background Fillbgcolor(((inputShowStochEvent == true) and (bRiseStochas == true)) ? color.blue : na)bgcolor(((inputShowStochEvent == true) and (bFallStochas == true)) ? color.red  : na)// Consecutive Losses Background Fillbgcolor(((inputShowConsecLoss == true) and (ncConsecLosses > 0)) ? color.red  : na)// -----------------------------------------------------------------------------// ----- [ BALE OUT MARKERS ]  -------------------------------------------------// -----------------------------------------------------------------------------if ((inputShowBaleOuts == true) and (bBailingOut == true))    string txtReport = " Bale Out Exit"    txtReport := txtReport + "\n" + " Net Profit: "    + tostring(fltNetProfit, "#.####")    txtReport := txtReport + "\n" + " Position Size: " + tostring(fltNumShares, "#.####")    txtReport := txtReport + "\n" + " Pyramid Count: " + tostring(ncPyramidCount)    txtReport := txtReport + "\n" + " MAE Level: "     + tostring(fltMAELevel,  "#.####")    txtReport := txtReport + "\n" + " Consec Losses: " + tostring(ncLastConsecs)    label.new(bar_index, high, txtReport, xloc=xloc.bar_index, yloc=yloc.belowbar, style=label.style_labelup, color=#FF0000, textcolor=color.white, size=size.normal, textalign=text.align_left)// -----------------------------------------------------------------------------// ----- [ REPORT ] ------------------------------------------------------------// -----------------------------------------------------------------------------int ncBarsOffChart = 8string txtReport = ""txtReport := txtReport +        "╒═════════════════╕"txtReport := txtReport + "\n" + "   Minimum Tick Size: "  + tostring(syminfo.mintick)txtReport := txtReport + "\n" + "   Maximum Pyramids: "   + tostring(ncHighestLevel + 1)txtReport := txtReport + "\n" + "   Consecutive Losses: " + tostring(ncMaxConsecs)txtReport := txtReport + "\n" + "   Date: "               + strBadRunDatetxtReport := txtReport + "\n" + "   Max TV Drawdown: "    + tostring(strategy.max_drawdown, "#.####")txtReport := txtReport + "\n" + "   Max TV Contracts: "   + tostring(strategy.max_contracts_held_all, "#.####")txtReport := txtReport + "\n" + "╘═════════════════╛"if (inputReport == true)    lblEndOfChart = label.new(time + (40 * (time - time[1])), low, txtReport, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_labeldown, color=color.navy, textcolor=color.white, size=size.normal, textalign=text.align_left)    label.delete(lblEndOfChart[1])