Pine Script v4 · Strategy
Zignaly Tutorial
A Pine Script v4 strategy with no technical-analysis calculation. It has 10 order rules, 4 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays 0.1% commission. 21 settings; defaults include (STRAT) Strategy Type _L_, (STOPTAKE) Take Profit % {3.0} 1.1 and (STOPTAKE) Stop Loss % {2.0} 2.0.
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 Zignaly Tutorial repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 15 of 15 trades.
- How did Zignaly Tutorial do on BTCUSDT 1D with default settings?
- −0.38%
- From 26 Jan 2024 to 21 Oct 2026, over 78 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Zignaly Tutorial 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 Zignaly Tutorial use a stop loss?
- Yes
- strategy.exit sets a stop on line 589, 591.
- Does Zignaly Tutorial run in Zeal Terminal?
- Yes
- It compiles in 589 ms and runs 1,000 bars in 139 ms, in the browser.
BTCUSDT · 1D · default settings
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −0.38%
- −$3.82
- Buy and hold
- +102.5%
- same period
- Closed trades
- 78
- 18 won · 60 lost
- Profitable
- 23.1%
- of closed trades
- Profit factor
- 0.99
- gross profit ÷ gross loss
- Max drawdown
- 9.97%
- −$104.57
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.
Nothing to point out.
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 tostring → str.tostring, sma → ta.sma, floor → math.floor.
v4 → v5
VerifiedSame 78 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 157: input(type = input.bool) → input.bool()
- Line 160: input(type = input.bool) → input.bool()
- Line 164: input(type = input.float) → input.float()
- Line 165: input(type = input.float) → input.float()
- Line 173: input(type = input.integer) → input.int()
21 more edits
- Line 174: tostring → str.tostring
- Line 180: input(type = input.float) → input.float()
- Line 255: tostring → str.tostring
- Line 258: tostring → str.tostring
- Line 266: tostring → str.tostring
- Line 270: tostring → str.tostring
- Line 274: tostring → str.tostring
- Line 274: tostring → str.tostring
- Line 324: tostring → str.tostring
- Line 327: tostring → str.tostring
- Line 336: tostring → str.tostring
- Line 340: tostring → str.tostring
- Line 344: tostring → str.tostring
- Line 344: tostring → str.tostring
- Line 417: sma → ta.sma
- Line 417: sma → ta.sma
- Line 418: sma → ta.sma
- Line 418: sma → ta.sma
- Line 474: floor → math.floor
- Line 570: floor → math.floor
- Line 574: floor → math.floor
⋯// © ruckard-//@version=4+//@version=5// Current version: v20201031 ( A061 )⋯// Order comments based debug-i_enableOrderCommentDebug = input(true, title="(DEBUG) Enable debug on order comments {True}", type=input.bool)+i_enableOrderCommentDebug = input.bool(true, title="(DEBUG) Enable debug on order comments {True}")i_enableTakeProfit = input(false, "(STOPTAKE) Take Profit? {false}")i_enableStopLoss = input(true, "(STOPTAKE) Stop Loss? {True}")-i_enableTrailingTakeProfit = input(true, title="(TRAILING) Enable Trailing Take Profit (%) {True}", type=input.bool)+i_enableTrailingTakeProfit = input.bool(true, title="(TRAILING) Enable Trailing Take Profit (%) {True}")i_TakeProfit = input(1.1, title="(STOPTAKE) Take Profit % {3.0}") / 100⋯// Trailing Take Profit - Inputs-i_trailingTakeProfitPercentageTrigger = input(1.2, "(TRAILING) Trailing Take Profit Trigger (%) {2.5}",minval=0,step=0.01,type=input.float) * 0.01+i_trailingTakeProfitPercentageTrigger = input.float(1.2, "(TRAILING) Trailing Take Profit Trigger (%) {2.5}",minval=0,step=0.01) * 0.01-i_trailingTakeProfitPercentageOffset = input(25.0, "(TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}",minval=0,step=0.01,type=input.float) * 0.01+i_trailingTakeProfitPercentageOffset = input.float(25.0, "(TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}",minval=0,step=0.01) * 0.01// Zignaly - Email (zignalye)⋯i_zignalyExchangeType = input(_ZIGEXTYPESPOT_, "(ZIG) Exchange Type {Spot}", options=[_ZIGEXTYPESPOT_, _ZIGEXFUTURES_])-i_zignalyLeverage = input(1, "(ZIG) Leverage {1}",minval=1,step=1,maxval=125,type=input.integer)+i_zignalyLeverage = input.int(1, "(ZIG) Leverage {1}",minval=1,step=1,maxval=125)-var i_zignalyLeverage_str = tostring(i_zignalyLeverage) // It needs to run only once+var i_zignalyLeverage_str = str.tostring(i_zignalyLeverage) // It needs to run only oncei_priceDecimalDigits = input(2, "Number of decimal digits for Prices {2}", minval=0, maxval=10, step=1)⋯i_CapitalQuote = input(100.0, title="(CAPITAL) Capital quote invested per order in USDT units {100.0}")-i_CapitalPercentage = input(25.0, title="(CAPITAL) Capital percentage invested per order (%) {25.0}",minval=0,step=0.01,type=input.float) * 0.01+i_CapitalPercentage = input.float(25.0, title="(CAPITAL) Capital percentage invested per order (%) {25.0}",minval=0,step=0.01) * 0.01// INPUTS - END⋯ float _floatEntryQuantityContractsUSDT = _entryQuantityContractsUSDT- _entryQuantityContractsUSDTStr = tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString())+ _entryQuantityContractsUSDTStr = str.tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString()) float _floatCurrentCapital = _currentCapital float _entryQuantityContractsPercent = (_floatEntryQuantityContractsUSDT / _floatCurrentCapital) * 100.00- _entryQuantityContractsPercentStr = tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString())+ _entryQuantityContractsPercentStr = str.tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString()) // This is actually not needed because with pyramiding=0 it's impossible that an order is scaled (and thus modified)⋯ if (i_enableStopLoss and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))- _zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((nz(_constantBuyStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote+ _zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + str.tostring((nz(_constantBuyStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else⋯ if (i_enableTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))- _zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote+ _zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "" + str.tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else⋯ if (i_enableTrailingTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))- _zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote+ _zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + str.tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + str.tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else⋯ float _floatEntryQuantityContractsUSDT = _entryQuantityContractsUSDT- _entryQuantityContractsUSDTStr = tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString())+ _entryQuantityContractsUSDTStr = str.tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString()) float _floatCurrentCapital = _currentCapital float _entryQuantityContractsPercent = (_floatEntryQuantityContractsUSDT / _floatCurrentCapital) * 100.00- _entryQuantityContractsPercentStr = tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString())+ _entryQuantityContractsPercentStr = str.tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString()) // This is actually not needed because with pyramiding=0 it's impossible that an order is scaled (and thus modified)⋯ if (i_enableStopLoss and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))- _zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((nz(_constantSellStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote+ _zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + str.tostring((nz(_constantSellStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else⋯ if (i_enableTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))- _zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote+ _zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + str.tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else⋯ if (i_enableTrailingTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))- _zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote+ _zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + str.tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + str.tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else⋯// shortCondition = crossunder(sma(close, 14), sma(close, 28))-longCondition = sma(close, 14) >= sma(close, 28)+longCondition = ta.sma(close, 14) >= ta.sma(close, 28)-shortCondition = sma(close, 14) < sma(close, 28)+shortCondition = ta.sma(close, 14) < ta.sma(close, 28)// Simple Logic to go LONG/LONG or go SHORT/SHORT - END⋯// We assume the current price is current bar close-entryQuantityContracts = (floor(((entryQuantity / close) * entryQuantityContractsReducer) * contractMultiplier) / contractMultiplier)+entryQuantityContracts = (math.floor(((entryQuantity / close) * entryQuantityContractsReducer) * contractMultiplier) / contractMultiplier)entryQuantityContractsUSDT = entryQuantityContracts * (close)⋯longTrailingTakeProfitOffsetFloat = longTmpTtpTop_value - longTmpTtpBaseValue-float longTrailingTakeProfitOffsetTick = floor (longTrailingTakeProfitOffsetFloat / syminfo.mintick)+float longTrailingTakeProfitOffsetTick = math.floor (longTrailingTakeProfitOffsetFloat / syminfo.mintick)shortTmpTtpBaseValue = positionPrice * (1 - i_trailingTakeProfitPercentageTrigger)⋯shortTrailingTakeProfitOffsetFloat = shortTmpTtpBaseValue - shortTmpTtpBottomValue-float shortTrailingTakeProfitOffsetTick = floor (shortTrailingTakeProfitOffsetFloat / syminfo.mintick)+float shortTrailingTakeProfitOffsetTick = math.floor (shortTrailingTakeProfitOffsetFloat / syminfo.mintick)if i_enableTrailingTakeProfit⋯Same 78 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 149: input() → input.bool()
- Line 158: input() → input.bool()
- Line 159: input() → input.bool()
- Line 161: input() → input.float()
- Line 162: input() → input.float()
- Line 175: input() → input.int()
3 more edits
- Line 177: input() → input.int()
- Line 178: input() → input.int()
- Line 179: input() → input.float()
⋯// Strategy - Inputs-i_enableZignalyAlert = input(true, "(ZIG) Enable Alert message {True}")+i_enableZignalyAlert = input.bool(true, "(ZIG) Enable Alert message {True}")_ZIGHYBRIDINTEGRATION_ = "Hybrid" , _ZIGTVONLYINTEGRATION_ = "TradingView only"⋯i_enableOrderCommentDebug = input.bool(true, title="(DEBUG) Enable debug on order comments {True}")-i_enableTakeProfit = input(false, "(STOPTAKE) Take Profit? {false}")+i_enableTakeProfit = input.bool(false, "(STOPTAKE) Take Profit? {false}")-i_enableStopLoss = input(true, "(STOPTAKE) Stop Loss? {True}")+i_enableStopLoss = input.bool(true, "(STOPTAKE) Stop Loss? {True}")i_enableTrailingTakeProfit = input.bool(true, title="(TRAILING) Enable Trailing Take Profit (%) {True}")-i_TakeProfit = input(1.1, title="(STOPTAKE) Take Profit % {3.0}") / 100+i_TakeProfit = input.float(1.1, title="(STOPTAKE) Take Profit % {3.0}") / 100-i_StopLoss = input(2.0, title="(STOPTAKE) Stop Loss % {2.0}", minval=0.01 ) / 100+i_StopLoss = input.float(2.0, title="(STOPTAKE) Stop Loss % {2.0}", minval=0.01 ) / 100// Trailing Take Profit - Inputs⋯var i_zignalyLeverage_str = str.tostring(i_zignalyLeverage) // It needs to run only once-i_priceDecimalDigits = input(2, "Number of decimal digits for Prices {2}", minval=0, maxval=10, step=1)+i_priceDecimalDigits = input.int(2, "Number of decimal digits for Prices {2}", minval=0, maxval=10, step=1)// Decimal - Inputs-i_contractMaximumDecimalNumber = input(3, title="(DECIMAL) Maximum number of decimal for contracts {3}",minval=0)+i_contractMaximumDecimalNumber = input.int(3, title="(DECIMAL) Maximum number of decimal for contracts {3}",minval=0)-i_tooRecentMinutesNumber = input(6, "(RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}", minval=1, maxval=100, step=1)+i_tooRecentMinutesNumber = input.int(6, "(RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}", minval=1, maxval=100, step=1)-i_CapitalQuote = input(100.0, title="(CAPITAL) Capital quote invested per order in USDT units {100.0}")+i_CapitalQuote = input.float(100.0, title="(CAPITAL) Capital quote invested per order in USDT units {100.0}")i_CapitalPercentage = input.float(25.0, title="(CAPITAL) Capital percentage invested per order (%) {25.0}",minval=0,step=0.01) * 0.01⋯Does it run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L406:C4: a 'bool' cannot be 'na' in Pine Script v6 — declare it as true or false. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © ruckard-//@version=5+//@version=6// Current version: v20201031 ( A061 )⋯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 |
|---|---|---|---|
| (ZIG) Enable Alert message {True} | true | bool | entry [B] close [B] entry [S] close [S] exit [SL/TP] |
| (ZIG) Integration type | _ZIGTVONLYINTEGRATION_ | value · options [_ZIGTVONLYINTEGRATION_, _ZIGHYBRIDINTEGRATION_] | line 265 line 269 line 273 line 335 line 339 line 343 |
| (ZIG) Provider type | _ZIGCOPYTRADERPROVIDER_ | value · options [_ZIGSIGNALPROVIDER_, _ZIGCOPYTRADERPROVIDER_] | line 278 line 348 line 467 |
| (STRAT) Strategy Type | _L_ | value · options [L_S, _L_, _S_] | line 479 line 498 line 517 |
| (DEBUG) Enable debug on order comments {True} | true | bool | line 389 |
| (STOPTAKE) Take Profit? {false} | false | bool | line 269 line 339 exit [SL/TP] |
| (STOPTAKE) Stop Loss? {True} | true | bool | line 265 line 335 exit [SL/TP] |
| (TRAILING) Enable Trailing Take Profit (%) {True} | true | bool | line 273 line 343 line 575 exit [SL/TP] |
| (STOPTAKE) Take Profit % {3.0} | 1.1 | float | _zignaleTakeProfitCombo LongTakeProfit ShortTakeProfit |
| (STOPTAKE) Stop Loss % {2.0} | 2.0 | float · min 0.01 | newBuyStopLoss newSellStopLoss |
| (TRAILING) Trailing Take Profit Trigger (%) {2.5} | 1.2 | float · min 0 · step 0.01 | _zignaleTrailingTakeProfitCombo longTrailingTakeProfitPrice shortTrailingTakeProfitPrice longTmpTtpBaseValue shortTmpTtpBaseValue |
| (TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0} | 25.0 | float · min 0 · step 0.01 | _zignaleTrailingTakeProfitCombo longTmpTtpTop_value shortTmpTtpBottomValue |
| (ZIG) Zignaly Alert Type {WebHook} | _ZIGNALYW_ | value · options [_ZIGNALYW_, _ZIGNALYE_] | line 209 |
| (ZIG) Exchange | _ZIGEXBINANCE_ | value · options [_ZIGEXBINANCE_, _ZIGEXKUCOIN_] | zignalyCommonAlertMessage |
| (ZIG) Exchange Type {Spot} | _ZIGEXTYPESPOT_ | value · options [_ZIGEXTYPESPOT_, _ZIGEXFUTURES_] | zignalyCommonAlertMessage |
| (ZIG) Leverage {1} | 1 | int (written input.integer) · min 1 · max 125 · step 1 | i_zignalyLeverage_str |
| Number of decimal digits for Prices {2} | 2 | int · min 0 · max 10 · step 1 | line 235 line 236 |
| (DECIMAL) Maximum number of decimal for contracts {3} | 3 | int · min 0 | contractMultiplier |
| (RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6} | 6 | int · min 1 · max 100 · step 1 | i_tooRecentMinutesNumber_ms |
| (CAPITAL) Capital quote invested per order in USDT units {100.0} | 100.0 | float | entryQuantity |
| (CAPITAL) Capital percentage invested per order (%) {25.0} | 25.0 | float · min 0 · step 0.01 | entryQuantity |
What it calculates
No technical-analysis calculation: the script works on prices and settings directly.
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 63 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 [B] long | LONG | On | 484 |
| Close [B] | LONG_CLOSE | On | 493 |
| Open [S] short | SHORT | On | 503 |
| Close [S] | SHORT_CLOSE | On | 512 |
| Open [B] long | LONG | On | 533 |
| Close [B] | LONG_CLOSE | On | 541 |
| Open [S] short | SHORT | On | 547 |
| Close [S] | SHORT_CLOSE | On | 555 |
| Exit [SL/TP] stop and limit | every bar | On | 589 |
| Exit [SL/TP] stop and limit | every bar | On | 591 |
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, and the live replay matched history.
- 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.4% | +102.5% | 78 | 23% | 0.99 | 10.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −3.6% | +5.5% | 38 | 26% | 0.61 | 4.6% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +17.8% | +9.8% | 76 | 22% | 1.54 | 9.5% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −0.2% | +8.4% | 46 | 30% | 0.99 | 4.2% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +30.7% | +16.7% | 100 | 20% | 1.60 | 9.2% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +6.0% | +21.5% | 40 | 28% | 1.43 | 4.7% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −2.9% | +148.3% | 94 | 14% | 0.93 | 24.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −5.2% | +17.1% | 40 | 35% | 0.56 | 8.6% | 8 May 2026 – 21 Oct 2026 |
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 | 22 | 18% | $2.60 |
| Sideways market | 37 | 27% | $40.19 |
| Falling market | 19 | 21% | −$46.61 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
13.6%
The 95th percentile of the worst drawdown when the same 78 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 6.4% to 13.6%; the tick is what actually happened, 9.8%. Order luck alone moves it this much.
All 78 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 23 Feb 2024 51,288.40 | 20 Mar 2024 60,801.00 | 26 | $37.60 |
| long | 21 Mar 2024 67,840.50 | 21 Mar 2024 66,483.70 | 0 | −$4.47 |
| long | 22 Mar 2024 65,501.30 | 22 Mar 2024 64,191.20 | 0 | −$4.32 |
| long | 23 Mar 2024 63,796.70 | 29 Mar 2024 70,780.60 | 6 | $20.55 |
| long | 6 Apr 2024 67,820.60 | 12 Apr 2024 66,464.20 | 6 | −$4.47 |
| long | 13 Apr 2024 67,116.50 | 13 Apr 2024 65,774.20 | 0 | −$4.43 |
| long | 14 Apr 2024 63,924.50 | 14 Apr 2024 62,646.00 | 0 | −$5.62 |
| long | 15 Apr 2024 65,661.90 | 15 Apr 2024 64,348.60 | 0 | −$4.33 |
| long | 19 May 2024 66,915.20 | 14 Jun 2024 65,576.90 | 26 | −$4.41 |
| long | 15 Jun 2024 66,044.00 | 17 Jun 2024 66,676.90 | 2 | $1.50 |
| long | 21 Jul 2024 67,140.00 | 21 Jul 2024 65,797.10 | 0 | −$4.43 |
| long | 22 Jul 2024 68,165.40 | 22 Jul 2024 66,802.00 | 0 | −$4.49 |
| long | 23 Jul 2024 67,532.00 | 23 Jul 2024 66,181.40 | 0 | −$4.45 |
| long | 24 Jul 2024 65,936.00 | 25 Jul 2024 64,617.30 | 1 | −$4.35 |
| long | 26 Jul 2024 65,800.00 | 1 Aug 2024 64,483.90 | 6 | −$4.34 |
| long | 2 Aug 2024 65,354.00 | 2 Aug 2024 64,046.90 | 0 | −$4.31 |
| long | 3 Aug 2024 61,498.30 | 3 Aug 2024 60,268.30 | 0 | −$5.41 |
| long | 4 Aug 2024 60,698.00 | 4 Aug 2024 59,484.00 | 0 | −$5.34 |
| long | 5 Aug 2024 58,161.00 | 5 Aug 2024 56,997.80 | 0 | −$5.11 |
| long | 6 Aug 2024 54,018.80 | 8 Aug 2024 55,133.80 | 2 | $4.02 |
| long | 27 Aug 2024 62,834.00 | 27 Aug 2024 61,577.30 | 0 | −$4.14 |
| long | 28 Aug 2024 59,415.00 | 28 Aug 2024 58,226.70 | 0 | −$5.22 |
| long | 29 Aug 2024 59,034.90 | 30 Aug 2024 57,854.20 | 1 | −$5.19 |
| long | 31 Aug 2024 59,124.00 | 1 Sep 2024 57,941.50 | 1 | −$5.20 |
| long | 2 Sep 2024 57,301.80 | 4 Sep 2024 56,155.70 | 2 | −$5.04 |
| long | 5 Sep 2024 57,970.90 | 5 Sep 2024 56,811.50 | 0 | −$5.10 |
| long | 6 Sep 2024 56,180.00 | 6 Sep 2024 55,056.40 | 0 | −$4.94 |
| long | 22 Sep 2024 63,349.00 | 1 Oct 2024 62,082.00 | 9 | −$4.18 |
| long | 2 Oct 2024 60,804.90 | 10 Oct 2024 59,588.80 | 8 | −$4.01 |
| long | 11 Oct 2024 60,326.40 | 12 Oct 2024 62,540.00 | 1 | $6.27 |
| long | 18 Oct 2024 67,421.80 | 23 Oct 2024 66,073.30 | 5 | −$4.45 |
| long | 24 Oct 2024 66,668.70 | 30 Dec 2024 93,738.20 | 67 | $80.73 |
| long | 15 Jan 2025 96,560.90 | 3 Feb 2025 94,629.60 | 19 | −$4.24 |
| long | 4 Feb 2025 101,329.00 | 4 Feb 2025 99,301.90 | 0 | −$4.45 |
| long | 5 Feb 2025 97,763.10 | 6 Feb 2025 95,807.90 | 1 | −$4.30 |
| long | 7 Feb 2025 96,554.40 | 8 Feb 2025 96,506.80 | 1 | −$0.48 |
| long | 31 Mar 2025 82,390.00 | 6 Apr 2025 80,742.20 | 6 | −$5.43 |
| long | 7 Apr 2025 78,430.00 | 7 Apr 2025 76,861.40 | 0 | −$5.17 |
| long | 22 Apr 2025 87,516.20 | 9 Jun 2025 105,734.00 | 48 | $36.05 |
| long | 20 Jun 2025 104,659.00 | 20 Jun 2025 102,565.00 | 0 | −$4.60 |
| long | 21 Jun 2025 103,298.00 | 21 Jun 2025 101,232.00 | 0 | −$4.54 |
| long | 22 Jun 2025 102,120.00 | 22 Jun 2025 100,078.00 | 0 | −$4.49 |
| long | 23 Jun 2025 100,964.00 | 24 Jun 2025 105,334.00 | 1 | $8.33 |
| long | 5 Jul 2025 107,984.00 | 6 Aug 2025 114,130.00 | 32 | $11.85 |
| long | 17 Aug 2025 117,381.00 | 18 Aug 2025 115,033.00 | 1 | −$5.16 |
| long | 19 Aug 2025 116,227.00 | 19 Aug 2025 113,902.00 | 0 | −$5.11 |
| long | 20 Aug 2025 112,873.00 | 25 Aug 2025 110,615.00 | 5 | −$4.96 |
| long | 26 Aug 2025 110,112.00 | 27 Aug 2025 111,763.00 | 1 | $2.86 |
| long | 15 Sep 2025 115,268.00 | 22 Sep 2025 112,963.00 | 7 | −$5.07 |
| long | 23 Sep 2025 112,651.00 | 25 Sep 2025 110,398.00 | 2 | −$4.95 |
| long | 26 Sep 2025 108,995.00 | 1 Oct 2025 114,049.00 | 5 | $9.66 |
| long | 6 Oct 2025 123,482.00 | 7 Oct 2025 121,013.00 | 1 | −$5.43 |
| long | 8 Oct 2025 121,333.00 | 10 Oct 2025 118,906.00 | 2 | −$5.33 |
| long | 11 Oct 2025 112,775.00 | 11 Oct 2025 110,519.00 | 0 | −$4.96 |
| long | 12 Oct 2025 110,644.00 | 16 Oct 2025 108,432.00 | 4 | −$4.86 |
| long | 17 Oct 2025 108,194.00 | 17 Oct 2025 106,030.00 | 0 | −$4.76 |
| long | 18 Oct 2025 106,432.00 | 20 Oct 2025 108,643.00 | 2 | $3.99 |
| long | 11 Dec 2025 92,015.40 | 11 Dec 2025 90,175.10 | 0 | −$4.05 |
| long | 12 Dec 2025 92,513.40 | 12 Dec 2025 90,663.10 | 0 | −$4.07 |
| long | 13 Dec 2025 90,268.40 | 14 Dec 2025 88,463.10 | 1 | −$3.97 |
| long | 15 Dec 2025 88,172.20 | 15 Dec 2025 86,408.70 | 0 | −$3.88 |
| long | 16 Dec 2025 86,432.10 | 18 Dec 2025 84,703.40 | 2 | −$3.80 |
| long | 19 Dec 2025 85,516.40 | 20 Dec 2025 88,136.90 | 1 | $4.89 |
| long | 7 Jan 2026 93,748.00 | 7 Jan 2026 91,873.00 | 0 | −$4.12 |
| long | 8 Jan 2026 91,364.20 | 8 Jan 2026 89,536.90 | 0 | −$4.02 |
| long | 9 Jan 2026 91,100.00 | 20 Jan 2026 89,278.00 | 11 | −$4.00 |
| long | 21 Jan 2026 88,427.70 | 25 Jan 2026 86,659.10 | 4 | −$3.89 |
| long | 26 Jan 2026 86,670.40 | 29 Jan 2026 89,300.00 | 3 | $4.91 |
| long | 10 Mar 2026 68,432.20 | 27 Mar 2026 67,063.50 | 17 | −$4.51 |
| long | 28 Mar 2026 66,407.30 | 29 Mar 2026 65,079.10 | 1 | −$4.38 |
| long | 30 Mar 2026 66,010.90 | 31 Mar 2026 66,797.40 | 1 | $1.96 |
| long | 14 Apr 2026 74,418.00 | 24 May 2026 76,752.00 | 40 | $6.55 |
| long | 14 Jul 2026 62,334.50 | 5 Aug 2026 64,106.50 | 22 | $4.94 |
| long | 20 Aug 2026 69,334.80 | 18 Sep 2026 76,417.00 | 29 | $20.81 |
| long | 23 Sep 2026 86,208.60 | 23 Sep 2026 84,484.40 | 0 | −$3.79 |
| long | 24 Sep 2026 84,397.60 | 28 Sep 2026 82,709.60 | 4 | −$3.71 |
| long | 29 Sep 2026 83,500.00 | 8 Oct 2026 81,830.00 | 9 | −$3.67 |
| long | 9 Oct 2026 81,754.50 | 15 Oct 2026 80,119.40 | 6 | −$5.39 |
Similar scripts
No other indicator or strategy here shares enough of its calculations.
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 589 ms | With a workaround 1,000 bars in 139 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.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © ruckard//@version=4// Current version: v20201031 ( A061 )// Tradingview Public description - BEGIN// // This strategy serves as a beginner's guide to connect TradingView signals to Zignaly Crypto Trading Platform.// // It was originally tested at BTCUSDT pair and 1D timeframe.// The strategy is a slightly modified copy of default TradingView strategy that appears when you create a blank new strategy.// It decides to go long when 14-period SMA crosses over 28-period SMA and goes short when 14-period SMA crosses under 28-period SMA.//// Before using this documentation it's recommended that you:// [LIST]// [*] Use default TradingView strategy script or another script and setup its associated alert manually. Just make the alert pop-up in the screen.// [*] Create a 'Copy-Trader provider' (or Signal Provider) in Zignaly and send signals to it either thanks to your browser or with some basic programming.// [/LIST]// [B]SETTINGS[/B]// [B]__ SETTINGS - Capital[/B]// [LIST]// [*] (CAPITAL) Capital quote invested per order in USDT units {100.0}. This setting is only used when '(ZIG) Provider type' is set to 'Signal Provider'.// [*] (CAPITAL) Capital percentage invested per order (%) {25.0}. This setting is only used when '(ZIG) Provider type' is set to 'Copy Trader Provider'.// [/LIST]// [B]__ SETTINGS - Misc[/B]// [LIST]// [*] (ZIG) Enable Alert message {True}: Whether to enable alert message or not.// [*] (DEBUG) Enable debug on order comments {True}: Whether to show alerts on order comments or not.// [*] Number of decimal digits for Prices {2}.// [*] (DECIMAL) Maximum number of decimal for contracts {3}.// [/LIST]// [B]__ SETTINGS - Zignaly[/B]// [LIST]// [*] (ZIG) Integration type {TradingView only}: [b]Hybrid[/b]: Both TradingView and Zignaly handle take profit, trailing stops and stop losses. Useful if you are scared about TradingView not firing an alert. It might arise problems if TradingView and Zignaly get out of sync. [b]TradingView only[/b]: TradingView sends entry and exit orders to Zignaly so that Zignaly only buys or sells. Zignaly won't handle stop loss or other settings on its own.// [*] (ZIG) Zignaly Alert Type {WebHook}: 'Email' or 'WebHook'.// [*] (ZIG) Provider type {Copy Trader Provider}: 'Copy Trader Provider' or 'Signal Provider'. 'Copy Trader Provider' sends a percentage to manage. 'Signal Provider' sends a quote to manage.// [*] (ZIG) Exchange: 'Binance' or 'Kucoin'.// [*] (ZIG) Exchange Type {Spot}: 'Spot' or 'Futures'.// [*] (ZIG) Leverage {1}. Set it to '1' when '(ZIG) Exchange Type' is set to 'Spot'.// [/LIST]// [B]__ SETTINGS - Strategy[/B]// [LIST]// [*] (STRAT) Strategy Type: 'Long and Short', 'Long Only' or 'Short Only'.// [*] (STOPTAKE) Take Profit? {false}: Whether to enable Take Profit.// [*] (STOPTAKE) Stop Loss? {True}: Whether to enable Stop Loss.// [*] (TRAILING) Enable Trailing Take Profit (%) {True}: Whether to enable Trailing Take Profit.// [*] (STOPTAKE) Take Profit % {3.0}: Take profit percentage. This setting is only used when '(STOPTAKE) Take Profit?' setting is set to true.// [*] (STOPTAKE) Stop Loss % {2.0}: Stop loss percentage. This setting is only used when '(STOPTAKE) Stop Loss?' setting is set to true.// [*] (TRAILING) Trailing Take Profit Trigger (%) {2.5}: Trailing Stop Trigger Percentage. This setting is only used when '(TRAILING) Enable Trailing Take Profit (%)' setting is set to true.// [*] (TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}: Trailing Stop Distance Percentage. This setting is only used when '(TRAILING) Enable Trailing Take Profit (%)' setting is set to true.// [*] (RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}.// [/LIST]// [B]DEFAULT SETTINGS[/B]// By default this strategy has been setup with these beginner settings:// [LIST]// [*] '(ZIG) Integration type' : TradingView only// [*] '(ZIG) Provider type' : 'Copy Trader Provider'// [*] '(ZIG) Exchange' : 'Binance'// [*] '(ZIG) Exchange Type' : 'Spot'// [*] '(STRAT) Strategy Type' : 'Long Only'// [*] '(ZIG) Leverage' : '1' (Or no leverage)// [/LIST]// but you can change those settings if needed.// [B]FIRST STEP[/B]// [LIST]// [*] For both future or spot markets you should make sure to change '(ZIG) Zignaly Alert Type' to match either WebHook or Email. If you have a non paid account in TradingView as in October 2020 you would have to use Email which it's free to use.// [/LIST]// [B]RECOMMENDED SETTINGS[/B]// [B]__ RECOMMENDED SETTINGS - Spot markets[/B]// [LIST]// [*] '(ZIG) Exchange Type' setting should be set to 'Spot'// [*] '(STRAT) Strategy Type' setting should be set to 'Long Only'// [*] '(ZIG) Leverage' setting should be set to '1'// [/LIST]// [B]__ RECOMMENDED SETTINGS - Future markets[/B]// [LIST]// [*] '(ZIG) Exchange Type' setting should be set to 'Futures'// [*] '(STRAT) Strategy Type' setting should be set to 'Long and Short'// [*] '(ZIG) Leverage' setting might be changed if desired.// [/LIST]// [B]__ RECOMMENDED SETTINGS - Signal Providers[/B]// [LIST]// [*] '(ZIG) Provider type' setting should be set to 'Signal Provider'// [*] '(CAPITAL) Capital quote invested per order in USDT units' setting might be changed if desired.// [/LIST]// [B]__ RECOMMENDED SETTINGS - Copy Trader Providers[/B]// [LIST]// [*] '(ZIG) Provider type' setting should be set to 'Copy Trader Provider'// [*] '(CAPITAL) Capital percentage invested per order (%)' setting might be changed if desired.// [*] Strategy Properties setting: 'Initial Capital' might be changed if desired.// [/LIST]// [B]INTEGRATION TYPE EXPLANATION[/B]// [LIST]// [*] 'Hybrid': Both TradingView and Zignaly handle take profit, trailing stops and stop losses. Useful if you are scared about TradingView not firing an alert. It might arise problems if TradingView and Zignaly get out of sync.// [*] 'TradingView only': TradingView sends entry and exit orders to Zignaly so that Zignaly only buys or sells. Zignaly won't handle stop loss or other settings on its own.// [/LIST]// [B]HOW TO USE THIS STRATEGY[/B]// [LIST]// [*] Beginner: Copy and paste the strategy and change it to your needs. Turn off '(DEBUG) Enable debug on order comments' setting.// [*] Medium: Reuse functions and inputs from this strategy into your own as if it was a library.// [*] Advanced: Check Strategy Tester. List of trades. Copy and paste the different suggested 'alert_message' variable contents to your script and change them to your needs.// [*] Expert: You needed a way to pass data from TradingView script to the alert. Now you know it's the 'alert_message' variable. You can find several examples in the source code using the variable. You also have seen 'ALERTS SETUP' explanation below. An additional quick look at 'Strategy Tester', 'List of Trades' and you are ready to go.// [/LIST]// [B] ALERTS SETUP[/B]// This is the important piece of information that allows you to connect TradingView to Zignaly in a semi-automatic manner.// [B] __ ALERTS SETUP - WebHook[/B]// [LIST]// [*] Webhook URL: https : // zignaly . com / api / signals.php?key=MYSECRETKEY// [*] Message: { {{strategy.order.alert_message}} , "key" : "MYSECRETKEY" }// [/LIST]// [B] __ ALERTS SETUP - Email[/B]// [LIST]// [*] Setup a new Hotmail account// [*] Add it as an 'SMS email' in TradingView Profile settings page.// [*] Confirm your own the email address// [*] Create a rule in your Hotmail account that 'Redirects' (not forwards) emails to 'signals @ zignaly . email' when (1): 'Subject' includes 'Alert', (2): 'Email body' contains string 'MYZIGNALYREDIRECTTRIGGER' and (3): 'From' contains 'noreply @ tradingview . com'.// [*] In 'More Actions' check: Send Email-to-SMS// [*] Message: ||{{strategy.order.alert_message}}||key=MYSECRETKEY||// MYZIGNALYREDIRECTTRIGGER// [/LIST]// '(DEBUG) Enable debug on order comments' is turned on by default so that you can see in the Strategy Tester. List of Trades. The different orders alert_message that would have been sent to your alert. You might want to turn it off it some many letters in the screen is problem.// [B]STRATEGY ADVICE[/B]// [LIST]// [*] If you turn on 'Take Profit' then turn off 'Trailing Take Profit'.// [/LIST]//// [B]ZIGNALY SIDE ADVICE[/B]// [LIST]// [*] If you are a 'Signal Provider' make sure that 'Allow reusing the same signalId if there isn't any open position using it?' setting in the profile tab is set to true.// [*] You can find your 'MYSECRETKEY' in your 'Copy Trader/Signal' provider Edit tab at 'Signal URL'.// [/LIST]//// [B]ADDITIONAL ZIGNALY DOCUMENTATION[/B]// This beginner's guide is quite basic and meant to be an introduction. Please read additional documentation to learn what you actually can do with Zignaly.// [LIST]// [*] docs . zignaly . com / signals / how-to -- How to send signals to Zignaly// [*] 3 Ways to send signals to Zignaly// [*] SIGNALS// [/LIST]//// [B]FINAL REMARKS[/B]// [LIST]// [*] This strategy tries to match the Pine Script Coding Conventions as best as possible.// [*] You can check my 'Ruckard TradingLatino' strategy for a more complex strategy that it's also integrated with Zignaly. Unfortunatley it does not use Pine Script Coding Conventions as much.// [/LIST]// Tradingview Public description - ENDstrategy("Zignaly Tutorial A061", shorttitle="A061ZigTuto", overlay=true, max_bars_back=5000, calc_on_order_fills=false, calc_on_every_tick=false, pyramiding=0, initial_capital=1000, slippage=1, commission_type=strategy.commission.percent, commission_value=0.1)// INPUTS - BEGIN// Strategy - Inputsi_enableZignalyAlert = input(true, "(ZIG) Enable Alert message {True}")_ZIGHYBRIDINTEGRATION_ = "Hybrid" , _ZIGTVONLYINTEGRATION_ = "TradingView only"i_zignalyIntegrationType = input(_ZIGTVONLYINTEGRATION_, "(ZIG) Integration type", options=[_ZIGTVONLYINTEGRATION_, _ZIGHYBRIDINTEGRATION_])_ZIGSIGNALPROVIDER_ = "Signal Provider" , _ZIGCOPYTRADERPROVIDER_ = "Copy Trader Provider"i_zignalyProviderType = input(_ZIGCOPYTRADERPROVIDER_, "(ZIG) Provider type", options=[_ZIGSIGNALPROVIDER_, _ZIGCOPYTRADERPROVIDER_])L_S = "Long and Short" , _L_ = "Long Only" , _S_ = "Short Only"i_strategyType = input(_L_, "(STRAT) Strategy Type", options=[L_S, _L_, _S_])// Order comments based debugi_enableOrderCommentDebug = input(true, title="(DEBUG) Enable debug on order comments {True}", type=input.bool)i_enableTakeProfit = input(false, "(STOPTAKE) Take Profit? {false}")i_enableStopLoss = input(true, "(STOPTAKE) Stop Loss? {True}")i_enableTrailingTakeProfit = input(true, title="(TRAILING) Enable Trailing Take Profit (%) {True}", type=input.bool)i_TakeProfit = input(1.1, title="(STOPTAKE) Take Profit % {3.0}") / 100i_StopLoss = input(2.0, title="(STOPTAKE) Stop Loss % {2.0}", minval=0.01 ) / 100// Trailing Take Profit - Inputsi_trailingTakeProfitPercentageTrigger = input(1.2, "(TRAILING) Trailing Take Profit Trigger (%) {2.5}",minval=0,step=0.01,type=input.float) * 0.01i_trailingTakeProfitPercentageOffset = input(25.0, "(TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}",minval=0,step=0.01,type=input.float) * 0.01// Zignaly - Email (zignalye)_ZIGNALYE_="Email", _ZIGNALYW_="WebHook"i_zignalyAlertType = input(_ZIGNALYW_, "(ZIG) Zignaly Alert Type {WebHook}", options=[_ZIGNALYW_, _ZIGNALYE_])_ZIGEXBINANCE_ = "Binance" , _ZIGEXKUCOIN_ = "Kucoin"i_zignalyExchange = input(_ZIGEXBINANCE_, "(ZIG) Exchange", options=[_ZIGEXBINANCE_, _ZIGEXKUCOIN_])_ZIGEXTYPESPOT_ = "spot" , _ZIGEXFUTURES_ = "futures"i_zignalyExchangeType = input(_ZIGEXTYPESPOT_, "(ZIG) Exchange Type {Spot}", options=[_ZIGEXTYPESPOT_, _ZIGEXFUTURES_])i_zignalyLeverage = input(1, "(ZIG) Leverage {1}",minval=1,step=1,maxval=125,type=input.integer)var i_zignalyLeverage_str = tostring(i_zignalyLeverage) // It needs to run only oncei_priceDecimalDigits = input(2, "Number of decimal digits for Prices {2}", minval=0, maxval=10, step=1)// Decimal - Inputsi_contractMaximumDecimalNumber = input(3, title="(DECIMAL) Maximum number of decimal for contracts {3}",minval=0)i_tooRecentMinutesNumber = input(6, "(RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}", minval=1, maxval=100, step=1)i_CapitalQuote = input(100.0, title="(CAPITAL) Capital quote invested per order in USDT units {100.0}")i_CapitalPercentage = input(25.0, title="(CAPITAL) Capital percentage invested per order (%) {25.0}",minval=0,step=0.01,type=input.float) * 0.01// INPUTS - END// Strategy - INIT - BEGIN// Dynamic Trailing Take Profit - Variablesvar int buyOrderOpenBarIndex = navar int sellOrderOpenBarIndex = navar float buyStopLoss = navar float sellStopLoss = navar float newBuyStopLoss = navar float newSellStopLoss = na// Handle to avoid two long and short orders being too next to each othervar bool _oldInsideABuyOrder = falsevar bool oldInsideASellOrder = falsevar bool insideABuyOrder = falsevar bool insideASellOrder = false_oldInsideABuyOrder := insideABuyOrderoldInsideASellOrder := insideASellOrdervar int lastOrderOpenBarTime = na// Handle recalculate after Stop Loss / Take Profit orderif (strategy.position_size == 0.0) insideABuyOrder := false insideASellOrder := falseelse lastOrderOpenBarTime := time_close// ZignalyexchangeTickerID = syminfo.basecurrency + syminfo.currencyvar string zignalySeparator = ","var string zignalyQuote = "\""var string zignalyEquals = "="if ( i_zignalyAlertType == _ZIGNALYE_) zignalySeparator := "||" zignalyQuote := "" zignalyEquals := "="else zignalySeparator := "," zignalyQuote := "\"" zignalyEquals := ":"zignalyCommonAlertMessage = zignalyQuote + "exchange" + zignalyQuote + zignalyEquals + zignalyQuote + i_zignalyExchange + zignalyQuote + zignalySeparator + zignalyQuote + "exchangeAccountType" + zignalyQuote + zignalyEquals + zignalyQuote + i_zignalyExchangeType + zignalyQuote + zignalySeparator + zignalyQuote + "pair" + zignalyQuote + zignalyEquals + zignalyQuote + "" + exchangeTickerID + zignalyQuote + zignalySeparator + zignalyQuote + "leverage" + zignalyQuote + zignalyEquals + zignalyQuote + i_zignalyLeverage_str + zignalyQuotevar string tmpOrderComment = navar string tmpOrderAlertMessage = navar int i_tooRecentMinutesNumber_ms = i_tooRecentMinutesNumber * 60 * 1000 // Convert minutes into milliseconds only once// Strategy - INIT - END// FUNCTIONS - BEGIN// Decimals - Functionsf_getContractMultiplier(_contractMaximumDecimalNumber) => _contractMultiplier = 1 if (_contractMaximumDecimalNumber == 0) _contractMultiplier // Return 1 else for _counter = 1 to _contractMaximumDecimalNumber _contractMultiplier:= _contractMultiplier * 10 _contractMultiplierf_priceDecimalDigitsZeroString () => // Dependencies: i_priceDecimalDigits (initialized in inputs). _zeroString = "" if not (i_priceDecimalDigits == 0) for _digit = 1 to i_priceDecimalDigits _zeroString := _zeroString + "0" _zeroString// Zignalye - Functions - BEGINf_getZignalyLongAlertMessage(_entryQuantityContractsUSDT, _currentCapital) => // Dependencies: i_enableStopLoss (initialized in inputs). // Dependencies: i_enableTakeProfit (initialized in inputs). // Dependencies: i_TakeProfit (initialized in inputs). // Dependencies: i_enableTrailingTakeProfit (initialized in inputs). // Dependencies: i_trailingTakeProfitPercentageOffset (initialized in inputs). // Dependencies: i_trailingTakeProfitPercentageTrigger (initialized in inputs). // Dependencies: i_zignalyIntegrationType (initialized in inputs). // Function Dependencies: f_priceDecimalDigitsZeroString() var string _zignaleStopLossCombo = "" var string _zignaleTakeProfitCombo = "" var string _zignaleTrailingTakeProfitCombo = "" _zignalyLongCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "entry" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "long" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "LONG-" + exchangeTickerID + zignalyQuote float _floatEntryQuantityContractsUSDT = _entryQuantityContractsUSDT _entryQuantityContractsUSDTStr = tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString()) float _floatCurrentCapital = _currentCapital float _entryQuantityContractsPercent = (_floatEntryQuantityContractsUSDT / _floatCurrentCapital) * 100.00 _entryQuantityContractsPercentStr = tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString()) // This is actually not needed because with pyramiding=0 it's impossible that an order is scaled (and thus modified) float _constantBuyStopLoss = na if (_oldInsideABuyOrder and insideABuyOrder) _constantBuyStopLoss := buyStopLoss else _constantBuyStopLoss := newBuyStopLoss if (i_enableStopLoss and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_)) _zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((nz(_constantBuyStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else _zignaleStopLossCombo := "" if (i_enableTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_)) _zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else _zignaleTakeProfitCombo := "" if (i_enableTrailingTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_)) _zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else _zignaleTrailingTakeProfitCombo := "" var string _message = "" if (i_zignalyProviderType == _ZIGCOPYTRADERPROVIDER_) _message := zignalyCommonAlertMessage + zignalySeparator + _zignalyLongCommonAlertMessage + zignalySeparator + zignalyQuote + "positionSizePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsPercentStr + zignalyQuote + _zignaleStopLossCombo + _zignaleTakeProfitCombo + _zignaleTrailingTakeProfitCombo else // _ZIGSIGNALPROVIDER_ _message := zignalyCommonAlertMessage + zignalySeparator + _zignalyLongCommonAlertMessage + zignalySeparator + zignalyQuote + "positionSizeQuote" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsUSDTStr + zignalyQuote + _zignaleStopLossCombo + _zignaleTakeProfitCombo + _zignaleTrailingTakeProfitCombo _messagef_getZignalyLongCloseAlertMessage() => // Dependencies: zignalyQuote // Dependencies: zignalyEquals // Dependencies: zignalySeparator // Dependencies: zignalyCommonAlertMessage _zignalyLongCloseCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "exit" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "long" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "LONG-" + exchangeTickerID + zignalyQuote var string _message = "" _message := zignalyCommonAlertMessage + zignalySeparator + _zignalyLongCloseCommonAlertMessage _messagef_getZignalyShortAlertMessage(_entryQuantityContractsUSDT, _currentCapital) => // Dependencies: i_enableStopLoss (initialized in inputs). // Dependencies: i_enableTakeProfit (initialized in inputs). // Dependencies: i_TakeProfit (initialized in inputs). // Dependencies: i_enableTrailingTakeProfit (initialized in inputs). // Dependencies: i_trailingTakeProfitPercentageOffset (initialized in inputs). // Dependencies: i_trailingTakeProfitPercentageTrigger (initialized in inputs). // Dependencies: i_zignalyIntegrationType (initialized in inputs). // Function Dependencies: f_priceDecimalDigitsZeroString() var string _zignaleStopLossCombo = "" var string _zignaleTakeProfitCombo = "" var string _zignaleTrailingTakeProfitCombo = "" _zignalyLongCloseCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "entry" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "short" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "SHORT-" + exchangeTickerID + zignalyQuote float _floatEntryQuantityContractsUSDT = _entryQuantityContractsUSDT _entryQuantityContractsUSDTStr = tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString()) float _floatCurrentCapital = _currentCapital float _entryQuantityContractsPercent = (_floatEntryQuantityContractsUSDT / _floatCurrentCapital) * 100.00 _entryQuantityContractsPercentStr = tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString()) // This is actually not needed because with pyramiding=0 it's impossible that an order is scaled (and thus modified) float _constantSellStopLoss = na if (oldInsideASellOrder and insideASellOrder) _constantSellStopLoss := sellStopLoss else _constantSellStopLoss := newSellStopLoss if (i_enableStopLoss and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_)) _zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((nz(_constantSellStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else _zignaleStopLossCombo := "" if (i_enableTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_)) _zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else _zignaleTakeProfitCombo := "" if (i_enableTrailingTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_)) _zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote else _zignaleTrailingTakeProfitCombo := "" var string _message = "" if (i_zignalyProviderType == _ZIGCOPYTRADERPROVIDER_) _message := zignalyCommonAlertMessage + zignalySeparator + _zignalyLongCloseCommonAlertMessage + zignalySeparator + zignalyQuote + "positionSizePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsPercentStr + zignalyQuote + _zignaleStopLossCombo + _zignaleTakeProfitCombo + _zignaleTrailingTakeProfitCombo else // _ZIGSIGNALPROVIDER_ _message := zignalyCommonAlertMessage + zignalySeparator + _zignalyLongCloseCommonAlertMessage + zignalySeparator + zignalyQuote + "positionSizeQuote" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsUSDTStr + zignalyQuote + _zignaleStopLossCombo + _zignaleTakeProfitCombo + _zignaleTrailingTakeProfitCombo _messagef_getZignalyShortCloseAlertMessage() => // Dependencies: zignalyQuote // Dependencies: zignalyEquals // Dependencies: zignalySeparator // Dependencies: zignalyCommonAlertMessage zignalyShortCloseCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "exit" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "short" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "SHORT-" + exchangeTickerID + zignalyQuote var string _message = "" _message := zignalyCommonAlertMessage + zignalySeparator + zignalyShortCloseCommonAlertMessage _message// Zignalye - Functions - END// Order comment - Functions - BEGINf_getOrderComment(_typeOrder, _side, _alertMessage) => // Dependencies: i_enableOrderCommentDebug (initialized in inputs). // TODO: Add descriptive comments // _typeOrder="entry" or _typeOrder="close" // _side: true means long ; false means short ; We can use strategy.long or strategy.short as true and false aliases // _alertMessage var string _orderComment = "" if (i_enableOrderCommentDebug) _orderComment := _alertMessage else // TODO: Use human explanations instead of default order comment value (na) _orderComment := na _orderComment// Order comment - Functions - END// Too recent orders functionsf_getTooRecentOrderNotOpenAdvice () => // Dependencies: i_tooRecentMinutesNumber_ms // Dependencies: lastOrderOpenBarTime // Condition 1: The order was open // Condition 2: The order was long or short // Condition 3: Time since order was last open is smaller than minimum between orders // Returns boolean bool _isTooRecent = ((time_close) <= (lastOrderOpenBarTime + i_tooRecentMinutesNumber_ms)) bool _tooRecentOrderBuyNotOpenAdvice = na if (na(lastOrderOpenBarTime)) _tooRecentOrderBuyNotOpenAdvice := false else _tooRecentOrderBuyNotOpenAdvice := _isTooRecent _tooRecentOrderBuyNotOpenAdvice// FUNCTIONS - END// Strategy Body - BEGIN// Simple Logic to go LONG/LONG or go SHORT/SHORT - BEGIN// longCondition = crossover(sma(close, 14), sma(close, 28))// shortCondition = crossunder(sma(close, 14), sma(close, 28))longCondition = sma(close, 14) >= sma(close, 28)shortCondition = sma(close, 14) < sma(close, 28)// Simple Logic to go LONG/LONG or go SHORT/SHORT - END// Position price calculation - BEGINfloat positionPrice = naif (insideASellOrder or insideABuyOrder) positionPrice := strategy.position_avg_priceelse positionPrice := close // Position price calculation - ENDtooRecentOrderNotOpenAdvice = f_getTooRecentOrderNotOpenAdvice ()newBuyStopLoss := i_StopLossnewSellStopLoss := i_StopLoss// Decide if we are going to LONG/Go LONG - BEGINPRE_LONG = falsePRE_LONG := longCondition and (not tooRecentOrderNotOpenAdvice)// LONG = PRE_LONG[1] and PRE_LONG // Wait for confirmationLONG = PRE_LONG // Do not wait for confirmation// Decide if we are going to LONG/Go LONG - END// Decide if we are going to SHORT/Go SHORT - BEGINPRE_SHORT = falsePRE_SHORT := shortCondition and (not tooRecentOrderNotOpenAdvice)// SHORT = PRE_SHORT[1] and PRE_SHORT // Wait for confirmationSHORT = PRE_SHORT // Do not wait for confirmation// Decide if we are going to SHORT/Go SHORT - END// Decide if a LONG/LONG entry should be closed - BEGINLONG_CLOSE = trueLONG_CLOSE := not (longCondition)// Let's make sure LONG does not trigger if LONG_CLOSE would tell us to close the LONGif LONG_CLOSE LONG := false// Decide if a LONG/LONG entry should be closed - END// Decide if a SHORT/SHORT entry should be closed - BEGINSHORT_CLOSE = trueSHORT_CLOSE := not (shortCondition)// Let's make sure SHORT does not trigger if SHORT_CLOSE would tell us to close the SHORTif SHORT_CLOSE SHORT := false// Decide if a SHORT/SHORT entry should be closed - END// How much to LONG/GO LONG/SHORT/GO SHORT - BEGIN// Custom take profit and stop lossLongTakeProfit = positionPrice * (1 + i_TakeProfit)ShortTakeProfit = positionPrice * (1 - i_TakeProfit)float LongStopLoss = nafloat ShortStopLoss = naLongStopLoss := positionPrice * (1 - buyStopLoss)ShortStopLoss := positionPrice * (1 + sellStopLoss)float entryQuantity = nafloat currentCapital = strategy.initial_capital + strategy.netprofitif (i_zignalyProviderType == _ZIGCOPYTRADERPROVIDER_) entryQuantity := i_CapitalPercentage * currentCapitalelse // _ZIGSIGNALPROVIDER_ entryQuantity := i_CapitalQuotefloat entryQuantityContractsReducer = 0.99contractMultiplier = f_getContractMultiplier(i_contractMaximumDecimalNumber)// We assume the current price is current bar closeentryQuantityContracts = (floor(((entryQuantity / close) * entryQuantityContractsReducer) * contractMultiplier) / contractMultiplier)entryQuantityContractsUSDT = entryQuantityContracts * (close)// How much to LONG/GO LONG/SHORT/GO SHORT - END// GO LONG only logic - BEGINvar float tmpPositionBeforeOpeningOrder = naif (i_strategyType == _L_) if LONG tmpPositionBeforeOpeningOrder := strategy.position_avg_price tmpOrderAlertMessage := f_getZignalyLongAlertMessage(entryQuantityContractsUSDT, currentCapital) tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage) strategy.entry("[B]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment) if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened buyOrderOpenBarIndex := bar_index + 1 if (not insideABuyOrder) buyStopLoss := newBuyStopLoss insideABuyOrder := true 0 // Workaround for making every if branch to return the same type of value else if LONG_CLOSE tmpOrderComment := f_getOrderComment("close", strategy.long, f_getZignalyLongCloseAlertMessage()) strategy.close("[B]", alert_message=i_enableZignalyAlert ? f_getZignalyLongCloseAlertMessage() : na, comment=tmpOrderComment) insideABuyOrder := false 0 // Workaround for making every if branch to return the same type of value// GO LONG only logic - END// GO SHORT only logic - BEGINif (i_strategyType == _S_) if SHORT tmpPositionBeforeOpeningOrder := strategy.position_avg_price tmpOrderAlertMessage := f_getZignalyShortAlertMessage(entryQuantityContractsUSDT, currentCapital) tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage) strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment) if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened sellOrderOpenBarIndex := bar_index + 1 if (not insideASellOrder) sellStopLoss := newSellStopLoss insideASellOrder := true 0 // Workaround for making every if branch to return the same type of value else if SHORT_CLOSE tmpOrderComment := f_getOrderComment("close", strategy.short, f_getZignalyShortCloseAlertMessage()) strategy.close("[S]", alert_message=i_enableZignalyAlert ? f_getZignalyShortCloseAlertMessage() : na, comment=tmpOrderComment) insideASellOrder := false 0 // Workaround for making every if branch to return the same type of value// GO SHORT only logic - END// GO LONG and SHORT logic - BEGINif (i_strategyType == L_S)// Asumption: Above we have:// if LONG_CLOSE// LONG := false// if SHORT_CLOSE// SHORT := false // LONG and SHORT cannot be true at the same time // Anyways we will take it into account if (LONG == true) and (SHORT == true) LONG := true SHORT := false SHORT_CLOSE := true if LONG tmpPositionBeforeOpeningOrder := strategy.position_avg_price tmpOrderAlertMessage := f_getZignalyLongAlertMessage(entryQuantityContractsUSDT, currentCapital) tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage) strategy.entry("[B]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment) if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened buyOrderOpenBarIndex := bar_index + 1 if (not insideABuyOrder) buyStopLoss := newBuyStopLoss insideABuyOrder := true if LONG_CLOSE tmpOrderComment := f_getOrderComment("close", strategy.long, f_getZignalyLongCloseAlertMessage()) strategy.close("[B]", alert_message=i_enableZignalyAlert ? f_getZignalyLongCloseAlertMessage() : na, comment=tmpOrderComment) insideABuyOrder := false if SHORT tmpPositionBeforeOpeningOrder := strategy.position_avg_price tmpOrderAlertMessage := f_getZignalyShortAlertMessage(entryQuantityContractsUSDT, currentCapital) tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage) strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment) if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened sellOrderOpenBarIndex := bar_index + 1 if (not insideASellOrder) sellStopLoss := newSellStopLoss insideASellOrder := true if SHORT_CLOSE tmpOrderComment := f_getOrderComment("close", strategy.short, f_getZignalyShortCloseAlertMessage()) strategy.close("[S]", alert_message=i_enableZignalyAlert ? f_getZignalyShortCloseAlertMessage() : na, comment=tmpOrderComment) insideASellOrder := false// GO LONG and SHORT logic - END// Handle STOP LOSS (and similar) order exits - BEGIN// Quick Paste - BEGINfloat longTrailingTakeProfitPrice = nafloat longTrailingTakeProfitPoints = nafloat longTrailingTakeProfitOffset = nafloat shortTrailingTakeProfitPrice = nafloat shortTrailingTakeProfitPoints = nafloat shortTrailingTakeProfitOffset = na// Calculate trailing_take_profit_offset based on tick unitslongTmpTtpBaseValue = positionPrice * (1 + i_trailingTakeProfitPercentageTrigger)longTmpTtpTop_value = longTmpTtpBaseValue * (1 + i_trailingTakeProfitPercentageOffset)longTrailingTakeProfitOffsetFloat = longTmpTtpTop_value - longTmpTtpBaseValuefloat longTrailingTakeProfitOffsetTick = floor (longTrailingTakeProfitOffsetFloat / syminfo.mintick)shortTmpTtpBaseValue = positionPrice * (1 - i_trailingTakeProfitPercentageTrigger)shortTmpTtpBottomValue = shortTmpTtpBaseValue * (1 - i_trailingTakeProfitPercentageOffset)shortTrailingTakeProfitOffsetFloat = shortTmpTtpBaseValue - shortTmpTtpBottomValuefloat shortTrailingTakeProfitOffsetTick = floor (shortTrailingTakeProfitOffsetFloat / syminfo.mintick)if i_enableTrailingTakeProfit longTrailingTakeProfitPrice := positionPrice * (1 + i_trailingTakeProfitPercentageTrigger) longTrailingTakeProfitOffset := longTrailingTakeProfitOffsetTick shortTrailingTakeProfitPrice := positionPrice * (1 - i_trailingTakeProfitPercentageTrigger) shortTrailingTakeProfitOffset := shortTrailingTakeProfitOffsetTickelse longTrailingTakeProfitPrice := na longTrailingTakeProfitOffset := na shortTrailingTakeProfitPrice := na shortTrailingTakeProfitOffset := na// Quick Paste - END// This might trigger additional close orders than needed in zignaly// Better close an existing order twice than regreting zignaly not having closed it.tmpOrderComment := f_getOrderComment("close", strategy.long, f_getZignalyLongCloseAlertMessage())strategy.exit("[SL/TP]", "[B]", stop= i_enableStopLoss ? LongStopLoss : na, limit= i_enableTakeProfit ? LongTakeProfit : na, trail_price= i_enableTrailingTakeProfit ? longTrailingTakeProfitPrice : na, trail_offset = i_enableTrailingTakeProfit ? longTrailingTakeProfitOffset : na, alert_message= i_enableZignalyAlert ? f_getZignalyLongCloseAlertMessage() : na, comment=tmpOrderComment)tmpOrderComment := f_getOrderComment("close", strategy.short, f_getZignalyShortCloseAlertMessage())strategy.exit("[SL/TP]", "[S]", stop= i_enableStopLoss ? ShortStopLoss : na, limit= i_enableTakeProfit ? ShortTakeProfit : na, trail_price= i_enableTrailingTakeProfit ? shortTrailingTakeProfitPrice : na, trail_offset = i_enableTrailingTakeProfit ? shortTrailingTakeProfitOffset : na, alert_message= i_enableZignalyAlert ? f_getZignalyShortCloseAlertMessage() : na, comment=tmpOrderComment)// Handle STOP LOSS (and similar) order exits - END// Strategy Body - END