Tradingview: Stop Losses

This weeks post comes courtesy of CryptoJoncis, a Backtest Rookies reader who got in touch via Twitter looking for some help with setting stop losses in Tradingview. So without further ado, let’s dive into it.

Stop Loss Fundamentals

Before we dive into code examples showing how to set a stop loss, it is useful to understand the fundamentals behind stop losses/stop orders. Once you have a good grasp on the basics, the strange behaviour that you think you are seeing likely has a valid reason.

It may seem counter-intuitive but stop losses are not always used for stopping losses. This is because you can actually send a stop order to the market when you don’t even hold a current position. Due to this, they are often called stop orders instead of stop losses.

Stop orders really refer to an order to buy or sell something at a disadvantageous price. In other words, a price that is worse than you can have now. So when you are in a long position, that makes sense. We set the stop price at a level lower than the current (or entry) price even though we could sell now for a better price.

So why would you send a stop order when you are not in a position and why would you choose to do this at a worse price than you could have now? Well, one case might be to send a stop order right on a breakout level above the current price. This will allow you to enter the position right at the exact moment price breaks out. If you take a look at Tradingview’s built-in PSAR strategy, you will see that the strategy does just that!


Once a stop order is sent it sits on your broker’s or the stock exchange’s order book (If you have direct market access). The order then sits there until it is triggered, expires or is cancelled. In the real world, triggering means that someone else has executed a market order and is willing to trade at the level you set. The two trades are then matched up and a transaction occurs.

However, In our backtesting isolation, things do not quite work this way. We are testing with historical data and without any transaction history. It is just assumed that you would be filled at the order level you set. This assumption is fine for very liquid markets like S&P500 stocks, Bonds, Forex etc but not for small-cap stocks. This is because in markets where there are not a lot of people buying and selling,, there might not actually be anyone willing to buy at that your stop loss level! You will then be filled at the next closest price that someone is willing to buy at. This is known as slippage and probably a topic for another day.

Sending Stop Orders:

Ok, so back to Tradingview and Pine-Script. There are actually a number different functions that we can use to send a stop order into the market. These are:

  • strategy.entry()
  • strategy.exit()
  • strategy.order()

One of the first questions that spring to mind for beginners is which one should you use? Unfortunately, the answer is all of them! There is a reason why the Tradingview team offer multiple functions and each is useful in different scenarios. So instead of telling you which to use, let’s take a look at ideal use-cases for each function.

If you are looking to use a simple stop loss to EXIT a position, it is easier to work with strategy.exit().

If you want to use a stop order to ENTER a position rather than exit one, then strategy.entry() is the function to use. All you need to do is add the stopparameter and provide a valid price that is worse than the current price. In other words, a higher price for a long entry or a lower price for a short entry. If you are wondering what the stopparameter is and how to use it, don’t worry, an example shall follow later.

Finally, if you just want to perform some advanced position management (e.g take of half a position) or link orders together (so one order cancels another), then the strategy.order()function is for you.

Simple Stop Loss Example

In our first example, we are going to set a simple stop loss using the strategy.exit()function. To demonstrate this effectively, we should already be in a position. Therefore the code below includes some simple entry criteria. In addition, it shall also show you how to plot the stop loss on the chart.


To calculate the stop level, our example uses strategy.position_avg_priceas a base. This allows use to determine the entry price. When we know our entry price, we can easily set a stop loss at a level above/below that price. Note that strategy.position_avg_price works well if you only have one entry. If you like to work into positions over a few trades, then this might not be the best option for you as each new entry would affect the average price and therefore the stop loss.

The example has been coded in a way that we can return a value for the stop loss every single bar. This allows us to easily plot the stop loss. Plotting the stop-loss lines enables us to quickly see what has happened in our strategy and why the position has exited.

It is also worth noting that, when we don’t have a position in the market the strategy.position_avg_pricevalue equals na. This is again helpful for plotting because we are able to plot the stop loss line only when we are in a position. nais never plotted.

However, to ensure this is plotted tidily, the linebrstyle should be used. This will ensure that you don’t have long lines joining up gaps between when the value is na. You will see the difference if you just use a normal line style.

Stop Losses: Simple Stop Loss

Loss vs Stop

If you read the documentation for strategy.exit(), you might notice that there are two very similar sounding parameters. These are stopand lossso what is that all about?

Some people love to work in ticks, others prefer to work with price levels. That pretty sums up the difference between these two parameters. Thelossparameter expects to receive a value measured in ticks whilst the stopparameter expects to receive a specific price.

Here is a quick example of code using ticks to define the loss level.

As you will see in the code, the using the lossparameter is a bit easier. You just provide the number of ticks you want to set and away you go. However, this method is not without its drawbacks. First of all, it is harder to calculate you $ amount of risk unless you work with the syminfo.mintickparameter to determine the value of one tick.

If you are new to trading, the minimum tick is the smallest amount that price can move from one level to another. In other words, stocks, shares etc cannot be valued at any price imaginable. The move in small fixed steps.

Incorrect Prices

The next thing one must be aware of is that you set your stop loss levels on the correct side of price. If you don’t do this, the stop loss will trigger immediately at the open of the next bar. Let’s take a look:

The following example shows a chart where the stop loss level is passed for a long trade above the current price level.

Stop Losses: Example chart showing what happens when incorrect stop loss prices are set

We can see that the stop loss is triggered immediately on the bar it entered the market. If we look at a long example, this is because the price is already below the stop level we requested.  As we learned in the fundamentals section, a stop order is triggered whenever price touches or goes beyond the stop level. Therefore it must be triggered immediately.


The strategy.order()is perhaps the most flexible function as it can be used to both enter and exit positions. In addition, it can be used to add or remove a specific qty from a position.

The added flexibility, also brings added complexity and as such, there are a number of things one must be aware of when using it:

  • First of all, we need to set whether the order is an order to buy or an order to sell. We do this using trueorfalseas you will see in the example code below.
  • We cannot place a stop and limit level inside the same order.
  • Once an order is in the market, we need to remember to cancel it once we no longer want it. Otherwise, it will sit there forever until it is triggered. This is especially true when working with multiple orders such as a take profit and a stop loss at the same time. I.e Once the take profit is triggered, we no longer need the stop loss. If you don’t cancel the order, it could eventually force you into a new position. To avoid this we are able to link orders together using the oca_name and oca_typeparameters so that when one order is triggered, the other is automatically cancelled.
  • Tradingview places a limit on backtests of 2000 orders. Using strategy.order() can end up eating into the 2000 order limit very quickly. To combat this, it is a good idea to create the order inside an ifstatement or use the whenparameter to limit how often an order is sent. This will ensure you don’t fire off a new order every single bar!

This script should act in the same manner as the first simple stop loss example above. However, you will immediately notice that the code is more complex. Therefore I don’t recommend using strategy.order()for simple stops. Save this one for when you want to start experimenting with more complex strategies and having multiple orders in the market.

Stop Order Entry Example

Moving onto our final example, we are going to use stop orders to enter the market. We will do this using the stopparameter of strategy.entry(). The result is that we are able to enter the market at the exact moment when price touches a 200 period moving average.

In this example, we can see that we are using a stop order to enter the market but we don’t actually enter a position until the order is triggered. I.e until price touches the 200 day MA.

Stop Order used for entry on a 200 day SMA

And there we have it…

I hope this provided an easy to follow overview of how to set a stop loss in pine-script. If not, let us know in the comments below and the article will be updated!

Find This Post Useful?

If this post saved you time and effort, please consider support the site! There are many ways to support us and some won’t even cost you a penny.