Daveatt

Ultimate Strategy Template

Hello Traders

As most of you know, I'm a member of the PineCoders community and I sometimes take freelance pine coding jobs for TradingView users.

Off the top of my head, users often want to:

- convert an indicator into a strategy, so as to get the backtesting statistics from TradingView
- add alerts to their indicator/strategy
- develop a generic strategy template which can be plugged into (almost) any indicator

My gift for the community today is my Ultimate Strategy Template

Step 1: Create your connector

Adapt your indicator with only 2 lines of code and then connect it to this strategy template.

For doing so:

1) Find in your indicator where are the conditions printing the long/buy and short/sell signals.
2) Create an additional plot as below

I'm giving an example with a Two moving averages cross.

Please replicate the same methodology for your indicator wether it's a MACD , ZigZag , Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions

//@version=4
study(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)

type_ma1 = input(title="MA1 type", defval="SMA", options=["RMA", "SMA", "EMA"])
length_ma1 = input(10, title = "  [ALL but VWAP] MA1 length", type=input.integer)
type_ma2 = input(title="MA2 type", defval="SMA", options=["RMA", "SMA", "EMA"])
length_ma2 = input(100, title = "  [ALL but VWAP] MA2 length", type=input.integer)

// MA
f_ma(smoothing, [symbol=src]src[/symbol], length) =>
    iff(smoothing == "RMA",     rma([symbol=src]src[/symbol], length), 
     iff(smoothing == "SMA",    [__tag__=simplemovingaverage]sma[/__tag__]([symbol=src]src[/symbol], length),
     iff(smoothing == "EMA",    [__tag__=ema]ema[/__tag__]([symbol=src]src[/symbol], length), [symbol=src]src[/symbol])))

MA1 = f_ma(type_ma1, close, length_ma1)
MA2 = f_ma(type_ma2, close, length_ma2)

// buy and sell conditions
buy        =  crossover(MA1, MA2)
sell       =  crossunder(MA1, MA2)

plot(MA1, color=color_ma1, title="Plot MA1", linewidth=3)
plot(MA2, color=color_ma2, title="Plot MA2", linewidth=3)

plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color_ma1, size=size.normal)
plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color_ma2, size=size.normal)

/////////////////////////// SIGNAL FOR STRATEGY /////////////////////////

Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)

Basically, I identified my buy, sell conditions in the code and added this at the bottom of my indicator code

Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)

Important Notes

🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal, and -1 for the bearish signal

Now you can connect your indicator to the Strategy Template using the method below or that one

Step 2: Connect the connector

1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings and in the Data Source field select your 🔌Connector🔌 (which comes from your indicator)

From then, you should start seeing the signals and plenty of other stuff on your chart

🔥 Note that whenever you'll update your indicator values, the strategy statistics and visual on your chart will update in real-time

Settings

- Color Candles: Color the candles based on the trade state ( bullish , bearish , neutral)
- Close positions at market at the end of each session: useful for everything but cryptocurrencies
- Session time ranges: Take the signals from a starting time to an ending time
- Close Direction: Choose to close only the longs, shorts, or both
- Date Filter: Take the signals from a starting date to an ending date
- Set the maximum losing streak length with an input
- Set the maximum winning streak length with an input
- Set the maximum consecutive days with a loss
- Set the maximum drawdown (in % of strategy equity)
- Set the maximum intraday loss in percentage
- Limit the number of trades per day
- Limit the number of trades per week
- Stop-loss: None or Percentage or Trailing Stop Percentage or ATR
- Take-Profit: None or Percentage or ATR
- Risk-Reward based on ATR multiple for the Stop-Loss and Take-Profit

This script is open-source so feel free to use it, and optimize it as you want

Alerts

Maybe you didn't know it but alerts are available on strategy scripts.

I added them in this template - that's cool because:

- if you don't know how to code, now you can connect your indicator and get alerts
- you have now a cool template showing you how to create alerts for strategy scripts

Source: https://www.tradingview.com/blog/en/stra...

I hope you'll like it, use it, optimize it and most importantly....make some optimizations to your indicators thanks to this Strategy template

Special Thanks

Special thanks to @JosKodify as I borrowed a few risk management snippets from his website: https://kodify.net/tradingview-programmi...

Additional features

I thought of plenty of extra filters that I'll add later on this week on this strategy template

Best
Dave
Release Notes: V2.0
Added the trade direction feature

You can now:

