Has touched

Created at 28 Aug 2017, 15:58
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
HT

HTtrader

Joined 19.07.2017

Has touched
28 Aug 2017, 15:58


Hi all,

I am onto my next project now and need a little help. I am wondering how exactly would I code an Onbar action that recognises if the bar has touched or has not touched an indicator.

I am trying to code 20EMA and have the last  x number of bars to not have touched the EMA.

I have looked at using hascrossedabove and hascrossedbelow, but was wondering is this the right approach?

Thanks for an answer,

Tony


@HTtrader
Replies

croucrou
28 Aug 2017, 17:04

RE:

Make a "for" loop up to 20, to check if the moving average is smaller than the bar's high and higher than the bar's low at the same time.


@croucrou

HTtrader
30 Aug 2017, 14:32

Hi Croucrou,

If I understand you right something like should work?

protected override void OnBar()
        {
            var last = ema.Result.Last(0);

            Print("{0}", last);

            int N = 10;
            var open = MarketSeries.Open.Last(N);
            var close = MarketSeries.Close.Last(N);
            var high = MarketSeries.High.Last(N);
            var low = MarketSeries.Low.Last(N);
            for (int N = 10; N >= 0; N--)
            {
                if (last < ema && last > ema)
                {
                    Print("No touch EMA for last {0} bars", N);
                }
            }

where N is last number of bars rather than 20 I can specify any number


@HTtrader

croucrou
01 Sep 2017, 01:27

I would do it like:

        MovingAverage myEma;
        int x;

        double ema(int index)
        {
            return myEma.Result.Last(index);
        }

        protected override void OnStart()
        {
            myEma = Indicators.MovingAverage(MarketSeries.Close, 20, MovingAverageType.Exponential);
        }

        protected override void OnBar()
        {
            x = 10;

            for (int i = 1; i <= x; i++)
            {
                if (ema(i) >= MarketSeries.Low.Last(i) && ema(i) <= MarketSeries.High.Last(i))
                    break;
                else if (i == x && !(ema(i) >= MarketSeries.Low.Last(i) && ema(i) <= MarketSeries.High.Last(i)))
                    Print("The price haven't touched EMA for the last {0} bars", i);
            }
        }

Notice that OnBar logic is executed with the start of new bar, so it doesn't take the action on the current bar into account.

If you want to include the current bar into the check, you might want to use OnTick. 


@croucrou