Account Margin not resetting when backtesting bot
Account Margin not resetting when backtesting bot
14 May 2024, 03:21
I'm testing the modification of a bot's lot size and updating it on every bar (tried onBar, onBarClosed, same errors occurring) based on some indicator (not important just for reference). It runs fine for a little bit then just does minimum lot size entries. After a bit of investigation it seems like Margin isn't resetting even though trades are being closed? I've triple checked open positions and whatnot through debugging and it shows all positions are closed. I believe this is a bug and I did submit an error weeks ago but haven't heard anything so I thought I'd raise it here. I've tried using both ModifyPosition and partially closing trades to no avail.
Also weirdly enough it doesn't seem to work as it's supposed to when back testing without visual box being ticked. If I tick the box it works how I expect it to (up until the margin gets too high and then it just does minimums which also doesn't make sense it shouldn't work at all).
Wrote a quick bot to highlight for testing:
using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo;
using cAlgo.Indicators;
using System.Runtime.InteropServices;
using System.Linq;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.EAustraliaStandardTime, AccessRights = AccessRights.FullAccess)]
public class MyTradingBot : Robot
{
[Parameter("ATR", DefaultValue = 30)]
public int ATR { get; set; }
[Parameter("SL Multiplier", DefaultValue = 1)]
public double SLMultiplier { get; set; }
[Parameter("TP Multiplier", DefaultValue = 1)]
public double TPMultiplier { get; set; }
[Parameter("Risk %", DefaultValue = 1)]
public double Risk { get; set; }
// Position Management
public double StopLoss;
public double LotSize;
// Indicators
private AverageTrueRange _atr;
private AverageTrueRange _barAtr;
private RelativeStrengthIndex _rsi;
private MovingAverage _ma1;
private MovingAverage _ma2;
protected override void OnStart()
{
// Initialize EMAs
_atr = Indicators.AverageTrueRange(ATR, MovingAverageType.Exponential);
_barAtr = Indicators.AverageTrueRange(3, MovingAverageType.Exponential);
_rsi = Indicators.RelativeStrengthIndex(Bars.MedianPrices, 14);
_ma1 = Indicators.MovingAverage(Bars.ClosePrices, 14, MovingAverageType.Exponential);
_ma2 = Indicators.MovingAverage(Bars.ClosePrices, 50, MovingAverageType.Exponential);
}
protected override void OnBar()
{
// Barry's Godly Multiplier
double pipSize = Symbol.PipSize;
int multiplier = (int)Math.Pow(10, -Math.Log10(pipSize));
// ATR and Daily Open Price
double atrValue = _atr.Result.Last(1);
// Position Management
double atrStop = atrValue * multiplier * SLMultiplier;
double atrTP = atrValue * multiplier * TPMultiplier;
// Define the start and end times of your trading window
DateTime currentBarTime = Bars.OpenTimes.LastValue;
// Risk Management
double baseRisk = Risk / 100; // Your base risk percentage
double riskAmount = Account.Balance * baseRisk;
double pipValuePerStandardLot = Symbol.PipValue;
double riskPerPip = riskAmount / atrStop;
double freeMargin = Account.FreeMargin;
double LotSize = CalculateLotSize(riskPerPip, pipValuePerStandardLot, freeMargin);
// Indicators
double ma1 = _ma1.Result.Last(1);
double prevMa1 = _ma1.Result.Last(2);
double ma2 = _ma2.Result.Last(1);
// Entries
// Long Signal
if (prevMa1 < ma2 && ma1 > ma2)
{
if (Positions.FindAll("Buy Order").Length == 0 && Positions.FindAll("Sell Order").Length == 0)
{
ExecuteMarketOrder(TradeType.Buy, SymbolName, LotSize, "Buy Order", null, null);
}
}
// Short Signal
if (prevMa1 > ma2 && ma1 < ma2)
{
if (Positions.FindAll("Buy Order").Length == 0 && Positions.FindAll("Sell Order").Length == 0)
{
ExecuteMarketOrder(TradeType.Sell, SymbolName, LotSize, "Sell Order", null, null);
}
}
}
protected override void OnBarClosed()
{
// Barry's Godly Multiplier
double pipSize = Symbol.PipSize;
int multiplier = (int)Math.Pow(10, -Math.Log10(pipSize));
// ATR and Daily Open Price
double atrValue = _atr.Result.Last(1);
double atrStop = atrValue * multiplier * SLMultiplier;
double baseRisk = Risk / 100; // Your base risk percentage
double riskAmount = Account.Balance * baseRisk;
double pipValuePerStandardLot = Symbol.PipValue;
double riskPerPip = riskAmount / atrStop;
double freeMargin = Account.FreeMargin;
double LotSize = CalculateLotSize(riskPerPip, pipValuePerStandardLot, freeMargin);
foreach (Position position in Positions)
{
double currentSize = position.VolumeInUnits;
if (currentSize < LotSize)
{
ModifyPosition(position, LotSize);
}
if (currentSize > LotSize)
{
ClosePosition(position, currentSize-LotSize);
}
}
}
protected override void OnTick()
{
double closePrice = Bars.ClosePrices.Last(1);
double esOne = _ma1.Result.Last(1);
double esTwo = _ma2.Result.Last(1);
// Position Management
foreach (Position position in Positions)
{
if (position.TradeType == TradeType.Buy && esOne < esTwo)
{
ClosePosition(position);
Print("Open Positions: " + Positions.Count);
}
if (position.TradeType == TradeType.Sell && esOne > esTwo)
{
ClosePosition(position);
Print("Open Positions: " + Positions.Count);
}
}
}
private double CalculateLotSize(double riskPerPip, double pipValuePerStandardLot, double freeMargin)
{
double lotSize = riskPerPip / pipValuePerStandardLot; // Calculate the initial lot size based on risk per pip
double minLotSizeIncrement = Symbol.VolumeInUnitsMin; // Get the minimum lot size increment from the symbol settings
lotSize = Math.Ceiling(lotSize / minLotSizeIncrement) * minLotSizeIncrement; // Round the lot size up to the nearest minimum lot size increment
double estimatedMarginPerLot = Symbol.GetEstimatedMargin(TradeType.Buy, minLotSizeIncrement); // Estimate the margin required for the minimum lot size increment
double maxLotSizeWithinMargin = Math.Floor(freeMargin / estimatedMarginPerLot) * minLotSizeIncrement; // Calculate the maximum lot size that can be supported by the free margin
lotSize = Math.Min(lotSize, maxLotSizeWithinMargin); // Adjust the lot size to not exceed the maximum lot size that fits within the free margin
// Ensure the final lot size is within the broker's allowed range and is a multiple of the minimum lot size increment
double minLotSize = Symbol.VolumeInUnitsMin;
double maxLotSize = Symbol.VolumeInUnitsMax;
lotSize = Math.Max(minLotSize, lotSize);
lotSize = Math.Min(maxLotSize, lotSize);
return lotSize;
}
}
}
I'd love to get this working as the concept of a continuous market position is something I've been chasing for a while now.
Cheers,
Vik.
Replies
Phluxxed
14 May 2024, 06:51
( Updated at: 15 May 2024, 05:17 )
RE: Account Margin not resetting when backtesting bot
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
@Phluxxed
PanagiotisCharalampous
15 May 2024, 12:32
RE: RE: Account Margin not resetting when backtesting bot
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
@PanagiotisCharalampous
Phluxxed
15 May 2024, 13:43
RE: RE: RE: Account Margin not resetting when backtesting bot
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
Ah fantastic, glad to see it wasn't something I was doing! You got a rough timeframe on when that update may be?
@Phluxxed
PanagiotisCharalampous
16 May 2024, 05:45
RE: RE: RE: RE: Account Margin not resetting when backtesting bot
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
Ah fantastic, glad to see it wasn't something I was doing! You got a rough timeframe on when that update may be?
Unfortunately we do not have a timeframe at the moment
@PanagiotisCharalampous
Phluxxed
19 Jun 2024, 00:58
RE: RE: RE: RE: RE: Account Margin not resetting when backtesting bot
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
Ah fantastic, glad to see it wasn't something I was doing! You got a rough timeframe on when that update may be?
Unfortunately we do not have a timeframe at the moment
PanagiotisCharalampous hey mate the issue seems to have returned again? It was working fine after the last update but I'm running into it again.
@Phluxxed
PanagiotisCharalampous
19 Jun 2024, 05:11
RE: RE: RE: RE: RE: RE: Account Margin not resetting when backtesting bot
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
Ah fantastic, glad to see it wasn't something I was doing! You got a rough timeframe on when that update may be?
Unfortunately we do not have a timeframe at the moment
PanagiotisCharalampous hey mate the issue seems to have returned again? It was working fine after the last update but I'm running into it again.
Hi there,
Can you share new screenshots showing the version as well?
Best regards,
Panagiotis
@PanagiotisCharalampous
Phluxxed
19 Jun 2024, 05:56
RE: RE: RE: RE: RE: RE: RE: Account Margin not resetting when backtesting bot
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
Ah fantastic, glad to see it wasn't something I was doing! You got a rough timeframe on when that update may be?
Unfortunately we do not have a timeframe at the moment
PanagiotisCharalampous hey mate the issue seems to have returned again? It was working fine after the last update but I'm running into it again.
Hi there,
Can you share new screenshots showing the version as well?
Best regards,
Panagiotis
@Phluxxed
PanagiotisCharalampous
19 Jun 2024, 12:36
RE: RE: RE: RE: RE: RE: RE: RE: Account Margin not resetting when backtesting bot
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Phluxxed said:
PanagiotisCharalampous said:
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
Parameters are the default ones built into the bot as it's just an example and it's what I used to replicate. Back testing was a number of markets (forex, spot metals, spot indices, crypto, whatever else I tested it on) and dates are anything available in the range of 2013 - now that runs for longer than 100 trades. Tested on both 1m, the 2h and 15m charts I was testing on and tick data.
See below to show that the balance and equity is basically full but margin is more than the balance of the account:
And then you can see here the only position I have open is minimum lot size:
Thanks Vik,
We managed to reproduce the problem and it will be fixed in an upcoming update.
Best regards,
Panagiotis
Ah fantastic, glad to see it wasn't something I was doing! You got a rough timeframe on when that update may be?
Unfortunately we do not have a timeframe at the moment
PanagiotisCharalampous hey mate the issue seems to have returned again? It was working fine after the last update but I'm running into it again.
Hi there,
Can you share new screenshots showing the version as well?
Best regards,
Panagiotis
Thank you, the fix for this issue was not released yet. It will be released in an upcoming update.
Best regards,
Panagiotis
@PanagiotisCharalampous
PanagiotisCharalampous
14 May 2024, 05:51
Hi there,
Please provide us with dates, cBot parameters and backtesting settings so that we can reproduce this behavior on backtesting. Also share some screenshots demonstrating these positions.
Best regards,
Panagiotis
@PanagiotisCharalampous