jeudi 21 janvier 2021

Call the method in the constructor after the initialization

The CalcTradePrice method should be called right after Trade object's initialization. Right now, it is being called before that, which leads to an exception:

System.DivideByZeroException: 'Attempted to divide by zero.'

var trade = new Trade
{
    Pair = pair,
    OpenRate = buyCandle.Close,
    OpenDate = buyCandle.OpenTime,
    Amount = currentBalance / buyCandle.Close,
    OpenFee = _backtestOptions.OpenFee,
    CloseFee = _backtestOptions.CloseFee,
    IsOpen = true
};

I know I can manually call the method after the initialization, just like that:

var trade = new Trade
{
    Pair = pair
};
CalcTradePrice();

or to create a derived class which executes it, but I don't want to. Any recommendations?

The Trade class:

public class Trade
{
    public string Pair { get; set; }
    public decimal OpenRate { get; set; }
    public decimal CloseRate { get; set; }
    public DateTime OpenDate { get; set; }
    public DateTime CloseDate { get; set; }
    public decimal OpenTradePrice { get; set; }
    public decimal Amount { get; set; }
    public decimal OpenFee { get; set; }
    public decimal CloseFee { get; set; }
    public SellType SellType { get; set; }
    
    public Trade()
    {
        CalcTradePrice();
    }
    
    public void CalcTradePrice()
    {
        this.OpenTradePrice = ... // DivideByZeroException because all elements are null at that moment
    }
}

Aucun commentaire:

Enregistrer un commentaire