Replies

DR.SHADI_JARRAR
17 May 2024, 21:30

RE: Robot Backtesting doesnt work for all pairs!

PanagiotisCharalampous said: 

Hi there,

Can you please provide more information about the issue? What do you mean when you say it doesn't work? Can you share the source code as well as steps to reproduce?

Best regards,

Panagiotis

simply the cbot doesnt excute any positions in all pairs except in indices. here is the result of backtesting when used with Japan225 for example:

 

On the other hand, for usdjpy backtesting this is the result: 

 

 

 

Here is the code of the cbot: 

 

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using System.Linq;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class YarabRobot : Robot
    {
                // تحديد الثوابت والمراجع
        private Yarabindicator _Yarabindicator;
        private bool tradeExecutedThisHour = false;
        private double initialLotSize = 0.01;
        private double currentLotSize = 0.01; 
        private bool previousPositionInLoss = false; 
        private bool IsNewHour()
        {
            return Server.Time.Minute == 0 && Server.Time.Second == 0;
        }

                // استدعاء المؤشر
        protected override void OnStart()
        {
            // Initialize the dLagema indicator
            _Yarabindicator = Indicators.GetIndicator<Yarabindicator>(3, 100, 60,1, 7,17);
        }

                // طريقة البار لفتح الصفقات

                 protected override void OnBar()
        {
                    int index = MarketSeries.Close.Count - 1;
                    
            // السماح بفتح الصفقات لمرة واحدة فقط بمجرد بداية الساعة                 
                if (IsNewHour())
                tradeExecutedThisHour = false;
            
            // اشتري بهذه الشروط واعلن اتمام فتح صفقة
            if ((Bars.ClosePrices[index-1] > _Yarabindicator.DLagEMAs[index-1]&&Bars.ClosePrices[index-2] < _Yarabindicator.DLagEMAs[index-2]) )
            {
                ExecuteMarketOrder(TradeType.Buy, Symbol, currentLotSize, "Open BUY Position", null,null,null, "Buy");
                tradeExecutedThisHour = true;
            }
            // بيع بهذه الشروط واعلن اتمام فتح صفقة
            else if ((Bars.ClosePrices[index-1] < _Yarabindicator.DLagEMAs[index-1]&&Bars.ClosePrices[index-2] > _Yarabindicator.DLagEMAs[index-2]))
            {
                ExecuteMarketOrder(TradeType.Sell, Symbol, currentLotSize, "Open SELL Position",null, null,null, "Sell");
                tradeExecutedThisHour = true;  
                
            }
         }    
         
         
                // طريقة التيك لاغلاق الصفقات
        protected override void OnTick()
        {
                    int index = Bars.ClosePrices.Count - 1;


            // أغلق صفقة الشراء باحدى الحالتين التاليتين
            if (Bars.HighPrices[index ] > _Yarabindicator.sr[index ]||Bars.LowPrices[index ] < _Yarabindicator.DLagEMAs2[index ] )
            {
                var buyPositions = Positions.Where(p => p.TradeType == TradeType.Buy).ToList();
                foreach (var position in buyPositions)
                    
                    if (position.GrossProfit < 0)
                    {
                    currentLotSize=currentLotSize*1;
                    ClosePosition(position);
                    }
                    else if (position.GrossProfit > 0)
                    {
                    currentLotSize=initialLotSize;
                    ClosePosition(position);
                    }
            }

            // أغلق صفقة الشراء باحدى الحالتين التاليتين
            if (Bars.LowPrices[index ] < _Yarabindicator.sr[index ]||Bars.HighPrices[index ] > _Yarabindicator.DLagEMAs2[index ])
            {
                var sellPositions = Positions.Where(p => p.TradeType == TradeType.Sell).ToList();
                foreach (var position in sellPositions)
 
                    if (position.GrossProfit < 0)
                    {
                    currentLotSize=currentLotSize*1;
                    ClosePosition(position);
                    }
                    else if (position.GrossProfit > 0)
                    {
                    currentLotSize=initialLotSize;
                    ClosePosition(position);
                    }
            }     
        }
       }
      }
 


@DR.SHADI_JARRAR

DR.SHADI_JARRAR
13 May 2024, 18:33

RE: Help: indicator plots different on historical data and in backtesting!

PanagiotisCharalampous said: 

Hi there,

Calculate() method is called once per bar for historical bars and once per tick for live bars. The part below will behave differently when the method is called once per bar, compared to once per tick

            if ((Bars.ClosePrices[index] > DLagEMAs[index] && Bars.ClosePrices[index - 1] < DLagEMAs[index - 1]) ||               (Bars.ClosePrices[index] < DLagEMAs[index] && Bars.ClosePrices[index - 1] > DLagEMAs[index - 1]))            {                barsSinceEvent = 0;            }            else            {                barsSinceEvent++;            }

You need to rethink your logic and make sure this part is called only once for each bar.

Best regards,

Panagiotis

Thanks for your response, I really did my best several ways but couldnt solve it yet, can you suggest anyway to do it!


@DR.SHADI_JARRAR

DR.SHADI_JARRAR
13 May 2024, 08:57 ( Updated at: 13 May 2024, 10:13 )

RE: Help: indicator plots different on historical data and in backtesting!

PanagiotisCharalampous said: 

Hi there,

It looks like a logical bug in your code. Share your indicator code in case somebody can have a look and spot it.

Best regards,

Panagiotis

thank for your reply .. here is the indicators code: 

