{
  Function to export the trades of a strategy to an external CSV file.

  Copyright StrategyQuant 2016
}

input:
FileName(String),  // file name where the trades results will be written
ATRPeriod(NumericSimple); // period for ATR indicator that will be exported together with the data
        
        	
Var:
NumberOfTrades(0),                
NewCurrBarTrades(0),
Index1(0),
Index2(0),  
DataToLog("");

NewCurrBarTrades = TotalTrades - NumberOfTrades;

// delete the file if this is initial call to this function
if BarNumber = 1 then FileDelete(FileName);

If NewCurrBarTrades > 0 and BarStatus(1) >= 0 then begin

	for Index1 = 0 to NewCurrBarTrades - 1 Begin
		Index2 = NewCurrBarTrades - Index1;
     	
        DataToLog = "TRADE," + 
        			DateTimeToString(EntryDateTime(Index2).ELDateTimeEx) + "," + 
        			NumtoStr(EntryPrice(Index2), 5) + "," + 
        			DateTimeToString(ExitDateTime(Index2).ELDateTimeEx) + "," + 
        			NumtoStr(ExitPrice(Index2), 5) + "," + 

                    GetSymbolName + "," + 
                    NumtoStr(MarketPosition(Index2), 0) + "," + 
                    NumtoStr(MaxContracts(Index2), 0) + "," + 

                    NumtoStr(PositionProfit(Index2), 2) + "," + 
                    NumtoStr(Average(TrueRange, ATRPeriod)[FindBar(EntryDate(Index2), EntryTime(Index2)) + 1], 4) + "," +
                    NumtoStr(MaxPositionProfit(Index2), 4) + "," + 
                    NumtoStr(MaxPositionLoss(Index2), 4)  +  "," +
                    Newline;    
 
        FileAppend(FileName, DataToLog);
        
        NumberOfTrades = NumberOfTrades + 1;
	end;
 end; 
 
 SQExportTrades = NumberofTrades;