Author: Amba
Orders Execution
Checks for the total of closed orders
Miscellaneous
Implements a curve of type %1It writes information to fileIt writes information to fileIt writes information to fileIt reads information from a file
0 Views
0 Downloads
0 Favorites
AccEq
ÿþ//+------------------------------------------------------------------+

//|                                                        AccEq.mq4 |

//|                                                             Amba |

//|                                                                a |

//+------------------------------------------------------------------+

#property copyright "Amba"

#property link      "a"

#property version   "2.05"

#property strict

#property indicator_chart_window

#property indicator_buffers 5

#property indicator_color1 clrGray

#property indicator_color2 clrGray

#property indicator_color3 clrRed

#property indicator_color4 clrDodgerBlue

#property indicator_color5 clrViolet

#property indicator_style5 STYLE_SOLID

#property indicator_type5 DRAW_LINE



extern bool bShowBalance = true; //Show Balance line

extern bool bShowEquity = true;//Show Equity changes

input string _s1 = "--- SERVICE ---";

input bool bDelPeriod = false; // Delete from history:

input datetime dDateFrom = 0; //  - from

input datetime dDateTo = 0; //  - to



//--- buffers

double ExtLowHighBuffer[];

double ExtHighLowBuffer[];

double ExtOpenBuffer[];

double ExtCloseBuffer[];

double ExtBalance[];

//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//|------------------------------------------------------------------|

string pref = "ATB";

string  ACCEQ_NM = "";



datetime startd;



int _an = 0;

double _ab = 0;





#define MAX_VAL  9999999

#define MIN_VAL -9999999





//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int OnInit(void)

  {



//Print(__FUNCTION__);



   IndicatorShortName(pref);

   IndicatorDigits(2);

//--- indicator lines

   SetIndexStyle(0, DRAW_HISTOGRAM, 0, 1);

   SetIndexBuffer(0, ExtLowHighBuffer);

   SetIndexStyle(1, DRAW_HISTOGRAM, 0, 1);

   SetIndexBuffer(1, ExtHighLowBuffer);

   SetIndexStyle(2, DRAW_HISTOGRAM, 0, 2);

   SetIndexBuffer(2, ExtOpenBuffer);

   SetIndexStyle(3, DRAW_HISTOGRAM, 0, 2);

   SetIndexBuffer(3, ExtCloseBuffer);

   SetIndexBuffer(4, ExtBalance);



   for(int i = 1; i < 5; i++)

      SetIndexEmptyValue(i, 0);

//---



   SetIndexLabel(0, "AE.Low");

   SetIndexLabel(1, "AE.High");

   SetIndexLabel(2, "AE.Open");

   SetIndexLabel(3, "AE.Close");

   SetIndexLabel(4, "ABalance");



   if(bDelPeriod && (dDateFrom <= 0 || dDateTo <= 0 || dDateTo < dDateFrom))

     {

      Comment("INCORRECT PARAMS");

      return INIT_PARAMETERS_INCORRECT;

     }









   if(bShowEquity)

      HLineCreate(0, pref + "HL", 0, AccountEquity(), clrOrange, STYLE_DOT, 1, false, false);



   EventSetTimer(1);

//--- initialization done

   return INIT_SUCCEEDED;

  }





int HstHandle;

ulong HstPos;

MqlRates rt;



//+------------------------------------------------------------------+

int WriteHistoryHeader(int FileHandle, int NewPeriod)

  {

   string c_copyright;

   int    i_digits = 2;

   int    i_unused[13] = {0};

   int    vers = 401;



   if(FileHandle < 0)

      return (-1);

   c_copyright = "(C)opyright 2003, MetaQuotes Software Corp.";

   FileWriteInteger(FileHandle, vers, LONG_VALUE);

   FileWriteString(FileHandle, c_copyright, 64);

   FileWriteString(FileHandle, ACCEQ_NM, 12);

   FileWriteInteger(FileHandle, NewPeriod, LONG_VALUE);

   FileWriteInteger(FileHandle, 2, LONG_VALUE);

   FileWriteInteger(FileHandle, 0, LONG_VALUE);       //timesign

   FileWriteInteger(FileHandle, 0, LONG_VALUE);       //last_sync

   FileWriteArray(FileHandle, i_unused, 0, ArraySize(i_unused));

   FileFlush(FileHandle);

   return (0);

  }



//-------------------

MqlRates buf[];





