Pine Script v4 · Strategy
KISS Strategy- SMA + EMA
A Pine Script v4 strategy built on SMA (close, 13), EMA (close, fast) and Crossover (SH_SMA, LG_SMA). It has 8 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 5% of equity and pays no commission. 21 settings; defaults include Price Source close, Run Strategy Trending Up, Down, or Both Both and SH SMA Length 13.
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 KISS Strategy- SMA + EMA repaint?
- No
- No repainting patterns were found in the source.
- How did KISS Strategy- SMA + EMA do on BTCUSDT 1D with default settings?
- −1.52%
- From 26 Jan 2024 to 21 Oct 2026, over 9 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can KISS Strategy- SMA + EMA be converted to Pine Script v5?
- Yes
- The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
- Does KISS Strategy- SMA + EMA use a stop loss?
- Yes
- strategy.exit sets a stop on line 161, 162, 164, 169, 170, 172.
- Does KISS Strategy- SMA + EMA run in Zeal Terminal?
- Yes
- It compiles in 38 ms and runs 1,000 bars in 125 ms, in the browser.
BTCUSDT · 1D · default settings
- SH SMA
- LG SMA
- GV SMA
- Shape
- Shape
- HC-LB
- HC-SB
- Long Trail Stop
- Short Trail Stop
- Short Trail Stop
- Short Trail Stop
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −1.52%
- −$304.63
- Buy and hold
- +102.5%
- same period
- Closed trades
- 9
- 2 won · 7 lost
- Profitable
- 22.2%
- of closed trades
- Profit factor
- 0.62
- gross profit ÷ gross loss
- Max drawdown
- 2.96%
- −$594.22
One run with the author's default settings, $20,000 starting capital, commission as the script sets it. A long position was still open at the last bar. 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.
-
Likely bug
sma(macd, 9) ignores the settings line 40
Line 40 hard-codes 9 where line 28 uses “SH SMA Length”. Changing those settings moves one band but not this one.
sma(macd, 9)sma(macd, SH_SMA_length) -
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
Uses an argument v6 removed
when = on line 126, 130, 161, 162, 164, 169, 170, 172. The upgraded version below moves each call inside an if block.
-
Note
Uses iff(), which v5 removed line 75
iff() on line 75, 107, 109, 121, 121, 122, 122, 124, 124, 128, 128. v5 writes it as the ternary c ? a : b.
-
Note
Uses transp =, which v5 removed line 89
transp = on line 89, 100. v5 folds the transparency into the colour with color.new(c, transp).
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 sma → ta.sma, ema → ta.ema, security → request.security, crossover → ta.crossover, crossunder → ta.crossunder, abs → math.abs, max → math.max, min → math.min.
- 8 strategy calls use the when = argument (line 126, 130, 161, 162, 164, 169, 170, 172). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 9 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 1: //@version=4 → //@version=5
- Line 28: sma → ta.sma
- Line 29: sma → ta.sma
- Line 30: sma → ta.sma
- Line 35: ema → ta.ema
- Line 36: ema → ta.ema
37 more edits
- Line 40: sma → ta.sma
- Line 42: security → request.security
- Line 43: security → request.security
- Line 69: crossover → ta.crossover
- Line 70: crossunder → ta.crossunder
- Line 73: abs → math.abs
- Line 74: abs → math.abs
- Line 75: iff(c, a, b) → (c ? a : b)
- Line 75: abs → math.abs
- Line 77: input(type = input.integer) → input.int()
- Line 78: input(type = input.integer) → input.int()
- Line 79: input(type = input.integer) → input.int()
- Line 80: input(type = input.integer) → input.int()
- Line 81: input(type = input.integer) → input.int()
- Line 82: input(type = input.integer) → input.int()
- Line 84: input(type = input.bool) → input.bool()
- Line 89: transp = 90 → color.new(showDate and window() ? color.gray : na, 90)
- Line 100: transp = 70 → color.new(color.silver, 70)
- Line 107: iff(c, a, b) → (c ? a : b)
- Line 109: iff(c, a, b) → (c ? a : b)
- Line 113: input(type = input.string) → input.string()
- Line 114: input(type = input.string) → input.string()
- Line 121: iff(c, a, b) → (c ? a : b)
- Line 121: crossunder → ta.crossunder
- Line 121: iff(c, a, b) → (c ? a : b)
- Line 122: iff(c, a, b) → (c ? a : b)
- Line 122: crossunder → ta.crossunder
- Line 122: iff(c, a, b) → (c ? a : b)
- Line 124: iff(c, a, b) → (c ? a : b)
- Line 124: iff(c, a, b) → (c ? a : b)
- Line 128: iff(c, a, b) → (c ? a : b)
- Line 128: iff(c, a, b) → (c ? a : b)
- Line 135: input(type = input.float) → input.float()
- Line 136: input(type = input.float) → input.float()
- Line 137: input(type = input.float) → input.float()
- Line 142: max → math.max
- Line 149: min → math.min
-//@version=4+//@version=5// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/⋯GV_SMA_length= input(title="SH SMA Length", defval=200) //Gravitational SMA length-SH_SMA=sma(price, SH_SMA_length) //short SMA +SH_SMA=ta.sma(price, SH_SMA_length) //short SMA -LG_SMA=sma(price, LG_SMA_length) //long SMA+LG_SMA=ta.sma(price, LG_SMA_length) //long SMA-GV_SMA=sma(price, GV_SMA_length) //gravitational SMA+GV_SMA=ta.sma(price, GV_SMA_length) //gravitational SMA//calculate MACD⋯//define parameters to calculate MACD-fastMA = ema(price, fast)+fastMA = ta.ema(price, fast)-slowMA = ema(price, slow)+slowMA = ta.ema(price, slow)//define MACD line⋯//define SIGNAL line-signal = sma(macd, 9)+signal = ta.sma(macd, 9)//Determine what type of trend we are in-dcp = security(syminfo.tickerid, 'D', close) //daily close price +dcp = request.security(syminfo.tickerid, 'D', close) //daily close price -wcp = security(syminfo.tickerid, 'W', close) //weekly close price +wcp = request.security(syminfo.tickerid, 'W', close) //weekly close price WiT = input(title="Weeks In Trend", defval=1, maxval=5, minval=1) //User input for how many weeks of price action to evaluate (Weeks in Trend = WiT)⋯//Determine if crossings occur-SH_LGcrossover = crossover(SH_SMA, LG_SMA) //returns true if short crosses over long+SH_LGcrossover = ta.crossover(SH_SMA, LG_SMA) //returns true if short crosses over long-SH_LGcrossunder = crossunder(SH_SMA, LG_SMA) //returns true if short crosses under long+SH_LGcrossunder = ta.crossunder(SH_SMA, LG_SMA) //returns true if short crosses under long//Determine the slope of the SMAs when a cross over occursSlopeFactor= input(title="Slope Factor", defval=.01, minval=0, step = 0.001) //user input variable for what slope to evaluate against-XSlopeSH = abs(SH_SMA-SH_SMA[2]) //slope of short moving average (time cancels out)+XSlopeSH = math.abs(SH_SMA-SH_SMA[2]) //slope of short moving average (time cancels out)-XSlopeLG = abs(LG_SMA-LG_SMA[2]) //slope of long moving average (time cancels out)+XSlopeLG = math.abs(LG_SMA-LG_SMA[2]) //slope of long moving average (time cancels out)-StrongSlope = iff (abs(XSlopeSH-XSlopeLG)>SlopeFactor, true, false) //create a boolean variable to determine is slope intensity requirement is met+StrongSlope = (math.abs(XSlopeSH-XSlopeLG)>SlopeFactor ? true : false) //create a boolean variable to determine is slope intensity requirement is met// ************************************ INPUT BACKTEST RANGE ******************************************=== coutesy of alanaster-fromMonth = input(defval = 4, title = "From Month", type = input.integer, minval = 1, maxval = 12)+fromMonth = input.int(defval = 4, title = "From Month", minval = 1, maxval = 12)-fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)+fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)-fromYear = input(defval = 2020, title = "From Year", type = input.integer, minval = 1970)+fromYear = input.int(defval = 2020, title = "From Year", minval = 1970)-thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)+thruMonth = input.int(defval = 1, title = "Thru Month", minval = 1, maxval = 12)-thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)+thruDay = input.int(defval = 1, title = "Thru Day", minval = 1, maxval = 31)-thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)+thruYear = input.int(defval = 2112, title = "Thru Year", minval = 1970)// === INPUT SHOW PLOT ===-showDate = input(defval = true, title = "Show Date Range", type = input.bool)+showDate = input.bool(defval = true, title = "Show Date Range")// === FUNCTION EXAMPLE ===⋯window() => time >= start and time <= finish ? true : false // create function "within window of time"-bgcolor(color = showDate and window() ? color.gray : na, transp = 90) +bgcolor(color = color.new(showDate and window() ? color.gray : na, 90)) // === EXECUTION ===⋯plot(LG_SMA, title = "LG SMA", color = trendcolorLG)-plot(GV_SMA, title = "GV SMA", color = color.silver, linewidth = 4, transp = 70)+plot(GV_SMA, title = "GV SMA", color = color.new(color.silver, 70), linewidth = 4)//Highlight crossovers⋯RunTrendUp=false //Varibile for running the Strategy in an UpTrend-RunTrendUp:= iff(RunTrend == "Up" or RunTrend == "Both", true, false)+RunTrendUp:= (RunTrend == "Up" or RunTrend == "Both" ? true : false)RunTrendDWN=false //Varibile for running the Strategy in a DownTrend-RunTrendDWN:= iff(RunTrend == "Down" or RunTrend == "Both", true, false)+RunTrendDWN:= (RunTrend == "Down" or RunTrend == "Both" ? true : false)//Define countback variable⋯//User input for what evaluations to run: SMA or SMA + EMA-SMA_Y_N=input(defval = "Y", title="Run SMA", type=input.string, options=["Y", "N"])+SMA_Y_N=input.string(defval = "Y", title="Run SMA", options=["Y", "N"])-MACD_Y_N=input(defval = "N", title="Run MACD", type=input.string, options=["Y", "N"])+MACD_Y_N=input.string(defval = "N", title="Run MACD", options=["Y", "N"])//Calculate SMA Cross entry conditions⋯//Calculate MACD Cross entry conditions-MACDbuy = iff(MACD_Y_N=="Y", crossunder(signal[countback], macd[countback]), true) and iff(MACD_Y_N=="Y", macd[countback]<0, true) and StrongSlope and BearTrend //enter long if fast MACD crosses over slow MACD & there is a strong slope & security has been in a BearTrend for 'n' days back+MACDbuy = (MACD_Y_N=="Y" ? ta.crossunder(signal[countback], macd[countback]) : true) and (MACD_Y_N=="Y" ? macd[countback]<0 : true) and StrongSlope and BearTrend //enter long if fast MACD crosses over slow MACD & there is a strong slope & security has been in a BearTrend for 'n' days back-MACDsell = iff(MACD_Y_N=="Y", crossunder(macd[countback], signal[countback]), true) and iff(MACD_Y_N=="Y", signal[countback]>0, true) and StrongSlope and BullTrend //enter short if fast MACD crosses under slow MACD & there is a strong slope & security has been in a BullTrend for 'n' days back+MACDsell = (MACD_Y_N=="Y" ? ta.crossunder(macd[countback], signal[countback]) : true) and (MACD_Y_N=="Y" ? signal[countback]>0 : true) and StrongSlope and BullTrend //enter short if fast MACD crosses under slow MACD & there is a strong slope & security has been in a BullTrend for 'n' days back//long entry condition-dataHCLB=(iff(SMA_Y_N=="Y", SMAbuy, true) and iff(MACD_Y_N=="Y", MACDbuy, true) and RunTrendUp)+dataHCLB=((SMA_Y_N=="Y" ? SMAbuy : true) and (MACD_Y_N=="Y" ? MACDbuy : true) and RunTrendUp)plotshape(dataHCLB, title= "HC-LB", color=color.lime, style=shape.circle, text="HC-LB")⋯//short entry condition-dataHCSB=(iff(SMA_Y_N=="Y", SMAsell, true) and iff(MACD_Y_N=="Y", MACDsell, true) and RunTrendDWN)+dataHCSB=((SMA_Y_N=="Y" ? SMAsell : true) and (MACD_Y_N=="Y" ? MACDsell : true) and RunTrendDWN)plotshape(dataHCSB, title= "HC-SB", color=color.fuchsia, style=shape.circle, text="HC-SB")⋯trailStop_YN=input(title="Run a Trailing Stop", defval="N", options=["Y", "N"])-TrailPerc = input(title="Trail Loss %", type=input.float, minval=0, step=1, defval=6) /100+TrailPerc = input.float(title="Trail Loss %", minval=0, step=1, defval=6) /100-stopPer = input(12, title='Stop Loss %', type=input.float) / 100+stopPer = input.float(12, title='Stop Loss %') / 100-takePer = input(25, title='Take Profit %', type=input.float) / 100+takePer = input.float(25, title='Take Profit %') / 100//calculate Trail stop price for MD_EMA TGT% condition⋯ stopValue = close * (1 - TrailPerc) - max(stopValue, longStopPrice[1])+ math.max(stopValue, longStopPrice[1])else⋯ shortStopValue = close * (1 + TrailPerc) - min(shortStopValue, shortStopPrice[1])+ math.min(shortStopValue, shortStopPrice[1])else⋯Same 9 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 20: input() → input.source()
- Line 22: input() → input.string()
- Line 25: input() → input.int()
- Line 26: input() → input.int()
- Line 27: input() → input.int()
- Line 44: input() → input.int()
11 more edits
- Line 72: input() → input.float()
- Line 111: input() → input.int()
- Line 126: when = dataHCLB and window() → if block
- Line 130: when = dataHCSB and window() → if block
- Line 134: input() → input.string()
- Line 161: when = window() → if block
- Line 162: when = window() → if block
- Line 164: when = window() → if block
- Line 169: when = window() → if block
- Line 170: when = window() → if block
- Line 172: when = window() → if block
⋯//define calculations price source-price = input(title="Price Source", defval=close)+price = input.source(title="Price Source", defval=close)//Does user want to run the Strategy for Trending Up or Trending Down-RunTrend=input(title="Run Strategy Trending Up, Down, or Both", defval="Both", options=["Up", "Down", "Both"])+RunTrend=input.string(title="Run Strategy Trending Up, Down, or Both", defval="Both", options=["Up", "Down", "Both"])// 2. Calculate strategy values*************************************************************************************************************************************************************************//Calculate 13/30/200SMA -SH_SMA_length= input(title="SH SMA Length", defval=13) //short SMA length+SH_SMA_length= input.int(title="SH SMA Length", defval=13) //short SMA length-LG_SMA_length= input(title="LG SMA Length", defval=30) //long SMA length+LG_SMA_length= input.int(title="LG SMA Length", defval=30) //long SMA length-GV_SMA_length= input(title="SH SMA Length", defval=200) //Gravitational SMA length+GV_SMA_length= input.int(title="SH SMA Length", defval=200) //Gravitational SMA lengthSH_SMA=ta.sma(price, SH_SMA_length) //short SMA ⋯wcp = request.security(syminfo.tickerid, 'W', close) //weekly close price -WiT = input(title="Weeks In Trend", defval=1, maxval=5, minval=1) //User input for how many weeks of price action to evaluate (Weeks in Trend = WiT)+WiT = input.int(title="Weeks In Trend", defval=1, maxval=5, minval=1) //User input for how many weeks of price action to evaluate (Weeks in Trend = WiT)BearTrend = false //initialize trend variables as false⋯//Determine the slope of the SMAs when a cross over occurs-SlopeFactor= input(title="Slope Factor", defval=.01, minval=0, step = 0.001) //user input variable for what slope to evaluate against+SlopeFactor= input.float(title="Slope Factor", defval=.01, minval=0, step = 0.001) //user input variable for what slope to evaluate againstXSlopeSH = math.abs(SH_SMA-SH_SMA[2]) //slope of short moving average (time cancels out)⋯//Define countback variable-countback=input(minval=0, maxval=5, title="Price CountBack", defval=0)+countback=input.int(minval=0, maxval=5, title="Price CountBack", defval=0)//User input for what evaluations to run: SMA or SMA + EMA⋯plotshape(dataHCLB, title= "HC-LB", color=color.lime, style=shape.circle, text="HC-LB")-strategy.entry("HC-Long", strategy.long, comment="HC-Long", when = dataHCLB and window())+if dataHCLB and window()+ strategy.entry("HC-Long", strategy.long, comment="HC-Long")//short entry condition⋯plotshape(dataHCSB, title= "HC-SB", color=color.fuchsia, style=shape.circle, text="HC-SB")-strategy.entry("HC-Short", strategy.short, comment="HC-Short", when=dataHCSB and window())+if dataHCSB and window()+ strategy.entry("HC-Short", strategy.short, comment="HC-Short")// 5. Submit Profit and Loss Exit Calculations Orders*************************************************************************************************************************************************************************⋯//Does user want to run a Trailing Stop-trailStop_YN=input(title="Run a Trailing Stop", defval="N", options=["Y", "N"])+trailStop_YN=input.string(title="Run a Trailing Stop", defval="N", options=["Y", "N"])TrailPerc = input.float(title="Trail Loss %", minval=0, step=1, defval=6) /100⋯ if trailStop_YN=="Y"- strategy.exit(id="Close Long", when = window(), stop=longStop, limit=longTake, qty_percent=50)// sell 50% when either the TGT or the SL is hit then transition to a trailing stop loss+ if window()+ strategy.exit(id="Close Long", stop=longStop, limit=longTake, qty_percent=50)// sell 50% when either the TGT or the SL is hit then transition to a trailing stop loss- strategy.exit(id="Close Long Trailing Stop", when = window(), stop=longStopPrice, qty_percent=100)+ if window()+ strategy.exit(id="Close Long Trailing Stop", stop=longStopPrice, qty_percent=100) if trailStop_YN=="N"- strategy.exit(id="Close Long", when = window(), stop=longStop, limit=longTake)// sell when either the TGT or the SL is hit + if window()+ strategy.exit(id="Close Long", stop=longStop, limit=longTake)// sell when either the TGT or the SL is hit ⋯ if trailStop_YN=="Y"- strategy.exit(id="Close Short", when = window(), stop=shortStop, limit=shortTake, qty_percent=50)// sell 50% when either the TGT or the SL is hit then transition to a trailing stop loss+ if window()+ strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, qty_percent=50)// sell 50% when either the TGT or the SL is hit then transition to a trailing stop loss- strategy.exit(id="Close Short Trailing Stop", when = window(), stop=shortStopPrice, qty_percent=100)+ if window()+ strategy.exit(id="Close Short Trailing Stop", stop=shortStopPrice, qty_percent=100) if trailStop_YN=="N"- strategy.exit(id="Close Short", when = window(), stop=shortStop, limit=shortTake)// sell when either the TGT or the SL is hit+ if window()+ strategy.exit(id="Close Short", stop=shortStop, limit=shortTake)// sell when either the TGT or the SL is hit// Plot stop trailing loss values for confirmation⋯Does it run in Pine Script v6?
Yes
Same 9 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.
-//@version=5+//@version=6// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Price Source | close | source | SH_SMA LG_SMA GV_SMA fastMA slowMA line 54 line 57 line 62 line 65 |
| Run Strategy Trending Up, Down, or Both | Both | string · options ["Up", "Down", "Both"] | RunTrendUp RunTrendDWN |
| SH SMA Length | 13 | int | SH_SMA |
| LG SMA Length | 30 | int | LG_SMA |
| SH SMA Length | 200 | int | GV_SMA |
| Weeks In Trend | 1 | int · min 1 · max 5 | n m SMAbuy SMAsell line 53 line 61 |
| Slope Factor | .01 | float · min 0 · step 0.001 | StrongSlope |
| From Month | 4 | int (written input.integer) · min 1 · max 12 | start |
| From Day | 1 | int (written input.integer) · min 1 · max 31 | start |
| From Year | 2020 | int (written input.integer) · min 1970 | start |
| Thru Month | 1 | int (written input.integer) · min 1 · max 12 | finish |
| Thru Day | 1 | int (written input.integer) · min 1 · max 31 | finish |
| Thru Year | 2112 | int (written input.integer) · min 1970 | finish |
| Show Date Range | true | bool | bgcolor |
| Price CountBack | 0 | int · min 0 · max 5 | MACDbuy MACDsell |
| Run SMA | Y | string · options ["Y", "N"] | dataHCLB dataHCSB |
| Run MACD | N | string · options ["Y", "N"] | MACDbuy MACDsell dataHCLB dataHCSB |
| Run a Trailing Stop | N | string · options ["Y", "N"] | exit Close Long exit Close Long Trailing Stop exit Close Long exit Close Short exit Close Short Trailing Stop exit Close Short line 160 line 163 line 168 line 171 Long Trail Stop Short Trail Stop |
| Trail Loss % | 6 | float · min 0 · step 1 | longStopPrice stopValue shortStopPrice shortStopValue |
| Stop Loss % | 12 | float | longStop shortStop |
| Take Profit % | 25 | float | shortTake longTake |
What it calculates
- SMA (
sma,ta.smain v5)Price Source (close), SH SMA Length (13)SH_SMA · line 28 - SMA (
sma,ta.smain v5)Price Source (close), LG SMA Length (30)LG_SMA · line 29 - SMA (
sma,ta.smain v5)Price Source (close), SH SMA Length (200)GV_SMA · line 30 - EMA (
ema,ta.emain v5)Price Source (close), fastfastMA · line 35 - EMA (
ema,ta.emain v5)Price Source (close), slowslowMA · line 36 - SMA (
sma,ta.smain v5)macd, 9signal · line 40 - Crossover (
crossover,ta.crossoverin v5)SH_SMA, LG_SMASH_LGcrossover · line 69 - Crossunder (
crossunder,ta.crossunderin v5)SH_SMA, LG_SMASH_LGcrossunder · line 70
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 68 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open HC-Long long | dataHCLB and window() | On | 126 |
| Open HC-Short short | dataHCSB and window() | On | 130 |
| Exit Close Long stop and limit | window() | On | 161 |
| Exit Close Long Trailing Stop stop | window() | On | 162 |
| Exit Close Long stop and limit | window() | On | 164 |
| Exit Close Short stop and limit | window() | On | 169 |
| Exit Close Short Trailing Stop stop | window() | On | 170 |
| Exit Close Short stop and limit | window() | On | 172 |
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 script reads request.security() at the chart's own timeframe, which Zeal Terminal's engine answers one bar late in live mode but not in history, so this replay cannot tell repainting from that engine issue.
- ClearHigher-timeframe data2 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
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −1.5% | +102.5% | 9 | 22% | 0.62 | 3.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −1.0% | +5.5% | 19 | 21% | 0.58 | 1.6% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +1.2% | +9.8% | 9 | 33% | 1.45 | 1.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −0.5% | +8.4% | 24 | 42% | 0.84 | 1.6% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +4.3% | +16.7% | 9 | 67% | 3.62 | 1.8% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +1.7% | +21.5% | 16 | 50% | 1.69 | 1.5% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −5.3% | +148.3% | 10 | 0% | 0.00 | 5.3% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −2.4% | +17.1% | 18 | 33% | 0.27 | 3.2% | 8 May 2026 – 21 Oct 2026 |
Higher-timeframe data for request.security(): BINANCE:BTCUSDT W (Binance BTCUSDT 1w), fetched from Binance's public market data for each market.
Backtests are simulations on historical data and are not investment advice.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 3 | 0% | −$321.33 |
| Sideways market | 3 | 67% | $371.80 |
| Falling market | 3 | 0% | −$355.10 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
3.9%
The 95th percentile of the worst drawdown when the same 9 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 1.8% to 3.9%; the tick is what actually happened, 3.0%. Order luck alone moves it this much.
All 9 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 18 Apr 2024 61,277.40 | 20 May 2024 66,274.00 | 32 | −$81.54 |
| long | 20 May 2024 66,274.00 | 4 Jul 2024 58,321.10 | 45 | −$119.51 |
| long | 17 Oct 2024 67,620.00 | 11 Nov 2024 84,525.00 | 25 | $247.49 |
| long | 17 Jan 2025 99,987.30 | 25 Feb 2025 87,988.80 | 39 | −$120.28 |
| short | 8 Apr 2025 79,163.20 | 22 Apr 2025 88,662.80 | 14 | −$119.56 |
| long | 5 Oct 2025 122,391.00 | 10 Oct 2025 107,704.00 | 5 | −$118.84 |
| long | 13 Dec 2025 90,268.40 | 31 Jan 2026 79,436.20 | 49 | −$118.13 |
| long | 14 Apr 2026 74,418.00 | 3 Jun 2026 65,487.80 | 50 | −$117.42 |
| long | 20 Aug 2026 69,334.80 | 21 Sep 2026 86,668.50 | 32 | $243.15 |
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| KISS Strategy- SMA + EMA this page | — | v4 strategy | −1.5% | 9 | 3.0% |
| MACD Long Strat by TheGrindToday | ema sma | v4 strategy | +24.0% | 79 | 20.1% |
| Stock trending strategy by exlux99 | ema sma | v4 strategy | +35.3% | 21 | 14.7% |
| 4-Hour Stochastic EMA Trend by slymnturkoglu | ema sma | v4 strategy | No trades on this market | ||
| 4X EMA and volume strategy by SoftKill21 | ema sma | v4 strategy | +1.8% | 3 | 25.8% |
| Simple Momentum Strategy Based on SMA, EMA and Volume by slip_stream | sma ema | v4 strategy | +7.4% | 18 | 27.4% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 38 ms | With a workaround 1,000 bars in 125 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“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.
//@version=4// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © MakeMoneyCoESTB2020//*********************Notes for continued work***************//************************************************************//Hello my fellow investors//I am creating a simple non-cluttered strategy that uses 3(+1) simple means to determine: viability, entry, and exit//1) Has a consistent trend been maintained for several days/weeks//2) SH SMA crossover LG SMA = Bullish entry/LG SMA crossover SH SMA = Bearish entry//3) Use the Slope factor & Weeks in Trend (WiT) to dertermine how strong of an entry signal you are comfortable with//3+1) For added confidence in trend detection: Apply MACD check - buy--> MACD line above signal line and corssover below histogram \\ sell --> MACD line below signal line and crossover above histogram.//4) Exit position based on next SMA cross and trend reversal or stop loss%//*)This code also allows you to determine your desired backtesting date compliments of alanaster//This code is the product of many hours of hard work on the part of the greater tradingview community. The credit goes to everyone in the community who has put code out there for the greater good.//Happy Hunting!// 1. Define strategy settings*************************************************************************************************************************************************************************//Titlestrategy("KISS Strategy: SMA + EMA", shorttitle="KISS Strat", default_qty_type=strategy.percent_of_equity, default_qty_value=5, initial_capital=20000,slippage=2, currency=currency.USD, overlay=true, pyramiding=2)//define calculations price sourceprice = input(title="Price Source", defval=close)//Does user want to run the Strategy for Trending Up or Trending DownRunTrend=input(title="Run Strategy Trending Up, Down, or Both", defval="Both", options=["Up", "Down", "Both"])// 2. Calculate strategy values*************************************************************************************************************************************************************************//Calculate 13/30/200SMA SH_SMA_length= input(title="SH SMA Length", defval=13) //short SMA lengthLG_SMA_length= input(title="LG SMA Length", defval=30) //long SMA lengthGV_SMA_length= input(title="SH SMA Length", defval=200) //Gravitational SMA lengthSH_SMA=sma(price, SH_SMA_length) //short SMA LG_SMA=sma(price, LG_SMA_length) //long SMAGV_SMA=sma(price, GV_SMA_length) //gravitational SMA//calculate MACD//define variables for speedfast = 12, slow = 26//define parameters to calculate MACDfastMA = ema(price, fast)slowMA = ema(price, slow)//define MACD linemacd = fastMA - slowMA//define SIGNAL linesignal = sma(macd, 9)//Determine what type of trend we are indcp = security(syminfo.tickerid, 'D', close) //daily close price wcp = security(syminfo.tickerid, 'W', close) //weekly close price WiT = input(title="Weeks In Trend", defval=1, maxval=5, minval=1) //User input for how many weeks of price action to evaluate (Weeks in Trend = WiT)BearTrend = false //initialize trend variables as falseBullTrend = false //initialize trend variables as false// BullTrend := (wcp > SH_SMA) and (SH_SMA > LG_SMA) //true if price is trending up based on weekly price close// BearTrend := (wcp < SH_SMA) and (SH_SMA < LG_SMA) //true if price is trending down based on weekly price close// BullTrend := (price > SH_SMA) and (SH_SMA > LG_SMA) //true if price is trending up// BearTrend := (price < SH_SMA) and (SH_SMA < LG_SMA) //true if price is trending down//Determine if the market has been in a trend for 'n' weeksn=WiT //create loop internal counting variablefor i=1 to WiT //create loop to determine if BearTrend=true to set number of weeks if (wcp[n] < price) //evaluate if BearTrend=false comparing the current price to a paticular week close BearTrend := false //set value to false if older price value is less than newer: trending up break //break out of for loop when trend first falters if (wcp[n] > price) //evaluate if BearTrend=true comparing the current price to a paticular week close BearTrend := true //set value to true if older price value is greater than newer: trending down n:=n-1 //set internal counter one day closer to presentm=WiT //create loop internal counting variablefor j=1 to WiT //create loop to determine if BearTrend=true to set number of weeks if (wcp[m] > price) //evaluate if BullTrend=false comparing the current price to a paticular week close BullTrend := false //set value to false if older price value is greater than newer: trending down break //break out of for loop when trend first falters if (wcp[m] < price) //evaluate if BullTrend=true comparing the current price to a paticular week close BullTrend := true //set value to true if older price value is less than newer: trending up m:=m-1 //set internal counter one day closer to present//Determine if crossings occurSH_LGcrossover = crossover(SH_SMA, LG_SMA) //returns true if short crosses over longSH_LGcrossunder = crossunder(SH_SMA, LG_SMA) //returns true if short crosses under long//Determine the slope of the SMAs when a cross over occursSlopeFactor= input(title="Slope Factor", defval=.01, minval=0, step = 0.001) //user input variable for what slope to evaluate againstXSlopeSH = abs(SH_SMA-SH_SMA[2]) //slope of short moving average (time cancels out)XSlopeLG = abs(LG_SMA-LG_SMA[2]) //slope of long moving average (time cancels out)StrongSlope = iff (abs(XSlopeSH-XSlopeLG)>SlopeFactor, true, false) //create a boolean variable to determine is slope intensity requirement is met// ************************************ INPUT BACKTEST RANGE ******************************************=== coutesy of alanasterfromMonth = input(defval = 4, title = "From Month", type = input.integer, minval = 1, maxval = 12)fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)fromYear = input(defval = 2020, title = "From Year", type = input.integer, minval = 1970)thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)// === INPUT SHOW PLOT ===showDate = input(defval = true, title = "Show Date Range", type = input.bool)// === FUNCTION EXAMPLE ===start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start windowfinish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish windowwindow() => time >= start and time <= finish ? true : false // create function "within window of time"bgcolor(color = showDate and window() ? color.gray : na, transp = 90) // === EXECUTION ===//strategy.entry("L", strategy.long, when = window() and crossOv) // enter long when "within window of time" AND crossover//strategy.close("L", when = window() and crossUn) // exit long when "within window of time" AND crossunder// 3. Output strategy data*************************************************************************************************************************************************************************//Embolden line if a trend existstrendcolorLG = BearTrend?color.red:color.black //highlights beartrend condition met graphicallytrendcolorSH = BullTrend?color.green:color.black //highlights beartrend condition met graphically//plot SMAsplot(SH_SMA, title = "SH SMA", color = trendcolorSH)plot(LG_SMA, title = "LG SMA", color = trendcolorLG)plot(GV_SMA, title = "GV SMA", color = color.silver, linewidth = 4, transp = 70)//Highlight crossoversplotshape(series=SH_LGcrossover, style=shape.arrowup, location=location.belowbar,size=size.normal, color=color.green)plotshape(series=SH_LGcrossunder, style=shape.arrowdown, location=location.abovebar,size=size.normal, color=color.red)// 4. Determine Long & Short Entry Calculations*************************************************************************************************************************************************************************//Determine when to run the strategy based on user input for uptrend or downtrendRunTrendUp=false //Varibile for running the Strategy in an UpTrendRunTrendUp:= iff(RunTrend == "Up" or RunTrend == "Both", true, false)RunTrendDWN=false //Varibile for running the Strategy in a DownTrendRunTrendDWN:= iff(RunTrend == "Down" or RunTrend == "Both", true, false)//Define countback variablecountback=input(minval=0, maxval=5, title="Price CountBack", defval=0)//User input for what evaluations to run: SMA or SMA + EMASMA_Y_N=input(defval = "Y", title="Run SMA", type=input.string, options=["Y", "N"])MACD_Y_N=input(defval = "N", title="Run MACD", type=input.string, options=["Y", "N"])//Calculate SMA Cross entry conditionsSMAbuy=falseSMAsell=falseSMAbuy := SH_LGcrossover and StrongSlope and BearTrend[WiT*7] //enter long if short SMA crosses over long SMA & security has been in a BearTrend for 'n' days backSMAsell := SH_LGcrossunder and StrongSlope and BullTrend[WiT*7] //enter short if short SMA crosses under long SMA & security has been in a BullTrend for 'n' days back//Calculate MACD Cross entry conditionsMACDbuy = iff(MACD_Y_N=="Y", crossunder(signal[countback], macd[countback]), true) and iff(MACD_Y_N=="Y", macd[countback]<0, true) and StrongSlope and BearTrend //enter long if fast MACD crosses over slow MACD & there is a strong slope & security has been in a BearTrend for 'n' days backMACDsell = iff(MACD_Y_N=="Y", crossunder(macd[countback], signal[countback]), true) and iff(MACD_Y_N=="Y", signal[countback]>0, true) and StrongSlope and BullTrend //enter short if fast MACD crosses under slow MACD & there is a strong slope & security has been in a BullTrend for 'n' days back//long entry conditiondataHCLB=(iff(SMA_Y_N=="Y", SMAbuy, true) and iff(MACD_Y_N=="Y", MACDbuy, true) and RunTrendUp)plotshape(dataHCLB, title= "HC-LB", color=color.lime, style=shape.circle, text="HC-LB")strategy.entry("HC-Long", strategy.long, comment="HC-Long", when = dataHCLB and window())//short entry conditiondataHCSB=(iff(SMA_Y_N=="Y", SMAsell, true) and iff(MACD_Y_N=="Y", MACDsell, true) and RunTrendDWN)plotshape(dataHCSB, title= "HC-SB", color=color.fuchsia, style=shape.circle, text="HC-SB")strategy.entry("HC-Short", strategy.short, comment="HC-Short", when=dataHCSB and window())// 5. Submit Profit and Loss Exit Calculations Orders*************************************************************************************************************************************************************************//User Options to Change Inputs //Does user want to run a Trailing StoptrailStop_YN=input(title="Run a Trailing Stop", defval="N", options=["Y", "N"])TrailPerc = input(title="Trail Loss %", type=input.float, minval=0, step=1, defval=6) /100stopPer = input(12, title='Stop Loss %', type=input.float) / 100takePer = input(25, title='Take Profit %', type=input.float) / 100//calculate Trail stop price for MD_EMA TGT% conditionlongStopPrice=0.0//long side entry stop variablelongStopPrice := if (strategy.position_size > 0) stopValue = close * (1 - TrailPerc) max(stopValue, longStopPrice[1])else 0 shortStopPrice=0.0//short side entry stop variableshortStopPrice := if (strategy.position_size < 0) shortStopValue = close * (1 + TrailPerc) min(shortStopValue, shortStopPrice[1])else 999999 // Determine where you've entered and in what directionlongStop = strategy.position_avg_price * (1 - stopPer)shortStop = strategy.position_avg_price * (1 + stopPer)shortTake = strategy.position_avg_price * (1 - takePer)longTake = strategy.position_avg_price * (1 + takePer)//exit position conditions and ordersif strategy.position_size > 0 //long side exit conditions if trailStop_YN=="Y" strategy.exit(id="Close Long", when = window(), stop=longStop, limit=longTake, qty_percent=50)// sell 50% when either the TGT or the SL is hit then transition to a trailing stop loss strategy.exit(id="Close Long Trailing Stop", when = window(), stop=longStopPrice, qty_percent=100) if trailStop_YN=="N" strategy.exit(id="Close Long", when = window(), stop=longStop, limit=longTake)// sell when either the TGT or the SL is hit if strategy.position_size < 0 //short side exit conditions if trailStop_YN=="Y" strategy.exit(id="Close Short", when = window(), stop=shortStop, limit=shortTake, qty_percent=50)// sell 50% when either the TGT or the SL is hit then transition to a trailing stop loss strategy.exit(id="Close Short Trailing Stop", when = window(), stop=shortStopPrice, qty_percent=100) if trailStop_YN=="N" strategy.exit(id="Close Short", when = window(), stop=shortStop, limit=shortTake)// sell when either the TGT or the SL is hit// Plot stop trailing loss values for confirmationplot(series=(strategy.position_size > 0 and (trailStop_YN=="Y")) ? longStopPrice : na, color=color.fuchsia, style=plot.style_cross, linewidth=2, title="Long Trail Stop") //plot the trailing stop on the chart for an uptrendplot(series=(strategy.position_size < 0 and (trailStop_YN=="Y")) ? shortStopPrice : na, color=color.fuchsia, style=plot.style_cross, linewidth=2, title="Short Trail Stop") //plot the trailing stop on the chart for a downtrend//plot fixed stop loss valueplot(series=(strategy.position_size > 0 and (trailStop_YN=="N")) ? longStop : na, color=color.fuchsia, style=plot.style_cross, linewidth=2, title="Long Trail Stop") //plot the stop on the chart for an uptrendplot(series=(strategy.position_size < 0 and (trailStop_YN=="N")) ? shortStop : na, color=color.fuchsia, style=plot.style_cross, linewidth=2, title="Short Trail Stop") //plot the stop on the chart for a downtrend//plot the TGT profit pointsplot(series=(strategy.position_size > 0 ) ? longTake : na, color=color.lime, style=plot.style_cross, linewidth=2, title="Short Trail Stop") //plot the TGT% for long positionplot(series=(strategy.position_size < 0 ) ? shortTake : na, color=color.lime, style=plot.style_cross, linewidth=2, title="Short Trail Stop") //plot the TGT% for short position// // Determine where you've entered and in what direction// longStop = strategy.position_avg_price * (1 - stopPer)// shortStop = strategy.position_avg_price * (1 + stopPer)// shortTake = strategy.position_avg_price * (1 - takePer)// longTake = strategy.position_avg_price * (1 + takePer)// //exit position conditions and orders// if strategy.position_size > 0//or crossunder(price[countback], upperBB)// strategy.exit(id="Close Long", when = window(), stop=longStop, limit=longTake)// if strategy.position_size < 0 //or crossover(price[countback], lowerBB)// strategy.exit(id="Close Short", when = window(), stop=shortStop, limit=shortTake)//Evaluate/debug equation***************************************************************************************************************************************************************************// plotshape((n==5? true : na), title='n=5', style=shape.labeldown, location=location.abovebar, text='5', color=color.white, textcolor=color.black, transp=0) //print n value if 5// plotshape((n==4? true : na), title='n=4', style=shape.labeldown, location=location.abovebar, text='4', color=color.white, textcolor=color.black, transp=0) //print n value if 4 // plotshape((n==3? true : na), title='n=3', style=shape.labeldown, location=location.abovebar, text='3', color=color.white, textcolor=color.black, transp=0) //print n value if 3// plotshape((n==2? true : na), title='n=2', style=shape.labeldown, location=location.abovebar, text='2', color=color.white, textcolor=color.black, transp=0) //print n value if 2// plotshape((n==1? true : na), title='n=1', style=shape.labeldown, location=location.abovebar, text='1', color=color.white, textcolor=color.black, transp=0) //print n value if 1// lineValue = 11 //set random visible line value to check when equation is true// colorP = (BearTrend==true) ? color.green : color.red// plot (lineValue, title = "BearTrend", color = colorP) //Plot when condition true=green, false=red// plot (XSlopeLG+15, color=color.white) //used for code debugging// plot (XSlopeSH+15, color=color.blue) //used for code debugging// plot (abs(XSlopeSH-XSlopeLG)+20, color=color.fuchsia) //used for code debugging