show 2 most recent instances only


Category:
0
0

Hi all,
I have a code that checks every bar and display up/down arrow when price crosses EMA. I only want it to show the last two instances instead of every candle on the chart because it is too messy to look at during market hours. What can I add to my code to make that happen. Your help is greatly appreciated.

input MA_Period1 = 10;
input averageType = AverageType.EXPONENTIAL;

def ema1 = MovingAverage(averageType, close, MA_Period1);

plot signal = open < ema1 and close > ema1;
plot signal2 = open > ema1 and close < ema1;
signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
signal.SetDefaultColor(Color.magenta);
signal.SetLineWeight(1);
signal2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signal2.SetDefaultColor(Color.magenta);
signal2.SetLineWeight(1);

 

Attachments:
RESOLVED
Marked as spam
Posted by (Questions: 1, Answers: 1)
Asked on August 7, 2020 4:42 pm
67 views
1
Private answer

The only way you can do this is to create a loop that looks backward to find the last two signals and remove all the signals that came before them. There is no way for the code to know how many bars back it needs to look to find those two signals. So the code needs to loop through every single bar in the chart, backwards. And it needs to run that loop every time a price changes on the chart. The code itself is already running a loop from left to right. Now we have to add another loop that runs from right to left. The loop that runs from left to right is adding plots to the chart while the loop that runs from right to left is removing some of them. Sound like complete madness yet? It should, because it is.

The performance hit for doing something like this far out-ways the benefit of removing those extra signals. Especially for a trading platform that runs on the Java VM, especially for a trading platform that is already plagued by poor performance during heavy market activity, especially for a trading platform that uses a scripting language. I hope by now you get the idea.

The best solution we could apply in this environment is to declare a specified number of bars to the left of the last bar on the chart. Let's arbitrarily pick 20 bars. Then create a filter that is only true for the last 20 bars on the chart. We then use that filter as a true/false condition to limit any signals from plotting to only the last 20 bars on the chart.

input numberOfBars = 20;
def okToPlot = IsNaN(close[-numberOfBars]);

Now, how do you use that in your code?

plot signal = if okToPlot then open < ema1 and close > ema1 else no;
plot signal2 = if okToPlot then open > ema1 and close < ema1 else no;

Marked as spam
Posted by (Questions: 37, Answers: 4086)
Answered on August 7, 2020 7:33 pm