Tradingview: Simulating Positions in a Study

It seems that more and more people are interested in using Tradingview as a tool for fully automating strategies. Although it is not something I recommend (for reasons we will go into later), there are some arguments going for it. Namely, users can continue to use a platform they are familiar with. Additionally, they don’t need to learn a new coding language and they don’t need to spend more time/energy porting their strategy to another platform. Afterall, a lot of Tradingview users and pine script beginners are not developers by trade. If you find yourself nodding in agreement with the last few sentences, then this post is for you. We will look at one of the first basic techniques you need in order to simulate strategy functionality in a study script.

Why do we need to simulate positions?

First, for those unaware, it should be noted that at the time of writing, Tradingview does not officially support automated trading in any capacity. This is surprising to some people. They see that Tradingview can connect to brokers and allow them to place trades manually. This leads to the assumption that pine script can be used for Trading. However, it cannot. There is no link between pine script and any of the supported brokers at the moment.

Since there is a clear market demand for fully automating via Tradingview, a series of 3rd party services or browser extensions such as Autoview have emerged. They generally take advantage of Tradingview’s alert system to execute trades. They monitor browser notifications or email alerts and then read the contents of your alertcondition() message. This will tell it what to buy or sell and the service will then connect to your exchange and perform the trade for you.

So now we know a bit of background and we know that we need to use Tradingview’s alert system. This will help understand what we need to use a study() script and ultimately, why we need to simulate strategy() script functionality. The issue we have is that (again at the time of writing) we can not add alerts to a strategy script. They can only be added to study scripts (indicators). This means we need to redevelop our strategies as indicators.

And a study script comes with it’s own limitations

Just as a strategy()script does not have access to the alertcondition()function, study()scripts do not have access to a whole host of strategy specific variables and functions. Some of these include, but are not limited to the following:

  • strategy.position_size
  • strategy.position_avg_price
  • strategy.open_profit
  • strategy.entry()
  • strategy.exit()

To name just a few…

You can imagine then that if you want to use a stoploss and have no access to strategy.exit(), you would need to simulate sending an order to the market and monitoring it to see when it would have been executed yourself. The same goes with any of the other built-in variable that you want to use. Want to know your average price? Well, if you allow for scaling in, you will need to keep track of the entry price and size for every buy/sell in the position before it can be calculated.

As you can imagine, the more complex the strategy, the more difficult it will be to port. For this reason, this post cannot tackle every tool needed in your toolbox but we can at least make a start. So as the title suggests, let’s take a look at simulating whether we are in a position.

A Word Of Warning

Personally, I am not a fan of using Tradingview for actually running live strategies and trading with real money. There are a number of reasons for this which include.

  • Live Trading is not officially supported. Tradingview can change the platform at any time which may break compatibility with our extensions/services.
  • The Alerts system was not designed for automated trading. Don’t expect immediate alerts. Don’t even expect to receive alerts every time.
  • Requires 3rd party plugin’s to bridge the gap between Tradingview and your Broker/Exchange. We now have an extra point of failure.
  • There is no communication between the broker and Tradingview. Your study()has no idea whether your order was filled or rejected or slipped a few dollars. It just assumes you entered and carries on. It has no idea if your position was liquidated or closed by the broker. The list goes on.
  • Following on from above – It is really easy to lose synchronization between the study() and what is happening in real life. This can be quite dangerous to your wallet. If your study()thinks you are flat when you are actually in a position, you could end up with double the size you intended (more risk) at a higher average cost price. Or maybe you end up in a short position when you intend to be long.

When real money is on the line, it is better to use tools which were made for the job. We wouldn’t use a cricket bat to tee off at the first hole. Sure it is possible to hit the golf ball down the fairway, but the cricket bat does not have the precision, power, control and accuracy needed to get the ball anywhere near the green. Similarly, using Tradingview in conjunction with 3rd party services can get the job done, much in the same way as the cricket bat on a golf course but you may ultimately end up frustrated and out in the bushes.

Simulating Positions

Ok, so if you are still reading and have not been put off, let’s get to it! The following code snippet provides a simplified way of simulating positions. There are many ways to skin a cat and as your strategies become more complex, this method may no longer be suitable. It assumes that we only allow one entry at a time (No pyramiding/scaling in).

So why simulate positions anyway? The idea is to ensure that we only receive an alert when a strategy would buy and sell. The issue some people find is that the buy and sell conditions can be trueeven whilst you are in a position. This means that an alert will fire again and we might not want to buy and sell again. Therefore, we should take action to prevent unwanted alerts from firing.

Base Strategy

To highlight this issue, we will take a simple strategy. Once it is converted it to a study, we should see that multiple long or short alerts will fire in a row. In the examples below, we will plot a marker on the chart whenever the alertcondition() is true. This will allow you to see when an alert would have fired.

The base strategy we shall use is available as one of Tradingview’s built-in strategy. It will enter a position after a number of consecutive green or red candles are detected. Given that a consecutive run of green/red candles is quite common, it should be perfect for this post.

Conversion to Study

Now we will do the most basic of conversions. We shall simply:

  • Change strategy()to study()
  • Remove the strategy.entry() calls
  • Add alertconditions() when ups >= consecutiveBarsUp and dns >= consecutiveBarsDown
  • Plot markers on the chart when our alert conditions are met.

The Code

So after the simple conversion, we can place the base strategy and study on the charts at the same time. Once we compare the two, it becomes immediately obvious that something is not quite right.

Comparison of Study and Strategy

On the chart above, we have added both the Base strategy and converted study at the same time. The strategies, entries and exits can be clearly seen. Then we have the green and red arrows which show the alert conditions from the study script. We can see that the study is firing off alerts much, much more frequently than the strategy is entering and reversing positions. This is not ideal.

The Simple Solution

Below is the final code snippet where we add some extra basic checks to see if we are in a position or not. We then only allow a long alert if we are short or flat. Similarly, we only allow a short alert if we are long or flat.

And when we plot the code above on the charts, we can immediately see the difference.

Study showing simulating positions

Now, some readers might point out that the markers are early. Those readers may also assume that it is not in sync! However, remember that for a normal market order, it is always executed at the open of the following bar. In other words, the conditions are true on the strategy on the bar before you see the Long/Short markers on the chart. We want the same with our alerts. They should fire at the close of the bar so we can try and open a position as near to the open of the following bar as possible.