- open only the longs or shorts or both
- close only the longs or shorts or both
Release Notes: - Added the close on opposite mode
When only longs or shorts are selected, close on opposite forces the closing of the trades based on the opposite signal
It's recommended to select it if your backtest is unidirectional without exits (TP, SL, etc...)
Release Notes: - Added two fields for strategy.exit and strategy.entry functions

1) comment (string) An optional parameter. Additional notes on the order. Replaces the {{strategy.order.comment}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.

2) alert_message (string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.

Both placeholders in alerts to make the strategy compatible with automated trading bots (3commas, ProfitView, Gunbot, etc.)
Release Notes: - Added the custom close signal (lines 117 to 119)
Now you can also send a custom close based on your indicator.

Use Case

Your connected indicator already contains signals to exit based on hard exit/indicator and you want to use those signals in the strategy template to exit the opened trades.

How to use it?

Option enabled only if you use the Use Custom Close from the Strategy Template

Use the values:

  • 1 for a Long Entry
  • -1 for a Short Entry
  • 2 for a Close Long Exit
  • -2 for a Close Short Exit

In your connected indicator, update your external connector like this

Signal = buy ? 1 : sell ? -1 : exit_buy ? 2 : exit_sell ? -2 : 0
plot(Signal, title="🔌Connector🔌", transp=100)
Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.

Want to use this script on a chart?
💰 Results/Blogs: https://bit.ly/2ULUtjo

⏩ Signals/Pricing: https://best-trading-indicator.com/pages/pricing

🐦 Twitter: https://twitter.com/bti_trading

👉 Get a $30 discount on TradingView: https://bit.ly/2UM5OA0

📺 Youtube: https://bit.ly/3bKvnZu

Kommentarer

500 coins
+13 Svara
Great, Love to see more scripts from you
200 coins
+3 Svara
Daveatt techtrader29
@techtrader29, it's gonna pay for my coffee this morning
much appreciated, thanks a lot
+4 Svara
seanbaker Daveatt
@Daveatt, Then pay for his coffee too! 😊
+6 Svara
Hi Daveat. Thank you for this beautiful script. Am a complete starter in Pine. If my buy/sell signals require 2 conditions for a trigger, how should it be expressed in each of the steps you mentioned. Any modifications neccessary?
+8 Svara
Daveatt hpq2412
@hpq2412, then I would do something like this in your indicator with the 2 conditions for the trigger

Imagine your 2 conditions are called condition_buy_1 and conditon_buy_2 (and same for the sell signals)

merged_condition_buy = condition_buy_1 and condition_buy_2
merged_condition_sell = condition_sell_1  and condition_sell_2

Signal = merged_condition_buy ? 1 : merged_condition_sell ? -1 : 0
plot(Signal, title="Connector", transp=100)
+9 Svara
hpq2412 Daveatt
@Daveatt, lots of thanks.
+1 Svara
This is massive. I used a template of my own. This has several times more options. The only part that I would be using is to see Trailing Stop exactly where it is, but I can use that part from my template if I need it. Tanks.
+4 Svara
Daveatt greenmask9
@greenmask9, thank you for your kind words
actually, the stop-loss/trailing-stop are being displayed (with a red dotted plot by default)
The trailing stop updates at each new candle
+3 Svara
greenmask9 Daveatt
@Daveatt, I see it now. The plot() function is dug deep beneath all the coding. I am still about to try it.

As I was searching for the function, I found that you only have one capital calculation type - percent of equity. If you want to make further improvements, I suggest adding other viable options. My script also has an option for the percentage of initial capital and also a manually set value which I used for some cryptocurrencies where the other options went error.

And one of my customers wanted a trailing profit function. When the price reached the target OR when the close conditions were triggered, instead of closing, it would enable a trailing stop order which would be closer to the price than the usual trailing stop which is in play from the beginning if it is on.

Lastly, the alert function, if I am not mistaken, does not allow the 3Commas bot commands integration which I worked on too before.

If you want to add any of that or have a look, I can send you a complete code suggestion this weekend. I would just have to find it. Great script regardless ☺
+4 Svara
Hem Aktie-screener Forex-screener Krypto-screener Ekonomisk kalender Om Diagramfunktioner Priser Tipsa en vän Ordningsregler Hjälpcenter Webbsidor och mäklarlösningar Widgets Diagramlösningar Lightweight Charting Library Blogg och nyheter Twitter
Profil Profilinställningar Konto och fakturering Hänvisade vänner Mynt Mina kölappar Hjälpcenter Privata meddelanden Chatt Logga ut