//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int OpenHistory()

  {

   int ret = INVALID_HANDLE;



   MqlRates hst[], r1, r2, rs;

   int cnt = 0, err = 0;

   r2.time = 0;

   r1.time = 0;





   ret = FileOpenHistory(ACCEQ_NM + "1.hst", FILE_BIN | FILE_WRITE | FILE_READ | FILE_SHARE_READ | FILE_SHARE_WRITE);

   if(ret != INVALID_HANDLE)

     {

      if(FileSize(ret) < 149)

        {

         WriteHistoryHeader(ret, 1);

         HstPos = FileTell(ret);

        }

      else

        {

         FileSeek(ret, 148, SEEK_SET);

         FileReadArray(ret, hst);

         FileClose(ret);

         ret = FileOpenHistory(ACCEQ_NM + "1.hst", FILE_BIN | FILE_WRITE);

         err = GetLastError();

         WriteHistoryHeader(ret, 1);

         Array_Sort_Quick3(hst, 0, ArraySize(hst) - 1);

         for(int p = 0; p < ArraySize(hst); p++)

            hst[p].time = TimeStartOfTF(hst[p].time, 1);



         for(int p = 0; p < ArraySize(hst); p++)

           {

            r1 = hst[p];

            if(bDelPeriod && r1.time >= dDateFrom && rt.time <= dDateTo)

               continue;

            if(!(r1.open > 0 && r1.close > 0 && r1.high > 0 && r1.low > 0))

               continue;

            if(r1.time != r2.time)

              {

               ////Print(r2.time);

               if((int)r2.time > 100 && r2.open > 0 && r2.close > 0 && r2.high > 0 && r2.low > 0)

                 {

                  FileWriteStruct(ret, r2);

                  rt = r2;

                 }

               r2 = r1;

              }

            else

              {

               ////Print(r2.time);

               r1.high = fmax(r1.open, r1.high);

               r1.high = fmax(r1.close, r1.high);

               r1.low = fmin(r1.open, r1.low);

               r1.low = fmin(r1.close, r1.low);



               r2.high = fmax(r2.open, r2.high);

               r2.high = fmax(r2.close, r2.high);

               r2.high = fmax(r1.high, r2.high);

               r2.low = fmin(r2.open, r2.low);

               r2.low = fmin(r2.close, r2.low);

               r2.low = fmin(r1.low, r2.low);

               r2.close = r1.close;

               r1 = r2;

              }

           }



         HstPos = FileTell(ret);

         if((r1.open > 0 && r1.close > 0 && r1.high > 0 && r1.low > 0))

            if(!(bDelPeriod && r1.time >= dDateFrom && rt.time <= dDateTo))

              {

               FileWriteStruct(ret, r1);

               rt = r1;

              }



         FileFlush(ret);

         ////Print(FileSize(ret));

         FileClose(ret);

         ret = FileOpenHistory(ACCEQ_NM + "1.hst", FILE_BIN | FILE_WRITE | FILE_READ | FILE_SHARE_READ | FILE_SHARE_WRITE);

         FileSeek(ret, 148, SEEK_SET);

         FileReadArray(ret, buf);



        }

     }

   return(ret);

  }



//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void RunInit()

  {

//Print(__FUNCTION__);

  

   if(HstHandle != INVALID_HANDLE)

     {

      FileClose(HstHandle);

      HstHandle = INVALID_HANDLE;

     }







   ArrayResize(buf,0);

   ACCEQ_NM = "ACCEQU_" + (string)_an + "_";

   HstHandle = OpenHistory();

   



   ArrayInitialize(ExtLowHighBuffer, EMPTY_VALUE);

   ArrayInitialize(ExtOpenBuffer, 0);

   ArrayInitialize(ExtCloseBuffer, 0);

   ArrayInitialize(ExtHighLowBuffer, 0);

   ArrayInitialize(ExtBalance, 0);



   if(bShowEquity)

     {

      ArraySetAsSeries(buf, true);

      for(int i = 0; i < ArraySize(buf) - 1 ;       i++)

        {

         int sh = iBarShift(NULL, 0, buf[i].time);

         MergeBuf(sh, buf[i]);

        }

     }



   if(bShowBalance)

     {

      double pr = 0;

      int fsh = 0, lsh = 0, sh = 0;

      datetime lastdt = 0;

      for(int i = 0; i < OrdersHistoryTotal() - 1; i++)

        {

         if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) && OrderProfit() + OrderCommission() + OrderSwap() == 0)

            continue;

         datetime dt = OrderCloseTime();

         //if(lastdt>dt)

         //   //Print(dt," ",lastdt);



         //lastdt=dt;

         sh = iBarShift(NULL, 0, dt);

         fsh = fmax(fsh, sh);



         pr = OrderProfit() + OrderCommission() + OrderSwap();

         for(int j = sh; j >= 0; j--)

            ExtBalance[j] += pr;

        }



      double AB = AccountBalance(), delta = AB - ExtBalance[0];

      for(int i = 0; i < fsh + 1; i++)

         ExtBalance[i] += delta;

     }



  }



