//+------------------------------------------------------------------+
//|                                               Trades History.mq4 |
//+------------------------------------------------------------------+

#property indicator_chart_window

#include <hanover --- function header (np).mqh>

extern string     ShowOrderTypes         = "COP";             // C=Closed orders; O=Open orders; P=Pending orders
extern string     EntrySettings          = "White,2,0";
extern string     SLSettings             = "Red,2,0";
extern string     TPSettings             = "Green,2,0";
extern string     ExitLossSettings       = "Red,2,0";
extern string     ExitProfitSettings     = "Green,2,0";
extern int        HorizLineLength        = 3;
extern string     EquityCalcBasis        = "E";               // B=Balance; E=Equity; F=Free margin
extern string     PriceFormat            = "': 'TB3.5";
extern string     PriceFormatJPY         = "': 'TB5.3";
extern string     PipsFormat             = "' = 'TB-3.1' p'";
extern string     AmountFormat           = "' = 'TB$,-7.2";
extern string     PercentFormat          = "' = 'TR%-2.2";
extern string     RFormat                = "' = 'TBR3.2' R'";
extern string     LotsFormat             = "'  :  'T,4.2' lots'";
extern string     PipValueFormat         = "' = 'TR$,7.2' /pip'";
extern string     DurationFormat         = "@H4!hI!m";
extern string     DateTimeFormat         = "'('w D n Y  H:Ia')'";
extern string     Visibility             = "M1,M5,M15,M30,H1,H4,D1,W1,MN";
extern string     OutputFile             = "Trades_History.txt";

string   ccy, sym, IndiName, arr[3];
int      dig, tf, tmf, h;
double   spr, pnt, tickval, bidp, askp, minlot, lswap, sswap;
string   optypes[6] = {"BUY","SELL","BUY LIMIT","SELL LIMIT","BUY STOP","SELL STOP"};
color    EntryColor, TPColor, SLColor, ExitProfitColor, ExitLossColor;
int      EntryWidth, TPWidth, SLWidth, ExitProfitWidth, ExitLossWidth;
int      EntryStyle, TPStyle, SLStyle, ExitProfitStyle, ExitLossStyle;

//+------------------------------------------------------------------+
int init()  {
//+------------------------------------------------------------------+
  IndiName = "#ON #";
  IndicatorShortName(IndiName);

  sym     = Symbol();
  ccy     = Symbol();
  tmf     = Period();
  bidp    = MarketInfo(ccy,MODE_BID);
  askp    = MarketInfo(ccy,MODE_ASK);
  pnt     = MarketInfo(ccy,MODE_POINT);
  dig     = MarketInfo(ccy,MODE_DIGITS);
  spr     = MarketInfo(ccy,MODE_SPREAD);
  tickval = MarketInfo(ccy,MODE_TICKVALUE);
  minlot  = MarketInfo(ccy,MODE_MINLOT);
  lswap   = MarketInfo(ccy,MODE_SWAPLONG);
  sswap   = MarketInfo(ccy,MODE_SWAPSHORT);
  if (dig == 3 || dig == 5) {
    pnt     *= 10;
    spr     /= 10;
    tickval *= 10;
  }  
  
  StrToStringArray(EntrySettings,arr);       EntryColor = StrToColor(arr[0]);        EntryWidth = StrToInteger(arr[1]);        EntryStyle = StrToInteger(arr[2]);
  StrToStringArray(SLSettings,arr);          SLColor = StrToColor(arr[0]);           SLWidth = StrToInteger(arr[1]);           SLStyle = StrToInteger(arr[2]);
  StrToStringArray(TPSettings,arr);          TPColor = StrToColor(arr[0]);           TPWidth = StrToInteger(arr[1]);           TPStyle = StrToInteger(arr[2]);
  StrToStringArray(ExitProfitSettings,arr);  ExitProfitColor = StrToColor(arr[0]);   ExitProfitWidth = StrToInteger(arr[1]);   ExitProfitStyle = StrToInteger(arr[2]);
  StrToStringArray(ExitLossSettings,arr);    ExitLossColor = StrToColor(arr[0]);     ExitLossWidth = StrToInteger(arr[1]);     ExitLossStyle = StrToInteger(arr[2]);
  
  del_obj();
  plot_obj();
  return(0);
}

//+------------------------------------------------------------------+
int deinit()  {
//+------------------------------------------------------------------+
  del_obj();
  return(0);
}

