How to write your own stock trading strategy / Indicator on TradingView
Being a trader working with Technical Analysis , we all look at multiple indictors like RSI , MACD , Moving Averages , Bollinger Bands … and the list goes on . In order to confirm our trades , we check these indicators , and combine it with other strategies like support, resistance, volume etc. When they all give a definite signal , we take position.
There is a way we can script(automate) this logic using TradingView’s PineScript. With Pinescript ->
- We can create a new strategy (combination of multiple indicators and logic)
- An indicator for that strategy
- Backtest it (test it against the previous time duration — past candles) — how well it could have performed .
And once the strategy gives us a signal , we can set alarms or in case you are making a trading bot , you can automate the process of taking positions as well.
Writing a simple strategy script (using sma crossover )
Let’s look at an easy example to get a better understanding. Suppose our strategy is -> we get confirmations from the values of SMA(Simple Moving Averages — SMA-9 and SMA-20) , whenever sma9 crosses up sma20 , we long or buy otherwise we sell or short when sma20 crosses up sma9.
sma 9 — blue
sma20 — red
- point 1 -> sma20 has crossed up sma9 , hence short
- point 2 -> sma9 has crossed up sma20 , hence long
Let’s begin :
Go to Pine Editor tab on any chart on tradingview ->
and start writing below code ->
strategy(“sma-x”)sma9 = ta.sma(close,9)
sma20 = ta.sma(close,20)plot(sma9 , “SMA9” ,color=color.new(#0000ff, 0), linewidth=3)
plot(sma20 , “SMA20” ,color=color.new(#ff0000, 0), linewidth=3)
- “strategy” is a built-in funtion and we have given a name “sma-x” a name for it
- sma9 and sma20 are variables to which we are assigning sma values , you can name it anything.
- “ta.sma” , is a built-in function for simple moving average.
— close,9 => it will calculate sma for values of candle closes for past 9 candles. (Instead of close , you can have high,low,open as well)
— close,20 => it will calculate sma for values of candle closes for past 20 candles.
- plot is a built-in function , to plot your indicators (sma9 and sma20 in our case) on the chart. It’s arguments are self-explanatory ->
#1 — value to plot
#2 — name of the indictor line to plot
#3 — color of the line
#4 — line width.
At this point click on the “Add to Chart” and you will see lines plotted on chart.
Create a strategy entry condition and backtest time frame -
longcond = ta.crossover(sma9,sma20)
shortcond = ta.crossover(sma20,sma9)start = timestamp(2021,01,01,0,0,0)
end = timestamp(2026,01,19,0,0,0)
- longcond — is true if “ta.crossover(sma9,sma20)” happens where ta.crossover is a built-in function , i.e sma9 crosses up sma20. Similar for shortcond.
- start and end — are our start and end date of backtesting to test our indicator , where timestamp is a built-in function , date format here used is (yyyy,MM,dd,hh,mm,ss) .
Tip → all built-in functions will be blue in color and you can read the documentation (how to use them) by ctrl+click if using windows or command+click for mac.
Place orders (for backtesting or future signals)
if time>=start and time<=end
strategy.entry(“Long”,strategy.long,100,when=longcond)
strategy.entry(“Short”,strategy.short,100,when=shortcond)longExitPrice = strategy.position_avg_price * (1 + 0.01)
shortExitPrice = strategy.position_avg_price * (1–0.01)
- time is a in-built keyword which will compare to our start and end , if time is in our provided range , we will take entry for long and short.
- strategy.entry is a built-in funtion for taking position , arguments (id of the position , strategy direction (long or short ) , quantity , )
- when , condition of the order , in our case if longcond or shortcond will be true corresponding entry will execute.
- longExitPrice and shortExitPrice are the prices where we exit the market position. For both sides , when the price difference (profit) is 1% , we exit the trade.
Finally , exiting the position …
if strategy.position_size > 0if strategy.position_entry_name == “Long”
strategy.exit(“Long”,limit=longExitPrice)if strategy.position_size < 0if strategy.position_entry_name == “Short”
strategy.exit(“Short”,limit=shortExitPrice)
- strategy.position_size, If the value is > 0, the market position is long, If the value is < 0, the market position is short. So if current position taken is Long , then exit “Long” and vice versa.
- strategy.exit , is a built-in funtion to exit the position , where limit is the exit price.
The complete code (with stoploss price as well)->
* Be very careful if you’re copy pasting the code from here , as the characters might change when you paste in strategy editor of TradingView. If that happens , just write it from the scratch in the editor.
* Take notice of the spaces as well while typing/copying ,as pine script uses whitespace indentation to define scope similar to python.
strategy(“sma-x”)sma9 = ta.sma(close,9)
sma20 = ta.sma(close,20)plot(sma9 , “SMA9” ,color=color.new(#0000ff, 0), linewidth=3)
plot(sma20 , “SMA20” ,color=color.new(#ff0000, 0), linewidth=3)longcond = ta.crossover(sma9,sma20)
shortcond = ta.crossover(sma20,sma9)start = timestamp(2021,01,01,0,0,0)
end = timestamp(2026,01,19,0,0,0)if time>=start and time<=end
strategy.entry(“Long”,strategy.long,100,when=longcond)
strategy.entry(“Short”,strategy.short,100,when=shortcond)// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 — .1)
shortStopPrice = strategy.position_avg_price * (1 + .1)longExitPrice = strategy.position_avg_price * (1 + 0.01)
shortExitPrice = strategy.position_avg_price * (1–0.01)if strategy.position_size > 0if strategy.position_entry_name == “Long”
strategy.exit(“Long”,limit=longExitPrice,stop=longStopPrice)if strategy.position_size < 0if strategy.position_entry_name == “Short”
strategy.exit(“Short”,limit=shortExitPrice,stop=shortStopPrice)
That’s it , as soon as you save the script , you will be redirected to Strategy Tester, which will show you the backtesting results, how your strategy would have performed for the time period specified.
- As you can see , we took 552 trades for this time period with this strategy , not so profitable as you can see , Net profit is quite negative.
- You can go to List of Trades to see what all trades we entered and exited.
Making the condition stricter ->
Let’s replace order position conditions — longcond and shortcond with the following -
longcond = ta.crossover(sma9,sma20) and volume[1] > volume[2]
shortcond = ta.crossover(sma20,sma9) and volume[1] > volume[2]
- where previous candle volume values are accessed with square brackets operator []. So if both crossover and volume conditions are true , then only position is entered.
Now that our condition has more variables , number of trades are reduced and profitability increased.
- So , go ahead and code out your strategy , use all the indicators that you use and make use of TradingView’s Pinescript documentation to explore more functions that will be helpful to implement your strategy.
- You can also add alerts in your code which I’ve not covered in this article. So when the condition is true , you can get alerts on email as well and take positions accordingly.
- A lot of Pinescript examples are on https://kodify.net/tradingview-programming-articles/ for your reference.
Note — The script results and values will change according to the time frame , right now we have done all our testing on 1h charts.
Goodluck and let me know in the comments how your strategy works !!!
Support me @ https://www.buymeacoffee.com/sairavdev