//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void MergeBuf(int sh, MqlRates &r)

  {

   if(ExtCloseBuffer[sh] == 0)

      ExtCloseBuffer[sh] = r.close;



   if(ExtLowHighBuffer[sh] == EMPTY_VALUE)

      ExtLowHighBuffer[sh] = r.low;

   else

      ExtLowHighBuffer[sh] = fmin(ExtLowHighBuffer[sh], r.low);



   if(ExtHighLowBuffer[sh] == 0)

      ExtHighLowBuffer[sh] = r.high;

   else

      ExtHighLowBuffer[sh] = fmax(ExtHighLowBuffer[sh], r.high);



   ExtOpenBuffer[sh] = r.open;

  }



//+------------------------------------------------------------------+

//| Custom indicator iteration function                              |

//+------------------------------------------------------------------+

int OnCalculate(const int rates_total,

                const int prev_calculated,

                const datetime &time[],

                const double &open[],

                const double &high[],

                const double &low[],

                const double &close[],

                const long &tick_volume[],

                const long &volume[],

                const int &spread[])

  {

//Print(__FUNCTION__);

   Recalc();

//--- return value of prev_calculated for next call

   return(rates_total);

  }



//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void SetScale()

  {



   if(!bShowBalance && !bShowEquity)

      return;



   int brsw = WindowBarsPerChart(),

       bar = WindowFirstVisibleBar(),

       sz = ArraySize(ExtOpenBuffer);



   if(sz < (bar - brsw))

      ChartSetInteger(0, CHART_SCALEFIX, 0, false);

   else

     {

      ChartSetInteger(0, CHART_SCALEFIX, 0, true);

      int st = 0, cnt = 0;

      st = fmax(0, bar - brsw);

      cnt = fmin(sz - st, fmin(brsw, bar));

      double hm = MIN_VAL, lm = MAX_VAL, hb = MIN_VAL, lb = MAX_VAL;

      if(bShowEquity)

        {

         hm = ExtHighLowBuffer[ArrayMaximum(ExtHighLowBuffer, cnt, st)];

         lm = ExtLowHighBuffer[ArrayMinimum(ExtLowHighBuffer, cnt, st)];

        }



      if(bShowBalance)

        {

         hb = ExtBalance[ArrayMaximum(ExtBalance, cnt, st)];

         hm = fmax(hm, hb);



         for(int i = st; i < (cnt + st); i++)

            if(ExtBalance[i] > 0 && lm > ExtBalance[i])

               lm = ExtBalance[i];

        }



      ////Printf("%d %d %d %d %d %f %f",bar,brsw,sz,st,cnt, lm,hm);

      double h = hm - lm + 1;

      ChartSetDouble(0, CHART_FIXED_MAX, hm + h * .05);

      ChartSetDouble(0, CHART_FIXED_MIN, lm - h * .05);



     }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void OnChartEvent(const int id,

                  const long &lparam,

                  const double &dparam,

                  const string &sparam)

  {



   if(id == CHARTEVENT_CHART_CHANGE && ArraySize(ExtOpenBuffer) > 0)

     {

      SetScale();

     }

  }

//+------------------------------------------------------------------+





//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void Recalc()

  {

//Print(__FUNCTION__);

   int accno = AccountInfoInteger(ACCOUNT_LOGIN);

   if(accno > 0)

     {

      if(_an == accno)

        {

         WriteEq();

        }

      else

        {

         if(_ab != AccountBalance())

           {

           //Print(_ab,"!=", AccountBalance());

            _an = accno;

            _ab = AccountBalance();

            RunInit();

           }

        }

     }

  }

//+------------------------------------------------------------------+

void WriteEq()

  {

//Print(__FUNCTION__);

   double AE = AccountEquity();



   if(bShowEquity)

     {



      ObjectSetDouble(0, pref + "HL", OBJPROP_PRICE, AE);



      if(ExtOpenBuffer[0] == 0)

         ExtOpenBuffer[0] = AE;



      if(ExtLowHighBuffer[0] == EMPTY_VALUE)

         ExtLowHighBuffer[0] = AE;

      else

         ExtLowHighBuffer[0] = fmin(ExtLowHighBuffer[0], AE);



      if(ExtHighLowBuffer[0] == 0)

         ExtHighLowBuffer[0] = AE;

      else

         ExtHighLowBuffer[0] = fmax(ExtHighLowBuffer[0], AE);



      ExtCloseBuffer[0] = AE;

     }

//return;



   int i = 1;

     {

      datetime dt = TimeStartOfTF(TimeCurrent(), 1);

      if(rt.time != dt) //if(cnc.NW(per[i])||)

        {

         FileFlush(HstHandle);

         HstPos = FileSize(HstHandle);

         rt.open = AE;

         rt.low = AE;

         rt.high = AE;

         rt.close = AE;

         rt.time = dt;

        }

      else

        {

         if(rt.low == 0)

            rt.low = AE;

         rt.low = fmin(rt.low, AE);

         rt.high = fmax(rt.high, AE);

         rt.close = AE;

        }



      FileSeek(HstHandle, HstPos, SEEK_SET);

      if((rt.open > 0 && rt.close > 0 && rt.high > 0 && rt.low > 0))

         FileWriteStruct(HstHandle, rt, sizeof(rt));

      //FileFlush(HstHandle[i]);

     }



   _ab = AccountBalance();

   if(bShowBalance)

      ExtBalance[0] = _ab;

  }

//+------------------------------------------------------------------+

void OnTimer()

  {

//Print(__FUNCTION__);

   Recalc();

   if(TimeCurrent() % 10 == 0)

     {

      SetScale();

      if(HstHandle > -1)

         FileFlush(HstHandle);

     }

  }

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

   DeleteObjects(pref, true);

   ChartSetInteger(0, CHART_SCALEFIX, 0, false);

   EventKillTimer();

   Sleep(2000);

   if(HstHandle > -1)

     {

      FileFlush(HstHandle);

      FileClose(HstHandle);

     }

  }

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

