Exception

Created at 27 Nov 2012, 09:34
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!
PH

phamvanthanh

Joined 07.10.2012

Exception
27 Nov 2012, 09:34


Hi, 

I build my robot succeeded but when I do the backtest it gives me this error: 

    Crashed in OnTick with System.NullReferenceException: Object reference not set to an instance of an object.  

I am using a customized indicator and I alse added Reference for the robot. Could any one please help me with this

Thanks

 

 

 

 


@phamvanthanh
Replies

admin
27 Nov 2012, 09:45

It referes to a variable that has not been initialized. You may send us the code to point out exactly where the error is.

 


@admin

phamvanthanh
27 Nov 2012, 11:34

//#reference: ..\Indicators\NonLagDot.algo
//
// -------------------------------------------------------------------------------------------------
//
//
// -------------------------------------------------------------------------------------------------

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

namespace cAlgo.Robots
{
    [Robot]
   
    public class NonLagDotBot : Robot
    {
        private NonLagDot trnd;
        
        private Position position;
        
        [Parameter]
        public DataSeries Price { get; set; }         
        
        //[Parameter("Take Profit", DefaultValue = 10)]
        //public int TakeProfitInPips { get; set; }
        
        [Parameter("Length", DefaultValue = 60)]
        public int Length { get; set; }

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

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

        [Parameter("Color", DefaultValue = 1)]
        public int ColorFront { get; set; }

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

        [Parameter("Deviation", DefaultValue = 0)]
        public double Deviation { get; set; }
        
        [Parameter("Volume", DefaultValue = 10000, MinValue = 0)]
        public int Volume { get; set; }
        
        [Parameter("Stop Loss", DefaultValue = 10)]
        public int StopLoss { get; set; }
        
        

        protected override void OnStart()
        {
            trnd = Indicators.GetIndicator<NonLagDot>(Price, Length, Displace, Filter, ColorFront, ColorBarBack, Deviation);
        }

        protected override void OnTick()
        {
            if (Trade.IsExecuting) return;
            
            bool longposition = position != null & position.TradeType == TradeType.Buy;            
            bool shortposition = position != null & position.TradeType == TradeType.Sell;

            if (trnd.markettrend > 0.0 && shortposition)
        	{
        	    ClosePosition();
        	    Buy();        	   
        	}

            if (trnd.markettrend < 0.0  && longposition)
            {
                ClosePosition();
        	    Sell();    
            }
        }

        private void ClosePosition()
        {
            if (position != null)
            {
                Trade.Close(position);
                position = null;
            }
        }
        
        private void Buy()
        {        
            Trade.CreateBuyMarketOrder(Symbol, Volume);
        }
        
        private void Sell()
        {        
            Trade.CreateSellMarketOrder(Symbol, Volume);
        }

        protected override void OnPositionOpened(Position openedPosition)
        {
            position = openedPosition;
            Trade.ModifyPosition(openedPosition, GetAbsoluteStopLoss(openedPosition, StopLoss), null);
        }

        private double GetAbsoluteStopLoss(Position position, int StopLoss)
        {
            return position.TradeType == TradeType.Buy
                ? position.EntryPrice - Symbol.PipSize * StopLoss
                : position.EntryPrice + Symbol.PipSize * StopLoss;
        }
    }
}



and this is the indicator

using System;
using cAlgo.API;

namespace cAlgo.Indicators
{
    [Indicator("NonLagDot", IsOverlay = true, ScalePrecision = 5)]
    public class NonLagDot : Indicator
    {
        #region Input

        [Parameter]
        public DataSeries Price { get; set; }

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

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

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

        [Parameter("Color", DefaultValue = 1)]
        public int ColorFront { get; set; }

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

        [Parameter("Deviation", DefaultValue = 0)]
        public double Deviation { get; set; }
        
        public double markettrend = 0;

        #endregion

        #region indicator line
        [Output("NLD", Color = Colors.Yellow, PlotType = PlotType.Points)]
        public IndicatorDataSeries MABuffer { get; set; }

        [Output("Up", Color = Colors.RoyalBlue, PlotType = PlotType.Points)]
        public IndicatorDataSeries UpBuffer { get; set; }

        [Output("Dn", Color = Colors.Red, PlotType = PlotType.Points)]
        public IndicatorDataSeries DnBuffer { get; set; }
        
        //[Output("markettrend")]
        //public trend markettrend { get; set; }

        #endregion

        private IndicatorDataSeries price;
        private IndicatorDataSeries trend;
        private const double Cycle = 4;

        /// <summary>
        /// Indicator initialization function
        /// </summary>
        protected override void Initialize()
        {
            price = CreateDataSeries();
            trend = CreateDataSeries();

        }

