The easiest and most efficient way to make a script that "looks back in time" is to use a
var varible. With a
var variable you can save data without it being erased at the next bar. When one indicator crosses over another you save the current
bar_index value to the
var variable.
You can then subtract the current
bar_index value with the
var variable value and see how many bars back the crossover occurred. Or in your case you subract the different
var varibles and see how close they are to each other.
I made a script that plots an "X" where your buy condition is true. You may need to change some values to make it buy right.
On the right, you can see at what
bar_index the last crossover occurred. You man move the mouse over the price to make them change in realtime.
Here is the script:
Code: Select all
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CanYouCatchMe
//@version=4
study("many indicators crossover", overlay=true)
//All the indicators
st_fast = stoch(close, low, high, 20)
st_slow = stoch(close, low, high, 100)
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
ema_fast = ema(close, 10)
ema_slow = ema(close, 20)
//Saving the index when the indicators cross over. It is a "var", so the variable is saved between bars.
var int st_crossover_index = na
var int macd_crossover_index = na
var int ema_crossover_index = na
//Checking when they are crossed over and adding the index to the "var"
if (crossover(st_fast, st_slow))
st_crossover_index := bar_index
if (crossover(macdLine, signalLine))
macd_crossover_index := bar_index
if (crossover(ema_slow, ema_fast))
ema_crossover_index := bar_index
buy_condition = false
//Checks the distance between the indexs and buying
if (st_crossover_index < macd_crossover_index) //The Stochastic Crossover must always occur at least 1 Bar before the MACD Crossover
if (abs(st_crossover_index - macd_crossover_index) <= 5) //Once the Stochastic Crossover occurs the MACD Crossover must occur within 5 bars. The abs() is used to make the distance positive.
if (abs(macd_crossover_index - ema_crossover_index) <= 8) //Once the MACD Crossover occurs the EMA Crossover must occur within 8 bars
buy_condition := true
plotshape(buy_condition, style=shape.xcross, color=color.green, size=size.small) //Plotting an green "X" where it should buy
//Writeing the varible value in "Data Window" on the right. For Debugging
plotchar(st_crossover_index, "st_crossover_index", "", location = location.top)
plotchar(macd_crossover_index, "macd_crossover_index", "", location = location.top)
plotchar(ema_crossover_index, "ema_crossover_index", "", location = location.top)