datetime TimeStartOfTF(datetime dt, ENUM_TIMEFRAMES per)

  {

////Print(dt, " ", per);

   if(per < PERIOD_W1)

      return((datetime)floor(dt / per / 60) * per * 60);

   else

      if(per == PERIOD_MN1)

         dt = dt - (TimeDay(dt) - 1) * 86400;

      else

         if(per == PERIOD_W1)

            dt = dt - TimeDayOfWeek(dt) * 86400;



   dt = TimeStartOfTF(dt, PERIOD_D1);

   return(dt);

  }





/*************************

** debug()

** //Print data to the console

*************************/

void debug(string a, string b)

  {

   //Print(a + " ==> " + b);

  }



//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void DeleteObjects(string pr, bool start_with = false)

  {

   int obj_total = ObjectsTotal();

   for(int i = obj_total - 1; i >= 0; i--)

     {

      string name = ObjectName(i);

      if(start_with)

        {

         if(StringFind(name, pr) == 0)

            ObjectDelete(name);

        }

      else

        {

         if(StringFind(name, pr) >= 0)

            ObjectDelete(name);

        }

     }

  }



//+------------------------------------------------------------------+

//+------------------------------------------------------------------+

void Array_Sort_Quick3(MqlRates  &a[], int s, int n)

  {

   if(n <= s)

      return;



// choose pivot

   Array_Swap(a, n, (s + n + 1) / 2);



// 3-way partition

   int i = s, k = s, p = n;

   while(i < p)

     {

      int cmpr = Array_Compare(a, i, n);

      if(cmpr < 0)

        {

         Array_Swap(a, i, k);

         i++;

         k++;

        }

      else

         if(cmpr == 0)

           {

            p--;

            Array_Swap(a, i, p);

           }

         else

            i++;

     }



// move pivots to center

   int m = MathMin(p - k, n - p + 1);



   int j1 = k, j2 = n - m + 1;

   while(j1 < k + m && j2 < n + 1)

     {

      Array_Swap(a, j1, j2);

      j1++;

      j2++;

     }



// recursive sorts

   Array_Sort_Quick3(a, s, k - 1);

   Array_Sort_Quick3(a, n - p + k + 1, n);

  }



