MLSOnGraphics

Download script
Author: Copyright � Trofimov Evgeniy Vitalyevich, 2008
MLSOnGraphics

This script implements a sophisticated mathematical model known as the Method of Least Squares to analyze price trends on a trading chart. Unlike standard moving averages that simply follow the price, this tool attempts to find the "line of best fit" by calculating the most mathematically accurate trend path based on historical data.

Core Logic and Functionality

1. Trend Line Construction (Linear Regression) The primary goal of the script is to identify the underlying direction of the market. It looks at a specific number of previous price bars (determined by the user) and calculates two distinct linear equations: one for the highest prices (Highs) and one for the lowest prices (Lows).

By using the Method of Least Squares, the script minimizes the distance between these calculated lines and the actual data points. This results in a trend line that represents the "average" path of the market's movement rather than just reacting to every small fluctuation.

2. High and Low Bounds The indicator produces several distinct visual components:

  • Trend Lines: It creates an upper boundary based on the high prices and a lower boundary based on the low prices.
  • Midpoint Baseline: It calculates a central value by averaging the high and low trend lines, providing a balanced "spine" for the current price action.

3. Deflection and Deviation Analysis One of the more advanced features of this script is its ability to calculate "deflection." Instead of just showing where the price should be according to the trend, the script measures how much the actual price is currently "deviating" from that perfect line.

  • It calculates the sum of the squares of the differences between the actual prices and the calculated trend lines.
  • This allows the indicator to provide a visual representation of volatility or "stretch"—showing whether the market is overextending itself away from its established trend.

4. Real-Time Behavior Options The logic includes a specific toggle for how it handles the most recent, unfinished candle (the "live" bar):

  • It can be set to update instantly with every tick of price movement.
  • Alternatively, it can be set to "lock" the current bar’s value based on completed historical data, providing a more stable visual for users who prefer to avoid "repainting" or fluctuating lines during active trading.

Summary for the User

In plain terms, this script acts as a trend stabilizer. It filters out market noise by calculating the most mathematically logical path for price to follow. By identifying where the price ought to be versus where it actually is, it helps traders visualize the strength of a trend and identify when the market is moving significantly far away from its "normal" path.

Miscellaneous
Implements a curve of type %1
9 Views
0 Downloads
0 Favorites
MLSOnGraphics
//+---------------------------------------------------------------------+
//|                                        MLSOnGraphics.mq4            |
//| The Method of Least Squares                                         |
//|      High and Low ver. 7                                            |
//|             Copyright © Trofimov 2008                               |
//+---------------------------------------------------------------------+
//| Ìåòîä íàèìåíüøèõ êâàäðàòîâ                                          |
//|   ïî âåðõíåé è íèæíåé îòìåòêå ñâå÷è                                 |
//| Îïèñàíèå: Ðàñ÷¸ò ìèíèìàëüíîãî êâàäðàòè÷íîãî îòëîíåíèÿ îò ïðÿìîé     |
//|           â ïóíêòàõ. Åñëè ðûíîê êîëåáëåòñÿ â ïðåäåëàõ òàíãåíñà      |
//|           óãëà íàêëîíà ëèíèè òðåíäà ê ãîðèçîíòàëüíîé ïðÿìîé         |
//|           òî òðåíä ðàçâèâàåòñÿ óâåðåííî è ðàâíîìåðíî.               |
//| Àâòîðñêîå ïðàâî ïðèíàäëåæèò Òðîôèìîâó Åâãåíèþ Âèòàëüåâè÷ó, 2008     |
//+---------------------------------------------------------------------+


#property copyright "Copyright © Trofimov Evgeniy Vitalyevich, 2008"
#property link      "http://multitest.semico.ru/mnk.htm"

//---- Ñâîéñòâà èíäèêàòîðà
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_color1 DarkBlue
#property indicator_width1 2
#property indicator_color2 FireBrick
#property indicator_width2 2
#property indicator_color3 Blue
#property indicator_width3 1
#property indicator_color4 Red
#property indicator_width4 1
#property indicator_color5 Silver
#property indicator_width5 1


//---- Âõîäÿùèå ïàðàìåòðû
extern int MyPeriod=12;
extern int Shift=0;
extern int Future=0;
extern bool CalculateDeflection=true;
extern bool ReDraw=true; //-åñëè âêëþ÷åí, òî ïåðåðèñîâûâàåò íóëåâîé áàð ïðè êàæäîì íîâîì òèêå
                          // åñëè âûêëþ÷åí, òî íóëåâîé áàð ñîäåðæèò ôèêñèðîâàííîå çíà÷åíèå, âû÷èñëåííîå ïî ïðåäûäóùèì (ãîòîâûì) áàðàì

