Topics
Replies
mattbarfoot
09 May 2024, 20:56
( Updated at: 10 May 2024, 05:27 )
RE: OnPositionClosed event firing multiple times
PanagiotisCharalampous said:
Hi there,
Can you please share with us the source code of your cBot and provide us with instructions on how to reproduce this problem?
Best regards,
Panagiotis
Hey Panagiotis, I am attempting to log each position that closes in either the OnPositionClosed event or a CloseTrade sub. Multiple cbots with multiple instances will be running. Positions are logged in a csv file. Typically multiple entries are created in the csv which have different instanceIDs but have the same Label, which is set to the InstanceId when opening.
scenario 1 (CloseTrade)
Position Opened: ExecuteMarketOrder(TradeType.Buy, SymbolName, adjustedContracts, InstanceId, null, null);
Position Closes on x number of bars being reached, which then calls CloseTrade
private void CloseTrade(Position position)
{
LogTrade(position);
ClosePosition(position);
}
scenario 2 (OnPositionClosed event)
Position Opened:
ExecuteMarketOrder(TradeType.Sell, SymbolName, adjustedContracts, InstanceId, StopLossPips, TargetPips);
result.Position.ModifyTrailingStop(true);
private void OnPositionClosed(PositionClosedEventArgs args)
{
LogTrade(args.Position);
}
private void LogTrade(Position _position)
{
string log = $"{strategyName},{DateTime.Now},{Chart.TimeFrame},{0},{_position.TradeType},{_position.EntryTime}, {DateTime.UtcNow},{_position.Symbol},{_position.Pips}, {_position.NetProfit},{_position.GrossProfit},{_position.Id},{_position.Label}";
string Path;
File.AppendAllText(Path,log + Environment.NewLine);
}
@mattbarfoot
mattbarfoot
10 May 2024, 06:43
RE: RE: RE: OnPositionClosed event firing multiple times
PanagiotisCharalampous said:
Hey Panagiotis, So to confirm, a new instance is created every time a new position opens. So would the code below reference the correct instance:
ExecuteMarketOrder(TradeType.Sell, SymbolName, adjustedContracts, InstanceId, StopLossPips, TargetPips);
result.Position.ModifyTrailingStop(true);
and close event looks like:
private void OnPositionClosed(PositionClosedEventArgs args)
{
if(instanceID == args.Position.Label)
LogTrade(args.Position);
}
@mattbarfoot