using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class DoubleLagEMA : Indicator
    {
        [Parameter("Period", DefaultValue = 3)]
        public int Period { get; set; }

        [Parameter("EMA Period", DefaultValue = 100)]
        public int EMAPeriod { get; set; }

        [Parameter("Rlagema Period", DefaultValue = 60)]
        public int RlagemaPeriod { get; set; }

        [Parameter("Smoothing Period", DefaultValue = 30)]
        public int SmoothingPeriod { get; set; }

        [Parameter("Factor", DefaultValue = 10)]
        public int Factor { get; set; }

        [Output("DLagEMAs", LineColor = "DodgerBlue")]
        public IndicatorDataSeries DLagEMAs { get; set; }

        [Output("Rlagema", LineColor = "Red")]
        public IndicatorDataSeries Rlagema { get; set; }

        [Output("Smooth", LineColor = "Yellow")]
        public IndicatorDataSeries sr { get; set; }

        private ExponentialMovingAverage _ema1;
        private ExponentialMovingAverage _ema2;
        private MovingAverage smoothenedRlagema;
        private MovingAverage _emaRlagema;
        private int barsSinceEvent = 0;
        private AverageTrueRange atr;

        protected override void Initialize()
        {
            _ema1 = Indicators.ExponentialMovingAverage(Bars.ClosePrices, Period);
            _ema2 = Indicators.ExponentialMovingAverage(_ema1.Result, EMAPeriod);
            smoothenedRlagema = Indicators.MovingAverage(Rlagema, SmoothingPeriod, MovingAverageType.Exponential);
            _emaRlagema = Indicators.MovingAverage(Bars.OpenPrices, RlagemaPeriod, MovingAverageType.Exponential);
            atr = Indicators.AverageTrueRange(1000, MovingAverageType.Exponential);
        }

        public override void Calculate(int index)
        {
            DLagEMAs[index] = _ema2.Result[index] + _ema2.Result[index] - _ema1.Result[index];

            if ((Bars.ClosePrices[index] > DLagEMAs[index] && Bars.ClosePrices[index - 1] < DLagEMAs[index - 1]) ||
               (Bars.ClosePrices[index] < DLagEMAs[index] && Bars.ClosePrices[index - 1] > DLagEMAs[index - 1]))
            {
                barsSinceEvent = 0;
            }
            else
            {
                barsSinceEvent++;
            }

            if (barsSinceEvent > Factor * 5)
            {
                barsSinceEvent = Factor * 5;
            }

            var difference2 = Bars.OpenPrices[index] - _emaRlagema.Result[index];
            Rlagema[index] = Bars.OpenPrices[index] + difference2;

            if (Bars.ClosePrices[index] > DLagEMAs[index])
            {
                sr[index] = smoothenedRlagema.Result[index] + atr.Result[index] * (Factor - barsSinceEvent * 0.2);
            }
            else if (Bars.ClosePrices[index] < DLagEMAs[index])
            {
                sr[index] = smoothenedRlagema.Result[index] - atr.Result[index] * (Factor - barsSinceEvent * 0.2);
            }
            else 
            {
                sr[index] = smoothenedRlagema.Result[index];
            }

        }
    }
}

 

 

 

 

and here is the robots code:

 

 

 

 

using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class DoubleLagEMARobot : Robot
    {
        private DoubleLagEMA _doubleLagEMA;
        private const double LotSize = 0.1;

        protected override void OnStart()
        {
            _doubleLagEMA = Indicators.GetIndicator<DoubleLagEMA>(3, 100, 60, 30, 10);
            
        }

        protected override void OnBar()
        {             int index = Bars.ClosePrices.Count - 1;

            // Closing previous sell position and opening new buy position if the previous bar closes above and the bar before it closes below Dlagemas
            if (Bars.ClosePrices[index-1] < _doubleLagEMA.DLagEMAs[index-1] && Bars.ClosePrices[index] > _doubleLagEMA.DLagEMAs[index])
            {
                CloseSellPositions();
                ExecuteMarketOrder(TradeType.Buy, Symbol, LotSize, "Buy");
            }
            // Closing previous buy position and opening new sell position if the previous bar closes below and the bar before it closes above Dlagemas
            else if (Bars.ClosePrices[index-1] > _doubleLagEMA.DLagEMAs[index-1] && Bars.ClosePrices[index] < _doubleLagEMA.DLagEMAs[index])
            {
                CloseBuyPositions();
                ExecuteMarketOrder(TradeType.Sell, Symbol, LotSize, "Sell");
            }
        }

        protected override void OnTick()
        {  int index = Bars.ClosePrices.Count - 1;
            // Closing all buy positions if high price rises above sr and sr is higher than Dlagemas
            if (Symbol.Bid > _doubleLagEMA.sr[index] && _doubleLagEMA.sr[index] > _doubleLagEMA.DLagEMAs[index])
            {
                CloseBuyPositions();
            }

            // Closing all sell positions if low price drops below sr and sr is lower than Dlagemas
            if (Symbol.Ask < _doubleLagEMA.sr[index] && _doubleLagEMA.sr[index] < _doubleLagEMA.DLagEMAs[index])
            {
                CloseSellPositions();
            }
        }

        private void CloseBuyPositions()
        {
            foreach (var position in Positions.FindAll("Buy", Symbol, TradeType.Buy))
            {
                ClosePosition(position);
            }
        }

        private void CloseSellPositions()
        {
            foreach (var position in Positions.FindAll("Sell", Symbol, TradeType.Sell))
            {
                ClosePosition(position);
            }
        }
    }
}


@DR.SHADI_JARRAR