Help with Object reference not set to an instance of an object - Error

Created at 17 Nov 2015, 05:37
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!
SI

sim_trader

Joined 03.08.2013

Help with Object reference not set to an instance of an object - Error
17 Nov 2015, 05:37


Hi Everyone,

I am still new in terms of C-algo experience. But I am making surprising progress in a couple of weeks.  I nearly have my systems fully working and even as is it does seem to way outperform MT4. However, I have one bug I cannot solve.

I need to copy in some stop order from MT4. So I have edited the MT4 to C-trader copier by siamfx, such that it copies over stop orders. It seemed to working without crashing for a few days

// ---------------------------------------------------------------------------------------
//
//    CSV reader to tansfer only stop orders from CSV  
//    mt4 writes to file 
//    version1 
//    lotsize calculation fixed _july1_siamfx
//
// ---------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo
{

    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    //AccessRights.FullAccess

    public class MT2cTrader : Robot
    {



        [Parameter("Close Hour", DefaultValue = 18, MinValue = 0, MaxValue = 23)]
        public int CloseHour { get; set; }

        [Parameter("Close Minute", DefaultValue = 30, MinValue = 0, MaxValue = 59)]
        public int CloseMinute { get; set; }

        [Parameter("Orders Input File Path", DefaultValue = "C:\\PFDMT4\\MQL4\\Files\\TradeCopy.csv")]
        //MT4 -1 
        //C:\\Users\\trader\\AppData\\Roaming\\MetaQuotes\\Terminal\\69420FB8433504FEA0FA029C390238DB\\MQL4\\Files\\TradeCopy.csv


        public string orders_input_file { get; set; }

        [Parameter("Slippage", DefaultValue = 3.5)]
        public double slippage { get; set; }


        [Parameter("Delimiter", DefaultValue = ";")]
        public string delimiter { get; set; }

        protected override void OnStart()
        {
            Timer.Start(3);
            //start timer with 3 second interval
            Print(Server.Time.DayOfWeek, Server.Time.Hour, Server.Time.Minute);





            //  var triggerTimeInLocalTimeZone = new DateTime(DateTime.Now.Year, DateTime.Now.Month, CloseDay, CloseHour, CloseMinute, 0);
            // _triggerTimeInServerTimeZone = TimeZoneInfo.ConvertTime(triggerTimeInLocalTimeZone, TimeZoneInfo.Local, TimeZone);


        }

        private bool debug = true;

        protected override void OnTimer()
        {
            //todo, check M.D.
            //price = marketDepth.AskEntries[0].Price; 
            //volume = marketDepth.AskEntries[0].Volume;


            //
            if ((Server.Time.DayOfWeek == DayOfWeek.Friday) && (Server.Time.Hour == CloseHour) && (Server.Time.Minute >= CloseMinute))
            {


                foreach (var order in PendingOrders)
                {
                    CancelPendingOrder(order);
                }

                var positions = Positions.FindAll(null);

                foreach (var position in positions)
                {
                    ClosePosition(position);
                }

                Print("End of Week Shutdown");

                // then stop the robot
                int milliseconds = 18000000;
                System.Threading.Thread.Sleep(milliseconds);

                // Stop();


            }


            string[] lines = new String[0];

            try
            {
                lines = File.ReadAllLines(orders_input_file);

            } catch (Exception e)
            {
                // return -july 4th
                Print("Exception Error on MT2cTrader: " + e.Message);
                return;
            }

            List<string> existing_positions = new List<string>();

            foreach (string line in lines)
            {

                OrderData order = new OrderData(line.Split(delimiter.Length > 0 ? delimiter[0] : ','), MarketData);
                existing_positions.Add(order.label);

                if (debug)
                    Print(line);
                var allowtrade = 1;

                double lotratio = (Account.Balance / order.senderbalance);
                double hmm = Convert.ToDouble(order.lot);
                hmm = (hmm * lotratio);
                // order.lot = Symbol.QuantityToVolume(hmm);
                order.lot = Symbol.NormalizeVolume(hmm, RoundingMode.Down);

                Print("Order Voume is  {0}", order.lot);
                Print("Lot Ration is  {0}", lotratio);
                Print("Lots before conversion are  {0}", hmm);


                foreach (var exorder in PendingOrders)
                {
                    if (exorder.Comment == order.comment)
                    {
                        allowtrade = 0;

                    }
                }


                foreach (HistoricalTrade trade in History)
                {
                    if (trade.Comment == order.comment)
                    {
                        allowtrade = 0;

                    }
                }

                if (order.isCorrect() && (allowtrade == 1) && (Positions.Find(order.comment) == null) && order.label != "331815188" && (Server.Time.DayOfWeek == DayOfWeek.Monday) || (Server.Time.DayOfWeek == DayOfWeek.Tuesday) || (Server.Time.DayOfWeek == DayOfWeek.Wednesday) || (Server.Time.DayOfWeek == DayOfWeek.Thursday) || (Server.Time.DayOfWeek == DayOfWeek.Friday))


                    PlaceStopOrder(order.type, order.symbol, order.lot, order.price, order.label, order.sl, order.tp, null, order.comment);
            }
//=== error


        }

    }

    public class OrderData
    {

        private const long mt_lot_coefficient = 100000;
        //corrected_100000_july1
        public Symbol symbol;
        public TradeType type;
        public long lot;
        public double price;
        public int sl;
        public int tp;
        public string label;
        public string comment;
        public double senderbalance;
        private bool initialized_properly = true;

        public OrderData(string[] raw_pieces, MarketData market_data)
        {
            try
            {
                this.comment = raw_pieces[0].Trim();
                this.symbol = market_data.GetSymbol(raw_pieces[1].Trim());
                this.setType(Convert.ToInt32(raw_pieces[2].Trim()));
                this.lot = Convert.ToInt64(this.parseDouble(raw_pieces[3]) * mt_lot_coefficient);
                this.price = this.parseDouble(raw_pieces[4]);
                this.sl = this.getPipDistance(price, this.parseDouble(raw_pieces[5]));
                this.tp = this.getPipDistance(price, this.parseDouble(raw_pieces[6]));
                this.label = raw_pieces[7].Trim();
                this.senderbalance = this.parseDouble(raw_pieces[8]);
            } catch (Exception e)
            {
                this.initialized_properly = false;
            }
        }

        public bool isCorrect()
        {
            return this.initialized_properly;
        }

        private double parseDouble(string value)
        {
            return double.Parse(value.Trim().Replace(',', '.'), System.Globalization.CultureInfo.InvariantCulture);
        }





        private void setType(int mt_type)
        {
            this.type = mt_type == 4 ? TradeType.Buy : TradeType.Sell;
        }

        private int getPipDistance(double basic_price, double close_price)
        {
            return Convert.ToInt32(Math.Round(Math.Abs(basic_price - close_price) / this.symbol.PipSize));
        }

    }

}

 and now it crashes over and over with the error.

