Mira cómo descargar robots gratis
Find us on Facebook!
Join our fan page
¿Es interesante este script?
Deje un enlace a él, ¡qué los demás también lo valoren!
¿Le ha gustado el script?
Evalúe su trabajo en el terminal MetaTrader 5
Visualizaciones:
1003
Ranking:
(61)
Publicado:
2018.10.26 13:46
\MQL5\Indicators\
Test_iCanvas.mq5 (6.64 KB) ver
\MQL5\Include\Canvas\
iCanvas.mqh (31.88 KB) ver
¿Necesita un robot o indicador basado en este código? Solicítelo en la bolsa freelance Pasar a la bolsa
Esta librería y la clase iCanvas simplificarán el desarrollo de programas a través de Canvas.

Aquí tenemos el ejemplo de un indicador simple con el uso de dicha librería y su demostración.

Por favor, nótese que en este ejemplo no hay función del procesamiento de eventos OnChartEvent en el cuerpo del indicador. Aunque también puede estar presente.

#property indicator_chart_window
#include <Canvas\iCanvas.mqh>
//+------------------------------------------------------------------+
int OnInit()
  {
   EventSetMillisecondTimer(30);
   ChartSetInteger(0,CHART_SHOW,true);
   ChartSetInteger(0,CHART_CROSSHAIR_TOOL,false);  // turn off the crosshair
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason) {if(reason<2) {ChartSetInteger(0,CHART_CROSSHAIR_TOOL,true); ChartRedraw();}}
//+------------------------------------------------------------------+
void  OnTimer()
  {
   static int X=0;
   static int Y=0;
   if(X!=W.MouseX || Y!=W.MouseY)
     {
      Canvas.Erase(0);
      // Dibujamos una mancha desvaída   Draw a blurry spot
      for(int ix=-20;ix<=20;ix++) for(int iy=-20;iy<=20;iy++)
        {
         double p=sqrt(ix*ix+iy*iy)/20.0;
         if(p>1) p=1;
         uchar P=(uchar)Round((1.0-p)*255.0);
         Canvas.PixelSet(W.MouseX+ix,W.MouseY+iy,ARGB(P,100,0,200));
        }
      //  Mostramos el bloque informativo   Display the information block
      int Y1=(int)Canvas.Y(Canvas.Close(W.MouseX));  // coordenada Y es el precio Close en el lugar donde se encuentra el puntero del ratón
      Canvas.FillRectangle(W.MouseX,Y1,W.MouseX+140,Y1+67,0xA0808080);
      Canvas.TextPosition(W.MouseX+5,Y1+2);
      Canvas.CurentFont("Arial",14,16,clrWhite);
      Canvas.Comm("Close = "+DoubleToString(Canvas.Close(W.MouseX),_Digits));
      Canvas.Comm("Bar = "+DoubleToString(W.MouseBar,2));
      Canvas.Comm(TimeToString(W.MouseTime,TIME_DATE|TIME_SECONDS));
      Canvas.Comm("SubWindow = "+string(W.MouseSubWin));
      //  Cursor en cruz  Crosshairs
      Canvas.LineHorizontal(0,W.Width-1,W.MouseY,~W.Color);
      Canvas.LineVertical(W.MouseX,0,W.Height-1,~W.Color);
      int Ym=(W.MouseY>W.Height/2)?(W.MouseY-16):(W.MouseY+2);
      int Xm=(W.MouseX< W.Width/2)?(W.MouseX+4):(W.MouseX-105);
      Canvas.TextOut(W.Width-50,Ym,DoubleToString(W.MousePrice,_Digits),~W.Color);
      Canvas.TextOut(Xm,W.Height-16,TimeToString(W.MouseTime,TIME_DATE|TIME_SECONDS),~W.Color);

      Canvas.Update();
      X=W.MouseX; Y=W.MouseY;
     }
  }
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const int begin,
                const double &price[])
  {
   return(rates_total);
  }

Particularidades de esta librería:

  • cuando se conecta la librería, de inmediato  se crea una instancia con el nombre Canvas de la clase iCanvas, siendo ésa el heredero de la clase CCanvas.
  • el tamaño de esta instancia es de la ventana entera. Luego, cuando se cambian los tamaños de la ventana, se cambian automáticamente los tamaños del lienzo (salvo los sripts).
  • el uso de la función del manejador de eventos OnChartEvent no es obligatorio.
  • además, la instancia de la estructura Window con el nombre W también se encuentra dentro de la librería. Dentro de esta estructura, se encuentran y se actualizan automáticamente las características principales de la ventana (salvo los scripts).

Estructura Window:

struct Window
  {
   long              ChartId;     // current window identifier
   uint              Color;       // window background color
   int               Width;       // window width
   int               Height;      // window height
   int               Left_bar;    // number of the leftmost bar in the window
   double            Right_bar;   // number of the rightmost bar in the window
   double            Total_bars;  // the maximum number of bars in the window
   int               BarsInWind;  // number of visible bars in the window
   double            Y_min;       // The minimum value of the price in the window
   double            Y_max;       // The maximum value of the price in the window
   double            dy_pix;      // price change for one pixel
   int               dx_pix;      // changing the number of bars per pixel
   int               MouseX;      // coordinate X of the current position of the mouse pointer
   int               MouseY;      // coordinate Y of the current position of the mouse pointer
   double            MouseBar;    // the current bar position of the mouse pointer 
   double            MousePrice;  // the current price of the mouse pointer
   datetime          MouseTime;   // the current time of the mouse pointer
   int               MouseSubWin; // number of the subwindow in which the mouse pointer is located
   int               WindowsTotal;// total subwindows, including the main window
   int               SubWin;      // current subwindow
   datetime          time[];      // array of opening time of all visible bars in the window
  };


Clase iCanvas:

class iCanvas : public CCanvas
  {
private:
   datetime          T[1];
   double            Pr[1];
   bool              FullWinCanvW; // using full window canvas by width
   bool              FullWinCanvH; // using full window canvas by height
public:
                     iCanvas(int Xpos=0,int Ypos=0,string Name="iCanvas",int width=0,int height=0,ENUM_COLOR_FORMAT formatCF=COLOR_FORMAT_ARGB_NORMALIZE,int subwin=-1);
                    ~iCanvas() { Destroy();};
   double            X(double bar);
   double            X(datetime Time) {return X((double)Ceil(W.Right_bar)+iBarShift(NULL,0,Time));};
   double            Y(double Price)  {return((W.Y_max-Price)/W.dy_pix); };
   double            Price(int y)     {return (W.Y_max-y*(W.Y_max-W.Y_min)/W.Height);};
   double            Bar(int x) {return((double)W.Left_bar+1-(double)x/(double)W.dx_pix);};   // Número de la barra según la coordenada X
   datetime          TimePos(int x) {double B=Bar(x); CopyTime(_Symbol,_Period,Floor(B),1,T); return T[0]+int((double)PeriodSeconds()*(1-B+(int)B));};  // Hora según la coordenada X
   double            Close(int x)     {CopyClose(_Symbol,_Period,int(Bar(x)),1,Pr); return Pr[0];};
   double            Open(int x)      {CopyOpen(_Symbol,_Period,int(Bar(x)),1,Pr); return Pr[0];};
   double            High(int x)      {CopyHigh(_Symbol,_Period,int(Bar(x)),1,Pr); return Pr[0];};
   double            Low(int x)       {CopyLow(_Symbol,_Period,int(Bar(x)),1,Pr); return Pr[0];};
   bool              FullWinCanvWidth()  {return FullWinCanvW;}; // using full window canvas by width  
   bool              FullWinCanvHeight() {return FullWinCanvH;}; // using full window canvas by height   
   void              Comm(string text) {TextOut(TextPosX,TextPosY,text,TextColor); TextPosY+=StepTextLine;}; // Impresión del comentario
   void              TextPosition(int x,int y) {TextPosX=x; TextPosY=y;};                                    // Establecimiento de la posición XY para mostrar el comentario en píxeles
   void              CurentFont(string FontName="Courier New",int size=18,int LineStep=20,color clr=clrDarkOrchid,double transp=1.0);  // Establecimiento de los parámetros de la fuente para el comentario. LineStep - paso entre 
                                                                                                                                       // las líneas. transp - transparencia de 0 a 1
   void              TextPosition(double x,double y) // Establecimiento de la posición XY para mostrar el comentario en por cientos respecto al ancho y al alto de la ventana
     {
      if(x>100) x=100; else if(x<0) x=0; TextPosX=Round(x*W.Width/100);
      if(y>100) y=100; else if(y<0) y=0; TextPosY=Round(y*W.Height/100);
     };
   int               TextPosX;      // Posición X para el texto del comentario
   int               TextPosY;      // Posición Y para el texto del comentario
   int               StepTextLine;  // paso entre las líneas del comentario
   uint              TextColor;     // Color de la fuente para el comentario
   ENUM_PROGRAM_TYPE ProgType;
  };

Traducción del ruso realizada por MetaQuotes Ltd
Artículo original: https://www.mql5.com/ru/code/22164

TradeTransactions TradeTransactions

Acceso a los datos de OnTradeTransaction en cualquier lugar del programa

Skyscraper Skyscraper

Indicador de tendencia del tipo NRTR con una línea media adicional

Previous Candle Breakdown 3 Previous Candle Breakdown 3

Asesor Experto «ruptura de la vela anterior».

Rollback system Rollback system

Determina la anchura del canal para el día anterior.