Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Simple and Profitable Scalping Strategy (ForexSignals TV)

A Pine Script v5 strategy built on EMA (close, 8), ATR (14) and Highest (high, 5). It has 4 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 1 in cash and pays no commission. 20 settings; defaults include Trend Filter Tf 60, Fast EMA Length 8 and Slow EMA Length 21.

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 Simple and Profitable Scalping Strategy (ForexSignals TV) repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
How did Simple and Profitable Scalping Strategy (ForexSignals TV) do on BTCUSDT 1D with default settings?
Not measured
It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
Does Simple and Profitable Scalping Strategy (ForexSignals TV) run in Pine Script v6?
Not tested
Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download.
Does Simple and Profitable Scalping Strategy (ForexSignals TV) use a stop loss?
Yes
strategy.exit sets a stop on line 276.
Does Simple and Profitable Scalping Strategy (ForexSignals TV) run in Zeal Terminal?
Yes
It compiles in 112 ms and runs 1,000 bars in 188 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • Plot
  • fanGap
  • bullEmaOrder
  • bullFanOutGap
  • bullBreakout
  • bullPullback
  • bearEmaOrder
  • bearFanOutGap
  • bearBreakout
  • bearPullback
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,000$2,025Equity from $1,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. The live re-run is not offered here: the script requests BINANCE:BTCUSDT 60, which this page cannot load in your browser.

Needs BINANCE:BTCUSDT 60 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Values that depend on it are empty on this chart.

Net profit
0.00%
$0.00
Buy and hold
+102.5%
same period
Closed trades
0
0 won · 0 lost
Profitable
0.0%
of closed trades
Profit factor
—
gross profit ÷ gross loss
Max drawdown
0.00%
$0.00

One run with the author's default settings, $1,000 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

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

  • Check

    No commission

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

  • Note

    5 settings have no label

    In the settings dialog trendFilterTf (line 60), startMonth (line 82), startDate (line 83), endMonth (line 85), endDate (line 86) show an empty name. The labels on this page come from the variable names.

  • Note

    No slippage

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

Settings

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

SettingDefaultType and rangeFeeds
Strategy: Higher Timeframe Trend Filter
Trend Filter Tf (no label in the script)Higher timeframe to use for finding main trand direction60timeframefastSec slowSec
Fast EMA Length Length of Fast EMA of higher timeframe8int · min 1trendFastEma
Slow EMA Length Length of Slow EMA of higher timeframe21int · min 1trendSlowEma
Strategy: Trade Entry Conditions
Fast EMA Length Fast EMA used to find entry candles when price pulls back into this line8int · min 1entryFastEma
Medium EMA Length Medium EMA used to filter out entries when lines are not fanned out or not trending in the desired direction13int · min 1entryMedEma
Slow EMA Length Slow EMA used to filter out entries when lines are not fanned out or not trending in the desired direction.\n\nAlso used to cancel open orders which close below this EMA before entry has been triggered21int · min 1entrySlowEma
EMA Fanout ATR Multiplier ATR multiplier to determine how but the fanout gap must be between the Fast EMA and Slow EMA over the specified number of candles0.5float · step 0.1fanOutGap
EMA Fanout Lookback Number of candles over which the entry EMA lines must be fanned out by the specified amount3int · min 1line 179 line 183
Price Buffer ATR Multiplier ATR multiplier to determine how big of a butter should be set above/below trade entry and stop loss0.5float · step 0.1priceBuffer
Entry Price High/Low Lookback Number of candles to lookback on to find the local high/low which is used to establish the stop order entry price5int · min 1localHigh localLow
Strategy: Risk Management
Risk : Reward 1 :Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.2float · min 0 · step 0.1tpPercent
Portfolio Risk % Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.1float · min 0 · step 0.1riskAmt
Strategy: Date Range
Start Date 2022int · min 1900 · max 2100inDateRange
Start Month (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]inDateRange
Start Date (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]inDateRange
End Date 2100int · min 1900 · max 2100inDateRange
End Month (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]inDateRange
End Date (no label in the script)1int · options [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]inDateRange
Strategy: Drawings
Show TP / SL BoxesShow or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.trueboolline 140 line 148
Show Trade Exit LabelsUseful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.falseboolline 156