//---- Ìàññèâ äàííûõ èíäèêàòîðà
double MLS_H[];
double MLS_L[];
double MLS_HD[];
double MLS_LD[];
double MLS_b[];
//+------------------------------------------------------------------+
//|                Ôóíêöèÿ èíèöèàëèçàöèè èíäèêàòîðà                  |
//+------------------------------------------------------------------+
int init()
  {
//---- x äîïîëíèòåëüíûõ áóôåðà, èñïîëüçóåìûõ äëÿ ðàñ÷åòà
   IndicatorBuffers(5);
//---- ïàðàìåòðû ðèñîâàíèÿ (óñòàíîâêà íà÷àëüíîãî áàðà)
   SetIndexDrawBegin(0,MyPeriod);
   SetIndexDrawBegin(1,MyPeriod);
   SetIndexDrawBegin(2,MyPeriod);
   SetIndexDrawBegin(3,MyPeriod);
   SetIndexDrawBegin(4,MyPeriod);
   SetIndexShift(0,Shift);
   SetIndexShift(1,Shift);
   SetIndexShift(2,Shift);
   SetIndexShift(3,Shift);
   SetIndexShift(4,Shift);
//---- x ðàñïðåäåëåííûõ áóôåðà èíäèêàòîðà
   SetIndexBuffer(0,MLS_H);
   SetIndexBuffer(1,MLS_L);
   SetIndexBuffer(2,MLS_HD);
   SetIndexBuffer(3,MLS_LD);
   SetIndexBuffer(4,MLS_b);
//---- èìÿ èíäèêàòîðà è ïîäñêàçêè äëÿ ëèíèé
   IndicatorShortName("MLSOnGraphics("+MyPeriod+") = ");
   SetIndexLabel(0,"HighLine("+MyPeriod+")");
   SetIndexLabel(1,"LowLine("+MyPeriod+")");
   SetIndexLabel(2,"HighDeflection("+MyPeriod+")");
   SetIndexLabel(3,"LowDeflection("+MyPeriod+")");
   SetIndexLabel(4,"b("+MyPeriod+")");
   SetIndexStyle(4,DRAW_NONE);
   return(0);
  }
//+------------------------------------------------------------------+
//|                Ôóíêöèÿ èíäèêàòîðà                                |
//+------------------------------------------------------------------+
int start() {
   //static datetime LastTime;
   int limit, RD;
   if(ReDraw) RD=1;
   
   // Ïðîïóùåííûå áàðû
   int counted_bars=IndicatorCounted();
//---- îáõîäèì âîçìîæíûå îøèáêè
   if(counted_bars<0) return(-1);
//---- íîâûå áàðû íå ïîÿâèëèñü è ïîýòîìó íè÷åãî ðèñîâàòü íå íóæíî
   limit=Bars-counted_bars-1+RD;
//---- îñíîâíûå ïåðåìåííûå
   double ha, hb, hk1, hi1, hj1, hk2, hi2, j2;
   double la, lb, lk1, li1, lj1, lk2, li2;
   double H, L;
   
   int x;
//---- îñíîâíîé öèêë
   for(int t=limit-RD; t>-RD; t--) {
      //if(LastTime==iTime(NULL,0,t)) return(0);
      //LastTime=iTime(NULL,0,t);
      //if(t<5) Print(t,"===== ",TimeToStr(LastTime)," =====");
   
      hk1=0; hi1=0; hj1=0; hk2=0; hi2=0;
      lk1=0; li1=0; lj1=0; lk2=0; li2=0;
      for(x=t+MyPeriod-1; x>=t; x--)
        { // ñîñòàâëÿåì íîðìàëüíûå óðàâíåíèÿ k1=a*i1+b*j1 è k2=a*i2+b*j2
         H=High[x];
         hk1=hk1+H*x;    hk2=hk2+H;
         hi1=hi1+x*x;    hi2=hi2+x;
         hj1=hj1+x;
         
         L=Low[x];
         lk1=lk1+L*x;    lk2=lk2+L;
         li1=li1+x*x;    li2=li2+x;
         lj1=lj1+x;
        } //Next x
      j2=MyPeriod;
      //Ðåøàåì ñèñòåìó óðàâíåíèé
      ha=(hk1*j2-hj1*hk2)/(hi1*j2-hj1*hi2);
      hb=(hk2-hi2*ha)/j2;
      la=(lk1*j2-lj1*lk2)/(li1*j2-lj1*li2);
      lb=(lk2-li2*la)/j2;
      //Òåïåðü âñå òî÷êè High è Low, íà äàííûé ìîìåíò âðåìåíè,
      //ïðèáëèçèòåëüíî ðàñïîëîæåíû âäîëü ïðÿìîé, îïèñàíîé óðàâíåíèåì y=ax+b,
      //ãäå x - ýòî íîìåð ñâå÷è, à y - çíà÷åíèå öåíû.
      MLS_b[t]=(hb+lb)/2;
      if(!ReDraw && t==1) MLS_b[0]=(hb+lb)/2; 
      //Ïðåäïîëîæèì, ÷òî öåíà ïîéä¸ò äàëüøå âäîëü òîé æå ïðÿìîé
      MLS_H[t]=ha*(t-Future)+hb+Point;
      if(!ReDraw && t==1) MLS_H[0]=ha*(t-Future+1)+hb+Point;
      MLS_L[t]=la*(t-Future)+lb-Point;
      if(!ReDraw && t==1) MLS_L[0]=la*(t-Future+1)+lb-Point;
      if(CalculateDeflection) { //ðàñ÷¸ò îòêëîíåíèÿ
         double hS, lS;
         hS=0;lS=0;
         for(x=t+MyPeriod-1; x>=t; x--) {
            hS=hS+MathPow(High[x]-MLS_H[x],2);
            lS=lS+MathPow(Low[x] -MLS_L[x],2);
         } //Next x
         MLS_HD[t]=MLS_H[t]+MathSqrt(hS)/2;
         if(!ReDraw && t==1) MLS_HD[0]=MLS_H[0]+MathSqrt(hS)/2;
         MLS_LD[t]=MLS_L[t]-MathSqrt(lS)/2;
         if(!ReDraw && t==1) MLS_LD[0]=MLS_L[0]-MathSqrt(lS)/2;
      }
   } //Next t
   return(0);
}
//+------------------------------------------------------------------+

Comments