//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int Array_Compare(MqlRates  &a[], int i1, int i2)

  {

// //Print(__FUNCTION__,a[i1].time,a[i2].time);

   if(a[i1].time > a[i2].time)

      return(1);

   else

      if(a[i1].time < a[i2].time)

         return(-1);

   return(0);

  }





//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void Array_Swap(MqlRates  &a[], int i1, int i2)

  {

   if(i1 == i2)

      return; //||MathMin(i1,i2)<0||MathMax(i1,i2)>ArrayRange(a,0)) return(0);

   MqlRates prom;

// //Print(__FUNCTION__,a[i1].time,a[i2].time);

   prom = (a[i1]);

   a[i1] = (a[i2]);

   a[i2] = (prom);

// //Print(__FUNCTION__,a[i1].time,a[i2].time);

  }



//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

bool HLineCreate(const long            chart_ID = 0,      // ID 3@0D8:0

                 const string          name = "HLine",    // 8<O ;8=88

                 const int             sub_window = 0,    // =><5@ ?>4>:=0

                 double                price = 0,         // F5=0 ;8=88

                 const color           clr = clrRed,      // F25B ;8=88

                 const ENUM_LINE_STYLE style = STYLE_SOLID, // AB8;L ;8=88

                 const int             width = 1,         // B>;I8=0 ;8=88

                 const bool            back = false,      // =0 704=5< ?;0=5

                 const bool            selection = true,  // 2K45;8BL 4;O ?5@5<5I5=89

                 const bool            hidden = true,     // A:@KB 2 A?8A:5 >1J5:B>2

                 const long            z_order = 0)       // ?@8>@8B5B =0 =060B85 <KHLN

  {

//--- 5A;8 F5=0 =5 7040=0, B> CAB0=>28< 55 =0 C@>2=5 B5:CI59 F5=K Bid

   if(!price)

      price = SymbolInfoDouble(Symbol(), SYMBOL_BID);

//--- A1@>A8< 7=0G5=85 >H81:8

   ResetLastError();

//--- A>74048< 3>@87>=B0;L=CN ;8=8N

   if(!ObjectCreate(chart_ID, name, OBJ_HLINE, sub_window, 0, price))

     {

      ////Print(__FUNCTION__,

      //      ": =5 C40;>AL A>740BL 3>@87>=B0;L=CN ;8=8N! >4 >H81:8 = ",GetLastError());

      //return(false);

     }

//--- CAB0=>28< F25B ;8=88

   ObjectSetInteger(chart_ID, name, OBJPROP_COLOR, clr);

//--- CAB0=>28< AB8;L >B>1@065=8O ;8=88

   ObjectSetInteger(chart_ID, name, OBJPROP_STYLE, style);

//--- CAB0=>28< B>;I8=C ;8=88

   ObjectSetInteger(chart_ID, name, OBJPROP_WIDTH, width);

//--- >B>1@078< =0 ?5@54=5< (false) 8;8 704=5< (true) ?;0=5

   ObjectSetInteger(chart_ID, name, OBJPROP_BACK, back);

//--- 2:;NG8< (true) 8;8 >B:;NG8< (false) @568< ?5@5<5I5=8O ;8=88 <KHLN

//--- ?@8 A>740=88 3@0D8G5A:>3> >1J5:B0 DC=:F859 ObjectCreate, ?> C<>;G0=8N >1J5:B

//--- =5;L7O 2K45;8BL 8 ?5@5<5I0BL. =CB@8 65 MB>3> <5B>40 ?0@0<5B@ selection

//--- ?> C<>;G0=8N @025= true, GB> ?>72>;O5B 2K45;OBL 8 ?5@5<5I0BL MB>B >1J5:B

   ObjectSetInteger(chart_ID, name, OBJPROP_SELECTABLE, selection);

   ObjectSetInteger(chart_ID, name, OBJPROP_SELECTED, selection);

//--- A:@>5< (true) 8;8 >B>1@078< (false) 8<O 3@0D8G5A:>3> >1J5:B0 2 A?8A:5 >1J5:B>2

   ObjectSetInteger(chart_ID, name, OBJPROP_HIDDEN, hidden);

//--- CAB0=>28< ?@8>@8B5B =0 ?>;CG5=85 A>1KB8O =060B8O <KH8 =0 3@0D8:5

   ObjectSetInteger(chart_ID, name, OBJPROP_ZORDER, z_order);

//--- CA?5H=>5 2K?>;=5=85

   return(true);

  }

//+------------------------------------------------------------------+

Comments