//+------------------------------------------------------------------+
void del_obj()  {
//+------------------------------------------------------------------+
  int k=0;
  while (k<ObjectsTotal())   {
    string objname = ObjectName(k);
    if (StringSubstr(objname,0,StringLen(IndiName)) == IndiName)  
      ObjectDelete(objname);
    else
      k++;
  }    
  return(0);
}

//+------------------------------------------------------------------+
int start()  {
//+------------------------------------------------------------------+
  del_obj();
  plot_obj();
  return(0);
}

//+------------------------------------------------------------------+
void plot_obj()   {
//+------------------------------------------------------------------+
  h=-1;
  if (StringLen(OutputFile)>0)  {
    h = FileOpen(OutputFile,FILE_WRITE|FILE_CSV,'`');
    string out = "TRADES HISTORY of " + Symbol() + "," + TFToStr(Period()) + DateToStr(TimeCurrent(), "' at 'w D n Y  H:Ia");
    FileWrite(h,out);
  }  
  for (int i=OrdersHistoryTotal()-1; i>=0; i--)
  {
    OrderSelect(i, SELECT_BY_POS, MODE_HISTORY);
    plot_order(i);
  }
  for (i=OrdersTotal()-1; i>=0; i--)
  {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    plot_order(i);
  }
  if (h>0)   FileClose(h);
  return(0);
}

