TradingView quirks — blending candles
Sometimes trading strategies seem too good to be true. We found a great one recently and only after a lot of digging around did we find out that TradingView quirks were causing the problem.
This post is to help others understand that there is a TradingView bug to be aware of. There are a lot of Pine scripts still circulating that rely upon this bug for their great performance.
A strategy that is too good to be true
Here is a simple strategy script that looks to get great results. This strategy does a great job of buying low and selling high and generate massive profits using the TradingView strategy tester.

This strategy trades on the 4 hour timescale but uses information from longer time periods (roughly 1 day candles) in making its decisions.
The offending Pine script
Here is the Pine script that looks to get great results …
//@version=2
strategy("My Strategy", overlay=true)tim=input('1360')
out1 = security(tickerid, tim, open)
out2 = security(tickerid, tim, close)
plot(out1,color=red)
plot(out2,color=green)
longCondition = crossover(security(tickerid, tim, close),security(tickerid, tim, open))if (longCondition)
strategy.entry("long", strategy.long) shortCondition = crossunder(security(tickerid, tim, close),security(tickerid, tim, open)) if (shortCondition)
strategy.entry("short", strategy.short)
The TradingView bug
The issue is caused by these two lines
out1 = security(tickerid, tim, open)
out2 = security(tickerid, tim, close)
The security()
function (documented here) is meant to enable this bot to pick up values from candles different than the candle period chosen in the chart. In the image above, the chart is on the 4 hour candle and the algorithm wants to look at the most recent 1360 minute candle (almost one day) for triggers.
When doing the backtesting, though TradingView does something different. It looks forward rather than looks back when using the security()
function. This is definitely not the behaviour you would expect in a backtest as it allows the algorithm to take a future price into account in deciding if it should be long or short now.
Is this a real bug or just very badly documented? The look forward is mentioned in the documentation if you read it carefully, but it is certainly not expected behaviour, and has caught many people out. I would like TradingView to document it much more clearly.
So we got some pretty fantastic strategy results using the security()
function in TradingView that were an illusion. If you are doing backtesting using TradingView then be careful if your script includes this function.
If it looks too good to be true, then it probably is …