Bug with Hull Moving average on Typical price / Multiple timeframe ?

Created at 18 Nov 2020, 11:28
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!
NO

Nobody

Joined 14.01.2016

Bug with Hull Moving average on Typical price / Multiple timeframe ?
18 Nov 2020, 11:28


Hello,

i am facing a strange behavior, i reviewed my code several times but nothing seems to be wrong...maybe you could help me to solve the issue i am facing.

I use multiple timeframes (bot timeframe is 1mn) in my program and on the HULL MOVING AVERAGE on 2h TIMEFRAME used with TYPICALPRICE it seems that i do not have same values in backtest than on CHART (very big difference).

at 3h on 16 nov, as you can show on Chart 2h DAX Hull quote 12520.46 (1st picture) and in the bot during this lapstime, i put logs and the indicator shows 13192 for the _hma17_ms2.Result.Last(2) (cf picture 2) (.Last(2) is the 23h candle 2h timeframe quoting 12498.26 on the chart picture 3) => how is it possible ? what i am doing wrong, i never faced this kind of issue !

 

here an extract of lines using this indicator (full code below but depends on external C# package) :

//TIME FRAME 5
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms5_timeframe { get; set; }

//UT5 TIMEFRAME INDICATORS (2h)
        private int _ms5_index = 0;
        private Bars _ms5;
        private HullMovingAverage _hma420_ms5;
       

 _hma420_ms5 = Indicators.HullMovingAverage(_ms5.TypicalPrices, 420);
            _log.Write("_hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2)  => " + _hma420_ms5.Result.Last(1) + " < " + _hma420_ms5.Result.Last(2));
            if (_hma17_ms2.Result.Last(0) < _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) > _hma17_ms2.Result.Last(2) && _hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2) && Symbol.Bid < _pm._last_pos_buy.EntryPrice)
                _pm.closeAllPositions();

Thanks for your help !!!!

 

 

And then Here is my code :

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.Collections.Generic;
using System.Web.Script.Serialization;
// Add System.Web.Extension reference
using Microsoft.CSharp.RuntimeBinder;
// Add Microsoft.CSharp reference
using System.Dynamic;
using System.Globalization;
using cAlgoHbTools;


namespace cAlgo
{
    [Robot(AccessRights = AccessRights.FullAccess, TimeZone = TimeZones.WEuropeStandardTime)]
//TimeZone = TimeZones.WEuropeStandardTime, 

    public class BOT_MOD : Robot
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      PARAMETERS INITIALIZATION
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public enum TradeTypeFilter
        {
            No,
            Buy,
            Sell
        }

