Смотри, как бесплатно скачать роботов
Ищи нас в Facebook!
Ставь лайки и следи за новостями
Интересный скрипт?
Поставь на него ссылку - пусть другие тоже оценят
Понравился скрипт?
Оцени его работу в терминале MetaTrader 5
Библиотеки

Easy Canvas - библиотека для MetaTrader 5

Просмотров:
6776
Рейтинг:
(61)
Опубликован:
2018.09.06 10:48
Обновлен:
2024.03.10 04:43
Нужен робот или индикатор на основе этого кода? Закажите его на бирже фрилансеров Перейти на биржу
Данная библиотека и класс iCanvas упростит написание программ с применением Canvas и увеличит скорость работы с графикой благодаря минимизации работы с долгими асинхронными функциями.

Примера простого индикатора для рисования синусов с применением данной библиотеки: (см. файл sine.mq5)


а так же пример пустого советника с визуализацией:

 

Код этого советника:

#include <Canvas\iCanvas_CB.mqh> //https://www.mql5.com/ru/code/22164

//+------------------------------------------------------------------+
int OnInit() {
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {}
//+------------------------------------------------------------------+
void OnTick() {
   Draw();
}
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam) {
   if (id == CHARTEVENT_CHART_CHANGE || id == CHARTEVENT_MOUSE_MOVE) Draw();
}
//+------------------------------------------------------------------+
void Draw() {
   static uint last = 0;         //
   uint cur = GetTickCount();    //  Needed to optimize performance
   if (cur-last<25) return;      //  Especially important for the tester
   last = cur;                   //
   if (Canvas.tester) ChartChanged();   // for correct work in the tester.
   Canvas.Erase(0x00FFFFFF);   // this mask is needed for correct font output
   Canvas.CurentFont("Calibri Light", 16,16,0xFF000000);
   for (int shift = -1000; shift<=1000; shift+=50 ) {
      uint clr = (Canvas.Grad((shift+1000.0)/2000.0) & 0x00FFFFFF)|0x40000000;
      int bar = Round(Canvas.Bar(double(_MouseX+shift)));
      double price  = iHigh(_Symbol,PERIOD_CURRENT,bar);
      int x = int(Canvas.X(double(bar)));
      int y = (int)_Y(price);
      Canvas.FillRectangleA(x,y,x+150,y-60,clr);

      _CommXY(x+5,y-55,"high = "+DoubleToString(price,_Digits));
      _Comment("bar = "+(string)bar);
      _Comment("time = " + TimeToString(iTime(_Symbol,PERIOD_CURRENT,bar)));
   }
   Canvas.Update();
}

Особенности данной библиотеки:

  • при подключении библиотеки сразу создается один экземпляр  с именем Canvas класса iCanvas, который является потомком класса CCanvas.
  • размер данного экземпляра составляет все окно. Далее при изменении размеров окна происходит автоматическое изменение размеров данного холста (кроме скриптов).
  • использование функции обработчика событий OnChartEvent является не обязательным.
  • внутри библиотеки также находится экземпляр структуры Window с именем W. Внутри этой структуры находятся и автоматически обновляются главные характеристики окна (кроме скриптов).

Структура Window:

struct Window
  {
   long              ChartId;     // current window identifier
   uint              Color;       // window background color
   int               Width;       // window width
   int               Height;      // window height
   int               height[];    // sub_windows 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
   mouse_status      MouseStatus; // 5 values: NO_PRESSED, LEFT_BUTTON_PRESSED,RIGHT_BUTTON_PRESSED, LEFT_AND_RIGHT_BUTTONS_PRESSED, KEY_PRESSED
   int               IdEvent;     // id value of the last event
   long              lparam;      // last lparam
   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
  };

