Pine Script v5 · Strategy
Investments-swing trading strategy for different assets
A Pine Script v5 strategy built on SMA (source, 20), Stdev (source, 20) and TR. It has 12 order rules, 3 entries among them, and trades long only with the default settings. Exits use a stop loss. Each trade commits 1 in cash and pays 0.05 commission. 45 settings; defaults include Initial/Actual Capital 1000000.0, % account risk per trade 2.5 and Time session 0000-2400.
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 Investments-swing trading strategy for different assets repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- How did Investments-swing trading strategy for different assets do on BTCUSDT 1D with default settings?
- +4.17%
- From 26 Jan 2024 to 21 Oct 2026, over 17 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Does Investments-swing trading strategy for different assets run in Pine Script v6?
- Yes
- Same 17 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
- Does Investments-swing trading strategy for different assets use a stop loss?
- Yes
- strategy.exit sets a stop on line 184, 187, 196, 199, 208, 211.
- Does Investments-swing trading strategy for different assets run in Zeal Terminal?
- Yes
- It compiles in 91 ms and runs 1,000 bars in 317 ms, in the browser.
BTCUSDT · 1D · default settings
- Plot
- Amount purchase currency units
- Stop loss % distance
- Plot
- Plot
- Plot
- Plot
- Plot
- Stop loss price
- Target price for break event
- Winning trade
- Losing trade
- Exit at a stop or limit price
- Equity
- Buy and hold
- Net profit
- +4.17%
- $4,168.55
- Buy and hold
- +102.5%
- same period
- Closed trades
- 17
- 3 won · 14 lost
- Profitable
- 17.6%
- of closed trades
- Profit factor
- 1.18
- gross profit ÷ gross loss
- Max drawdown
- 17.65%
- −$21,405.70
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Likely bug
ta.crossover(val, 0) ignores the settings line 164
Line 164 hard-codes 0 where line 160 uses “Over sold line rsi”. Changing those settings moves one band but not this one.
ta.crossover(val, 0)ta.crossover(val, oversold) -
Likely bug
ta.crossunder(val, 0) ignores the settings line 163
Line 163 hard-codes 0 where line 162 uses “Over bought line rsi”. Changing those settings moves one band but not this one.
ta.crossunder(val, 0)ta.crossunder(val, overbought) -
Check
4 settings do nothing
“How to use the strategy ----->”, “MACD Line ”, “Signal Line ”, “Read ------>” are declared but never read.
-
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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Information | |||
| How to use the strategy ----->When there is a buy signal at the end of the candle, buy. To close, you must wait for the candle to close, exit in breakeven or, failing that, exit through stop loss. Use the amounts and stop loss based on the values provided in the upper left corner by the indicator (choose the candlestick where the signal was produced to obtain the position information). Do not modify the parameters of the indicators as it is the most optimal setting for different assets from different markets. Use the info boxes to see more information about using the strategy | true | bool | unused |
| Position amount calculator | |||
| Initial/Actual CapitalEnter the current amount of your capital. This amount will be used to calculate the size of your position that will be reflected in the upper left corner of the indicator. Remember that to change the amount in the back test you must go to properties. >>The amount in currency units is the green value<< | 1000000.0 | float | buy_amount number_of_contracts line 128 |
| % account risk per trade | 2.5 | float · step 1 | buy_amount_atr_actual_candle buy_amount_atr_past_candle |
| Time filter | |||
| Initial dateEnter the start date and time of the strategy | timestamp("01 Jan 1800 13:30 +0000") | time | entry Buy exit Cl Buy entry Buy exit Cl Buy entry Buy. exit Cl Buy. bgcolor line 179 line 191 line 203 |
| Final dateEnter the end date and time of the strategy | timestamp("1 Jan 2030 19:30 +0000") | time | entry Buy exit Cl Buy entry Buy exit Cl Buy entry Buy. exit Cl Buy. bgcolor line 179 line 191 line 203 |
| Time sessionSession time to operate. It may be different depending on your time zone, you have to find the correct hours manually. | 0000-2400 | session | entry Buy exit Cl Buy entry Buy exit Cl Buy entry Buy. exit Cl Buy. bgcolor line 179 line 191 line 203 |
| Date backgroundAdd color to the period of time of the strategy tester | false | bool | bgcolor |
| Session backgroundAdd color to session time background | false | bool | bgcolor |
| Source | close | source | fast_ma slow_ma |
| Squeeze Momentum | |||
| BB Length | 20 | int | ma dev |
| BB MultFactor | 2.0 | float | dev |
| KC Length | 20 | int | rangema val |
| KC MultFactor | 1.5 | float | upperKC lowerKC |
| Use TrueRange (KC) | true | bool | range_1 |
| Appearance | |||
| Show squeeze momentum ? | false | bool | plot |
| Show Ema ? | true | bool | plot |
| Show Rsi ? | false | bool | plot hline |
| Show Macd ? | false | bool | Histogram |
| Show stop loss and break even ? | true | bool | Stop loss price Target price for break event |
| Draw position on chart ?Activate to graphically display profit, stop loss and break even | true | bool | position_price break_even_price sl1_price sl2_price sl3_price position_profit_price plot |
| Draw signals on chart ? | true | bool | plotshape |
| Trend | |||
| Ema length | 200 | int · min 1 · max 500 | ema200 |
| Rsi | |||
| Over bought line rsi | 70 | int · min 50 · max 100 | sell_rsi_signal hline |
| Over sold line rsi | 30 | int · min 0 · max 50 | buy_rsi_signal |
| Rsi Length | 5 | int · min 1 · max 200 | rsi_filter |
| Macd | |||
| Fast Length | 16 | int | fast_ma |
| Slow Length | 26 | int | slow_ma |
| Signal Smoothing | 8 | int · min 1 · max 50 | signal |
| Oscillator MA Type | EMA | string · options ["SMA", "EMA"] | fast_ma slow_ma |
| Signal Line MA Type | EMA | string · options ["SMA", "EMA"] | signal |
| Color Settings | |||
| MACD Line | #2962FF | value | unused |
| Signal Line | #FF6D00 | value | unused |
| Histogram | |||
| Above Grow | #26A69A | value | Histogram |
| Fall | #B2DFDB | value | Histogram |
| Below Grow | #FFCDD2 | value | Histogram |
| Fall | #FF5252 | value | Histogram |
| Atr stop loss | |||
| Source | close | source | shortStopLoss longStopLoss |
| Period | 14 | int · min 1 | shortStopLoss longStopLoss atr_past_candle_buy |
| Atr multiplierDefines the stop loss distance based in the Atr stop loss indicator | 1.6 | float · min 0.1 · step 0.1 | shortStopLoss longStopLoss atr_past_candle_buy |
| Risk management | |||
| % Account risk per trade for backtestingPercentage of total account to risk per trade. >>The price of the stop loss is the red value<<. >>The distance of the stop loss is the orange value<<. It is recommended not to use more than 5% | 2.5 | float · step 1 | amount_1 amount_2 buy_amount |
| Risk reward for break evenRisk/reward level to determine the target price to move the stop loss to the buy price (neither win nor lose). >>It is the light blue value<< | 1.0 | float · step 0.1 | be_buy be_buy_calculator |
| Use leverage ?If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital. | false | bool | line 113 line 115 line 128 |
| Againts trend ?Activate to trade when the price is below the EMA of 200 periods. It can be useful in certain assets or timeframes like weelky and risky in others | false | bool | sl1_price entry Buy exit Cl Buy entry Buy exit Cl Buy line 179 line 191 plot |
| Break even using rsi ?Activate to apply break even when rsi crosses under overbought line. It appears as a blue arrow | false | bool | exit Cl Buy exit Cl Buy exit Cl Buy. line 185 line 197 line 209 plotshape |
| Final information | |||
| Read ------>Thank you for using this model, I hope it can be very useful for you when making decisions in the short/medium and long term. Remember that it is not a crystal ball and it is not the Holy Grail of investments, it is just a model that seeks to adapt to different market situations to position yourself in favor of having the chances in your favor and making management much easier. Any questions you have about the model, feel free to ask :). Don't forget to leave your boost! | true | bool | unused |
What it calculates
- SMAsource, BB Length (20)
ma · line 27 - Stdevsource, BB Length (20)
dev · line 29 - TR
range_1 · line 32 - SMArange_1, KC Length (20)
rangema · line 33 - Linreg / Highest / Lowest / SMAsource - math.avg(math.avg(ta.highest(high, lengthKC), ta.lowest(low, lengthKC)), ta.sma(close, lengthKC)), KC Length (20), 0
val · line 39 - EMAclose, Ema length (200)
ema200 · line 49 - RSIclose, Rsi Length (5)
rsi_filter · line 58 - SMA / EMASource (close), Fast Length (16) · chosen by Oscillator MA Type
fast_ma · line 78 - SMA / EMASource (close), Slow Length (26) · chosen by Oscillator MA Type
slow_ma · line 79 - SMA / EMAmacd, Signal Smoothing (8) · chosen by Signal Line MA Type
signal · line 81 - ATRPeriod (14)
shortStopLoss · line 92 - ATRPeriod (14)
longStopLoss · line 93 - ATRPeriod (14)
atr_past_candle_buy · line 94 - Crossunderval, 0
trend_sell_signal_sqz · line 163
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 102 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 Buy long | trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and againts_trend | On | 183 |
| Exit Cl Buy stop | trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and againts_trend | On | 184 |
| Exit Cl Buy stop | high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi | On | 187 |
| Close Buy | (bought and trend_sell_signal_sqz) | On | 189 |
| Open Buy long | trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and bullish and not againts_trend | On | 195 |
| Exit Cl Buy stop | trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and bullish and not againts_trend | On | 196 |
| Exit Cl Buy stop | high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi | On | 199 |
| Close Buy | (trend_sell_signal_sqz) | On | 201 |
| Open Buy. long | buy_macd_signal and dateFilter(initial_date, final_date) and inSession(timeSession) and bullish and strategy.opentrades<1 | On | 207 |
| Exit Cl Buy. stop | buy_macd_signal and dateFilter(initial_date, final_date) and inSession(timeSession) and bullish and strategy.opentrades<1 | On | 208 |
| Exit Cl Buy. stop | high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi | On | 211 |
| Close Buy. | (trend_sell_signal_sqz) | On | 213 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- CheckIntrabar recalculationcalc_on_every_tick = true. Live values can differ from history.
- ClearOrder timingprocess_orders_on_close = true: orders fill at the signal bar's close.
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 | +4.2% | +102.5% | 17 | 18% | 1.18 | 17.6% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −2.9% | +5.5% | 29 | 10% | 0.90 | 10.9% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +9.9% | +9.8% | 12 | 25% | 1.73 | 10.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +24.8% | +8.4% | 25 | 24% | 2.13 | 6.1% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +3.8% | +16.7% | 14 | 21% | 1.23 | 11.5% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +14.0% | +21.5% | 19 | 32% | 1.61 | 13.4% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +1.5% | +148.3% | 22 | 27% | 1.06 | 12.3% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +24.6% | +17.1% | 14 | 36% | 3.22 | 4.7% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
Settings heatmap
Two settings that feed the entry signal, moved around their defaults. The best in-sample pair (BB Length 10, KC Length 14) made +16.6% before 26 Dec 2025 and +3.1% after it, against −0.1% for the defaults. 75% of the 64 combinations made money in-sample and 63% out-of-sample.
| KC Length ↓ · BB Length → | 10 | 12 | 14 | 17 | 20 | 24 | 28 | 34 |
|---|---|---|---|---|---|---|---|---|
| 10 | +13% | +13% | +13% | +13% | +13% | +13% | +13% | +13% |
| 12 | +11% | +11% | +11% | +11% | +11% | +11% | +11% | +11% |
| 14 | +17% | +17% | +17% | +17% | +17% | +17% | +17% | +17% |
| 17 | +5% | +5% | +5% | +5% | +5% | +5% | +5% | +5% |
| 20 | +4% | +4% | +4% | +4% | +4% | +4% | +4% | +4% |
| 24 | −7% | −7% | −7% | −7% | −7% | −7% | −7% | −7% |
| 28 | −5% | −5% | −5% | −5% | −5% | −5% | −5% | −5% |
| 34 | +2% | +2% | +2% | +2% | +2% | +2% | +2% | +2% |
| KC Length ↓ · BB Length → | 10 | 12 | 14 | 17 | 20 | 24 | 28 | 34 |
|---|---|---|---|---|---|---|---|---|
| 10 | −2% | −2% | −2% | −2% | −2% | −2% | −2% | −2% |
| 12 | +2% | +2% | +2% | +2% | +2% | +2% | +2% | +2% |
| 14 | +3% | +3% | +3% | +3% | +3% | +3% | +3% | +3% |
| 17 | +2% | +2% | +2% | +2% | +2% | +2% | +2% | +2% |
| 20 | −0% | −0% | −0% | −0% | −0% | −0% | −0% | −0% |
| 24 | −2% | −2% | −2% | −2% | −2% | −2% | −2% | −2% |
| 28 | +7% | +7% | +7% | +7% | +7% | +7% | +7% | +7% |
| 34 | +8% | +8% | +8% | +8% | +8% | +8% | +8% | +8% |
Net P&L of trades opened in each period, as a share of starting capital. marks the defaults and the best in-sample cell. Hover a cell for its trade count. 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 | 8 | 25% | −$2,617.92 |
| Sideways market | 9 | 11% | $6,812.63 |
| Falling market | 0 | — | $0.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
16.4%
The 95th percentile of the worst drawdown when the same 17 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 8.4% to 16.4%; the tick is what actually happened, 16.2%. Order luck alone moves it this much.
All 17 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 6 Oct 2024 62,819.90 | 9 Dec 2024 97,276.50 stop | 64 | $21,312.90 |
| long | 11 Dec 2024 101,125.00 | 23 Dec 2024 94,881.50 stop | 12 | −$1,718.40 |
| long | 24 Dec 2024 98,663.60 | 27 Jan 2025 98,663.60 | 34 | −$27.83 |
| long | 9 Feb 2025 96,462.80 | 25 Feb 2025 89,626.30 | 16 | −$3,029.85 |
| long | 4 Mar 2025 87,282.00 | 10 Mar 2025 78,769.30 | 6 | −$2,941.84 |
| long | 24 Mar 2025 87,498.20 | 31 Mar 2025 81,544.80 | 7 | −$2,880.19 |
| long | 8 May 2025 103,262.00 | 31 May 2025 103,262.00 | 23 | −$60.73 |
| long | 2 Jun 2025 105,858.00 | 5 Jun 2025 101,081.00 | 3 | −$2,826.27 |
| long | 6 Jun 2025 104,288.00 | 21 Jun 2025 102,120.00 stop | 15 | −$828.04 |
| long | 23 Jun 2025 105,334.00 | 31 Jul 2025 115,764.00 stop | 38 | $2,971.34 |
| long | 3 Aug 2025 114,209.00 | 19 Aug 2025 114,209.00 | 16 | −$51.42 |
| long | 22 Aug 2025 116,936.00 | 29 Aug 2025 107,939.00 | 7 | −$2,782.33 |
| long | 1 Sep 2025 109,237.00 | 25 Sep 2025 109,237.00 | 24 | −$49.74 |
| long | 28 Sep 2025 112,164.00 | 10 Oct 2025 112,164.00 | 12 | −$48.64 |
| long | 23 Oct 2025 110,078.00 | 4 Nov 2025 100,965.00 | 12 | −$2,706.96 |
| long | 10 May 2026 82,210.10 | 13 May 2026 78,954.40 | 3 | −$2,672.86 |
| long | 14 Sep 2026 78,189.20 | 10 Oct 2026 82,988.40 stop | 26 | $2,535.56 |
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 |
|---|---|---|---|---|---|
| Investments-swing trading strategy for different assets this page | — | v5 strategy | +4.2% | 17 | 17.6% |
| [fpemehd] SSL Baseline Strategy by DuDu95 | ema sma highest lowest stdev tr atr | v5 strategy | +2.3% | 71 | 3.7% |
| SSL + Wave Trend Strategy by kevinmck100 | ema sma highest lowest stdev tr atr | v5 strategy | −1.0% | 1 | 1.0% |
| BTC 15 min by RafaelZioni | sma ema rsi linreg stdev highest lowest | v4 strategy | −25.7% | 119 | 38.9% |
| Solution Zigma - Fibonacci Impulse by ZoomerXeus | ema highest lowest atr rsi linreg sma | v5 strategy | does not run in Zeal Terminal | ||
| MZ SRSI Strategy V1.0 by MightyZinger | ema sma highest lowest stdev rsi | v4 strategy | No 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.
- 15 settings use the untyped input() (line 21, 22, 24, 25, 26, 64, 65, 66, 71, 72, 73, 74, 75, 76, 89). 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.
Same 17 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 21: input() → input.int()
- Line 22: input() → input.float()
- Line 24: input() → input.int()
- Line 25: input() → input.float()
- Line 26: input() → input.bool()
- Line 64: input() → input.int()
9 more edits
- Line 65: input() → input.int()
- Line 66: input() → input.source()
- Line 71: input() → input.color()
- Line 72: input() → input.color()
- Line 73: input() → input.color()
- Line 74: input() → input.color()
- Line 75: input() → input.color()
- Line 76: input() → input.color()
- Line 89: input() → input.source()
⋯// ------------------ Squeeze momentum Lazy Bear ------------------------length = input(20, title='BB Length', group = "Squeeze Momentum", inline = "c")+length = input.int(20, title='BB Length', group = "Squeeze Momentum", inline = "c")-mult = input(2.0, title='BB MultFactor', group = "Squeeze Momentum", inline = "c")+mult = input.float(2.0, title='BB MultFactor', group = "Squeeze Momentum", inline = "c")source = close-lengthKC = input(20, title='KC Length', group = "Squeeze Momentum", inline = "c")+lengthKC = input.int(20, title='KC Length', group = "Squeeze Momentum", inline = "c")-multKC = input(1.5, title='KC MultFactor', group = "Squeeze Momentum", inline = "c")+multKC = input.float(1.5, title='KC MultFactor', group = "Squeeze Momentum", inline = "c")-useTrueRange = input(true, title='Use TrueRange (KC)', group = "Squeeze Momentum", inline = "c")+useTrueRange = input.bool(true, title='Use TrueRange (KC)', group = "Squeeze Momentum", inline = "c")ma = ta.sma(source, length)⋯// Getting inputs-fast_length = input(title="Fast Length", defval=16, group = "Macd")+fast_length = input.int(title="Fast Length", defval=16, group = "Macd")-slow_length = input(title="Slow Length", defval=26, group = "Macd")+slow_length = input.int(title="Slow Length", defval=26, group = "Macd")-src = input(title="Source", defval=close)+src = input.source(title="Source", defval=close)signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 8, group = "Macd")⋯// Plot colors-col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")+col_macd = input.color(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")-col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")+col_signal = input.color(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")-col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")+col_grow_above = input.color(#26A69A, "Above Grow", group="Histogram", inline="Above")-col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")+col_fall_above = input.color(#B2DFDB, "Fall", group="Histogram", inline="Above")-col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")+col_grow_below = input.color(#FFCDD2, "Below Grow", group="Histogram", inline="Below")-col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")+col_fall_below = input.color(#FF5252, "Fall", group="Histogram", inline="Below")// Calculating⋯// -------------- Atr stop loss by Gatherio ------------------source_atr = input(close, title='Source', group = "Atr stop loss", inline = "A")+source_atr = input.source(close, title='Source', group = "Atr stop loss", inline = "A")length_atr = input.int(14, minval=1, title='Period', group = "Atr stop loss" , inline = "A")⋯Does it run in Pine Script v6?
Yes
Same 17 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.
⋯// Developed by © StrategiesForEveryone-//@version=5+//@version=6strategy('Investments/swing trading strategy for different assets', overlay=true, process_orders_on_close=true, initial_capital = 100000, default_qty_type = strategy.cash, pyramiding = 1, precision = 2, calc_on_every_tick = true, commission_value = 0.05)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 91 ms | With a workaround 1,000 bars in 317 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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/// Developed by © StrategiesForEveryone//@version=5strategy('Investments/swing trading strategy for different assets', overlay=true, process_orders_on_close=true, initial_capital = 100000, default_qty_type = strategy.cash, pyramiding = 1, precision = 2, calc_on_every_tick = true, commission_value = 0.05)how_to_use = input.bool(defval=true, title="How to use the strategy ----->", group = "Information", tooltip = "When there is a buy signal at the end of the candle, buy. To close, you must wait for the candle to close, exit in breakeven or, failing that, exit through stop loss. Use the amounts and stop loss based on the values provided in the upper left corner by the indicator (choose the candlestick where the signal was produced to obtain the position information). Do not modify the parameters of the indicators as it is the most optimal setting for different assets from different markets. Use the info boxes to see more information about using the strategy")// ------ Position amount calculator ------initial_actual_capital_c = input.float(defval=1000000.0, title = "Initial/Actual Capital", group = "Position amount calculator", tooltip = "Enter the current amount of your capital. This amount will be used to calculate the size of your position that will be reflected in the upper left corner of the indicator. Remember that to change the amount in the back test you must go to properties. >>The amount in currency units is the green value<<")risk_c = input.float(defval = 2.5, title = '% account risk per trade', step=1, group = "Position amount calculator")// ------ Date filter ---------initial_date = input.time(title="Initial date", defval=timestamp("01 Jan 1800 13:30 +0000"), group="Time filter", tooltip="Enter the start date and time of the strategy")final_date = input.time(title="Final date", defval=timestamp("1 Jan 2030 19:30 +0000"), group="Time filter", tooltip="Enter the end date and time of the strategy")dateFilter(int st, int et) => time >= st and time <= etcolorDate = input.bool(defval=false, title="Date background", tooltip = "Add color to the period of time of the strategy tester")bgcolor(colorDate and dateFilter(initial_date, final_date) ? color.new(color.blue, transp=90) : na)// ------ Session limits -------timeSession = input.session(title="Time session", defval="0000-2400", group="Time filter", tooltip="Session time to operate. It may be different depending on your time zone, you have to find the correct hours manually.")colorBG = input.bool(title="Session background", defval=false, tooltip = "Add color to session time background")inSession(sess) => na(time(timeframe.period, sess + ':1234567')) == falsebgcolor(inSession(timeSession) and colorBG ? color.rgb(0, 38, 255, 84) : na)// ------------------ Squeeze momentum Lazy Bear -----------------------length = input(20, title='BB Length', group = "Squeeze Momentum", inline = "c")mult = input(2.0, title='BB MultFactor', group = "Squeeze Momentum", inline = "c")source = closelengthKC = input(20, title='KC Length', group = "Squeeze Momentum", inline = "c")multKC = input(1.5, title='KC MultFactor', group = "Squeeze Momentum", inline = "c")useTrueRange = input(true, title='Use TrueRange (KC)', group = "Squeeze Momentum", inline = "c")ma = ta.sma(source, length)basis = madev = mult * ta.stdev(source, length)upperBB = basis + devlowerBB = basis - devrange_1 = useTrueRange ? ta.tr : high - lowrangema = ta.sma(range_1, lengthKC)upperKC = ma + rangema * multKClowerKC = ma - rangema * multKCsqzOn = lowerBB > lowerKC and upperBB < upperKCsqzOff = lowerBB < lowerKC and upperBB > upperKCnoSqz = sqzOn == false and sqzOff == falseval = ta.linreg(source - math.avg(math.avg(ta.highest(high, lengthKC), ta.lowest(low, lengthKC)), ta.sma(close, lengthKC)), lengthKC, 0)iff_1 = val > nz(val[1]) ? #00ff00 : #008000iff_2 = val < nz(val[1]) ? #FF0000 : #800000bcolor = val > 0 ? iff_1 : iff_2green_sqz = val > 0red_sqz = val < 0show_sqz = input.bool(defval=false, title = "Show squeeze momentum ?", group = "Appearance")plot(show_sqz ? val : na, color=bcolor, style=plot.style_columns, linewidth=4, display = display.all-display.price_scale-display.status_line)// ----------- Ema ----------------------ema = input.int(200, title='Ema length', minval=1, maxval=500, group = "Trend")ema200 = ta.ema(close, ema)bullish = close > ema200bearish = close < ema200show_ema = input.bool(defval=true, title="Show Ema ?", group = "Appearance")plot(show_ema ? ema200 : na, color=color.white, linewidth=2, display = display.all - display.status_line)// --------------- Custom Rsi ------------------overbought = input.int(70, title='Over bought line rsi', minval=50, maxval=100, group = "Rsi", inline = "b")oversold = input.int(30, title='Over sold line rsi', minval=0, maxval=50, group = "Rsi", inline = "b")periods = input.int(5, title='Rsi Length', minval=1, maxval=200, group = "Rsi", inline = "b")rsi_filter = ta.rsi(close, periods)show_rsi = input.bool(defval=false, title="Show Rsi ?", group = "Appearance")plot(show_rsi ? rsi_filter : na, color=color.white, linewidth=2, display = display.all-display.price_scale-display.status_line-display.data_window)hline(show_rsi ? overbought : na, color=color.green, linewidth = 1, display = display.all)// --------- Macd -----------// Getting inputsfast_length = input(title="Fast Length", defval=16, group = "Macd")slow_length = input(title="Slow Length", defval=26, group = "Macd")src = input(title="Source", defval=close)signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 8, group = "Macd")sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group = "Macd")sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group = "Macd")// Plot colorscol_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")// Calculatingfast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)macd = fast_ma - slow_masignal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)hist = macd - signal//hline(0, "Zero Line", color=color.new(#787B86, 50))show_macd = input.bool(defval=false, title = "Show Macd ?", group = "Appearance")plot(show_macd ? hist : na, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)), display = display.all-display.price_scale-display.status_line-display.data_window)//plot(macd, title="MACD", color=col_macd)//plot(signal, title="Signal", color=col_signal)// -------------- Atr stop loss by Gatherio -----------------source_atr = input(close, title='Source', group = "Atr stop loss", inline = "A")length_atr = input.int(14, minval=1, title='Period', group = "Atr stop loss" , inline = "A")multiplier = input.float(1.6, minval=0.1, step=0.1, title='Atr multiplier', group = "Atr stop loss", inline = "A", tooltip = "Defines the stop loss distance based in the Atr stop loss indicator")shortStopLoss = source_atr + ta.atr(length_atr) * multiplierlongStopLoss = source_atr - ta.atr(length_atr) * multiplieratr_past_candle_buy = close[1] - ta.atr(length_atr)[1] * multiplier[1]// ------- Money management ---------strategy_contracts = strategy.equity / closedistance_sl_buy = -1 * (longStopLoss - close) / closedistance_sl_buy_past_candle = -1 * (atr_past_candle_buy - close) / close // distancia stop loss en porcentajerisk = input.float(2.5, '% Account risk per trade for backtesting', step=1, group = "Risk management", tooltip = "Percentage of total account to risk per trade. >>The price of the stop loss is the red value<<. >>The distance of the stop loss is the orange value<<. It is recommended not to use more than 5%")amount_1 = strategy_contracts * (risk / 100) / distance_sl_buyamount_2 = strategy_contracts * (risk / 100) / distance_sl_buy_past_candle// ------- Risk management ---------risk_reward_breakeven = input.float(title='Risk reward for break even', defval=1.0, step=0.1, group = "Risk management", tooltip = "Risk/reward level to determine the target price to move the stop loss to the buy price (neither win nor lose). >>It is the light blue value<<")var float sl = navar float be_buy = navar float tp_buy = navar float stop_loss_distance = navar float buy_amount = na var float asset_amount = na var float be_buy_calculator = navar float stoploss_distance = naleverage=input.bool(defval=false, title="Use leverage ?", group = "Risk management", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")if not leverage and amount_1>strategy_contracts amount_1:=strategy.equity/closeif not leverage and amount_2>strategy_contracts amount_2:=strategy.equity/close// --------- Risk calculator --------------------------number_of_contracts = initial_actual_capital_c / closebuy_amount_atr_actual_candle = close * (number_of_contracts * (risk_c / 100) / distance_sl_buy)buy_amount_atr_past_candle = close * (number_of_contracts * (risk_c / 100) / distance_sl_buy_past_candle)// Plot purchase currency units amountif close>ema200 buy_amount:=close * (number_of_contracts * (risk / 100) / distance_sl_buy)if close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200 buy_amount:= close * (number_of_contracts * (risk / 100) / distance_sl_buy_past_candle)if close<ema200 buy_amount:=close * (number_of_contracts * (risk / 100) / distance_sl_buy)if not leverage and buy_amount>initial_actual_capital_c buy_amount:=initial_actual_capital_cplot(buy_amount, display = display.all - display.pane, color=color.rgb(0, 255, 55), title="Amount purchase currency units")// Plot stop loss pricedraw_sl_be = input.bool(defval=true, title="Show stop loss and break even ?", group = "Appearance")if close>ema200 sl:=longStopLossif close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200 sl:=atr_past_candle_buyif close<ema200 sl:=longStopLoss// Plot stop loss % distanceif close>ema200 stop_loss_distance:=(-1 * (longStopLoss - close) / close)*100 if close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200 stop_loss_distance:=(-1 * (atr_past_candle_buy - close) / close)*100 if close<ema200 stop_loss_distance:=(-1 * (longStopLoss - close) / close)*100 plot(stop_loss_distance, title="Stop loss % distance", color=color.rgb(255, 136, 0), display=display.all - display.pane)// Plot break even distance_stop_buy_break_even = close - longStopLossdistance_stop_buy_break_even_past_candle = close - atr_past_candle_buybe_buy_calculator:= close + distance_stop_buy_break_even * risk_reward_breakevenif close>ema200 be_buy_calculator:= close + distance_stop_buy_break_even * risk_reward_breakevenif close>ema200 and hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200 be_buy_calculator:=close + distance_stop_buy_break_even_past_candle * risk_reward_breakevenif close<ema200 be_buy_calculator:= close + distance_stop_buy_break_even * risk_reward_breakeven // ------- Conditions for buying -----------bought = strategy.position_size > 0sold = strategy.position_size < 0buy_rsi_signal = ta.crossover(rsi_filter, oversold) and red_sqz and bearish buy_macd_signal = hist[0] > hist[1] and close[0] > close[1] and hist<0 and red_sqz and open[1]>ema200sell_rsi_signal = ta.crossunder(rsi_filter, overbought) and green_sqz and bought trend_sell_signal_sqz = ta.crossunder(val, 0)trend_buy_signal_sqz = ta.crossover(val, 0) or (val>0 and (val[0] > val[1] and val[1] < val[2]))positive_close=strategy.openprofit>0information = input.bool(defval=true, title="Read ------>", group = "Final information", tooltip = "Thank you for using this model, I hope it can be very useful for you when making decisions in the short/medium and long term. Remember that it is not a crystal ball and it is not the Holy Grail of investments, it is just a model that seeks to adapt to different market situations to position yourself in favor of having the chances in your favor and making management much easier. Any questions you have about the model, feel free to ask :). Don't forget to leave your boost!")againts_trend = input.bool(defval=false, title="Againts trend ?", group ="Risk management", tooltip = "Activate to trade when the price is below the EMA of 200 periods. It can be useful in certain assets or timeframes like weelky and risky in others")break_even_with_rsi = input.bool(defval=false, title="Break even using rsi ?", group="Risk management", tooltip = "Activate to apply break even when rsi crosses under overbought line. It appears as a blue arrow")var float sl_1 = navar float sl_2 = navar float sl_3 = naif not bought sl_1:=na sl_2:=na sl_3:=na// --------- Use of strategy conditions ----------// ------------------------ Sqz momentum signal ------------------------// ---------------------- Againts Trend ----------------------if trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and againts_trend sl_1:=longStopLoss stoploss_distance:= close - longStopLoss be_buy := close + stoploss_distance * risk_reward_breakeven strategy.entry("Buy", strategy.long, qty=amount_1) strategy.exit("Cl Buy", "Buy", stop=sl_1)if high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi sl_1:=strategy.position_avg_price strategy.exit("Cl Buy", "Buy", stop=sl_1) if (bought and trend_sell_signal_sqz) strategy.close("Buy", comment="Cl Buy")//---------------In favor of the trend"---------------------if trend_buy_signal_sqz and dateFilter(initial_date, final_date) and inSession(timeSession) and strategy.opentrades<1 and bullish and not againts_trend sl_2:=longStopLoss stoploss_distance:= close - longStopLoss be_buy := close + stoploss_distance * risk_reward_breakeven strategy.entry('Buy', strategy.long, qty=amount_1) strategy.exit('Cl Buy', 'Buy', stop=sl_2)if high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi sl_2:=strategy.position_avg_price strategy.exit("Cl Buy", "Buy", stop=sl_2) if (trend_sell_signal_sqz) strategy.close("Buy", comment="Cl Buy")// ---------------------- Macd signal ----------------------------------------if buy_macd_signal and dateFilter(initial_date, final_date) and inSession(timeSession) and bullish and strategy.opentrades<1 sl_3:=atr_past_candle_buy stoploss_distance:= close - atr_past_candle_buy be_buy := close + stoploss_distance * risk_reward_breakeven strategy.entry('Buy.', strategy.long, qty=amount_2) strategy.exit('Cl Buy.', 'Buy.', stop=sl_3)if high > be_buy or sell_rsi_signal and positive_close and break_even_with_rsi sl_3:=strategy.position_avg_price strategy.exit("Cl Buy.", "Buy.", stop=sl_3) if (trend_sell_signal_sqz) strategy.close("Buy.", comment="Cl Buy.")// ---------- Draw position on chart -------------if high > be_buy be_buy:=nashow_position_on_chart = input.bool(defval=true, title="Draw position on chart ?", group = "Appearance", tooltip = "Activate to graphically display profit, stop loss and break even")position_price = plot(show_position_on_chart? strategy.position_avg_price : na, style=plot.style_linebr, color = color.new(#ffffff, 20), linewidth = 1, display = display.all - display.status_line)break_even_price = plot(strategy.position_size>0 and high<be_buy and show_position_on_chart ? be_buy : na , style = plot.style_linebr, color = color.new(#41a3ff, 20), linewidth = 1, display = display.all - display.status_line)sl1_price = plot(show_position_on_chart and bought and againts_trend ? sl_1 : na, style = plot.style_linebr, color = color.new(color.red, 20), linewidth = 1, display = display.all - display.status_line)sl2_price = plot(show_position_on_chart and bought ? sl_2 : na, style = plot.style_linebr, color = color.new(color.red, 20), linewidth = 1, display = display.all - display.status_line)sl3_price = plot(show_position_on_chart and bought ? sl_3 : na, style = plot.style_linebr, color = color.new(color.red, 20), linewidth = 1, display = display.all - display.status_line)position_profit_price = plot(strategy.position_size>0 and show_position_on_chart and positive_close ? close : na, style = plot.style_linebr, color = color.new(color.green, 20), linewidth = 1, display = display.all - display.status_line)fill(plot1 = position_price, plot2 = position_profit_price, color = color.new(color.green,90))fill(plot1 = position_price, plot2 = sl1_price, color = color.new(color.red,90))fill(plot1 = position_price, plot2 = sl2_price, color = color.new(color.red,90))fill(plot1 = position_price, plot2 = sl3_price, color = color.new(color.red,90))// --------- Strategy as indicator -----------show_signals = input.bool(defval=true, title="Draw signals on chart ?", group = "Appearance")plot(draw_sl_be and trend_buy_signal_sqz and not bought or draw_sl_be and buy_macd_signal and not bought? sl : na, title="Stop loss price", color=color.rgb(255, 255, 255), linewidth=1, style=plot.style_circles, display=display.all - display.price_scale)plot(draw_sl_be and trend_buy_signal_sqz and not bought or draw_sl_be and buy_macd_signal and not bought? be_buy_calculator : na, title="Target price for break event", color=color.rgb(72, 210, 245), linewidth=1, style=plot.style_circles, display=display.all - display.price_scale)plotshape(show_signals and break_even_with_rsi and bought? sell_rsi_signal : na, style = shape.triangledown, color = color.blue, size = size.tiny, display = display.all - display.price_scale - display.status_line)