Passing objects to class library

Created at 22 Jan 2024, 21:29
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!
CH

ChrisSpire

Joined 12.12.2022

Passing objects to class library
22 Jan 2024, 21:29


I want to move some code to class library. I have a class library with a class like the one below:

[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class AccountStats : Robot
{
    private Robot cBot;
    
    public AccountStats(Robot robot)
    {
        cBot = robot;
    }
    
    // (...)
}

I use OnStart() to initialize an object:

Stats = new AccountStats(this);

But I get errors “Object Reference Not Set To An Instance…” for example when using the code below inside class library:

var netProfit = cBot.History
                .Where(x => x.ClosingTime.Date == Server.Time.Date.AddDays(days))
                .Sum(x => x.NetProfit);

I believe that is caused by the fact that inside library class there is no instance of “Server” object?

In that case, what typical set of objects should I pass to external class library to use most common methods? Obviously I need to pass the main “robot” (as in constructor above). Now I know I should pass “Serwer” object. What else?

I know this is kind of silly question and the answer is “pass those objects you will use”. But I have great difficulty in debugging when I get “Object reference…”, so I would like to minimize risk of such crashes. And maybe I should not pass individual object and there is a solution to use all methods from within class library the same way I would use then inside main cBot?

 

UPDATE: Clearly I don't uderstand this because expanding the constructor to IServer obecjt did not change the behaviour

    public AccountStats(Robot robot, IServer server)
    {
        cBot = robot;
        cServer = server;
    }
    
    public double DaysProfit(int days)
    {
        double netProfit;  

        netProfit = cBot.History
                .Where(x => x.ClosingTime.Date == cServer.Time.Date.AddDays(days))
                .Sum(x => x.NetProfit);
        
        return netProfit;
    }

 


@ChrisSpire
Replies

PanagiotisCharalampous
23 Jan 2024, 06:32

Hi there,

Server object is a property of the Robot class. You should call it as a property of the robot e.g. 

cBot.Server.Time.Date.AddDays(days)

Best regards, 

Panagiotis


@PanagiotisCharalampous