What it calculates

  • EMAclose, Fast EMA Length (8)trendFastEma · line 101
  • EMAclose, Slow EMA Length (21)trendSlowEma · line 102
  • EMAclose, Fast EMA Length (8)entryFastEma · line 114
  • EMAclose, Medium EMA Length (13)entryMedEma · line 115
  • EMAclose, Slow EMA Length (21)entrySlowEma · line 116
  • ATR14fanOutGap · line 174
  • ATR14priceBuffer · line 229
  • Highesthigh, Entry Price High/Low Lookback (5)localHigh · line 230
  • Lowestlow, Entry Price High/Low Lookback (5)localLow · line 231

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 109 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long longopenLongOn245
Open Short shortopenShortOn254
cancel_all not activeTrade and ((inLong and close < entrySlowEma) or (inShort and close > entrySlowEma))On268
Exit TP/SL stop and limitevery barOn276

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.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • ClearHigher-timeframe data2 request.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.

Other markets

Not run on other markets: the script requests BINANCE:BTCUSDT 60, and that data is not available here (a lower timeframe than the chart; the engine does not evaluate intrabar data). Its results would rest on empty values.

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
Simple and Profitable Scalping Strategy (ForexSignals TV) this page—v5 strategy0.0%00.0%
Richard's Strategy by Deepak8369highest lowest atr emav4 strategy+34.6%7026.3%
Classic Long Term Trend Following System by Robrecht99ema highest lowest atrv5 strategy+2.9%51.1%
Strategy Myth-Busting #1 - UT Bot+STC+Hull [MYN] by myncryptoatr ema lowest highestv5 strategy−30.7%1063.5%
Strategy for UT Bot Alerts indicator by StrategiesForEveryoneema atr highest lowestv5 strategy−4.5%4215.7%
ATR + STC + MA by Romediusema lowest highest atrv5 strategy−1.2%153.3%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯//                                              NOTE: The original strategy uses 2 TP levels. I may add this in future but would like to see some better results from a single TP before I go to the effort to add this-//@version=5+//@version=6INITIAL_CAPITAL = 1000⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 112 msYes 1,000 bars in 188 msNot measured
PineTSNot testedNot testedNot 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.

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/// © kevinmck100// @description//// Strategy called SIMPLE and PROFITABLE Forex Scalping Strategy taken from YouTube channel ForexSignals TV.// See video for a detailed explaination of the whole strategy.//// It works on the basis of waiting for pullbacks into the EMAs while trading in the direction of the higher timeframe trend//// Strategy incorporates the following features:////      - Risk management:  Configurable X% loss per stop loss//                          Configurable R:R ratio////      - Trade entry:      Calculated position size based on risk tolerance//                          Entry price is a stop order set just above the recent swing high/low (long/short)////      - Trade exit:       Stop Loss is set just below trigger candle's low/high (long/short)//                          Take Profit calculated from Stop Loss using R:R ratio////      - Backtesting:      Configurable backtesting range by date////      - Trade drawings:   TP/SL boxes drawn for all trades. Can be turned on and off//                          Trade exit information labels. Can be turned on and off//                          NOTE: Trade drawings will only be applicable when using overlay strategies////      - Debugging:        Includes section with useful debugging techniques//// Strategy conditions:////      - Trade entry:      LONG:   C1: On higher timeframe trend EMAs, Fast EMA must be above Slow EMA//                                  C2: On higher timeframe trend EMAs, price must be above Fast EMA//                                  C3: On current timeframe entry EMAs, Fast EMA must be above Medium EMA and Medium EMA must be above Slow EMA//                                  C4: On current timeframe entry EMAs, all 3 EMA lines must have fanned out in upward direction for previous X candles//                                  C5: On current timeframe entry EMAs, previous candle must have closed above and not touched any EMA lines//                                  C6: On current timeframe entry EMAs, current candle must have pulled back to touch the EMA line(s)//                                  C7: Price must break through the high of the last X candles to trigger entry//                          //                          SHORT:  C1: On higher timeframe trend EMAs, Fast EMA must be below Slow EMA//                                  C2: On higher timeframe trend EMAs, price must be below Fast EMA//                                  C3: On current timeframe entry EMAs, Fast EMA must be below Medium EMA and Medium EMA must be below Slow EMA//                                  C4: On current timeframe entry EMAs, all 3 EMA lines must have fanned out in downward direction for previous X candles//                                  C5: On current timeframe entry EMAs, previous candle must have closed above and not touched any EMA lines//                                  C6: On current timeframe entry EMAs, current candle must have pulled back to touch the EMA line(s)//                                  C7: Price must break through the low of the last X candles to trigger entry////      - Trade exit:       Trade Invalidation: Price closes below/above (long/short) the current timeframe Slow EMA//                          Stop Loss:          Placed just below trigger candle low/high (long/short)//                          Take Profit:        R:R multiplier * Stop Loss is hit //                                              NOTE: The original strategy uses 2 TP levels. I may add this in future but would like to see some better results from a single TP before I go to the effort to add this//@version=5INITIAL_CAPITAL = 1000DEFAULT_COMMISSION = 0.02MAX_DRAWINGS = 500IS_OVERLAY = truestrategy("Simple and Profitable Scalping Strategy (ForexSignals TV)", "Scalping Strategy", overlay = IS_OVERLAY, initial_capital = INITIAL_CAPITAL, currency = currency.NONE, max_labels_count = MAX_DRAWINGS, max_boxes_count = MAX_DRAWINGS, max_lines_count = MAX_DRAWINGS, default_qty_type = strategy.cash, commission_type = strategy.commission.percent, commission_value = DEFAULT_COMMISSION)// =============================================================================// INPUTS// =============================================================================trendFilterTf       = input.timeframe   ("60",  "Trend Timeframe        ",          group = "Strategy: Higher Timeframe Trend Filter",  inline = "TF1",             tooltip = "Higher timeframe to use for finding main trand direction")trendFastEmaLen     = input.int         (8,     "Fast EMA Length        ",          group = "Strategy: Higher Timeframe Trend Filter",  inline = "TF2", minval = 1, tooltip = "Length of Fast EMA of higher timeframe")trendSlowEmaLen     = input.int         (21,    "Slow EMA Length          ",        group = "Strategy: Higher Timeframe Trend Filter",  inline = "TF3", minval = 1, tooltip = "Length of Slow EMA of higher timeframe")// ----------------------// Trade Entry Conditions// ----------------------entryFastEmaLen     = input.int         (8,     "Fast EMA Length          ",        group = "Strategy: Trade Entry Conditions",         inline = "TE1", minval = 1, tooltip = "Fast EMA used to find entry candles when price pulls back into this line")entryMedEmaLen      = input.int         (13,    "Medium EMA Length      ",          group = "Strategy: Trade Entry Conditions",         inline = "TE2", minval = 1, tooltip = "Medium EMA used to filter out entries when lines are not fanned out or not trending in the desired direction")entrySlowEmaLen     = input.int         (21,    "Slow EMA Length         ",         group = "Strategy: Trade Entry Conditions",         inline = "TE3", minval = 1, tooltip = "Slow EMA used to filter out entries when lines are not fanned out or not trending in the desired direction.\n\nAlso used to cancel open orders which close below this EMA before entry has been triggered")fanoutAtrMult       = input.float       (0.5,   "EMA Fanout ATR Multiplier    ",    group = "Strategy: Trade Entry Conditions",         inline = "TE4", step = 0.1, tooltip = "ATR multiplier to determine how but the fanout gap must be between the Fast EMA and Slow EMA over the specified number of candles")fanoutLookback      = input.int         (3,     "EMA Fanout Lookback      ",        group = "Strategy: Trade Entry Conditions",         inline = "TE5", minval = 1, tooltip = "Number of candles over which the entry EMA lines must be fanned out by the specified amount")priceBufferAtrMult  = input.float       (0.5,   "Price Buffer ATR Multiplier    ",  group = "Strategy: Trade Entry Conditions",         inline = "TE6", step = 0.1, tooltip = "ATR multiplier to determine how big of a butter should be set above/below trade entry and stop loss")localHighLookback   = input.int         (5,     "Entry Price High/Low Lookback ",   group = "Strategy: Trade Entry Conditions",         inline = "TE7", minval = 1, tooltip = "Number of candles to lookback on to find the local high/low which is used to establish the stop order entry price")// ---------------// Risk Management// ---------------riskReward          = input.float(2,    "Risk : Reward        1 :",                 group = "Strategy: Risk Management",                inline = "RM1", minval = 0, step = 0.1,     tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.")accountRiskPercent  = input.float(1,    "Portfolio Risk %         ",                group = "Strategy: Risk Management",                inline = "RM2", minval = 0, step = 0.1,     tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n  Portfolio Risk % * Risk : Reward\nif trade hits TP.")// ----------// Date Range// ----------startYear           = input.int (2022,  "Start Date       ",                        group = 'Strategy: Date Range',                     inline = 'DR1', minval    = 1900, maxval = 2100)startMonth          = input.int (1,     "",                                         group = 'Strategy: Date Range',                     inline = 'DR1', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])startDate           = input.int (1,     "",                                         group = 'Strategy: Date Range',                     inline = 'DR1', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])endYear             = input.int (2100,  "End Date      ",                           group = 'Strategy: Date Range',                     inline = 'DR2', minval    = 1900, maxval = 2100)endMonth            = input.int (1,     "",                                         group = 'Strategy: Date Range',                     inline = 'DR2', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])endDate             = input.int (1,     "",                                         group = 'Strategy: Date Range',                     inline = 'DR2', options   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])// ----------------// Drawing Settings// ----------------showTpSlBoxes       = input.bool(true,  "Show TP / SL Boxes",                       group = "Strategy: Drawings",                       inline = "D1",  tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.")showLabels          = input.bool(false, "Show Trade Exit Labels",                   group = "Strategy: Drawings",                       inline = "D2",  tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.")// =============================================================================// INDICATORS// =============================================================================// --------------------------// Trend Higher Timeframe EMA// --------------------------var float currTrendFastEma  = navar float currTrendSlowEma  = navar color emaFillColor      = natrendFastEma                = ta.ema(close, trendFastEmaLen)trendSlowEma                = ta.ema(close, trendSlowEmaLen)fastSec                     = request.security(syminfo.tickerid, trendFilterTf, trendFastEma, barmerge.gaps_off, barmerge.lookahead_off)slowSec                     = request.security(syminfo.tickerid, trendFilterTf, trendSlowEma, barmerge.gaps_off, barmerge.lookahead_off)currTrendFastEma           := na(fastSec) ? currTrendFastEma[1] : fastSeccurrTrendSlowEma           := na(slowSec) ? currTrendSlowEma[1] : slowSecfastEmaPlot                 = plot(fastSec, color=color.green)slowEmaPlot                 = plot(slowSec, color=color.red)emaFillColor               := fastSec > slowSec ? color.new(color.green, 80) : fastSec < slowSec ? color.new(color.red, 80) : emaFillColor[1]fill(fastEmaPlot, slowEmaPlot, color = emaFillColor, fillgaps = true)// ---------------// Trade Entry EMA// ---------------entryFastEma    = ta.ema(close, entryFastEmaLen)entryMedEma     = ta.ema(close, entryMedEmaLen)entrySlowEma    = ta.ema(close, entrySlowEmaLen)plot(entryFastEma,  color = color.orange)plot(entryMedEma,   color = color.yellow)plot(entrySlowEma,  color = color.purple)// =============================================================================// STRATEGY LOGIC// =============================================================================// ---------// FUNCTIONS// ---------printLabel(barIndex, msg) => label.new(barIndex, close, msg)percentAsPoints(pcnt) =>    math.round(pcnt / 100 * close / syminfo.mintick)    calcStopLossPrice(pointsOffset, entryPrice, isLong) =>    priceOffset = pointsOffset * syminfo.mintick    if isLong        entryPrice - priceOffset    else         entryPrice + priceOffsetcalcProfitTrgtPrice(pointsOffset, entryPrice, isLong) => calcStopLossPrice(-pointsOffset, entryPrice, isLong)            printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) =>     if showTpSlBoxes        box.new (left = left,   top = entryPrice,   right = right,  bottom = slPrice,   bgcolor = slHit ? color.new(color.red, 60)   : color.new(color.gray, 90), border_width = 0)        box.new (left = left,   top = entryPrice,   right = right,  bottom = tpPrice,   bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0)        line.new(x1 = left,     y1 = entryPrice,    x2 = right,     y2 = entryPrice,    color = color.new(color.yellow, 20))        line.new(x1 = left,     y1 = slPrice,       x2 = right,     y2 = slPrice,       color = color.new(color.red, 20))        line.new(x1 = left,     y1 = tpPrice,       x2 = right,     y2 = tpPrice,       color = color.new(color.green, 20))        printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) =>     if showTpSlBoxes        box.new (left = left,   top = entryPrice,   right = right,  bottom = slPrice,   bgcolor = color.new(color.orange, 90), border_width = 0)        box.new (left = left,   top = entryPrice,   right = right,  bottom = tpPrice,   bgcolor = color.new(color.orange, 90), border_width = 0)        line.new(x1 = left,     y1 = entryPrice,    x2 = right,     y2 = entryPrice,    color = color.new(color.yellow, 20))        line.new(x1 = left,     y1 = slPrice,       x2 = right,     y2 = slPrice,       color = color.new(color.red, 20))        line.new(x1 = left,     y1 = tpPrice,       x2 = right,     y2 = tpPrice,       color = color.new(color.green, 20))        printTradeExitLabel(x, y, posSize, entryPrice, pnl) =>     if showLabels        labelStr = pnl != 0 ? "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") : "Trade Cancelled"        label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : pnl < 0 ? color.new(color.red, 60) : color.new(color.orange, 60), textcolor = color.white, style = label.style_label_down)printVerticalLine(col) => line.new(bar_index, close, bar_index, close * 1.01, extend = extend.both, color = col)// ----------// CONDITIONS// ----------inDateRange         = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)// Condition 1: Higher timeframe trend EMAs must be in correct orderbullTrendDir        = currTrendFastEma > currTrendSlowEmabearTrendDir        = currTrendFastEma < currTrendSlowEma// Condition 2: Price must be outside the EMA trend bandbullTrendPrice      = close > currTrendFastEmabearTrendPrice      = close < currTrendFastEma// Condition 3: EMA lines must be in correct orderbullEmaOrder        = entryFastEma > entryMedEma and entryMedEma > entrySlowEmabearEmaOrder        = entryFastEma < entryMedEma and entryMedEma < entrySlowEma// Condition 4: EMA lines must fanned out for previous X candlesfanOutGap           = ta.atr(14) * fanoutAtrMultvar bullFanOutGap   = falsevar bearFanOutGap   = falsebullFanOutGap      := falsebearFanOutGap      := falsefor lookback = 0 to fanoutLookback - 1    bullFanOutGap := (entryFastEma[lookback] - fanOutGap) >  entrySlowEma[lookback]    if bullFanOutGap == false        breakfor lookback = 0 to fanoutLookback - 1    bearFanOutGap := (entryFastEma[lookback] + fanOutGap) <  entrySlowEma[lookback]    if bearFanOutGap == false        break        // This will ensure a given fannout gap exists between EACH EMA line, rather than just checking between Fast and Slow// Leaving it here in case  I decide to go back to it, or make it configurable between the two// for lookback = 0 to 3 - 1//     bullFanOutGap := (entryFastEma[lookback] - fanOutGap) > entryMedEma[lookback] and (entryMedEma[lookback] - fanOutGap) >  entrySlowEma[lookback]//     if bullFanOutGap == false//         break// for lookback = 0 to 3 - 1//     bearFanOutGap := (entryFastEma[lookback] + fanOutGap) < entryMedEma[lookback] and (entryMedEma[lookback] + fanOutGap) <  entrySlowEma[lookback]//     if bearFanOutGap == false//         break// Condition 5: Previous candle must not have touched any entry EMA linesbullBreakout        = low[1]  > entryFastEma[1]bearBreakout        = high[1] < entryFastEma[1]// Condition 6: Current candle must have touched the Fast EMAbullPullback        = low < entryFastEmabearPullback        = high > entryFastEma// Combine all entry conditionsgoLong              = inDateRange and bullTrendDir and bullTrendPrice and bullEmaOrder and bullFanOutGap and bullBreakout and bullPullbackgoShort             = inDateRange and bearTrendDir and bearTrendPrice and bearEmaOrder and bearFanOutGap and bearBreakout and bearPullback// Trade entry and exit variablesvar tradeEntryBar   = bar_indexvar profitPoints    = 0.var lossPoints      = 0.var slPrice         = 0.var slAmount        = 0.var slPercent       = 0.var tpPrice         = 0.var tpPercent       = 0.var inLong          = falsevar inShort         = falsevar float entryPrice= navar tradeCancelled  = falsevar tradeActive     = false// Entry decisionsopenLong            = (goLong and not inLong)openShort           = (goShort and not inShort)flippingSides       = (goLong and inShort) or (goShort and inLong)enteringTrade       = openLong or openShortinTrade             = inLong or inShort// Exit calculations// Condition 7: Price which must be broken to enter tradepriceBuffer         = ta.atr(14) * priceBufferAtrMultlocalHigh           = ta.highest(high, localHighLookback)localLow            = ta.lowest(low, localHighLookback)if enteringTrade    entryPrice     := goLong ? localHigh + priceBuffer : goShort ? localLow - priceBuffer : na    slPrice        := openLong ? low - priceBuffer : openShort ? high + priceBuffer : na    slAmount       := math.abs(entryPrice - slPrice)    slPercent      := math.abs((1 - (entryPrice - slAmount) / entryPrice) * 100)    tpPercent      := slPercent * riskReward// Risk calculationsriskAmt             = strategy.equity * accountRiskPercent / 100entryQty            = math.abs(riskAmt / slPercent * 100)  / closeif openLong    if strategy.position_size < 0        printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice)        printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit)    strategy.entry("Long", strategy.long, stop = entryPrice, qty = entryQty, alert_message = "Long Entry")    enteringTrade   := true    inLong          := true    inShort         := false    printVerticalLine(color.new(color.green, 60))if openShort    if strategy.position_size > 0        printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice)        printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit)    strategy.entry("Short", strategy.short, stop = entryPrice, qty = entryQty, alert_message = "Short Entry")    enteringTrade   := true    inShort         := true    inLong          := false    printVerticalLine(color.new(color.red, 60))// Check if trade is active or notlongActive = strategy.position_size[1] > 0shortActive = strategy.position_size[1] < 0activeTrade = longActive or shortActive// If price closes beyond the Slow EMA, then cancel any pending ordersif not activeTrade and ((inLong and close < entrySlowEma) or (inShort and close > entrySlowEma))    printVerticalLine(color.new(color.silver, 60))    inLong          := false    inShort         := false    strategy.cancel_all()    tradeCancelled := true    if enteringTrade    profitPoints    := percentAsPoints(tpPercent)    lossPoints      := percentAsPoints(slPercent)    tpPrice         := calcProfitTrgtPrice(profitPoints, entryPrice, openLong)    tradeEntryBar   := bar_indexstrategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert")// =============================================================================// DRAWINGS// =============================================================================// -----------// TP/SL Boxes// -----------exitedOnCurrentBar =  strategy.closedtrades.entry_bar_index(strategy.closedtrades - 1) == bar_indexslHit           = ((shortActive or exitedOnCurrentBar) and high >= slPrice) or ((longActive or exitedOnCurrentBar)  and low <= slPrice)tpHit           = ((longActive or exitedOnCurrentBar)  and high >= tpPrice) or ((shortActive or exitedOnCurrentBar) and low <= tpPrice)exitTriggered   = slHit or tpHitpnl             = strategy.closedtrades.profit      (strategy.closedtrades - 1)posSize         = strategy.closedtrades.size        (strategy.closedtrades - 1)// Print boxes for trades closed at profit or lossif (inTrade and exitTriggered and not tradeCancelled or exitedOnCurrentBar)     inShort    := false    inLong     := false     printTpSlHitBox(tradeEntryBar, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice)    printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl)// Print TP/SL box for current open tradeelse if barstate.islastconfirmedhistory and strategy.position_size != 0    printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice)// Trade cancelled before entryelse if tradeCancelled    tradeCancelled := false    printTpSlNotHitBox(tradeEntryBar, bar_index, entryPrice, slPrice, tpPrice)    printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit)    // =============================================================================// DEBUGGING// =============================================================================// Data window plots// Leaving all debugging plots in for now as they may be useful during future development/improvements for this strategyplotchar(currTrendFastEma,          "currTrendFastEma",     "")plotchar(currTrendSlowEma,          "currTrendSlowEma",     "")plotchar(fanOutGap,                 "fanGap",               "")plotchar(bullTrendDir,              "bullTrendDir",         "")plotchar(bullTrendPrice,            "bullTrendPrice",       "")plotchar(bullEmaOrder,              "bullEmaOrder",         "")plotchar(bullFanOutGap,             "bullFanOutGap",        "")plotchar(bullBreakout,              "bullBreakout",         "")plotchar(bullPullback,              "bullPullback",         "")plotchar(goLong,                    "goLong",               "")plotchar(inLong,                    "inLong",               "")plotchar(bearTrendDir,              "bearTrendDir",         "")plotchar(bearTrendPrice,            "bearTrendPrice",       "")plotchar(bearEmaOrder,              "bearEmaOrder",         "")plotchar(bearFanOutGap,             "bearFanOutGap",        "")plotchar(bearBreakout,              "bearBreakout",         "")plotchar(bearPullback,              "bearPullback",         "")plotchar(goShort,                   "goShort",              "")plotchar(inShort,                   "inShort",              "")plotchar(openLong,                  "openLong",             "")plotchar(openShort,                 "openShort",            "")plotchar(enteringTrade,             "enteringTrade",        "")plotchar(entryPrice,                "entryPrice",           "")plotchar(slPrice,                   "slPrice",              "")plotchar(tpPrice,                   "tpPrice",              "")plotchar(tpPercent,                 "tpPercent",            "")plotchar(slPercent,                 "slPercent",            "")plotchar(longActive,                "longActive",           "")plotchar(shortActive,               "shortActive",          "")plotchar(exitedOnCurrentBar,        "exitedOnCurrentBar",   "")plotchar(strategy.position_size,    "position_size After",  "")plotchar(slHit,                     "slHit",                "")plotchar(tpHit,                     "tpHit",                "")// Label plots// plotDebugLabels = false// if plotDebugLabels//     if bar_index == tradeEntryBar //         printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##"))