        //SIGNAL SETTINGS
        [Parameter("Main Signal Timeframe", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms2_timeframe { get; set; }

        //TIME FRAME 3
        [Parameter("Second Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms3_timeframe { get; set; }

        //TIME FRAME 4
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms4_timeframe { get; set; }

        //TIME FRAME 5
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms5_timeframe { get; set; }

        //TIME FRAME 6
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms6_timeframe { get; set; }



        ///////////////////////////////////////////////////////////////////////POSITION SETTINGS/////////////////////////////////////////////////////////////////

        //VOLUME : 1 for indices, 1000 for forex
        [Parameter("Volume", Group = "POSITION SETTINGS", DefaultValue = 1000, MinValue = 1)]
        public int _volume { get; set; }

        [Parameter("   - Balance reference(coef)", Group = "POSITION SETTINGS", DefaultValue = 1000)]
        public double _balance_ref { get; set; }

        [Parameter("Force Take Profit (pips)", Group = "POSITION SETTINGS", DefaultValue = 0, MinValue = 0)]
        public double _tp_pips { get; set; }

        [Parameter("Force Take Profit Pos. 2 (pips)", Group = "POSITION SETTINGS", DefaultValue = 0, MinValue = 0)]
        public double _tp2_pips { get; set; }


        [Parameter("€ TP Value/Min. volume (close all)", Group = "POSITION SETTINGS", DefaultValue = 0, MinValue = 0)]
        public double _TP_val_per_min_vol { get; set; }

        [Parameter("% Profit Max (/balance, close all)", Group = "POSITION SETTINGS", DefaultValue = 0, MinValue = 0, MaxValue = 1000)]
        public double _tot_profit_max_percent { get; set; }

        //Attention _tradetype_filter n'est pas une chaine de caractères il faut donc utiliser _tradetype_filter.ToString() pour l'utiliser ou _tradetype_filter.valeur
        [Parameter("Filter Trade Type", Group = "POSITION SETTINGS", DefaultValue = "Buy")]
        public TradeTypeFilter _tradetype_filter { get; set; }



        //RISK REWARD FILTERS
        [Parameter("Activ R/R Parameters :", Group = "RISK REWARD", DefaultValue = true)]
        public bool _use_RR_filters { get; set; }

        [Parameter("   - Take Profit Ratio to apply on SL Risk", Group = "RISK REWARD", DefaultValue = 0, MinValue = 0)]
        public double _RR_takeprofit_ratio { get; set; }

        [Parameter("   - Position Risk (% Balance)", Group = "RISK REWARD", DefaultValue = 5, MinValue = 0, MaxValue = 100)]
        public double _RR_risk_ratio { get; set; }

        [Parameter("   - Filter Signal Loss Min (pips)", Group = "RISK REWARD", DefaultValue = 0, MinValue = 0)]
        public double _RR_loss_min_pips { get; set; }

        [Parameter("   - Filter Signal Loss Max (pips)", Group = "RISK REWARD", DefaultValue = 0, MinValue = 0)]
        public double _RR_loss_max_pips { get; set; }

        [Parameter("   - Filter Risk/Reward min", Group = "RISK REWARD", DefaultValue = 0)]
        public double _RR_min { get; set; }





        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //STOP LOSS METHOD : "F=Fixed Distance", "M=MACD (High/Low)", "C=Prev Candle", "Z=SL0", "A = Moving average", "P = Percent Symbol price", "S = Customized SL"
        [Parameter("Stop Loss Max (pips)", Group = "STOP LOSS", DefaultValue = 0)]
        public double _sl_pips_max { get; set; }

        [Parameter("Trailing Method (Z, F, M, C, S, A, P)", Group = "STOP LOSS")]
        public string _sl_method { get; set; }

        [Parameter("   - Trailing Timeframe (if based on indic.)", Group = "STOP LOSS")]
        public TimeFrame _msSL_timeframe { get; set; }

        [Parameter("   - Moving Average period (A)", Group = "STOP LOSS", DefaultValue = 0)]
        public int _maSL_period { get; set; }

        //Percent trailing SL parameters
        [Parameter("   - % symbol price Profit to activ SL (P)", Group = "STOP LOSS", MinValue = 0, MaxValue = 100, DefaultValue = 0.24)]
        public double _sl_trail_percent_to_activ { get; set; }
        [Parameter("   - % symbol price Step (P)", Group = "STOP LOSS", MinValue = 0, MaxValue = 100, DefaultValue = 0.01)]
        public double _sl_trail_percent_step { get; set; }

        //PROFIT DISTANCE TO REACH BEFORE ACTIVATE SL
        [Parameter("   - Pips Profit to activ SL Zero (Z)", Group = "STOP LOSS", DefaultValue = 0)]
        public int _min_pips_profit_to_activ_SL0 { get; set; }

        //PIPS TO ADD TO THE SL 0 IN ORDER TO MAKE THE TRADE WIN
        [Parameter("   - Pips to add at the SL Zero win (Z)", Group = "STOP LOSS", DefaultValue = 0)]
        public double _pips_offset_SL0 { get; set; }


        [Parameter("   - Min Pips profit to activ Trailing SL (F, S)", Group = "STOP LOSS", DefaultValue = 0)]
        public int _min_pips_profit_activ_sl_trail { get; set; }

        //DISTANCE FOR TRAILING SL
        [Parameter("   - Fixed trailing SL Pips (F)", Group = "STOP LOSS", DefaultValue = 0)]
        public int _sl_pips_trail { get; set; }

        //PROFIT DISTANCE TO REACH BEFORE ACTIVATE SL
        [Parameter("   - € Profit /min. Vol. to activ SL0 (S)", Group = "STOP LOSS", DefaultValue = 5)]
        public int _min_profit_to_activ_SL { get; set; }


        //RISK SECURITY
        [Parameter("Max DD allowed (%) - Close All Pos.", Group = "RISK SECURITY", DefaultValue = 100)]
        public int _max_dd_allowed { get; set; }


        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //GRID SYSTEM
        [Parameter("Activ Grid", Group = "GRID SYSTEM", DefaultValue = false)]
        public bool _activ_grid { get; set; }

        [Parameter("   - Grid distance (in pips)", Group = "GRID SYSTEM", DefaultValue = 0)]
        public int _grid_pips { get; set; }

        [Parameter("   - Max positions", Group = "GRID SYSTEM", DefaultValue = 0, MinValue = 0)]
        public int _grid_max_pos { get; set; }

        [Parameter("   - Max positions (close all)", Group = "GRID SYSTEM", DefaultValue = 0, MinValue = 0)]
        public int _grid_max_pos_close { get; set; }

        [Parameter("   - Nb positions for Flat Exit", Group = "GRID SYSTEM", DefaultValue = 0, MinValue = 0)]
        public int _grid_flat_exit_pos { get; set; }

        [Parameter("   - Volume coef", Group = "GRID SYSTEM", DefaultValue = 1)]
        public double _grid_vol_coef { get; set; }


        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //GRID SYSTEM
        [Parameter("Activ Pyramid", Group = "PYRAMID SYSTEM", DefaultValue = false)]
        public bool _activ_pyramid { get; set; }

        [Parameter("   - Pyramid distance (in pips)", Group = "PYRAMID SYSTEM", DefaultValue = 0)]
        public int _pyramid_pips { get; set; }

        [Parameter("   - Max positions (close all)", Group = "PYRAMID SYSTEM", DefaultValue = 0, MinValue = 0)]
        public int _pyramid_max_pos { get; set; }

        [Parameter("   - Win stop factor (0=>1)", Group = "PYRAMID SYSTEM", DefaultValue = 1, MinValue = 0, MaxValue = 1)]
        public double _pyramid_SL0_offset_win { get; set; }


        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //MARTINGALE SYSTEM
        [Parameter("Activ Martingale System", Group = "MARTINGALE SYSTEM", DefaultValue = false)]
        public bool _activ_martingale { get; set; }

        [Parameter("Coefficient", Group = "MARTINGALE SYSTEM", DefaultValue = 2)]
        public double _martingale_coef { get; set; }


        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //SIGNAL PROVIDER SETTINGS
        [Parameter("Mirror comm. ($ / Million)", Group = "SIGNAL PROVIDER SETTINGS", DefaultValue = 0, MinValue = 0)]
        public double _mirror_comm { get; set; }

        //TRADING SESSION
        [Parameter("Limit trading session", Group = "TRADING SESSION TIME", DefaultValue = false)]
        public bool _limit_session { get; set; }

        [Parameter("   - OVN Close Position", Group = "TRADING SESSION TIME", DefaultValue = false)]
        public bool _closeOVN { get; set; }

        [Parameter("   - Trading start time 1", Group = "TRADING SESSION TIME", DefaultValue = "00:01:00")]
        public string _trade_start_time { get; set; }

        [Parameter("   - Trading end time 1", Group = "TRADING SESSION TIME", DefaultValue = "23:58:00")]
        public string _trade_end_time { get; set; }

        [Parameter("   - Trading start time 2", Group = "TRADING SESSION TIME", DefaultValue = "00:00:00")]
        public string _trade_start_time2 { get; set; }

        [Parameter("   - Trading end time 2", Group = "TRADING SESSION TIME", DefaultValue = "00:00:00")]
        public string _trade_end_time2 { get; set; }


        [Parameter("   - Trading start time 3", Group = "TRADING SESSION TIME", DefaultValue = "00:00:00")]
        public string _trade_start_time3 { get; set; }

        [Parameter("   - Trading end time 3", Group = "TRADING SESSION TIME", DefaultValue = "00:00:00")]
        public string _trade_end_time3 { get; set; }

        //LOGS PARAMETERS
        [Parameter("Logs screen", Group = "LOGS", DefaultValue = true)]
        public bool _log_screen { get; set; }

        [Parameter("Logs File", Group = "LOGS", DefaultValue = false)]
        public bool _log_file { get; set; }

        [Parameter("   - Filepath", Group = "LOGS", DefaultValue = "C:\\Temp\\BOT_T1_log.txt")]
        public string _log_filepath { get; set; }



        //MACD PARAMETERS
        public int _macd_long_cycle = 26;
        public int _macd_short_cycle = 12;
        public int _macd_period = 9;


        //STOCHASTIC PARAMETERS
        public int _sto_K_Periods = 8;
        public int _sto_D_Periods = 3;
        public int _sto_K_Slowing = 3;

        //MA PARAMETERS
        public MovingAverageType _MA_Type = MovingAverageType.Simple;


        //BOT TIME FRAME INDICATORS (1mn)
        private int _ms_index = 0;
        private Bars _ms;
        private BollingerBands _boll;
        private MacdCrossOver _macd;
        private RelativeStrengthIndex _rsi;

        //UT2 TIMEFRAME INDICATORS (5mn)
        private int _ms2_index = 0;
        private Bars _ms2;
        private BollingerBands _boll_ms2;
        private MacdCrossOver _macd_ms2;
        private RelativeStrengthIndex _rsi_ms2;
        private MovingAverage _ma7_ms2, _ma20_ms2, _ma50_ms2, _ma100_ms2;
        private HullMovingAverage _hma17_ms2;
        private StochasticforIndicators _stoRsi_ms2;

        //UT3 TIMEFRAME INDICATORS (15mn)
        private int _ms3_index = 0;
        private Bars _ms3;
        private BollingerBands _boll_ms3;
        private MacdCrossOver _macd_ms3;
        private RelativeStrengthIndex _rsi_ms3;
        private MovingAverage _ma6_ms3, _ma8_ms3;
        private HullMovingAverage _hma20_ms3;

        //UT4 TIMEFRAME INDICATORS (30mn)
        private int _ms4_index = 0;
        private Bars _ms4;
        private MovingAverage _ma3_ms4;
        private MovingAverage _ma6_ms4;

        //UT5 TIMEFRAME INDICATORS (2h)
        private int _ms5_index = 0;
        private Bars _ms5;
        private RelativeStrengthIndex _rsi_ms5;
        private StochasticforIndicators _stoRsi_ms5;
        private HullMovingAverage _hma420_ms5;
        private TriangularMovingAverage _tma40_ms5;
        private Supertrend _st_ms5;

        //UT6 TIMEFRAME INDICATORS (Daily)
        private int _ms6_index = 0;
        private Bars _ms6;


        //STOP LOSS TIME FRAME INDICATORS 
        private int _msSL_index = 0;
        private Bars _msSL;
        private MacdCrossOver _macd_msSL;
        private RelativeStrengthIndex _rsi_msSL;
        private MovingAverage _ma_msSL;

        //GLOBAL VARS
        private Logger _log;
        private PositionManager _pm;
        private Waves _wavesObj;
        private Comment _comment;
        private Signal _signal;
        private Candlestick _candle;
        private TrendLines _trendlines;

        // PYRAMID VARS
        private TimeSpan _timelimit_open_trade;



        //BOT NAME
        public string _cBotLabel = "BOT_MOD";



        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      OnStart METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnStart()
        {

            Print("Start...\r\n");

            //Complete Bot name
            _cBotLabel += "_" + Symbol.Code + "_" + TimeFrame.ToString() + "_" + _ms2_timeframe.ToString();
            Print("Bot Label : +" + _cBotLabel + "\r\n");

            //Set the offset of the current bar
            _ms_index = Bars.ClosePrices.Count - 1;

            //Set the time max to open a trade 1 hour before the end time asked in parameter
            _timelimit_open_trade = System.TimeSpan.Parse(_trade_end_time).Subtract(TimeSpan.FromMinutes(60));

            //ROBOT DEFAULT TIMEFRAME INDICATORS
            Print("Load Main TF Indicators...\r\n");
            _ms = MarketData.GetBars(TimeFrame);
            _boll = Indicators.BollingerBands(_ms.ClosePrices, 20, 2, _MA_Type);
            _macd = Indicators.MacdCrossOver(_macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi = Indicators.RelativeStrengthIndex(_ms.ClosePrices, 14);

            //SIGNAL TIMEFRAME INDICATORS
            Print("Load MS2 TF Indicators...\r\n");
            _ms2 = MarketData.GetBars(_ms2_timeframe);
            _boll_ms2 = Indicators.BollingerBands(_ms2.ClosePrices, 20, 2, _MA_Type);
            _macd_ms2 = Indicators.MacdCrossOver(_ms2.ClosePrices, _macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi_ms2 = Indicators.RelativeStrengthIndex(_ms2.ClosePrices, 10);
            _ma7_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 7, MovingAverageType.Simple);
            _ma20_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 23, MovingAverageType.Simple);
            _ma50_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 50, MovingAverageType.Simple);
            _ma100_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 100, MovingAverageType.Simple);
            _hma17_ms2 = Indicators.HullMovingAverage(_ms2.TypicalPrices, 17);
            _stoRsi_ms2 = Indicators.GetIndicator<StochasticforIndicators>(12, 3, MovingAverageType.Simple, 7, _rsi_ms2.Result);

            // TIMEFRAME 3 INDICATORS
            Print("Load MS3 TF Indicators...\r\n");
            _ms3 = MarketData.GetBars(_ms3_timeframe);
            _boll_ms3 = Indicators.BollingerBands(_ms3.ClosePrices, 20, 2, _MA_Type);
            _macd_ms3 = Indicators.MacdCrossOver(_ms3.ClosePrices, _macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi_ms3 = Indicators.RelativeStrengthIndex(_ms3.ClosePrices, 14);
            _ma6_ms3 = Indicators.MovingAverage(_ms3.TypicalPrices, 6, MovingAverageType.Simple);
            _ma8_ms3 = Indicators.MovingAverage(_ms3.TypicalPrices, 8, MovingAverageType.Simple);
            _hma20_ms3 = Indicators.HullMovingAverage(_ms3.TypicalPrices, 20);

            // TIMEFRAME 4 INDICATORS
            Print("Load MS4 TF Indicators...\r\n");
            _ms4 = MarketData.GetBars(_ms4_timeframe);
            _ma3_ms4 = Indicators.MovingAverage(_ms4.TypicalPrices, 3, MovingAverageType.Simple);
            _ma6_ms4 = Indicators.MovingAverage(_ms4.TypicalPrices, 6, MovingAverageType.Simple);

            //TIMEFRAME 5 INDICATORS
            Print("Load MS5 TF Indicators...\r\n");
            _ms5 = MarketData.GetBars(_ms5_timeframe);
            _rsi_ms5 = Indicators.RelativeStrengthIndex(_ms5.ClosePrices, 6);
            _stoRsi_ms5 = Indicators.GetIndicator<StochasticforIndicators>(19, 5, MovingAverageType.Simple, 3, _rsi_ms5.Result);
            _hma420_ms5 = Indicators.HullMovingAverage(_ms5.TypicalPrices, 420);
            _tma40_ms5 = Indicators.TriangularMovingAverage(_ms5.ClosePrices, 40);
            _st_ms5 = Indicators.Supertrend(3, 3);

            //TIMEFRAME 6 INDICATORS
            Print("Load MS6 TF Indicators...\r\n");
            _ms6 = MarketData.GetBars(_ms6_timeframe);


            //STOP LOSS TIMEFRAME INDICATORS
            Print("Load SL TF Indicators...\r\n");
            _msSL = MarketData.GetBars(_msSL_timeframe);
            _macd_msSL = Indicators.MacdCrossOver(_msSL.ClosePrices, _macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi_msSL = Indicators.RelativeStrengthIndex(_msSL.ClosePrices, 14);
            _ma_msSL = Indicators.MovingAverage(_msSL.ClosePrices, _maSL_period, _MA_Type);
            _msSL_index = _msSL.ClosePrices.Count - 1;

            _log = new Logger(thisref _ms, _cBotLabel, _log_filepath, _log_file, _log_screen);
            _wavesObj = new Waves(ref _log);
            _comment = new Comment();
            _candle = new Candlestick(this);

            _signal = new Signal();

            _pm = new PositionManager(thisref _log, ref _ms, ref _msSL, ref _macd_msSL, ref _rsi_msSL, ref _ma_msSL);
            _pm._pip_value = Symbol.PipValue;
            _pm._sl_pips_max = _sl_pips_max;
            _pm._tp_pips = _tp_pips;
            _pm._min_pips_profit_to_activ_SL0 = _min_pips_profit_to_activ_SL0;
            _pm._pips_offset_SL0 = _pips_offset_SL0;
            _pm._use_RR_filters = _use_RR_filters;
            _pm._RR_loss_min_pips = _RR_loss_min_pips;
            _pm._RR_loss_max_pips = _RR_loss_max_pips;
            _pm._RR_risk_ratio = _RR_risk_ratio;
            _pm._RR_min = _RR_min;
            _pm._RR_takeprofit_ratio = _RR_takeprofit_ratio;
            _pm._balance_ref = _balance_ref;
            _pm._martingale_coef = _martingale_coef;
            _pm._sl_method = _sl_method;
            _pm._min_pips_profit_activ_sl_trail = _min_pips_profit_activ_sl_trail;
            _pm._sl_pips_trail = _sl_pips_trail;
            _pm._sl_trail_percent_to_activ = _sl_trail_percent_to_activ;
            _pm._sl_trail_percent_step = _sl_trail_percent_step;
            _pm._max_dd_allowed = _max_dd_allowed;
            _pm._mirror_comm = _mirror_comm;

            _pm._activ_grid = _activ_grid;
            _pm._grid_max_pos_close = _grid_max_pos_close;
            _pm._grid_max_pos = _grid_max_pos;
            _pm._activ_pyramid = _activ_pyramid;
            _pm._pyramid_max_pos = _pyramid_max_pos;

            _pm._activ_martingale = _activ_martingale;

            _pm._limit_session = _limit_session;
            _pm._trade_start_time = _trade_start_time;
            _pm._trade_end_time = _trade_end_time;
            _pm._trade_start_time2 = _trade_start_time2;
            _pm._trade_end_time2 = _trade_end_time2;
            _pm._trade_start_time3 = _trade_start_time3;
            _pm._trade_end_time3 = _trade_end_time3;

            _pm._cBotLabel = _cBotLabel;

            //LISTENERS
            Positions.Opened += _pm.OnPositionOpened;
            Positions.Closed += _pm.OnPositionClosed;

            //Local Listeners
            Positions.Opened += OnPositionOpened;

            //Refresh  positions opened indicator object (which one LOAD the last pos in the same time)
            _pm.UpdateOpenedPositions();

            //Refresh current latent P&L
            _pm.UpdatePandL_tot_net();

            //Refresh Stop Loss
            _pm.UpdateTrailingStop();

            _log.Write("\r\n");
            _log.Write("START " + Bars.OpenTimes[_ms_index].TimeOfDay.ToString());
            _log.Write("ROBOT : " + _cBotLabel + "\r\nSYMBOL : " + Symbol.Name + "\r\nPipsize = " + Symbol.PipSize + "\r\nDigits = " + Symbol.Digits + "\r\nPip Value = " + Math.Round(Symbol.PipValue, 5) + "\r\nVolume min =" + Symbol.VolumeInUnitsMin + "\r\nLot Size = ");
            _log.Write("TRADING SESSION TIME PARAMETERS : " + System.TimeSpan.Parse(_trade_start_time) + " to " + System.TimeSpan.Parse(_trade_end_time));

            _trendlines = new TrendLines(ref _log, ref _ms2, ref _macd_ms2, ref _rsi_ms2, 50);
            _trendlines.LoadFromWaves();
        }




        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      OnTick METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnTick()
        {
            _pm.CheckDrawDown();
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      OnBar METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnBar()
        {
            //Refresh the offsets of the current bar
            _ms_index = Bars.ClosePrices.Count - 1;
            _ms2_index = _ms2.ClosePrices.Count - 1;
            _ms3_index = _ms3.ClosePrices.Count - 1;
            _ms4_index = _ms4.ClosePrices.Count - 1;
            _ms5_index = _ms5.ClosePrices.Count - 1;
            _ms6_index = _ms6.ClosePrices.Count - 1;


            //Check draw down
            _pm.CheckDrawDown();

            //Refresh current latent P&L
            //UpdatePandL_tot_net(); ==> Just done in CheckDrawDown() method

            //Refresh Stop Loss
            _pm.UpdateTrailingStop();

            //Check the famous signal
            CheckSignal();

            if (_ms2.OpenTimes.LastValue == _ms.OpenTimes.LastValue)
            {
                _trendlines.LoadFromWaves();
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      OnStop METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnStop()
        {
            _log.Write("Bot stopped");
            _log.Flush();
        }




        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //************************************************ RESERVED TO THE SPECIFIC TRADES IMPLEMENTATION*****************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        //*****************************************************************************************************************************************
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      OnPositionOpened METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public void OnPositionOpened(PositionOpenedEventArgs obj)
        {
            if (Object.ReferenceEquals(null, obj.Position))
                _log.Write("WOW ! FATAL ERROR !");

        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      SetSLandTP METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void SetSLandTP()
        {

        }



        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckSignal METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckSignal()
        {
            //Check if opened conditions needs to be closed (and close them)
            CheckConditionsToClosePositions();

            //Refresh opened positions
            _pm.UpdateOpenedPositions();


            //Use Grid if asked
            Grid();

            //Use Pyramid if asked
            Pyramid();


            //Re initialization of signal object
            _signal = new Signal();


            if (!_pm.CheckTradeTimeAllowed())
            {
                _pm.CancelAllPendingOrders(TradeType.Buy);
                _pm.CancelAllPendingOrders(TradeType.Sell);
                return;
            }


            //Check Buy signal
            if (_tradetype_filter != TradeTypeFilter.Sell && IsSignalBuy())
            {
                string comment = "";
                _signal.sl_dist_pips = (Symbol.Ask * 0.015) / Symbol.PipSize;
                _signal.tp_dist_pips = (Symbol.Ask * 0.016) / Symbol.PipSize;
                _pm.ExecuteOrder(_pm.VolumeBalanceCoefficed(_volume), TradeType.Buy, _signal.sl_dist_pips, _signal.tp_dist_pips, comment);

            }

            //Check Sell Signal
            if (_tradetype_filter != TradeTypeFilter.Buy && IsSignalSell())
            {
                string comment = "";
                _pm.ExecuteOrder(_pm.VolumeBalanceCoefficed(_volume), TradeType.Sell, _signal.sl_dist_pips, _signal.sl_dist_pips, comment);
            }

            //Add SL & TP
            SetSLandTP();
        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      IsSignalBuy METHOD
        //Condition 0 :
        //Condition 1 :
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private bool IsSignalBuy()
        {

            if (_pm._opened_pos_buy > 0)
                return false;

            if (_hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2))
                return false;

            if (_tma40_ms5.Result.Last(1) < _tma40_ms5.Result.Last(2))
                return false;

            if (_stoRsi_ms5.KLine.Last(1) < _stoRsi_ms5.DLine.Last(1))
                return false;

            if (_ms5.ClosePrices.Last(1) < Math.Max(_st_ms5.DownTrend.Last(1), _st_ms5.UpTrend.Last(1)))
                return false;

            if (_ma3_ms4.Result.Last(1) < _ma6_ms4.Result.Last(1))
                return false;

            if (_ma6_ms3.Result.Last(1) < _ma8_ms3.Result.Last(1))
                return false;


            if (_hma20_ms3.Result.Last(1) < _hma20_ms3.Result.Last(2))
                return false;

            if (_ms6.HighPrices.Last(0) - _ms2.HighPrices.Last(0) > 140)
                return false;

            if (!(_hma17_ms2.Result.Last(0) > _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) < _hma17_ms2.Result.Last(2)))
                return false;

            if (!(_stoRsi_ms2.KLine.Last(0) < _stoRsi_ms2.DLine.Last(0)))
                return false;

            return true;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      IsSignalSell METHOD
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private bool IsSignalSell()
        {

            return false;

        }




        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      Pyramid METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void Pyramid()
        {
            if (!_activ_pyramid)
                return;

            //_log.Write("Pyramid () :       _opened_pos_buy = " + _opened_pos_buy + "      _opened_pos_sell = " + _opened_pos_sell + "     BID/ASK = " + Symbol.Bid + " / " + Symbol.Ask);

            //If Buy Position Opened : Check grid condition to buy again
            if (_pm._opened_pos_buy > 0 && ((object)_pm._last_pos_buy) != null)
            {
                if (Symbol.Bid > _pm._last_pos_buy.EntryPrice && ((Symbol.Bid - _pm._last_pos_buy.EntryPrice) / Symbol.PipSize) >= _pyramid_pips)
                {
                    _comment.Deserialize(_pm._last_pos_buy.Comment);
                    string comment = "gpid:" + _comment.gpid + ";rk:" + _pm.GetNewRank() + ";ori:pyramid";
                    _pm.ExecuteOrder(_pm.VolumeBalanceCoefficed(_volume), TradeType.Buy, 0, 0, comment);
                }
            }

            //If sell Position Opened : Check grid condition to sell again
            if (_pm._opened_pos_sell > 0 && ((object)_pm._last_pos_sell) != null)
            {

                if (Symbol.Ask < _pm._last_pos_sell.EntryPrice && ((_pm._last_pos_sell.EntryPrice - Symbol.Ask) / Symbol.PipSize) >= _pyramid_pips)
                {
                    _comment.Deserialize(_pm._last_pos_sell.Comment);
                    string comment = "gpid:" + _comment.gpid + ";rk:" + _pm.GetNewRank() + ";ori:pyramid";
                    _pm.ExecuteOrder(_pm.VolumeBalanceCoefficed(_volume), TradeType.Sell, 0, 0, comment);
                }
            }

            return;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      Grid METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void Grid()
        {
            if (!_activ_grid)
                return;

            //_log.Write("Grid () : ");
            //_log.Write("      _opened_pos_buy = " + _opened_pos_buy + "      _opened_pos_sell = " + _opened_pos_sell + "     BID/ASK = " + Symbol.Bid + " / " + Symbol.Ask);

            //If Buy Position Opened : Check grid condition to buy again
            if (_pm._opened_pos_buy > 0 && ((object)_pm._last_pos_buy) != null)
            {
                if (Symbol.Ask < _pm._last_pos_buy.EntryPrice && ((_pm._last_pos_buy.EntryPrice - Symbol.Ask) / Symbol.PipSize) >= _grid_pips)
                {
                    _comment.Deserialize(_pm._last_pos_buy.Comment);
                    string comment = "gpid:" + _comment.gpid + ";rk:" + _pm.GetNewRank() + ";ori:grid";
                    _pm.ExecuteOrder(_pm.VolumeBalanceCoefficed(_volume), TradeType.Buy, 0, 0, comment);
                    //ExecuteOrder(VolumeCoefficed((long)_last_pos.VolumeInUnits, (double)_grid_vol_coef), TradeType.Buy, 0, 0, comment);
                }
            }

            //If sell Position Opened : Check grid condition to sell again
            if (_pm._opened_pos_sell > 0 && ((object)_pm._last_pos_sell) != null)
            {

                if (Symbol.Bid > _pm._last_pos_sell.EntryPrice && ((Symbol.Bid - _pm._last_pos_sell.EntryPrice) / Symbol.PipSize) >= _grid_pips)
                {
                    _comment.Deserialize(_pm._last_pos_sell.Comment);
                    string comment = "gpid:" + _comment.gpid + ";rk:" + _pm.GetNewRank() + ";ori:grid";
                    _pm.ExecuteOrder(_pm.VolumeBalanceCoefficed(_volume), TradeType.Sell, 0, 0, comment);
                    //ExecuteOrder(VolumeCoefficed((long)_last_pos.VolumeInUnits, (double)_grid_vol_coef), TradeType.Sell, 0, 0, comment);


                }
            }

            return;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToClosePositions METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToClosePositions()
        {
            //_log.Write("CheckConditionsToClosePositions in...");
            CheckConditionsToClosePendingOrders();

            //Exit if no positions to close
            if (_pm._opened_pos == 0)
                return;


            //First : Check if profit expected is reached to close positions   )

            if ((_TP_val_per_min_vol > 0 && _pm._PandL_per_min_vol >= _TP_val_per_min_vol))
            {
                _log.Write("Profit target reached => Close positions; profit_per_min_vol= " + Math.Round(_pm._PandL_per_min_vol, 2));
                _pm.closeAllPositions();
                return;
            }

            if (_tot_profit_max_percent > 0 && _pm._PandL_tot_net > 0 && (_pm._PandL_tot_net / Account.Balance) * 100 > _tot_profit_max_percent)
            {
                _log.Write("% Max profit/Balance reached => Close positions; _PandL_tot_net= " + Math.Round(_pm._PandL_tot_net, 2));
                _pm.closeAllPositions();
                return;
            }

            //SPECIFIC CONDITIONS
            CheckConditionsToClosePositionsBuy();
            CheckConditionsToClosePositionsSell();
            CheckConditionsToCloseGrid();
            CheckConditionsToClosePyramid();
            //_log.Write("CheckConditionsToClosePositions out");
        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToClosePendingOrders METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToClosePendingOrders()
        {
            if (_pm.PendingOrdersExists() < 1)
                return;


        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToClosePositionsBuy METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToClosePositionsBuy()
        {
            if (_pm._opened_pos_buy < 1)
                return;


            //Exit in profit (C6 & C8)
            if (_hma17_ms2.Result.Last(0) < _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) > _hma17_ms2.Result.Last(2) && _ma6_ms3.Result.Last(1) < _ma8_ms3.Result.Last(1) && Symbol.Bid > _pm._last_pos_buy.EntryPrice)
                _pm.closeAllPositions();

            //Exit at loss (C6 & C2)
            _log.Write("_hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2)  => " + _hma420_ms5.Result.Last(1) + " < " + _hma420_ms5.Result.Last(2));
            if (_hma17_ms2.Result.Last(0) < _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) > _hma17_ms2.Result.Last(2) && _hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2) && Symbol.Bid < _pm._last_pos_buy.EntryPrice)
                _pm.closeAllPositions();
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToClosePositionsSell METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToClosePositionsSell()
        {

        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToClosePyramid METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToClosePyramid()
        {


        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToCloseGrid METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToCloseGrid()
        {
            if (!_activ_grid)
                return;

            //_log.Write(" _wavesObj : high = " + _wavesObj._up_waves[1].high + " low =" + _wavesObj._up_waves[1].low + " ampl =" + _wavesObj._up_waves[1].ampl);

            if (_grid_flat_exit_pos > 0 && _pm._opened_pos >= _grid_flat_exit_pos && _pm._PandL_tot_net > 0)
            {
                _log.Write("Flat exit asked : Close all positions. P&L Tot net =" + _pm._PandL_tot_net + " ; per min vol=" + _pm._PandL_per_min_vol);
                _pm.closeAllPositions();
                return;
            }

            //Get Older Position
            Position pos = _pm.GetOlderOpenedPosition();

            //Oups..problem
            if ((object)pos == null)
            {
                _log.Write("CheckConditionsToClosePositions() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  PREVENT FATAL ERROR !!! (object)pos == null");
                return;
            }

            //Get Infos from comment
            _comment.Deserialize(pos.Comment);

            //1st case : M20 reached & position(s) in profit => SL0
            if (_pm._PandL_tot_net > 0 && pos.TradeType == TradeType.Buy && _ms.ClosePrices.Last(1) > _ma20_ms2.Result.LastValue)
            {
                //MoveGridStopLossToZero();
            }

            if (_pm._PandL_tot_net > 0 && pos.TradeType == TradeType.Sell && _ms.ClosePrices.Last(1) < _ma20_ms2.Result.LastValue)
            {
                //MoveGridStopLossToZero();
            }

            //2nd case : Boll reached & position(s) in profit => SL M20
            if (_pm._PandL_tot_net > 0 && pos.TradeType == TradeType.Buy && _ms.ClosePrices.Last(1) > _boll_ms2.Top.LastValue)
            {
                //_pm.MoveGridStopLoss(_ma20_ms2.Result.LastValue);
                _pm.closeAllPositions(TradeType.Buy);
            }

            if (_pm._PandL_tot_net > 0 && pos.TradeType == TradeType.Sell && _ms.ClosePrices.Last(1) < _boll_ms2.Bottom.LastValue)
            {
                //_pm.MoveGridStopLoss(_ma20_ms2.Result.LastValue);
                _pm.closeAllPositions(TradeType.Sell);
            }

            _wavesObj.Load(ref _ms, ref _macd, ref _rsi);
            double low = _wavesObj._up_waves[1].low;
            double high = _wavesObj._down_waves[1].high;

            //
            if (_pm._PandL_tot_net < 0 && pos.TradeType == TradeType.Buy && _ms.ClosePrices.Last(1) > _boll_ms2.Top.LastValue)
            {
                _pm.closeAllPositions(TradeType.Buy);
            }

            //
            if (_pm._PandL_tot_net < 0 && pos.TradeType == TradeType.Sell && _ms.ClosePrices.Last(1) < _boll_ms2.Bottom.LastValue)
            {
                _pm.closeAllPositions(TradeType.Sell);
            }


            if (_comment.rk == 1 && _pm._opened_pos > 1 && ((pos.TradeType == TradeType.Buy && pos.EntryPrice < Symbol.Bid) || (pos.TradeType == TradeType.Sell && pos.EntryPrice > Symbol.Ask)))
            {
                //_log.Write("Entry price of First position reached, close it : " + pos.Id);
                //ClosePosition(pos);
                //MoveGridStopLossToZero();
                //return;
            }

            //MoveGridStopLossToZero();
        }

    }
}


@Nobody
Replies

PanagiotisCharalampous
18 Nov 2020, 12:09

Hi Nobody,

Can you provide a simpler cBot code without dependencies that we can use to reproduce this behavior?

Best Regards,

Panagiotis 

Join us on Telegram


@PanagiotisCharalampous

Nobody
18 Nov 2020, 12:25

RE:

PanagiotisCharalampous said:

Hi Nobody,

Can you provide a simpler cBot code without dependencies that we can use to reproduce this behavior?

Best Regards,

Panagiotis 

Join us on Telegram

Hi Pangiotis, thanks, ok let me time to do that...

I just replaced HMA typical by a SMA100 for a test and no problem with it...and the same HMA (on typical price) seems to be OK too on the M5 timeframe....very very strange...

 

I come back with simpler code soon


@Nobody

Nobody
18 Nov 2020, 12:57 ( Updated at: 21 Dec 2023, 09:22 )

RE: RE:

Panagiotis,

 

here a simpler code that reproduce this issue... as you can see on printscreens : 2h HMA typical price 420 peiod in cbot = 13152 and for same parameters on chart 12.509

2h SMA 100 close is equal on chart and cbot as HMA  typical price 17 periods 5mn...unbelievable !

 

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.Collections.Generic;
using System.Web.Script.Serialization;
// Add System.Web.Extension reference
using Microsoft.CSharp.RuntimeBinder;
// Add Microsoft.CSharp reference
using System.Dynamic;
using System.Globalization;

namespace cAlgo
{
    [Robot(AccessRights = AccessRights.FullAccess, TimeZone = TimeZones.WEuropeStandardTime)]
//TimeZone = TimeZones.WEuropeStandardTime, 

    public class BOT_MOD : Robot
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      PARAMETERS INITIALIZATION
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public enum TradeTypeFilter
        {
            No,
            Buy,
            Sell
        }

        //SIGNAL SETTINGS
        [Parameter("Main Signal Timeframe", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms2_timeframe { get; set; }

        //TIME FRAME 3
        [Parameter("Second Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms3_timeframe { get; set; }

        //TIME FRAME 4
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms4_timeframe { get; set; }

        //TIME FRAME 5
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms5_timeframe { get; set; }

        //TIME FRAME 6
        [Parameter("Third Timeframe (optional)", Group = "SIGNAL SETTINGS")]
        public TimeFrame _ms6_timeframe { get; set; }



        //MACD PARAMETERS
        public int _macd_long_cycle = 26;
        public int _macd_short_cycle = 12;
        public int _macd_period = 9;


        //STOCHASTIC PARAMETERS
        public int _sto_K_Periods = 8;
        public int _sto_D_Periods = 3;
        public int _sto_K_Slowing = 3;

        //MA PARAMETERS
        public MovingAverageType _MA_Type = MovingAverageType.Simple;


        //BOT TIME FRAME INDICATORS (1mn)
        private int _ms_index = 0;
        private Bars _ms;
        private BollingerBands _boll;
        private MacdCrossOver _macd;
        private RelativeStrengthIndex _rsi;

        //UT2 TIMEFRAME INDICATORS (5mn)
        private int _ms2_index = 0;
        private Bars _ms2;
        private BollingerBands _boll_ms2;
        private MacdCrossOver _macd_ms2;
        private RelativeStrengthIndex _rsi_ms2;
        private MovingAverage _ma7_ms2, _ma20_ms2, _ma50_ms2, _ma100_ms2;
        private HullMovingAverage _hma17_ms2;
        private StochasticforIndicators _stoRsi_ms2;

        //UT3 TIMEFRAME INDICATORS (15mn)
        private int _ms3_index = 0;
        private Bars _ms3;
        private BollingerBands _boll_ms3;
        private MacdCrossOver _macd_ms3;
        private RelativeStrengthIndex _rsi_ms3;
        private MovingAverage _ma6_ms3, _ma8_ms3;
        private HullMovingAverage _hma20_ms3;

        //UT4 TIMEFRAME INDICATORS (30mn)
        private int _ms4_index = 0;
        private Bars _ms4;
        private MovingAverage _ma3_ms4;
        private MovingAverage _ma6_ms4;

        //UT5 TIMEFRAME INDICATORS (2h)
        private int _ms5_index = 0;
        private Bars _ms5;
        private RelativeStrengthIndex _rsi_ms5;
        private StochasticforIndicators _stoRsi_ms5;
        private HullMovingAverage _hma420_ms5;
        private TriangularMovingAverage _tma40_ms5;
        private Supertrend _st_ms5;
        private MovingAverage _ma5_ms100;

        //UT6 TIMEFRAME INDICATORS (Daily)
        private int _ms6_index = 0;
        private Bars _ms6;



        //BOT NAME
        public string _cBotLabel = "BOT_MOD";



        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      OnStart METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnStart()
        {

            //Set the offset of the current bar
            _ms_index = Bars.ClosePrices.Count - 1;

            //ROBOT DEFAULT TIMEFRAME INDICATORS
            Print("Load Main TF Indicators...\r\n");
            _ms = MarketData.GetBars(TimeFrame);
            _boll = Indicators.BollingerBands(_ms.ClosePrices, 20, 2, _MA_Type);
            _macd = Indicators.MacdCrossOver(_macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi = Indicators.RelativeStrengthIndex(_ms.ClosePrices, 14);

            //SIGNAL TIMEFRAME INDICATORS
            Print("Load MS2 TF Indicators...\r\n");
            _ms2 = MarketData.GetBars(_ms2_timeframe);
            _boll_ms2 = Indicators.BollingerBands(_ms2.ClosePrices, 20, 2, _MA_Type);
            _macd_ms2 = Indicators.MacdCrossOver(_ms2.ClosePrices, _macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi_ms2 = Indicators.RelativeStrengthIndex(_ms2.ClosePrices, 10);
            _ma7_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 7, MovingAverageType.Simple);
            _ma20_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 23, MovingAverageType.Simple);
            _ma50_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 50, MovingAverageType.Simple);
            _ma100_ms2 = Indicators.MovingAverage(_ms2.ClosePrices, 100, MovingAverageType.Simple);
            _hma17_ms2 = Indicators.HullMovingAverage(_ms2.TypicalPrices, 17);
            _stoRsi_ms2 = Indicators.GetIndicator<StochasticforIndicators>(12, 3, MovingAverageType.Simple, 7, _rsi_ms2.Result);

            // TIMEFRAME 3 INDICATORS
            Print("Load MS3 TF Indicators...\r\n");
            _ms3 = MarketData.GetBars(_ms3_timeframe);
            _boll_ms3 = Indicators.BollingerBands(_ms3.ClosePrices, 20, 2, _MA_Type);
            _macd_ms3 = Indicators.MacdCrossOver(_ms3.ClosePrices, _macd_long_cycle, _macd_short_cycle, _macd_period);
            _rsi_ms3 = Indicators.RelativeStrengthIndex(_ms3.ClosePrices, 14);
            _ma6_ms3 = Indicators.MovingAverage(_ms3.TypicalPrices, 6, MovingAverageType.Simple);
            _ma8_ms3 = Indicators.MovingAverage(_ms3.TypicalPrices, 8, MovingAverageType.Simple);
            _hma20_ms3 = Indicators.HullMovingAverage(_ms3.TypicalPrices, 20);

            // TIMEFRAME 4 INDICATORS
            Print("Load MS4 TF Indicators...\r\n");
            _ms4 = MarketData.GetBars(_ms4_timeframe);
            _ma3_ms4 = Indicators.MovingAverage(_ms4.TypicalPrices, 3, MovingAverageType.Simple);
            _ma6_ms4 = Indicators.MovingAverage(_ms4.TypicalPrices, 6, MovingAverageType.Simple);

            //TIMEFRAME 5 INDICATORS
            Print("Load MS5 TF Indicators...\r\n");
            _ms5 = MarketData.GetBars(_ms5_timeframe);
            _rsi_ms5 = Indicators.RelativeStrengthIndex(_ms5.ClosePrices, 6);
            _stoRsi_ms5 = Indicators.GetIndicator<StochasticforIndicators>(19, 5, MovingAverageType.Simple, 3, _rsi_ms5.Result);
            _hma420_ms5 = Indicators.HullMovingAverage(_ms5.ClosePrices, 420);
            _tma40_ms5 = Indicators.TriangularMovingAverage(_ms5.ClosePrices, 40);
            _st_ms5 = Indicators.Supertrend(3, 3);
            _ma5_ms100 = Indicators.MovingAverage(_ms5.ClosePrices, 100, MovingAverageType.Simple);

            //TIMEFRAME 6 INDICATORS
            Print("Load MS6 TF Indicators...\r\n");
            _ms6 = MarketData.GetBars(_ms6_timeframe);


        }



        protected override void OnTick()
        {
        }


        protected override void OnBar()
        {
            //Refresh the offsets of the current bar
            _ms_index = Bars.ClosePrices.Count - 1;
            _ms2_index = _ms2.ClosePrices.Count - 1;
            _ms3_index = _ms3.ClosePrices.Count - 1;
            _ms4_index = _ms4.ClosePrices.Count - 1;
            _ms5_index = _ms5.ClosePrices.Count - 1;
            _ms6_index = _ms6.ClosePrices.Count - 1;


            //Check the famous signal
            CheckSignal();

        }


        protected override void OnStop()
        {

        }


        public void OnPositionOpened(PositionOpenedEventArgs obj)
        {
            if (Object.ReferenceEquals(null, obj.Position))
                Print("WOW ! FATAL ERROR !");

        }

        private void CheckSignal()
        {
            //Check if opened conditions needs to be closed (and close them)
            CheckConditionsToClosePositions();


            //Check Buy signal
            if (IsSignalBuy())
            {
                double sl_dist_pips = (Symbol.Ask * 0.015) / Symbol.PipSize;
                double tp_dist_pips = (Symbol.Ask * 0.016) / Symbol.PipSize;
                ExecuteMarketOrder(TradeType.Buy, SymbolName, 1, _cBotLabel, Math.Round(sl_dist_pips, 1), Math.Round(tp_dist_pips, 1), "my_comment");

            }

        }

        private bool IsSignalBuy()
        {
            int opened_pos_buy = 0;
            foreach (Position position in Positions.FindAll(_cBotLabel, SymbolName))
            {
                if (position.TradeType == TradeType.Buy)
                    opened_pos_buy += 1;
            }

            if (opened_pos_buy > 0)
                return false;

            //UT2H : C1 = MMHull 2h doit être ascendante
            //if (_hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2))
            if (_ma5_ms100.Result.Last(1) < _ma5_ms100.Result.Last(2))
                return false;

            //UT2H : C11 = MM40 triangulaire UT2h doit être ascendnate
            if (_tma40_ms5.Result.Last(1) < _tma40_ms5.Result.Last(2))
                return false;

            //UT2H : C13 =  K Sto RSI UT2h doit être > D
            if (_stoRsi_ms5.KLine.Last(1) < _stoRsi_ms5.DLine.Last(1))
                return false;

            //UT2H :C3 = la clôture de la bougie précédente doit être supérieur à la valeur du SuperTrend[3,3] UT2h en cours 
            if (_ms5.ClosePrices.Last(1) < Math.Max(_st_ms5.DownTrend.Last(1), _st_ms5.UpTrend.Last(1)))
                return false;

            //UT30 : C15 = la MM 3 périodes (typicalprice) UT30  doit être >  MA  6 périodes(typicalprice) 
            if (_ma3_ms4.Result.Last(1) < _ma6_ms4.Result.Last(1))
                return false;

            //UT15 : C7 = la MM 6 périodes UT15 (sur typical price) doit être au dessus de la MM 8 périodes UT15 (sur typical price)
            if (_ma6_ms3.Result.Last(1) < _ma8_ms3.Result.Last(1))
                return false;


            //UT15 : C9 = la MM 20 périodes de Hull UT15 est ascendante
            if (_hma20_ms3.Result.Last(1) < _hma20_ms3.Result.Last(2))
                return false;

            //UT5 : La distance entre le plus haut du jour et le plus haut de la bougie Ut5mn actuelle soit inférieur à 140 points
            if (_ms6.HighPrices.Last(0) - _ms2.HighPrices.Last(0) > 140)
                return false;

            //UT5 : C5 =  en 5mn la MM de Hull 17 périodes est entrain de se retourner à la hausse (avec la bougie en cours)
            if (!(_hma17_ms2.Result.Last(0) > _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) < _hma17_ms2.Result.Last(2)))
                return false;

            //UT5 : C23 = Stochastic RSI 10 périodes lissé UT5mn à l’achat (K>D)
            if (!(_stoRsi_ms2.KLine.Last(0) < _stoRsi_ms2.DLine.Last(0)))
                return false;

            return true;
        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        //                                                      CheckConditionsToClosePositions METHOD
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void CheckConditionsToClosePositions()
        {
            int opened_pos_buy = 0;
            Position last_pos_buy = null;
            foreach (Position position in Positions.FindAll(_cBotLabel, SymbolName))
            {
                if (position.TradeType == TradeType.Buy)
                {
                    opened_pos_buy += 1;
                    last_pos_buy = position;
                }
            }
            if (opened_pos_buy < 1)
                return;


            //Exit in profit (C6 & C8)
            if (_hma17_ms2.Result.Last(0) < _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) > _hma17_ms2.Result.Last(2) && _ma6_ms3.Result.Last(1) < _ma8_ms3.Result.Last(1) && Symbol.Bid > last_pos_buy.EntryPrice)
            {
                foreach (Position position in Positions.FindAll(_cBotLabel, SymbolName, TradeType.Buy))
                    ClosePosition(position);
            }

            //Exit at loss (C6 & C2)

            Print("_hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2)  => " + _hma420_ms5.Result.Last(1) + " < " + _hma420_ms5.Result.Last(2) + "................ (_hma17_ms2.Result.Last(0) = " + _hma17_ms2.Result.Last(0));
            Print("_ma5_ms100.Result.Last(1) < _ma5_ms100.Result.Last(2)  => " + _ma5_ms100.Result.Last(1) + " < " + _ma5_ms100.Result.Last(2));
            //if (_hma17_ms2.Result.Last(0) < _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) > _hma17_ms2.Result.Last(2) && _hma420_ms5.Result.Last(1) < _hma420_ms5.Result.Last(2) && Symbol.Bid < _pm._last_pos_buy.EntryPrice)
            if (_hma17_ms2.Result.Last(0) < _hma17_ms2.Result.Last(1) && _hma17_ms2.Result.Last(1) > _hma17_ms2.Result.Last(2) && _ma5_ms100.Result.Last(1) < _ma5_ms100.Result.Last(2) && Symbol.Bid < last_pos_buy.EntryPrice)
            {
                foreach (Position position in Positions.FindAll(_cBotLabel, SymbolName, TradeType.Buy))
                    ClosePosition(position);
            }
        }
    }
}

 


@Nobody

PanagiotisCharalampous
18 Nov 2020, 15:21

Hi Nobody,

I guess that the problem is here

If you notice the series have only 96 bars but your are looking for a 420 moving average. You should make sure that you have at least as much bars as the moving average period else load more using LoadMoreHistory() method. Let me know if this resolves the problem.

Best Regards,

Panagiotis 

Join us on Telegram


@PanagiotisCharalampous

Nobody
18 Nov 2020, 15:43 ( Updated at: 21 Dec 2023, 09:22 )

RE:

PanagiotisCharalampous said:

Hi Nobody,

I guess that the problem is here

If you notice the series have only 96 bars but your are looking for a 420 moving average. You should make sure that you have at least as much bars as the moving average period else load more using LoadMoreHistory() method. Let me know if this resolves the problem.

Best Regards,

Panagiotis 

Join us on Telegram

...i am so...Stupid ! ;( thank you very much Panagiotis....i didn't think to check this ! solved !


@Nobody