Zeal Terminal Open Zeal Terminal

Pine Script v5 · Strategy

Dynamic Stop Loss Demo

A Pine Script v5 strategy built on Highest (high, 14), Lowest (low, 14) and RSI (limit, 14). It has 11 order rules, 1 entry among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade commits 100% of equity and pays 0.04 commission. 8 settings; defaults include Length 14, Over Sold 30 and Over Bought 70.

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 Dynamic Stop Loss Demo repaint?
No
No repainting patterns were found in the source.
Does Dynamic Stop Loss Demo run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (In 'array.get()' function. Index 1 is out of bounds, array size is 1.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
Does Dynamic Stop Loss Demo use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.
Does Dynamic Stop Loss Demo run in Zeal Terminal?
No
Not yet: In 'array.get()' function. Index 1 is out of bounds, array size is 1.
Does not run in Zeal Terminal yetIn 'array.get()' function. Index 1 is out of bounds, array size is 1. 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

    No stop loss

    Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    3 settings have no label

    In the settings dialog length (line 6), overSold (line 7), overBought (line 8) 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
rsi settings
Length (no label in the script)14intvrsi
Over Sold (no label in the script)30intco
Over Bought (no label in the script)70intcu
strategy settings
Profit and loss ratio1.5float · step 0.1line 45
ATR times2float · step 0.1ATR
Back test length14inthighest lowest ATR line 86 line 90
First take profit qty percent50intclose curId
qty precision2intqtyNum qtyTimes line 59

What it calculates

  • Highesthigh, Back test length (14)highest · line 15
  • Lowestlow, Back test length (14)lowest · line 16
  • RSIlimit, Length (14)vrsi · line 18
  • Crossovervrsi, Over Sold (30)co · line 19
  • Crossundervrsi, Over Bought (70)cu · line 20
  • ATRBack test length (14)ATR · line 66

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.

highhighprice databack_test_lengthBack test lengthsetting · 14lowlowprice datalengthLengthsetting · 14overSoldOver Soldsetting · 30overBoughtOver Boughtsetting · 70high · low · closehigh · low · closeprice dataatr_timesATR timessetting · 2closecloseprice dataqty_precisionqty precisionsetting · 2highestHighest→ highestlowestLowest→ lowestvrsiRSI→ vrsicoCrossover→ cocuCrossunder→ cuATRATR→ ATRlimitlimitvaluelong_condlong_condvalueshort_condshort_condvaluecurSize, curId, prefix, avaC, numStr, sDStop, lDStopcurSize · curId +57 valuesinfoinfovalueopenPrice, stopPrice, entrySizeopenPrice · stopPrice +13 valuesprofitPriceprofitPricevalueididvalueqtyNumqtyNumvalueqtyTimesqtyTimesvaluelongQty, shortQtylongQty · shortQty2 valuescurOpenPrice, curProfitPrice, curStopPrice, curEntrySizecurOpenPrice · curProfi…4 valueslong_stoplong_stopvaluelong_profitlong_profitvalueshort_stopshort_stopvalueshort_profitshort_profitvaluelstoplstopvaluesStopsStopvaluelprofitlprofitvaluesProfitsProfitvaluelopenlopenvaluesopensopenvaluehasFitFirstProfithasFitFirstProfitconditionisShorting, isLonging, isOpeningisShorting · isLonging …3 conditionsentry:idOpen idstrategy.entryclose:curIdClose curIdstrategy.closeplot:139long stop colorplotplot:140long profit colorplotplot:141long open colorplotplot:142long dynamic stop colorplotplot:143short stop colorplotplot:144short profit colorplotplot:145short open colorplotplot:146short dynamic stop colorplot

Order rules

OrderFires whenBy defaultLine
Open id direction == LONG ? strategy.long : strategy.shortevery barOn52
Close curIdlow < dynamicLongStopOn98
Close curIdclose < curStopPriceOn100
Close curIdlow < curOpenPriceOn102
Close curIdclose < curStopPriceOn109
Close curIdhigh > curProfitPriceOn111
Close curIdhigh > dynamicShortStopOn115
Close curIdclose > curStopPriceOn117
Close curIdhigh > curOpenPriceOn119
Close curIdclose > curStopPriceOn126
Close curIdlow < curProfitPriceOn128

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 dataThe script requests no other symbol or timeframe.
  • 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
M0PB (Momentum Pullback) by Marcns_rsi highest lowest atrv5 strategy+51.3%317.5%
Delayed RSI Strategy by tweakerIDlowest highest atr rsiv4 strategy−40.4%742.2%
Simple SuperTrend Strategy for BTCUSD 4H by StrategiesForEveryonersi atr highest lowestv5 strategy+1.1%7219.5%
Aggresive Scalper-Swing Crypto Strategy by exlux99lowest highest atrv4 strategy−7.4%316.0%
PlanB Quant Investing 101 v2 by fillipponersi highest lowestv4 strategyNo trades on this market

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.

  • 3 settings use the untyped input() (line 6, 7, 8). It still compiles in v6; input.int, input.float or input.source state the type.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

Not verified

The v5 script does not run in Zeal Terminal's engine (In 'array.get()' function. Index 1 is out of bounds, array size is 1.), so this step could not be checked.

  • Line 6: input() → input.int()
  • Line 7: input() → input.int()
  • Line 8: input() → input.int()
⋯// rsi settings-length = input( 14, group="rsi settings" )+length = input.int( 14, group="rsi settings" )-overSold = input( 30, group="rsi settings")+overSold = input.int( 30, group="rsi settings")-overBought = input( 70, group="rsi settings" )+overBought = input.int( 70, group="rsi settings" )// strategy settings⋯

Does it run in Pine Script v6?

Not tested

The v5 script does not run in Zeal Terminal's engine (In 'array.get()' function. Index 1 is out of bounds, array size is 1.), 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.

⋯// © Tindtily-//@version=5+//@version=6strategy("Dynamic Stop Loss Demo",overlay = true,initial_capital = 20000,max_bars_back = 100, pyramiding = 1, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, commission_value=0.04)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No In 'array.get()' function. Index 1 is out of bounds, array size is 1.Not 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/// © Tindtily//@version=5strategy("Dynamic Stop Loss Demo",overlay = true,initial_capital = 20000,max_bars_back = 100, pyramiding = 1, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, commission_value=0.04)// rsi settingslength = input( 14, group="rsi settings" )overSold = input( 30, group="rsi settings")overBought = input( 70, group="rsi settings" )// strategy settingsrr = input.float(1.5,'Profit and loss ratio',step = 0.1, group = 'strategy settings')atr_times = input.float(2,'ATR times', step = 0.1, group = 'strategy settings')back_test_length = input.int(14, 'Back test length', group = 'strategy settings')first_tp_qty = input.int(50, 'First take profit qty percent', group = 'strategy settings')qty_precision = input.int(2, "qty precision", group = "strategy settings")highest = ta.highest(high, back_test_length)lowest = ta.lowest(low, back_test_length)limit = closevrsi = ta.rsi(limit, length)co = ta.crossover(vrsi, overSold)cu = ta.crossunder(vrsi, overBought)long_cond = coshort_cond = cuhasFitFirstProfit = falsecurSize = strategy.position_sizecurId = strategy.position_entry_nameisShorting = curSize < 0isLonging = curSize > 0isOpening = isShorting or isLonging// enumsLONG = "long"SHORT = "short"getStrategyInfoFromId(id)=>    info = str.split(id, "_")    openPrice = float(na)    profitPrice = float(na)    stopPrice = float(na)    entrySize = float(na)    if array.size(info) != 0         openPrice := str.tonumber(array.get(info, 1))        profitPrice := str.tonumber(array.get(info, 3))        stopPrice := str.tonumber(array.get(info, 2))        entrySize := str.tonumber(array.get(info, 4))    [openPrice, profitPrice, stopPrice, entrySize]getBasicProfit(openPrice, stopPrice) =>    openPrice + (openPrice - stopPrice) * rrgetStrategyId(prefix, openPrice, stopPrice, profitPrice, size) =>    prefix + "_" + str.tostring(openPrice) + "_" + str.tostring(stopPrice) + "_" + str.tostring(profitPrice) + "_" + str.tostring(size)startStrategy(direction, openPrice, stopPrice, qty, entryComment) =>    prefix = direction    profitPrice = getBasicProfit(openPrice, stopPrice)    id = getStrategyId(prefix, openPrice, stopPrice, profitPrice, qty * (direction == LONG ? 1: -1))    strategy.entry(id, direction == LONG ? strategy.long : strategy.short, comment= entryComment, limit=openPrice, qty = qty)toOdd(num)=>    2 * math.round(num / 2)getQty(limit) =>    avaC = strategy.grossprofit - strategy.grossloss + strategy.initial_capital    qtyNum = math.round(avaC / limit, qty_precision)    qtyTimes = math.pow(10, qty_precision)    math.round(toOdd( qtyNum * qtyTimes) / qtyTimes, qty_precision)decimal(number, precision) =>    numStr = str.tostring(math.round(number, precision + 1))    str.tonumber(str.substring(numStr, 0, str.length(numStr) - 1))longQty = decimal(getQty(limit) , 2)shortQty = decimal(getQty(limit) , 2)calculateDynimacStop()=>    ATR = atr_times * ta.atr(back_test_length)    dynamicLongStop = float(na)    dynamicShortStop = float(na)    if (close > open)        dynamicLongStop := low - ATR        if (isLonging)            dynamicLongStop := math.max(dynamicLongStop, dynamicLongStop[1])    else        dynamicLongStop := dynamicLongStop[1]    if (close < open)        dynamicShortStop := high + ATR        if (isShorting)            dynamicShortStop := math.min(dynamicShortStop, dynamicShortStop[1])    else         dynamicShortStop := dynamicShortStop[1]    [dynamicLongStop, dynamicShortStop][dynamicLongStop, dynamicShortStop] = calculateDynimacStop()[curOpenPrice, curProfitPrice, curStopPrice, curEntrySize] = getStrategyInfoFromId(curId)hasFitFirstProfit := math.abs(curEntrySize) > math.abs(curSize)if isLonging == false and isShorting == false     if long_cond and bar_index > back_test_length        long_stop = lowest        long_profit = getBasicProfit(limit, long_stop)        startStrategy(LONG, limit, long_stop, longQty, "entry long")    if short_cond and bar_index > back_test_length        short_stop = highest        short_profit = getBasicProfit(limit, short_stop)        startStrategy(SHORT, limit, short_stop, longQty, "entry short")else    if isLonging        if hasFitFirstProfit             if low < dynamicLongStop                 strategy.close(curId, comment='stop long dynamic')            else if close < curStopPrice                strategy.close(curId, comment='stop long at stop')            else if low < curOpenPrice                strategy.close(curId, comment='stop long at open')            else if short_cond                short_stop = highest                short_profit = getBasicProfit(limit, short_stop)                startStrategy(SHORT, limit, short_stop, shortQty, "entry short")        else             if close < curStopPrice                strategy.close(curId, comment = 'stop long')            if high > curProfitPrice                strategy.close(curId, comment = "take long " + str.tostring(first_tp_qty) + '% profit',  qty_percent =first_tp_qty)    if isShorting        if hasFitFirstProfit             if high > dynamicShortStop                strategy.close(curId, comment='stop short dynamic')            else if close > curStopPrice                strategy.close(curId, comment='stop short at stop')            else if high > curOpenPrice                strategy.close(curId, comment='stop short at open')            else if long_cond                long_stop = lowest                long_profit = getBasicProfit(limit, long_stop)                startStrategy(LONG, limit, long_stop, longQty, "entry long")        else            if close > curStopPrice                strategy.close(curId, comment = 'stop short')            if low < curProfitPrice                 strategy.close(curId, comment = "take short " + str.tostring(first_tp_qty) + '% profit', qty_percent =first_tp_qty)               // plots  lstop = isLonging ? curStopPrice : nasStop = isShorting ? curStopPrice: nalprofit = isLonging ? curProfitPrice :na sProfit = isShorting ? curProfitPrice : na lopen = isLonging ? curOpenPrice : nasopen = isShorting ? curOpenPrice : na sDStop = dynamicShortStoplDStop = dynamicLongStopplot(isOpening?lstop:na, title="long stop color" ,color=color.red,style = plot.style_linebr,linewidth = 1)plot(isOpening?lprofit:na,title="long profit color",color=color.green,style = plot.style_linebr,linewidth = 1)plot(isOpening?lopen : na,title="long open color", color = color.silver, style = plot.style_linebr, linewidth = 1)plot(isLonging and hasFitFirstProfit? lDStop: na,title="long dynamic stop color", color=color.yellow, style = plot.style_linebr, linewidth = 1)plot(isOpening?sStop:na,title="short stop color" ,color=color.red,style = plot.style_linebr,linewidth = 1)plot(isOpening?sProfit:na,title="short profit color" ,color=color.green,style = plot.style_linebr,linewidth = 1)plot(isOpening?sopen : na,title="short open color" , color = color.silver, style = plot.style_linebr, linewidth = 1)plot(isShorting and hasFitFirstProfit? sDStop:na,title="short dynamic stop color" , color=color.yellow, style = plot.style_linebr, linewidth = 1)