Pine Script v4 · Strategy
Initial template
A Pine Script v4 strategy built on EMA (strategy.equity, 42), Crossover (ma2, ma3) and Valuewhen (longconmet, open). It has 7 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 100% of equity and pays 0.04% commission. 17 settings; defaults include lookback for average range (bars) 200, filter trades if range is less than (%) 1 and filter trades if equity is below ema() 42.
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 Initial template repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did Initial template 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. On ETHUSDT 1D it did trade; that row of the markets table below has its figures. A backtest, not investment advice.
- Can Initial template 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 Initial template use a stop loss?
- Yes
- strategy.exit sets a stop on line 176, 179, 184, 186.
- Does Initial template run in Zeal Terminal?
- Yes
- It compiles in 38 ms and runs 1,000 bars in 101 ms, in the browser.
BTCUSDT · 1D · default settings
- Plot
- Plot
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
- 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.
-
Likely bug
ema(close, 9) ignores the settings line 54
Line 54 hard-codes 9 where line 39 uses “filter trades if equity is below ema()”. Changing those settings moves one band but not this one.
ema(close, 9)ema(close, equityIn) -
Likely bug
ema(close, 21) ignores the settings line 55
Line 55 hard-codes 21 where line 39 uses “filter trades if equity is below ema()”. Changing those settings moves one band but not this one.
ema(close, 21)ema(close, equityIn) -
Likely bug
ema(close, 50) ignores the settings line 56
Line 56 hard-codes 50 where line 39 uses “filter trades if equity is below ema()”. Changing those settings moves one band but not this one.
ema(close, 50)ema(close, equityIn) -
Check
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 169, 172. The upgraded version below moves each call inside an if block.
-
Note
Uses long =, which v5 renamed line 169
long = on line 169, 172. v5 writes it as direction = strategy.long or strategy.short.
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames ema → ta.ema, crossover → ta.crossover, valuewhen → ta.valuewhen, max → math.max, min → math.min.
- 2 strategy calls use the when = argument (line 169, 172). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 4 trades and the same P&L on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 39: ema → ta.ema
- Line 54: ema → ta.ema
- Line 55: ema → ta.ema
- Line 56: ema → ta.ema
- Line 61: crossover → ta.crossover
9 more edits
- Line 62: crossover → ta.crossover
- Line 67: valuewhen → ta.valuewhen
- Line 68: valuewhen → ta.valuewhen
- Line 141: max → math.max
- Line 143: max → math.max
- Line 146: min → math.min
- Line 148: min → math.min
- Line 169: long = true → direction = strategy.long
- Line 172: long = false → direction = strategy.short
⋯// © TradingMentalist-//@version=4+//@version=5strategy("Initial template",initial_capital=1000, overlay=true, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD)⋯notsideways = side3 > sidein-equityMa = equitysw ? ema(strategy.equity, equityIn) : 0+equityMa = equitysw ? ta.ema(strategy.equity, equityIn) : 0equityCon = strategy.equity >= equityMa⋯////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////indicators-ma1 = ema(close, 9)+ma1 = ta.ema(close, 9)-ma2 = ema(close, 21)+ma2 = ta.ema(close, 21)-ma3 = ema(close, 50)+ma3 = ta.ema(close, 50)plot(ma1, color=color.new(#E8B6B0,50))⋯////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////conditions-longConditionTrigger = crossover(ma2,ma3)+longConditionTrigger = ta.crossover(ma2,ma3)-shortConditionTrigger = crossover(ma3,ma2)+shortConditionTrigger = ta.crossover(ma3,ma2)if longConditionTrigger⋯ shortconmet:=true-bestpricel = valuewhen(longconmet,open,0) * (1-bestpricein)+bestpricel = ta.valuewhen(longconmet,open,0) * (1-bestpricein)-bestprices = valuewhen(shortconmet,open,0) * (1+bestpricein)+bestprices = ta.valuewhen(shortconmet,open,0) * (1+bestpricein)longCondition1 = longconmet == true⋯ if not na(level[1])- level := max(level[1], level)+ level := math.max(level[1], level) if not na(level)- level := max(high, level)+ level := math.max(high, level) else if strategy.position_size < 0 if not na(level[1])- level := min(level[1], level)+ level := math.min(level[1], level) if not na(level)- level := min(low, level)+ level := math.min(low, level)calcTrailingOffsetLevel(points, offset) =>⋯ if strategy.position_size == 0 or strategy.position_size > 0 - strategy.entry(id="long", long=true, when=long, comment=enterlongcomment)+ strategy.entry(id="long", direction = strategy.long, when=long, comment=enterlongcomment) if shotinc if strategy.position_size == 0 or strategy.position_size < 0 - strategy.entry(id="short", long=false, when=short, comment = entershortcomment)+ strategy.entry(id="short", direction = strategy.short, when=short, comment = entershortcomment)curStage = getCurrentStage()⋯Same 4 trades and the same P&L on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 11: input() → input.int()
- Line 12: input() → input.int()
- Line 13: input() → input.int()
- Line 14: input() → input.bool()
- Line 15: input() → input.bool()
- Line 16: input() → input.float()
13 more edits
- Line 21: input() → input.bool()
- Line 22: input() → input.bool()
- Line 23: input() → input.bool()
- Line 24: input() → input.bool()
- Line 25: input() → input.bool()
- Line 26: input() → input.bool()
- Line 29: input() → input.int()
- Line 30: input() → input.int()
- Line 31: input() → input.int()
- Line 32: input() → input.int()
- Line 33: input() → input.bool()
- Line 169: when = long → if block
- Line 172: when = short → if block
⋯////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////inputs-sidein2 = input(200, step=10, title='lookback for average range (bars)')+sidein2 = input.int(200, step=10, title='lookback for average range (bars)')-sidein = input(1, title='filter trades if range is less than (%)')/100+sidein = input.int(1, title='filter trades if range is less than (%)')/100-equityIn = input(42, title='filter trades if equity is below ema()')+equityIn = input.int(42, title='filter trades if equity is below ema()')-sidewayssw = input(false, title='sideways filter?')+sidewayssw = input.bool(false, title='sideways filter?')-equitysw = input(false, title='equity filter?')+equitysw = input.bool(false, title='equity filter?')-bestpricein = input(0.003,step=0.001, title='best price +/-?')/100+bestpricein = input.float(0.003,step=0.001, title='best price +/-?')/100//longtpin = input(1,step=0.1, title='long TP %')/100⋯//shortslin = input(0.4,step=0.1, title='short SL %')/100-longinc=input(true, title="include longs?")+longinc=input.bool(true, title="include longs?")-lConSw2=input(true, title="condition two?")+lConSw2=input.bool(true, title="condition two?")-lConSw3=input(true, title="condition three?")+lConSw3=input.bool(true, title="condition three?")-shotinc=input(true, title="include shorts?")+shotinc=input.bool(true, title="include shorts?")-sConSw2=input(true, title="condition two?")+sConSw2=input.bool(true, title="condition two?")-sConSw3=input(true, title="condition three?")+sConSw3=input.bool(true, title="condition three?")percent2points(percent) => strategy.position_avg_price * percent / 100 / syminfo.mintick-sl = percent2points(input(2, title = "stop loss %%"))+sl = percent2points(input.int(2, title = "stop loss %%"))-tp1 = percent2points(input(3, title = "take profit 1 %%"))+tp1 = percent2points(input.int(3, title = "take profit 1 %%"))-tp2 = percent2points(input(7, title = "take profit 2 %%"))+tp2 = percent2points(input.int(7, title = "take profit 2 %%"))-tp3 = percent2points(input(22, title = "take profit 3 %%"))+tp3 = percent2points(input.int(22, title = "take profit 3 %%"))-activateTrailingOnThirdStep = input(true, title = "trail on stage 3? tp3=amount tp2=offset")+activateTrailingOnThirdStep = input.bool(true, title = "trail on stage 3? tp3=amount tp2=offset")////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////filters⋯ if strategy.position_size == 0 or strategy.position_size > 0 - strategy.entry(id="long", direction = strategy.long, when=long, comment=enterlongcomment)+ if long+ strategy.entry(id="long", direction = strategy.long, comment=enterlongcomment) if shotinc if strategy.position_size == 0 or strategy.position_size < 0 - strategy.entry(id="short", direction = strategy.short, when=short, comment = entershortcomment)+ if short+ strategy.entry(id="short", direction = strategy.short, comment = entershortcomment)curStage = getCurrentStage()⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 4 before, 4 after on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © TradingMentalist-//@version=5+//@version=6strategy("Initial template",initial_capital=1000, overlay=true, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD)⋯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 |
|---|---|---|---|
| lookback for average range (bars) | 200 | int · step 10 | side1 side2 |
| filter trades if range is less than (%) | 1 | int | notsideways |
| filter trades if equity is below ema() | 42 | int | equityMa |
| sideways filter? | false | bool | long short |
| equity filter? | false | bool | equityMa |
| best price +/-? | 0.003 | float · step 0.001 | bestpricel bestprices |
| include longs? | true | bool | line 167 |
| condition two? | true | bool | longCondition2in |
| condition three? | true | bool | longCondition3in |
| include shorts? | true | bool | line 170 |
| condition two? | true | bool | shortCondition2in |
| condition three? | true | bool | shortCondition3in |
| stop loss %% | 2 | int | stopLevel exit x |
| take profit 1 %% | 3 | int | stopLevel line 130 |
| take profit 2 %% | 7 | int | trailOffsetLevelTmp line 132 exit x |
| take profit 3 %% | 22 | int | profitLevel trailOffsetLevelTmp exit x |
| trail on stage 3? tp3=amount tp2=offset | true | bool | profitLevel exit x exit x line 182 |
What it calculates
- EMA (
ema,ta.emain v5)strategy.equity, filter trades if equity is below ema() (42)equityMa · line 39 - EMA (
ema,ta.emain v5)close, 9ma1 · line 54 - EMA (
ema,ta.emain v5)close, 21ma2 · line 55 - EMA (
ema,ta.emain v5)close, 50ma3 · line 56 - Crossover (
crossover,ta.crossoverin v5)ma2, ma3longConditionTrigger · line 61 - Crossover (
crossover,ta.crossoverin v5)ma3, ma2shortConditionTrigger · line 62 - Valuewhen (
valuewhen,ta.valuewhenin v5)longconmet, open, 0bestpricel · line 67 - Valuewhen (
valuewhen,ta.valuewhenin v5)shortconmet, open, 0bestprices · line 68
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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | long | On | 169 |
| Open short short | short | On | 172 |
| Exit x stop and limit | curStage == 1 | On | 176 |
| Exit x stop and limit | curStage == 2 | On | 179 |
| Exit x stop | activateTrailingOnThirdStep | On “trail on stage 3? tp3=amount tp2=offset” | 184 |
| Exit x stop and limit | activateTrailingOnThirdStep | On “trail on stage 3? tp3=amount tp2=offset” | 186 |
| cancel x | curStage == 3 | On | 188 |
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.
- 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.
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 | 0.0% | +102.5% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +10.0% | +9.8% | 4 | 25% | 2.65 | 5.9% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −2.2% | +8.4% | 3 | 0% | 0.00 | 3.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −15.3% | +16.7% | 20 | 20% | 0.64 | 29.5% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +10.5% | +21.5% | 10 | 20% | 1.88 | 9.2% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −5.2% | +148.3% | 6 | 17% | 0.34 | 8.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −4.7% | +17.1% | 8 | 25% | 0.54 | 6.4% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
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 |
|---|---|---|---|---|---|
| Initial template this page | — | v4 strategy | 0.0% | 0 | 0.0% |
| MACD 50x Leveraged Short Strategy with Real Equity by Noldo | ema valuewhen | v4 strategy | +15,109.2% | 39 | 2,974.0% |
| MACD 50x Leveraged Long Strategy Results with Real Equity by Noldo | ema valuewhen | v4 strategy | +40,225.0% | 38 | 1,581.6% |
| Yesterday's High v.17.07 by tumiza999 | valuewhen ema | v5 strategy | +10.1% | 127 | 1.8% |
| PCT Trailing Stoploss-Strategy by Thumpyr | ema valuewhen | v5 strategy | No trades on this market | ||
| Sentiment Oscillator by dannylimardi | ema valuewhen | v4 strategy | +1.4% | 5 | 20.6% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 38 ms | With a workaround 1,000 bars in 101 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as long = true, long = false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 169, 172) so the engine trades the way the script says.
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © TradingMentalist//@version=4strategy("Initial template",initial_capital=1000, overlay=true, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ordercommentsenterlongcomment = "ENTERLONGCOMMENT"entershortcomment = "ENTERSHORTCOMMENT"exitlongcomment = "EXITLONGCOMMENT"exitshortcomment = "EXITSHORTCOMMENT"////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////inputssidein2 = input(200, step=10, title='lookback for average range (bars)')sidein = input(1, title='filter trades if range is less than (%)')/100equityIn = input(42, title='filter trades if equity is below ema()')sidewayssw = input(false, title='sideways filter?')equitysw = input(false, title='equity filter?')bestpricein = input(0.003,step=0.001, title='best price +/-?')/100//longtpin = input(1,step=0.1, title='long TP %')/100//longslin = input(0.4,step=0.1, title='long SL %')/100//shorttpin = input(1,step=0.1, title='short TP %')/100//shortslin = input(0.4,step=0.1, title='short SL %')/100longinc=input(true, title="include longs?")lConSw2=input(true, title="condition two?")lConSw3=input(true, title="condition three?")shotinc=input(true, title="include shorts?")sConSw2=input(true, title="condition two?")sConSw3=input(true, title="condition three?")percent2points(percent) => strategy.position_avg_price * percent / 100 / syminfo.minticksl = percent2points(input(2, title = "stop loss %%"))tp1 = percent2points(input(3, title = "take profit 1 %%"))tp2 = percent2points(input(7, title = "take profit 2 %%"))tp3 = percent2points(input(22, title = "take profit 3 %%"))activateTrailingOnThirdStep = input(true, title = "trail on stage 3? tp3=amount tp2=offset")////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////filtersside1 = (close[1] + close[sidein2]) / 2side2 = close[1] - close[sidein2] side3 = side2 / side1notsideways = side3 > sideinequityMa = equitysw ? ema(strategy.equity, equityIn) : 0equityCon = strategy.equity >= equityMa////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////functionslongatm = strategy.position_size[0] > 0shortatm = strategy.position_size[0] < 0bought = strategy.opentrades[0] == 1 and strategy.position_size[0] > strategy.position_size[1]sold = strategy.opentrades[0] == 1 and strategy.position_size[0] < strategy.position_size[1]var longconmet = falsevar shortconmet = falseif strategy.position_size[1] > 0 and strategy.position_size[0] == 0 longconmet:=falseif strategy.position_size[1] < 0 and strategy.position_size[0] == 0 shortconmet:=falseexitcomment = longatm ? exitlongcomment : shortatm ? exitshortcomment : ""////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////indicatorsma1 = ema(close, 9)ma2 = ema(close, 21)ma3 = ema(close, 50)plot(ma1, color=color.new(#E8B6B0,50))plot(ma2, color=color.new(#B0E8BE,50))plot(ma3, color=color.new(#00EEFF,50))////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////conditionslongConditionTrigger = crossover(ma2,ma3)shortConditionTrigger = crossover(ma3,ma2)if longConditionTrigger longconmet:=trueif shortConditionTrigger shortconmet:=truebestpricel = valuewhen(longconmet,open,0) * (1-bestpricein)bestprices = valuewhen(shortconmet,open,0) * (1+bestpricein)longCondition1 = longconmet == truelongCondition2 = close[1] <= bestpricellongCondition3 = trueshortCondition1 = shortconmet == trueshortCondition2 = close[1] >= bestpricesshortCondition3 = truecloselong = shortCondition1closeshort = longCondition1longCondition1in = longCondition1longCondition2in = lConSw2 ? longCondition2 : truelongCondition3in = lConSw3 ? longCondition3 : trueshortCondition1in = shortCondition1shortCondition2in = sConSw2 ? shortCondition2: trueshortCondition3in = sConSw3 ? shortCondition3: truelongConditions = longCondition1in and longCondition2in and longCondition3inshortConditions = shortCondition1in and shortCondition2in and shortCondition3in////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////executionlong = sidewayssw ? notsideways and equityCon and longConditions : equityCon and longConditionsshort = sidewayssw ? notsideways and equityCon and shortConditions : equityCon and shortConditions////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////risk//longtplevel = strategy.position_avg_price * (1 + longtpin)//longsllevel = strategy.position_avg_price * (1 - longslin)//shorttplevel = strategy.position_avg_price * (1 - shorttpin)//shortsllevel = strategy.position_avg_price * (1 + shortslin)///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////timeframestartyear = 2000startmonth = 1startday = 1stopyear = 9999stopmonth = 12stopday = 31//(leave as is)startperiod = timestamp(startyear,startmonth,startday,0,0)periodstop = timestamp(stopyear,stopmonth,stopday,0,0)timeframe() => time >= startperiod and time <= periodstop ? true : false///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////exiting::::::::::credit to creator::::::::::adolgov::::::::::https://www.tradingview.com/script/jjhUHcje-Stepped-trailing-strategy-example::::::::::curProfitInPts() => if strategy.position_size > 0 (high - strategy.position_avg_price) / syminfo.mintick else if strategy.position_size < 0 (strategy.position_avg_price - low) / syminfo.mintick else 0 calcStopLossPrice(OffsetPts) => if strategy.position_size > 0 strategy.position_avg_price - OffsetPts * syminfo.mintick else if strategy.position_size < 0 strategy.position_avg_price + OffsetPts * syminfo.mintick else na calcProfitTrgtPrice(OffsetPts) => calcStopLossPrice(-OffsetPts)getCurrentStage() => var stage = 0 if strategy.position_size == 0 stage := 0 if stage == 0 and strategy.position_size != 0 stage := 1 else if stage == 1 and curProfitInPts() >= tp1 stage := 2 else if stage == 2 and curProfitInPts() >= tp2 stage := 3 stagecalcTrailingAmountLevel(points) => var float level = na level := calcProfitTrgtPrice(points) if not na(level) if strategy.position_size > 0 if not na(level[1]) level := max(level[1], level) if not na(level) level := max(high, level) else if strategy.position_size < 0 if not na(level[1]) level := min(level[1], level) if not na(level) level := min(low, level)calcTrailingOffsetLevel(points, offset) => float result = na amountLevel = calcTrailingAmountLevel(points) if strategy.position_size > 0 trailActiveDiff = amountLevel - calcProfitTrgtPrice(points) if trailActiveDiff > 0 result := trailActiveDiff + calcProfitTrgtPrice(offset) else if strategy.position_size < 0 trailActiveDiff = calcProfitTrgtPrice(points) - amountLevel if trailActiveDiff > 0 result := calcProfitTrgtPrice(offset) - trailActiveDiff resultfloat stopLevel = nafloat trailOffsetLevel = nafloat profitLevel = activateTrailingOnThirdStep ? calcTrailingAmountLevel(tp3) : calcProfitTrgtPrice(tp3)trailOffsetLevelTmp = calcTrailingOffsetLevel(tp3, tp2)////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ordersif timeframe() if longinc if strategy.position_size == 0 or strategy.position_size > 0 strategy.entry(id="long", long=true, when=long, comment=enterlongcomment) if shotinc if strategy.position_size == 0 or strategy.position_size < 0 strategy.entry(id="short", long=false, when=short, comment = entershortcomment)curStage = getCurrentStage()if curStage == 1 stopLevel := calcStopLossPrice(sl) strategy.exit("x", loss = sl, profit = tp3, comment = exitcomment)else if curStage == 2 stopLevel := calcStopLossPrice(0) strategy.exit("x", stop = stopLevel, profit = tp3, comment = exitcomment)else if curStage == 3 stopLevel := calcStopLossPrice(-tp1) if activateTrailingOnThirdStep trailOffsetLevel := trailOffsetLevelTmp strategy.exit("x", stop = stopLevel, trail_points = tp3, trail_offset = tp3-tp2, comment = exitcomment) else strategy.exit("x", stop = stopLevel, profit = tp3, comment = exitcomment)else strategy.cancel("x")plot(stopLevel, style = plot.style_linebr, color = color.red)plot(profitLevel, style = plot.style_linebr, color = color.blue)plot(trailOffsetLevel, style = plot.style_linebr, color = color.green)//strategy.exit("stop","long", limit=longtplevel, stop=longsllevel,comment=" ")//strategy.close(id="long", when=closelong, comment = " ")//strategy.exit("stop","short", limit=shorttplevel, stop=shortsllevel,comment = " ")//strategy.close(id="short", when=closeshort, comment = " ")