        /// <summary>
        /// NonLagMA_v4   main logic
        /// </summary>
        /// <param name="index"></param>
        public override void Calculate(int index)
        {
            if (index < Length*Cycle + Length)
            {
                MABuffer[index] = 0;
                UpBuffer[index] = 0;
                DnBuffer[index] = 0;
                
                return;
            }

            const double pi = 3.1415926535;
            const double Coeff = 3*pi;
            int Phase = Length - 1;
            double Len = Length*Cycle + Phase;
            double Weight = 0;
            double Sum = 0;
            double t = 0;

            for (int i = 0; i <= Len - 1; i++)
            {
                double g = 1.0/(Coeff*t + 1);
                if (t <= 0.5) 
                    g = 1;
                
                double beta = Math.Cos(pi*t);
                double alfa = g*beta;
                price[i] = Price[index - i];
                Sum += alfa*price[i];
                Weight += alfa;
                
                if (t < 1) 
                    t += 1.0/(Phase - 1);
                else if (t < Len - 1) 
                    t += (2*Cycle - 1)/(Cycle*Length - 1);
            }

            if (Weight > 0) 
                MABuffer[index] = (1.0 + Deviation/100)*Sum/Weight;
           
            double filterFactor = Filter*Symbol.PointSize;
            
            if (Filter > 0)
            {
                if (Math.Abs(MABuffer[index] - MABuffer[index - 1]) < filterFactor)
                    MABuffer[index] = MABuffer[index - 1];
            }

            if (ColorFront <= 0) return;
            trend[index] = trend[index - 1];

            if (MABuffer[index] - MABuffer[index - 1] > filterFactor) 
                trend[index] = 1;
            if (MABuffer[index - 1] - MABuffer[index] > filterFactor) 
                trend[index] = -1;

            DnBuffer[index] = double.NaN;
            UpBuffer[index] = double.NaN;

            if (trend[index] > 0)
            {
                UpBuffer[index] = MABuffer[index];
                if (trend[index - ColorBarBack] < 0)
                    UpBuffer[index - ColorBarBack] = MABuffer[index - ColorBarBack];
            }
            else if (trend[index] < 0)
            {
                DnBuffer[index] = MABuffer[index];
                if (trend[index - ColorBarBack] > 0)
                    DnBuffer[index - ColorBarBack] = MABuffer[index - ColorBarBack];
            }
             markettrend = trend[index];
            
          
             if (IsRealTime)
            {                
                ChartObjects.DrawText("markettrend", "markettrend = " + markettrend + " ",
                                     StaticPosition.TopLeft, Colors.White);              
            }
            
        }
    }
}

Hi admin,

above are robot and indicators

 

Thanks


@phamvanthanh

admin
27 Nov 2012, 18:07

The reason it is crasshing is here:

bool longposition = position != null & position.TradeType == TradeType.Buy;            
bool shortposition = position != null & position.TradeType == TradeType.Sell;

It has to be corrected to this:

bool longposition = position != null && position.TradeType == TradeType.Buy;            
bool shortposition = position != null && position.TradeType == TradeType.Sell;

One more note, you would need this line

        public IndicatorDataSeries MarketTrend { get; set; }

instead of

        public double markettrend = 0;

in order to be able to access the values.


@admin

phamvanthanh
28 Nov 2012, 06:04

Hi again,

Could I use 

 public double MarketTrend { get; set; }

instead of

public double MarketTrend { get; set; }

?

I have done that for the Indicator code an It returns the result as intended. But when I use MarketTrend in robot as below condition 

if (Trnd.MarketTrend >= 0.0 && !longposition) 

It doesn't work right. Then I use this method in the robot to check its value (Trnd.MarketTrend's value)

                         ChartObjects.DrawText("\nMarketTrend", "\nMarketTrend_Robot = " + Trnd.MarketTrend + " ",

                                     StaticPosition.TopLeft, Colors.White); 

and  this method to check in the Indicator

 

 

 

if (IsRealTime)

            {                

                ChartObjects.DrawText("MarketTrend", "MarketTrend_Indicator = " + MarketTrend + " ",

                                     StaticPosition.TopLeft, Colors.White);

                     

            }

and the screen shows

"MarketTrend_Indicator = 1" (or -1 denpends on market)

"MarketTrend_Robot =  0" (always)

as Image

 

I think this issue is easy to you but it quite difficult to me as I am newbie

 

Thanks

 

 

 

 

 


@phamvanthanh

phamvanthanh
28 Nov 2012, 06:16

 

Sorry,

 

I mean  I'd like to use 

public double MarketTrend { get; set; }

instead of

public IndicatorDataSeries MarketTrend { get; set; }

because I intend to use MarketTrend with the value "-1"and "1" depend on market's move as condition for robot.

If I use

public "IndicatorDataSeries MarketTrend { get; set; } I don't know how to use its value for the robot nor to convert it to double or integer.

thanks

 

 

 


@phamvanthanh