//+------------------------------------------------------------------+
void plot_order(int i)   {
//+------------------------------------------------------------------+
  if (StringFind(StringUpper(Visibility)+",",TFToStr(Period())+",") < 0)   return;

  ShowOrderTypes = StringUpper(ShowOrderTypes);
  if (StringFind(ShowOrderTypes,OrderStatus(OrderTicket())) < 0)           return;
  if (OrderSymbol() != Symbol())                                           return;

  if (StringSubstr(Symbol(),3,3) == "JPY")   PriceFormat = PriceFormatJPY;

  double AcctEquity = AccountBalance();
  if (StringUpper(EquityCalcBasis) == "E")    AcctEquity = AccountEquity();
  if (StringUpper(EquityCalcBasis) == "F")    AcctEquity = AccountFreeMargin();

  int bar0 = iBarShift(Symbol(),Period(),OrderOpenTime());
  int bar1 = iBarShift(Symbol(),Period(),OrderCloseTime());

  double RiskPips  = MathAbs(OrderOpenPrice() - OrderStopLoss()  ) / pnt;
  double RetnPips  = MathAbs(OrderOpenPrice() - OrderTakeProfit()) / pnt;
  double ExitPips = 0;
  if (MathMod(OrderType(),2) == 0)
    ExitPips  = (OrderClosePrice() - OrderOpenPrice()) / pnt;
  else
    ExitPips  = (OrderOpenPrice() - OrderClosePrice()) / pnt;
  if (OrderStopLoss()   == 0)   RiskPips = 0;
  if (OrderTakeProfit() == 0)   RetnPips = 0;
  if (OrderClosePrice() == 0)   ExitPips = 0;
  double RiskAmt   = OrderLots() * tickval * RiskPips; 
  double RetnAmt   = OrderLots() * tickval * RetnPips;
  double ExitAmt   = OrderProfit();
  double RiskPcnt  = 100*DivZero(RiskAmt,AcctEquity);  
  double RetnPcnt  = 100*DivZero(RetnAmt,AcctEquity);  
  double ExitPcnt  = 100*DivZero(ExitAmt,AcctEquity);
  double RR        = DivZero(RetnAmt,RiskAmt);
  
  string DispTP    = "";
  string DispSL    = "";
  string DispEntry = "";
  string DispExit  = "";
  if (OrderTakeProfit() > 0)  {
    DispTP = "TP" + NumberToStr(OrderTakeProfit(),PriceFormat) + NumberToStr(RetnPips,PipsFormat)
           + NumberToStr(RetnAmt,AmountFormat) + NumberToStr(RetnPcnt,PercentFormat);
    if (OrderStopLoss() > 0)  {
      DispTP = DispTP + NumberToStr(RR,RFormat);
  } }                 
  if (OrderStopLoss() > 0)  {
    DispSL = "SL" + NumberToStr(OrderStopLoss(),PriceFormat) + NumberToStr(RiskPips,PipsFormat)
           + NumberToStr(RiskAmt,AmountFormat) + NumberToStr(RiskPcnt,PercentFormat);
  }
  DispEntry = "Entry" + NumberToStr(OrderOpenPrice(),PriceFormat) + NumberToStr(OrderLots(),LotsFormat) 
            + NumberToStr(tickval*OrderLots(),PipValueFormat);
  DispExit  = "Exit" + NumberToStr(OrderClosePrice(),PriceFormat) + NumberToStr(ExitPips,PipsFormat)
            + NumberToStr(ExitAmt,AmountFormat) + NumberToStr(ExitPcnt,PercentFormat);
  if (OrderCloseTime() > OrderOpenTime())
    DispExit = DispExit + DateToStr(OrderCloseTime()-OrderOpenTime(),DurationFormat);
  string ord_type = " (" + StringLower(optypes[OrderType()]) + NumberToStr(OrderMagicNumber(),"','T12");
  if (StringLen(StringTrimRight(OrderComment())) > 0)
    ord_type = ord_type + StrToStr(OrderComment(),"','T10')'");
  else
    ord_type = ord_type + ")";

  // Plot entry line.....
  if (StringLen(EntrySettings)>0)  {
    string  objname = IndiName + NumberToStr(OrderTicket(),"T12") + "-ENTRY" + ord_type;
    PlotTL (objname, false, 0, OrderOpenTime(), OrderOpenPrice(), OrderOpenTime()+HorizLineLength*Period()*60, OrderOpenPrice(), EntryColor, EntryWidth, EntryStyle, false, false, 0, DispEntry);  // Plot trendline
  }
  // Plot SL line.....
  if (StringLen(SLSettings)>0)  {
    objname = IndiName + NumberToStr(OrderTicket(),"T12") + "-SL";
    PlotTL (objname, false, 0, OrderOpenTime(), OrderStopLoss(), OrderOpenTime()+HorizLineLength*Period()*60, OrderStopLoss(), SLColor, SLWidth, SLStyle, false, false, 0, DispSL);  // Plot trendline
  }
  // Plot TP line.....
  if (StringLen(TPSettings)>0)  {
    objname = IndiName + NumberToStr(OrderTicket(),"T12") + "-TP";
    PlotTL (objname, false, 0, OrderOpenTime(), OrderTakeProfit(), OrderOpenTime()+HorizLineLength*Period()*60, OrderTakeProfit(), TPColor, TPWidth, TPStyle, false, false, 0, DispTP);  // Plot trendline
  }
  // Plot exit line.....
  if (StringFind("OC",OrderStatus(OrderTicket())) >= 0)  {
    objname = IndiName + NumberToStr(OrderTicket(),"T12") + "-EXIT";
    datetime ctime = OrderCloseTime();
    if (ctime == 0)   ctime = TimeCurrent();
    double oprice = OrderOpenPrice();
    if (OrderStatus(OrderTicket()) == "O")  {
      oprice = OrderClosePrice();
      ctime  = OrderOpenTime()+HorizLineLength*Period()*60;
    }  
    if (OrderProfit() >= 0)  {
      if (StringLen(ExitProfitSettings)>0)
        PlotTL (objname, false, 0, OrderOpenTime(), oprice, ctime, OrderClosePrice(), ExitProfitColor, ExitProfitWidth, ExitProfitStyle, false, false, 0, DispExit);  // Plot trendline
    } else {
      if (StringLen(ExitLossSettings)>0)  
        PlotTL (objname, false, 0, OrderOpenTime(), oprice, ctime, OrderClosePrice(), ExitLossColor, ExitLossWidth, ExitLossStyle, false, false, 0, DispExit);        // Plot trendline
  } }  
  if (h>0)  {
    string ot = DateToStr(OrderOpenTime(),DateTimeFormat);
    string ct = DateToStr(OrderCloseTime(),DateTimeFormat);
    if (OrderCloseTime() == 0)    ct = "                          ";
    FileWrite(h,"\nSL                               = " + DispSL);    
    FileWrite(h,"Entry " + ot + " = " + DispEntry);    
    FileWrite(h,"Exit  "  + DateToStr(OrderCloseTime(),DateTimeFormat) + " = " + DispExit);    
    FileWrite(h,"TP                               = " + DispTP);    
  }
  return;
}
//+------------------------------------------------------------------+
#include <hanover --- extensible functions (np).mqh>