Класс 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(long chart_id=0,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(); ChartRedraw();};
   double            X(double bar){return((double)W.Left_bar-bar)*W.dx_pix;}; //The X coordinate by the bar number. The bar number must be of type double, otherwise, the bar will be interpreted as time.
   double            X(datetime Time);                                        //The X coordinate by the time.
   double            Y(double Price) {if(W.dy_pix==0) W.dy_pix=1; return((W.Y_max-Price)/W.dy_pix); }; //The Y coordinate by the price.
   double            Price(int y)     {return (W.Y_max-y*(W.Y_max-W.Y_min)/W.Height);};       // Price by the Y coordinate
   double            Bar(int x) {return((double)W.Left_bar+1-(double)x/(double)W.dx_pix);};   // bar number by coordinate X                                                                      
   datetime          TimePos(int x);                                                          // time by coordinate 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;}; // Print comment
   void              TextPosition(int x,int y) {TextPosX=x; TextPosY=y;};                                    // Setting the XY position for comment output in pixels
   void              CurentFont(string FontName="Courier New",int size=18,int LineStep=20,color clr=clrDarkOrchid,double transp=1.0);  // Set font options for comment. LineStep - step between lines. transp - transparency from 0 to 1                                                                                                                                        
   void              TextPosition(double x,double y); // Setting the XY position for outputting comments as a percentage of the width and height of the window
   void              LineD(double x1,double y1,double x2,double y2,const uint clr);    // Draw line with double coordinates (more accurate positioning)
   void              LineDA(double x1,double y1,double x2,double y2,const uint clr);   // Draw line with double coordinates with support for alpha channel (transparency)
   void              LineVerticalA(int x,int y1,int y2,const uint clr);                // Draw vertical line this alfa  channel 
   void              LineHorizontalA(int x1,int x2,int y,const uint clr);              // Draw horizontal line this alfa  channel 
   void              FillRectangleA(int x1,int y1,int x2,int y2,const uint clr);       // Draws a rectangle with transparency and confusion with background color
   void              MixColor(uint clr, uint &addr);                                   // mix the color in the cell at addr with the color clr and enter the new value in the same cell

   void              SetBack(const bool bck) {ObjectSetInteger(m_chart_id,m_objname,OBJPROP_BACK,bck);} // Set canvas behind the chart or in front of the chart
   int               TextPosX;      // Position X for comment text
   int               TextPosY;      // Position Y for comment text
   int               StepTextLine;  // line spacing for comment
   uint              TextColor;     // Font color for comment
   ENUM_PROGRAM_TYPE ProgType;
   int               SubWin;
   long              Handle;
  };

если не нужен экземпляр класса Canvas на полное окно, то его можно удалить и (или) изменить на частичное окно

Например:

delete Canvas;
Canvas= new iCanvas(0,0,0,"iCanvas",300,0);          // только левая полоса окна шириной 300 пикселей. Изменение размеров окна контролируется 
// Canvas= new iCanvas(0,0,0,"iCanvas",0,300);       // только верхняя полоса окна высотой 300 пикселей. Изменение размеров окна контролируется 
// Canvas= new iCanvas(0,200,100,"iCanvas",300,300); // квадрат 300x300 пикселей со стартовой позицей в точке (200,100). Изменение размеров окна не контролируется 

так же можно создавать новые экземпляры класса и инициализировать их в момент создания 

например:

iCanvas C2(0,300,200,"Canvas2",200,150,COLOR_FORMAT_XRGB_NOALPHA,1);

Внимание: Т.к. по умолчанию используется формат цвета с поддержкой прозрачности COLOR_FORMAT_ARGB_NORMALIZE , то при указании цвета необходимо учитывать старший байт прозрачности. 

Если использовать имена цветов, например clrRed, то в таком случае цвет будет абсолютно прозрачным ввиду того, что байт прозрачности будет равным 0. Поэтому необходимо использовать функцию ColorToARGB (например ColorToARGB (clrRed)) или указывать цвет явно с указанием ненулевой прозрачности. Например, удобным является 16-ричное представление цвета 0xFFAABBCC, где FF-байт прозрачности, AA - байт красного цвета, BB - байт зеленого цвета, CC - байт синего цвета.


    TradeTransactions TradeTransactions

    Доступ к данным OnTradeTransaction в любом месте программы

    XHullTrend_Digit_System XHullTrend_Digit_System

    Индикатор, реализующий пробойную систему с использованием облака индикатора XHullTrend_Digit

    Aroon_Horn Aroon_Horn

    Индикатор Aroon Horn

    Aroon_Filter Aroon_Filter

    Индикатор Aroon Filter