“Crashed in OnTime with NullReferenceException: Object reference not set to an instance of an object”

Can anyone tell what I have done wrong. I only have 1 week of c programming.

If you see the issue can you please let me know in simple terms how to solve it.

Thanks so so much

Cheers Sim


@sim_trader
Replies

ClickAlgo
17 Nov 2015, 07:59 ( Updated at: 21 Dec 2023, 09:20 )

Hi Sim,

If you want to fix this easy and future projects then I would advise that you download Visual Studio 2013 Community Edition from here, make sure you use 2013 and not 2015

https://www.visualstudio.com/en-us/news/vs2013-community-vs.aspx

Then from cAlgo right click your robot and choose edit with visual studio, when it opens visual studio put a break point in the OnStart method as shown below:-

How to set a break-point

Then build the project from Visual Studio, when it has built, choose from the drop-down Tools->Attach to process, as shown below:-

 

When you have attached the process you can now run the robot from cAlgo the code running will stop at your break-point and allow you to step through the code and debug it line by line, if you hover your mouse over variables you will see the values they contain, you should be able to easily identify your problem this way.

read more about debugging with Visual Studio here:-

https://www.visualstudio.com/en-us/get-started/code/debug-your-app-vs

It is better you learn this now to save you a lot of time later trying to work out why your robot is not working.

good luck.

Paul.


@ClickAlgo

ClickAlgo
17 Nov 2015, 08:04

Press F10 to step through the code and F11 for method calls, you will work it out.


@ClickAlgo

sim_trader
17 Nov 2015, 19:35

Thanks

Hi Paul,

Thanks so so much. That was probably the single most useful reply I have ever had on any forum. I really appreciate your time.

I downloaded visual studio. It located the error. From that I work out it was poorly placed brackets around some " || " statements which was calling the placestoporder when it should not have been.

Thanks so so much. I would never have worked that out without your help.

Cheers, Sim


@sim_trader