//+------------------------------------------------------------------+
//|                                                  WeeklyRange.mq4 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property show_inputs

#include <Files\FileTxt.mqh>
CFileTxt nFile;
string filename;

input int Lookback=261;  //How far we should look back

string Pairs[28]=
  {
   "EURUSD","GBPUSD","USDJPY","USDCAD","AUDUSD","NZDUSD",
   "EURAUD","EURCAD","EURJPY","EURNZD","EURGBP",
   "AUDCAD","AUDJPY","AUDNZD","GBPAUD",
   "CADJPY","GBPCAD","NZDCAD",
   "GBPJPY","NZDJPY",
   "GBPNZD",
   "USDCHF","GBPCHF","NZDCHF","CADCHF","AUDCHF","CHFJPY","EURCHF"
  };
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   filename="WeeklyRanges.csv";
   nFile.Open(filename,FILE_CSV|FILE_READ|FILE_WRITE,';');
   string header=StringConcatenate("Symbol",";","Average",";","Middle","\r\n");
   nFile.WriteString(header);
   nFile.Close();
   for(int i=0;i<ArraySize(Pairs);i++)
     {
      DoWeekly(Pairs[i]);
     }
  }
//+------------------------------------------------------------------+

void DoWeekly(string Sym)
{
   double wOpen=0.0, wClose=0.0, wDiff=0.0, wAverage=0.0, wMedian=0.0, wPoint=MarketInfo(Sym,MODE_POINT);
   double calcArray[];
   ArrayResize(calcArray,Lookback);
   ArrayInitialize(calcArray,0.0);
   for(int i=1;i<Lookback+1;i++)
     {
      calcArray[i-1]=MathAbs(iClose(Sym,0,i)-iOpen(Sym,0,i));
     }
   nFile.Close();
   ArraySort(calcArray,WHOLE_ARRAY,0,MODE_ASCEND);
   int iMedian=ArraySize(calcArray)/2;
   wMedian=(calcArray[iMedian])/wPoint;
   wAverage=(AverageFromArray(calcArray,Lookback))/wPoint;
   nFile.Open(filename,FILE_CSV|FILE_READ|FILE_WRITE,';');   
   string WriteMe=StringConcatenate(Sym,";",DoubleToString(wAverage,0),";",DoubleToString(wMedian,0),"\r\n");
   nFile.Seek(0,SEEK_END);
   nFile.WriteString(WriteMe);
   nFile.Close();   
}

double AverageFromArray(const double & array[],int size) 
  {//"Borrowed" from the help file.  I got lazy, give me a break!
   if(size<=0) return 0.0; 
   double sum=0.0; 
   double aver; 
//--- 
   for(int i=0;i<size;i++) 
     { 
      sum+=array[i];    // Summation for the double 
     } 
   aver=sum/size;       // Just divide the sum by the number 
//--- 
   //Print("Calculation of the average for an array of double type"); 
   return aver; 
  } 
