Hi Pablo,
Yes, this can be a tricky situation especially in cases where (as you noted) you have two or more trades occurring on the same bar.
The key here is not to rely on the BarsSinceExit keyword because (as you noticed), this can lead to erroneous results when you have consecutive trades on the same bar - which makes sense, because if you have two trades occurring on the same bar, the value for BarsSinceExit(1) {for the most recent trade} and BarsSinceExit(2) {for the trade immediately prior to it} will be the same.
A better solution is to keep a running variable that analyzes how many trades you've already written to the .csv file and then, at the end of each bar, compare that number to the value generated by the command "TotalTrades". In this way, you'll know whether you need to write one, two, three or a dozen trades to your file.
Then, based on the difference between these two values, you loop through the recent trades that happened since you last wrote to your .csv file, and write this data to your file. The counter for your loop will enable you to "look back" at all of the trades that have occurred since you last wrote to the .csv file.
Finally, you update your running variable to reflect the updated number of trades you've written to your .csv file. To put it in pseudo-code, it would be something like:
Code: Select all
Vars: NumTradesWritten(0);
If NumTradesWritten < TotalTrades Then Begin
value1 = TotalTrades - NumTradesWritten;
For value2 = 1 to value1 BEGIN
TradePL = MidStr(NumToStr(PositionProfit(value2) - 4.82, 2), 1, InStr(NumToStr(PositionProfit(value2) - 4.82, 2), ".")-1);
TradePL = TradePL + "," + RightStr(NumToStr(PositionProfit(value2) - 4.82, 2), 2) ;
sPrintLine = "MySystem_" + symbolroot + ";" + ";1;" + TradePL + NewLine;
FileAppend("C:\trades.csv", sPrintLine);
End;
NumTradesWritten = TotalTrades;
End;
I haven't tested this code to verify that it works, but hopefully it gives you the right idea. Let me know if anything is not clear or you have problems implementing it.
Good luck!