Bug report for backtest - margin logic is not correct
Bug report for backtest - margin logic is not correct
17 Mar 2023, 10:13
Good day,
I think that in the backtest logic there is an error in the margin calculation.
Before executing an order, I check if there is enough free margin. However, in the backtest, crazy results occurred, so I analyzed the cause.
The error seems to occur only when positions are partially opened and closed.
Here is a code to reproduce the error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
namespace cAlgo.Robots
{
[Robot(AccessRights = AccessRights.None)]
public class BugReport : Robot
{
protected override void OnTick()
{
Print (Account.FreeMargin);
}
protected override void OnBar()
{
ExecuteMarketOrder(TradeType.Buy, Symbol.Name, 5, Symbol.Name, 0, 0);
ExecuteMarketOrder(TradeType.Sell, Symbol.Name, 3, Symbol.Name, 0, 0);
var bestPostion = Positions.OrderBy(position => position.Pips).Last();
if (bestPostion.VolumeInUnits > Symbol.VolumeInUnitsMin)
ModifyPosition(bestPostion, bestPostion.VolumeInUnits - Symbol.VolumeInUnitsMin);
else
ClosePosition(bestPostion);
}
}
}
After modifying some positions, the Free Margin is not returned correctly. This can be seen in the following screenshot. Here OnTick is printing the Account.FreeMargin. As you can see the value is different from the Free Margin.
Another point is that in the backtest orders are possible with negative free margin. You can see this in this screenshot.
Please check and fix the problem if necessary.
In a live demo account attempt, this phenomenon does not seem to occur. However, I have tested here only in a short period of time.
Thank you very much!