Add files via upload

This commit is contained in:
amirghadiri1987
2025-02-07 19:17:11 +03:30
committed by GitHub
parent 781d26ab5c
commit f98c35d65d
48 changed files with 18642 additions and 0 deletions
+77
View File
@@ -0,0 +1,77 @@
//+------------------------------------------------------------------+
//| AutoPtr.mqh |
//| Copyright (c) 2019-2021, Marketeer |
//| https://www.mql5.com/en/users/marketeer |
//+------------------------------------------------------------------+
#define FREE(P) { if(CheckPointer(P) == POINTER_DYNAMIC) delete P; }
//+------------------------------------------------------------------+
//| Safe-pointer templated class |
//+------------------------------------------------------------------+
template<typename T>
class AutoPtr
{
private:
T *ptr;
public:
AutoPtr() : ptr(NULL)
{
#ifdef DEBUG_PRINT
Print(__FUNCSIG__, " ", &this, ": NULL");
#endif
}
AutoPtr(T *p) : ptr(p)
{
#ifdef DEBUG_PRINT
Print(__FUNCSIG__, " ", &this, ": ", ptr);
#endif
}
AutoPtr(AutoPtr &p)
{
#ifdef DEBUG_PRINT
Print(__FUNCSIG__, " ", &this, ": ", ptr, " -> ", p.ptr);
#endif
FREE(ptr);
ptr = p.ptr;
p.ptr = NULL;
}
~AutoPtr()
{
#ifdef DEBUG_PRINT
Print(__FUNCSIG__, " ", &this, ": ", ptr);
#endif
FREE(ptr);
}
AutoPtr *operator=(AutoPtr &ref)
{
#ifdef DEBUG_PRINT
Print(__FUNCSIG__, " ", &this, ": ", ptr, " -> ", ref.ptr);
#endif
FREE(ptr);
ptr = ref.ptr;
ref.ptr = NULL;
return &this;
}
T *operator=(const T *n)
{
#ifdef DEBUG_PRINT
Print(__FUNCSIG__, " ", &this, ": ", ptr, " -> ", n);
#endif
FREE(ptr);
ptr = (T *)n;
return ptr;
}
T *operator[](int x = 0) const
{
return ptr;
}
};
//+------------------------------------------------------------------+
+139
View File
@@ -0,0 +1,139 @@
class ColorThemes
{
public:
color CONTROLS_EDIT_ENABLE_COLOR, CONTROLS_EDIT_DISABLE_COLOR, CONTROLS_EDIT_BORDER_COLOR, CONTROLS_EDIT_BACKGROUND_COLOR, CONTROLS_BUTTON_ENABLE_COLOR,
CONTROLS_BUTTON_DISABLE_COLOR, CONTROLS_BUTTON_TEXT_COLOR, CONTROLS_BUTTON_BORDER_COLOR, CONTROLS_BUTTON_BACKGROUND_COLOR, CONTROLS_BORDER_COLOR,
CONTROLS_BACK_COLOR, CONTROLS_CLIENTBACK_COLOR, CONTROLS_CAPTION_TEXT_COLOR, CONTROLS_CAPTION_MAIN_BACKGROUND_COLOR, CONTROLS_CAPTION_BACK_BACKGROUND_COLOR,
CONTROLS_LABEL_TEXT_COLOR, CONTROLS_LABEL_TEXT_CAPION_COLOR, CONTROLS_LABEL_TEXT_TITLE_COLOR, CONTROLS_LABEL_TEXT_CONFIRMATION_COLOR, CONTROLS_PICTURE_BORDER_COLOR;
// enum SET_COLOR_THEMES
// {
// SET_COLOR_THEMES_ABSENT,
// SET_COLOR_THEMES_BANNER,
// SET_COLOR_THEMES_BRAVE,
// SET_COLOR_THEMES_BLINK,
// SET_COLOR_THEMES_CODECOURSE,
// SET_COLOR_THEMES_DOWNPOUR,
// SET_COLOR_THEMES_FODDER,
// SET_COLOR_THEMES_MUD,
// SET_COLOR_THEMES_VIOLACEOUS,
// SET_COLOR_THEMES_VISION,
// };
// enum TYPE_THEMES
// {
// Dark,
// Light
// };
void ApplyTheme(int theme,int type)
{
switch (theme)
{
default:
case SET_COLOR_THEMES_VISION:
if (type == Light)
{
CONTROLS_EDIT_ENABLE_COLOR = C'255,255,255';
CONTROLS_EDIT_DISABLE_COLOR = C'255,255,255';
CONTROLS_EDIT_BORDER_COLOR = C'255,255,255';
CONTROLS_EDIT_BACKGROUND_COLOR = C'255,255,255';
CONTROLS_BUTTON_ENABLE_COLOR = C'161,212,236'; //.
CONTROLS_BUTTON_DISABLE_COLOR = C'255,255,255';
CONTROLS_BUTTON_TEXT_COLOR = C'53,47,212'; //.
CONTROLS_BUTTON_BORDER_COLOR = C'40,40,41'; //.
CONTROLS_BUTTON_BACKGROUND_COLOR = C'255,255,255'; //.
CONTROLS_BORDER_COLOR = C'174,170,185'; //.
CONTROLS_BACK_COLOR = clrBlue; //.
CONTROLS_CLIENTBACK_COLOR = C'255,255,255'; //.
CONTROLS_CAPTION_TEXT_COLOR = C'12,12,12'; //.
CONTROLS_CAPTION_MAIN_BACKGROUND_COLOR = C'189,172,238'; //.
CONTROLS_CAPTION_BACK_BACKGROUND_COLOR = C'165,243,19'; //.
CONTROLS_LABEL_TEXT_COLOR = C'12,12,12'; //.
CONTROLS_LABEL_TEXT_CAPION_COLOR = C'53,47,212'; //.
CONTROLS_LABEL_TEXT_TITLE_COLOR = C'0,8,210'; //.
CONTROLS_LABEL_TEXT_CONFIRMATION_COLOR = C'25,140,25'; //.
CONTROLS_PICTURE_BORDER_COLOR = C'25,140,25'; //.
}
else
{
CONTROLS_EDIT_ENABLE_COLOR = C'255,255,255';
CONTROLS_EDIT_DISABLE_COLOR = C'255,255,255';
CONTROLS_EDIT_BORDER_COLOR = C'255,255,255';
CONTROLS_EDIT_BACKGROUND_COLOR = C'255,255,255';
CONTROLS_BUTTON_ENABLE_COLOR = C'255,255,255';
CONTROLS_BUTTON_DISABLE_COLOR = C'255,255,255';
CONTROLS_BUTTON_TEXT_COLOR = C'255,255,255';
CONTROLS_BUTTON_BORDER_COLOR = C'255,255,255';
CONTROLS_BUTTON_BACKGROUND_COLOR = C'255,255,255';
CONTROLS_BORDER_COLOR = C'255,255,255';
CONTROLS_BACK_COLOR = C'255,255,255';
CONTROLS_CLIENTBACK_COLOR = C'85,111,228';
CONTROLS_CAPTION_TEXT_COLOR = C'255,255,255';
CONTROLS_CAPTION_MAIN_BACKGROUND_COLOR = C'255,255,255';
CONTROLS_CAPTION_BACK_BACKGROUND_COLOR = C'255,255,255';
CONTROLS_LABEL_TEXT_TITLE_COLOR = C'255,255,255';
CONTROLS_LABEL_TEXT_COLOR = C'255,255,255';
CONTROLS_LABEL_TEXT_CAPION_COLOR = C'255,255,255';
CONTROLS_LABEL_TEXT_CONFIRMATION_COLOR = C'255,255,255';
CONTROLS_PICTURE_BORDER_COLOR = C'255,255,255';
}
break;
}
}
};
/*
CCTR_EDIT_EN_COL = C'64,240,102';
CCTR_EDIT_DIS_COL = C'238,182,182';
CCTR_EDIT_BOR_COL = C'248,5,5';
CCTR_EDIT_BG_COL = C'39,51,231';
CCTR_BUTTON_EN_COL = C'161,212,236'; //.
CCTR_BUTTON_DIS_COL = C'255,255,255';
CCTR_BUTTON_TXT_COL = C'0,165,243'; //
CCTR_BUTTON_BOR_COL = C'40,40,41'; //
CCTR_BUTTON_BG_COL = C'255,255,255'; //
CCTR_BOR_COL = C'174,170,185';
CCTR_BACK_COL = C'65,64,64';
CCTR_CLIENTBACK_COL = C'255,255,255';
CCTR_CAP_TXT_COL = C'12,12,12'; //
CCTR_CAP_MAIN_BG_COL = C'189,172,238'; //
CCTR_CAP_BACK_BG_COL = C'165,243,19'; //
CCTR_LBL_TXT_COL = C'12,12,12'; //
CCTR_LBL_TXT_CAP_COL = C'0,165,243';
ColorThemes myThemes;
// Apply the SET_COLOR_THEMES_VISION theme
myThemes.ApplyTheme(SET_COLOR_THEMES_VISION);
// Access individual color properties if needed
color editEnCol = myThemes.CCTR_EDIT_EN_COL;
color buttonTxtCol = myThemes.CCTR_BUTTON_TXT_COL;
// Apply the SET_COLOR_THEMES_BANNER theme
myThemes.ApplyTheme(SET_COLOR_THEMES_BANNER);
+27
View File
@@ -0,0 +1,27 @@
//+------------------------------------------------------------------+
//| Colors.mqh |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link "https://www.mql5.com"
//+------------------------------------------------------------------+
//| defines |
//+------------------------------------------------------------------+
// #define MacrosHello "Hello, world!"
// #define MacrosYear 2010
//+------------------------------------------------------------------+
//| DLL imports |
//+------------------------------------------------------------------+
// #import "user32.dll"
// int SendMessageA(int hWnd,int Msg,int wParam,int lParam);
// #import "my_expert.dll"
// int ExpertRecalculate(int wParam,int lParam);
// #import
//+------------------------------------------------------------------+
//| EX5 imports |
//+------------------------------------------------------------------+
// #import "stdlib.ex5"
// string ErrorDescription(int error_code);
// #import
//+------------------------------------------------------------------+
+7
View File
@@ -0,0 +1,7 @@
//+------------------------------------------------------------------+
//| ComboBoxNew.mqh |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <Controls/Element.mqh>
#include <Controls/ListView.mqh>
+410
View File
@@ -0,0 +1,410 @@
//+------------------------------------------------------------------+
//| Comment.mqh |
//| avoitenko |
//| https://login.mql5.com/en/users/avoitenko |
//+------------------------------------------------------------------+
#property copyright "avoitenko"
#property link "https://login.mql5.com/en/users/avoitenko"
#property version "1.00"
#property strict
#include <Canvas/Canvas.mqh>
#include <Arrays/List.mqh>
//---
#define EVENT_NO_EVENTS 0
#define EVENT_MOVE 1
#define EVENT_CHANGE 2
//+------------------------------------------------------------------+
//| TComment |
//+------------------------------------------------------------------+
class TComment : public CObject
{
public:
string text;
color colour;
};
//+------------------------------------------------------------------+
//| CComment |
//+------------------------------------------------------------------+
class CComment
{
private:
CPoint m_temp;
CCanvas m_comment;
CPoint m_pos;
CList m_list;
CSize m_size;
//---
string m_name;
string m_font_name;
int m_font_size;
bool m_font_bold;
double m_font_interval;
color m_border_color;
color m_back_color;
uchar m_back_alpha;
bool m_graph_mode;
bool m_auto_colors;
color m_auto_back_color;
color m_auto_text_color;
color m_auto_border_color;
color m_chart_back_color;
//+------------------------------------------------------------------+
color Color2Gray(const color value)
{
int gray=(int)round(0.3*GETRGBR(value)+0.59*GETRGBG(value)+0.11*GETRGBB(value));
if(gray>255) gray=255;
return((color)ARGB(0,gray,gray,gray));
}
//+------------------------------------------------------------------+
uchar GrayChannel(const color value)
{
int gray=(int)round(0.3*GETRGBR(value)+0.59*GETRGBG(value)+0.11*GETRGBB(value));
if(gray>255) gray=255;
return((uchar)gray);
}
//+------------------------------------------------------------------+
color Bright(const color value,const int percent)
{
int r,g,b;
//---
r=GETRGBR(value);
g=GETRGBG(value);
b=GETRGBB(value);
//---
if(percent>=0)
{
r+=(255-r)*percent/100;
if(r>255)r=255;
g+=(255-g)*percent/100;
if(g>255)g=255;
b+=(255-b)*percent/100;
if(b>255)b=255;
}
else
{
r+=r*percent/100;
if(r<0)r=0;
g+=g*percent/100;
if(g<0)g=0;
b+=b*percent/100;
if(b<0)b=0;
}
//---
return(ARGB(0,r,g,b));
}
//+------------------------------------------------------------------+
void CalcColors()
{
m_auto_back_color=(color)ChartGetInteger(0,CHART_COLOR_BACKGROUND);
color m_back_gray=Color2Gray(m_auto_back_color);
uchar channel=GrayChannel(m_back_gray);
//---
if(channel>120)
{
if(m_back_color==clrNONE)
m_auto_border_color=clrNONE;
else
m_auto_border_color=Bright(m_back_gray,-30);
m_auto_text_color=Bright(m_back_gray,-80);
}
else
{
if(m_back_color==clrNONE)
m_auto_border_color=clrNONE;
else
m_auto_border_color=Bright(m_back_gray,30);
m_auto_text_color=Bright(m_back_gray,80);
}
}
public:
//+------------------------------------------------------------------+
void CComment(void)
{
m_name=NULL;
m_font_name="Lucida Console";
m_font_size=14;
m_font_bold=false;
m_font_interval=1.7;
m_border_color=clrNONE;
m_back_color=clrBlack;
m_back_alpha=255;
m_graph_mode=true;
m_auto_colors=false;
m_chart_back_color=(color)ChartGetInteger(0,CHART_COLOR_BACKGROUND);
m_auto_back_color=clrBlack;
m_auto_border_color=clrNONE;
//---
ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,true);
};
//+------------------------------------------------------------------+
void Create(const string name,const uint x,const uint y)
{
m_name=name;
m_pos.x=(int)x;
m_pos.y=(int)y;
};
//+------------------------------------------------------------------+
int CoordY()
{
return(m_pos.y);
}
//+------------------------------------------------------------------+
int CoordX()
{
return(m_pos.x);
}
//+------------------------------------------------------------------+
void Move(const uint x,const uint y)
{
m_pos.x=(int)x;
m_pos.y=(int)y;
if(ObjectGetInteger(0,m_name,OBJPROP_XDISTANCE)!=m_pos.x)
ObjectSetInteger(0,m_name,OBJPROP_XDISTANCE,m_pos.x);
if(ObjectGetInteger(0,m_name,OBJPROP_YDISTANCE)!=m_pos.y)
ObjectSetInteger(0,m_name,OBJPROP_YDISTANCE,m_pos.y);
};
//+------------------------------------------------------------------+
void SetAutoColors(const bool value)
{
m_auto_colors=value;
if(value)
CalcColors();
}
//+------------------------------------------------------------------+
void SetGraphMode(const bool value)
{
m_graph_mode=value;
};
//+------------------------------------------------------------------+
void SetText(const int row,const string text,const color colour)
{
if(row<0)
return;
//---
int total=m_list.Total();
if(row<total)
{
TComment *item=m_list.GetNodeAtIndex(row);
item.text=text;
item.colour=colour;
}
else
{
//--- create new one string
for(int i=total; i<=row; i++)
{
m_list.Add(new TComment);
TComment *item=m_list.GetLastNode();
if(row==i)
{
item.text=text;
item.colour=colour;
}
else
{
item.text="";
item.colour=clrNONE;
}
}
}
}
//+------------------------------------------------------------------+
void SetFont(const string font_name,const int font_size,const bool bold,const double font_interval)
{
m_font_name=font_name;
m_font_size=font_size;
m_font_bold=bold;
m_font_interval=font_interval;
}
//+------------------------------------------------------------------+
void SetTransparency(const uchar alpha)
{
m_back_alpha=alpha;
}
//+------------------------------------------------------------------+
void SetColor(const color border,const color back,const uchar alpha)
{
m_border_color=border;
m_back_color=back;
m_back_alpha=alpha;
}
//+------------------------------------------------------------------+
void Destroy()
{
if(!m_graph_mode)
Comment("");
m_comment.Destroy();
m_name=NULL;
};
//+------------------------------------------------------------------+
void Clear()
{
m_list.Clear();
};
//+------------------------------------------------------------------+
int OnChartEvent(const int id,const long lparam,const double dparam,const string sparam)
{
//--- mouse position
CPoint p;
p.x = (int)lparam;
p.y = (int)dparam;
//---
if(id==CHARTEVENT_MOUSE_MOVE)
{
//--- panel size
CSize psize;
psize.cx=(int)ObjectGetInteger(0,m_name,OBJPROP_XSIZE);
psize.cy=(int)ObjectGetInteger(0,m_name,OBJPROP_YSIZE);
//--- panel position
CPoint pan;
pan.x=(int)ObjectGetInteger(0,m_name,OBJPROP_XDISTANCE);
pan.y=(int)ObjectGetInteger(0,m_name,OBJPROP_YDISTANCE);
//--- chart size
CSize screen;
screen.cx=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS);
screen.cy=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS);
if(sparam=="1")
{
//---
if(m_temp.x==-1 &&
p.x>=pan.x && p.x<pan.x+psize.cx &&
p.y>=pan.y && p.y<pan.y+psize.cy)
{
m_temp.x=p.x-pan.x;
}
//---
if(m_temp.y==-1 &&
p.x>=pan.x && p.x<pan.x+psize.cx &&
p.y>=pan.y && p.y<pan.y+psize.cy)
{
m_temp.y=p.y-pan.y;
}
//---
if(m_temp.x>=0 && m_temp.y>=0)
{
int new_x=p.x-m_temp.x;
if(new_x>screen.cx-psize.cx)new_x=screen.cx-psize.cx;
if(new_x<0)new_x=0;
int new_y=p.y-m_temp.y;
if(new_y>screen.cy-psize.cy)new_y=screen.cy-psize.cy;
if(new_y<0)new_y=0;
//---
ObjectSetInteger(0,m_name,OBJPROP_XDISTANCE,new_x);
m_pos.x=new_x;
ObjectSetInteger(0,m_name,OBJPROP_YDISTANCE,new_y);
m_pos.y=new_y;
ChartSetInteger(0,CHART_MOUSE_SCROLL,false);
#ifdef __MQL5__
ChartRedraw();
#endif
return(EVENT_MOVE);
}
}
else
{
m_temp.x=-1;
m_temp.y=-1;
ChartSetInteger(0,CHART_MOUSE_SCROLL,true);
}
}
//---
if(m_auto_colors && id==CHARTEVENT_CHART_CHANGE)
{
//--- changing background color event
if(m_chart_back_color!=(color)ChartGetInteger(0,CHART_COLOR_BACKGROUND))
{
CalcColors();
m_chart_back_color=(color)ChartGetInteger(0,CHART_COLOR_BACKGROUND);
Show();
return(EVENT_CHANGE);
}
}
//---
return(EVENT_NO_EVENTS);
}
//+------------------------------------------------------------------+
void Show()
{
int rows=m_list.Total();
//--- text mode
if(!m_graph_mode)
{
string text;
for(int i=0; i<rows; i++)
{
TComment *item=m_list.GetNodeAtIndex(i);
text+="\n"+item.text;
}
Comment(text);
return;
}
m_comment.FontSet(m_font_name,m_font_size,m_font_bold?FW_BOLD:0);
int text_height=m_comment.TextHeight(" ");
int max_height=(rows)*(int)round(text_height*m_font_interval)+text_height;
//--- calc max width
int max_width=0;
for(int i=0; i<rows; i++)
{
TComment *item=m_list.GetNodeAtIndex(i);
int width=m_comment.TextWidth(item.text);
if(width>max_width) max_width=width;
}
max_width+=text_height*2;
//--- create panel
if(ObjectFind(0,m_name)==-1)
{
m_comment.CreateBitmapLabel(0,0,m_name,m_pos.x,m_pos.y,max_width,max_height,COLOR_FORMAT_ARGB_NORMALIZE);
ObjectSetString(0,m_name,OBJPROP_TOOLTIP,"\n");
}
else
{
//--- resize panel
if(m_comment.Height()!=max_height ||
m_comment.Width()!=max_width)
{
if(!m_comment.Resize(max_width,max_height))
{
ObjectDelete(0,m_name);
ChartRedraw();
}
}
}
//---
m_comment.Erase(ColorToARGB(m_auto_colors?m_auto_back_color:m_back_color,m_back_alpha));
m_comment.Rectangle(0,0,max_width-1,max_height-1,ColorToARGB(m_auto_colors?m_auto_border_color:m_border_color));
//---
int h=text_height;
for(int i=0; i<rows; i++)
{
TComment *item=m_list.GetNodeAtIndex(i);
m_comment.TextOut(text_height,h,item.text,ColorToARGB(m_auto_colors?m_auto_text_color:item.colour));
h+=(int)round(text_height*m_font_interval);
}
//---
m_comment.Update();
}
};
//+------------------------------------------------------------------+
BIN
View File
Binary file not shown.
Binary file not shown.
+111
View File
@@ -0,0 +1,111 @@
//+------------------------------------------------------------------+
//| CreateLicense.mqh |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link "https://www.mql5.com"
class CreateLicense
{
private:
string mProductName;
string mProductKey;
string mExpiry;
string mUserID;
string mAccount;
public:
CreateLicense(void);
~CreateLicense(void);
void initalization(string productName, string productKey, datetime expiry, long userid, long account);
string KeyGen( string data ); // Allow account to pass in
string Hash( string data );
bool FileGen( string data );
void CreateTestLicenseFile();
};
CreateLicense::CreateLicense(void)
{
}
CreateLicense::~CreateLicense(void)
{
}
void CreateLicense::initalization(string productName, string productKey, datetime expiry, long userid, long account)
{
mProductName = productName;
mProductKey = productKey;
mExpiry = TimeToString(expiry,TIME_DATE);
mUserID = IntegerToString(userid);
mAccount = IntegerToString(account);
}
string CreateLicense::Hash( string data ) {
uchar dataCharArray[];
StringToCharArray(data, dataCharArray);
uchar combinedCharArray[];
int combinedSize = ArraySize(dataCharArray);
ArrayResize(combinedCharArray, combinedSize);
ArrayCopy(combinedCharArray, dataCharArray, 0, 0, ArraySize(dataCharArray));
// Generate SHA-256 hash
uchar hashResult[];
if (!CryptEncode(CRYPT_HASH_SHA256, combinedCharArray, combinedCharArray, hashResult)) {
Print("Error generating SHA-256 hash.");
return "";
}
// Base64 encode the hash result
uchar base64Result[];
if (!CryptEncode(CRYPT_BASE64, hashResult, hashResult, base64Result)) {
Print("Error encoding to Base64.");
return "";
}
// Convert Base64 result to string for the final passcode
string result = CharArrayToString(base64Result);
return result;
}
bool CreateLicense::FileGen( string data ) {
string licencePath = Hash( mProductName + "_" + mAccount ) + ".lic";
int handle = FileOpen( licencePath, FILE_WRITE | FILE_BIN | FILE_ANSI );
if ( handle == INVALID_HANDLE ) {
PrintFormat( "Could not create licence file %s", licencePath );
return ( false );
}
string data_hash = Hash(mAccount + "_" + mExpiry + "_" + mUserID + "_" + mProductName + "_" + mProductKey);
string signature = KeyGen(data_hash);
string contents = signature + data_hash + "\n" + mExpiry;
FileWriteString( handle, contents );
FileFlush( handle );
FileClose( handle );
Print( "Licence file '" + licencePath + "' created" );
return ( true );
}
string CreateLicense::KeyGen( string data ) {
string keyString = data + mProductName;
return Hash( keyString );
}
void CreateLicense::CreateTestLicenseFile() {
string data = Hash(mAccount + "_" + mExpiry + "_" + mUserID + "_" + mProductName + "_" + mProductKey);
// Create the file to ship to the customer
if ( !FileGen( data ) ) {
Print( "Failed to create licence file" );
return;
}
Print( "Created licence file" );
}
+200
View File
@@ -0,0 +1,200 @@
//+------------------------------------------------------------------+
//| Defines.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Enumerations |
//+------------------------------------------------------------------+
//--- properties flags
enum ENUM_WND_PROP_FLAGS
{
WND_PROP_FLAG_CAN_DBL_CLICK = 1, // can be double clicked by mouse
WND_PROP_FLAG_CAN_DRAG = 2, // can be dragged by mouse
WND_PROP_FLAG_CLICKS_BY_PRESS= 4, // generates the "click" event series on pressing left mouse button
WND_PROP_FLAG_CAN_LOCK = 8, // control with fixed state (usually it is a button)
WND_PROP_FLAG_READ_ONLY =16 // read only (usually it is a edit)
};
//--- state flags
enum ENUM_WND_STATE_FLAGS
{
WND_STATE_FLAG_ENABLE = 1, // "object is enabled" flag
WND_STATE_FLAG_VISIBLE = 2, // "object is visible" flag
WND_STATE_FLAG_ACTIVE = 4, // "object is active" flag
};
//--- mouse flags
enum ENUM_MOUSE_FLAGS
{
MOUSE_INVALID_FLAGS =-1, // no buttons state
MOUSE_EMPTY = 0, // buttons are not pressed
MOUSE_LEFT = 1, // left button pressed
MOUSE_RIGHT = 2 // right button pressed
};
//--- alignment flags
enum ENUM_WND_ALIGN_FLAGS
{
WND_ALIGN_NONE = 0, // no alignment
WND_ALIGN_LEFT = 1, // align by left border
WND_ALIGN_TOP = 2, // align by top border
WND_ALIGN_RIGHT = 4, // align by right border
WND_ALIGN_BOTTOM = 8, // align by bottom border
WND_ALIGN_WIDTH = WND_ALIGN_LEFT|WND_ALIGN_RIGHT, // justify
WND_ALIGN_HEIGHT = WND_ALIGN_TOP|WND_ALIGN_BOTTOM, // align by top and bottom border
WND_ALIGN_CLIENT = WND_ALIGN_WIDTH|WND_ALIGN_HEIGHT // align by all sides
};
//+------------------------------------------------------------------+
//| Drawing styles and colors |
//+------------------------------------------------------------------+
//--- common
#define CONTROLS_FONT_NAME "Trebuchet MS"
#define CONTROLS_FONT_SIZE (10)
//--- Text
#define CONTROLS_COLOR_TEXT C'0x3B,0x29,0x28'
#define CONTROLS_COLOR_TEXT_SEL White
#define CONTROLS_COLOR_BG White
#define CONTROLS_COLOR_BG_SEL C'0x33,0x99,0xFF'
//--- Button
#define CONTROLS_BUTTON_COLOR C'0x3B,0x29,0x28'
#define CONTROLS_BUTTON_COLOR_BG C'0xDD,0xE2,0xEB'
#define CONTROLS_BUTTON_COLOR_BORDER C'0xB2,0xC3,0xCF'
//--- Label
#define CONTROLS_LABEL_COLOR C'0x3B,0x29,0x28'
//--- Edit
#define CONTROLS_EDIT_COLOR C'0x3B,0x29,0x28'
#define CONTROLS_EDIT_COLOR_BG White
#define CONTROLS_EDIT_COLOR_BORDER C'0xB2,0xC3,0xCF'
//--- Scrolls
#define CONTROLS_SCROLL_COLOR_BG C'0xEC,0xEC,0xEC'
#define CONTROLS_SCROLL_COLOR_BORDER C'0xD3,0xD3,0xD3'
//--- Client
#define CONTROLS_CLIENT_COLOR_BG C'0xDE,0xDE,0xDE'
#define CONTROLS_CLIENT_COLOR_BORDER C'0x2C,0x2C,0x2C'
//--- ListView
#define CONTROLS_LISTITEM_COLOR_TEXT C'0x3B,0x29,0x28'
#define CONTROLS_LISTITEM_COLOR_TEXT_SEL White
#define CONTROLS_LISTITEM_COLOR_BG White
#define CONTROLS_LISTITEM_COLOR_BG_SEL C'0x33,0x99,0xFF'
#define CONTROLS_LIST_COLOR_BG White
#define CONTROLS_LIST_COLOR_BORDER C'0xB2,0xC3,0xCF'
//--- CheckGroup
#define CONTROLS_CHECKGROUP_COLOR_BG C'0xF7,0xF7,0xF7'
#define CONTROLS_CHECKGROUP_COLOR_BORDER C'0xB2,0xC3,0xCF'
//--- RadioGroup
#define CONTROLS_RADIOGROUP_COLOR_BG C'0xF7,0xF7,0xF7'
#define CONTROLS_RADIOGROUP_COLOR_BORDER C'0xB2,0xC3,0xCF'
//--- Dialog
#define CONTROLS_DIALOG_COLOR_BORDER_LIGHT White
#define CONTROLS_DIALOG_COLOR_BORDER_DARK C'0xB6,0xB6,0xB6'
#define CONTROLS_DIALOG_COLOR_BG C'0xF0,0xF0,0xF0'
#define CONTROLS_DIALOG_COLOR_CAPTION_TEXT C'0x28,0x29,0x3B'
#define CONTROLS_DIALOG_COLOR_CLIENT_BG C'0xF7,0xF7,0xF7'
#define CONTROLS_DIALOG_COLOR_CLIENT_BORDER C'0xC8,0xC8,0xC8'
//+------------------------------------------------------------------+
//| Constants for the controls |
//+------------------------------------------------------------------+
//--- common
#define CONTROLS_INVALID_ID (-1) // invalid ID
#define CONTROLS_INVALID_INDEX (-1) // invalid index of array
#define CONTROLS_SELF_MESSAGE (-1) // message to oneself
#define CONTROLS_MAXIMUM_ID (10000) // maximum number of IDs in application
#define CONTROLS_BORDER_WIDTH (1) // border width
#define CONTROLS_SUBWINDOW_GAP (3) // gap between sub-windows along the Y axis
#define CONTROLS_DRAG_SPACING (50) // sensitivity threshold for dragging
#define CONTROLS_DBL_CLICK_TIME (100) // double click interval
//--- BmpButton
#define CONTROLS_BUTTON_SIZE (16) // default size of button (16 x 16)
//--- Scrolls
#define CONTROLS_SCROLL_SIZE (18) // default lateral size of scrollbar
#define CONTROLS_SCROLL_THUMB_SIZE (22) // default length of scroll box
//--- RadioButton
#define CONTROLS_RADIO_BUTTON_X_OFF (3) // X offset of radio button (for RadioButton)
#define CONTROLS_RADIO_BUTTON_Y_OFF (3) // Y offset of radio button (for RadioButton)
#define CONTROLS_RADIO_LABEL_X_OFF (20) // X offset of label (for RadioButton)
#define CONTROLS_RADIO_LABEL_Y_OFF (0) // Y offset of label (for RadioButton)
//--- CheckBox
#define CONTROLS_CHECK_BUTTON_X_OFF (3) // X offset of check button (for CheckBox)
#define CONTROLS_CHECK_BUTTON_Y_OFF (3) // Y offset of check button (for CheckBox)
#define CONTROLS_CHECK_LABEL_X_OFF (20) // X offset of label (for CheckBox)
#define CONTROLS_CHECK_LABEL_Y_OFF (0) // Y offset of label (for CheckBox)
//--- Spin
#define CONTROLS_SPIN_BUTTON_X_OFF (2) // X offset of button from right (for SpinEdit)
#define CONTROLS_SPIN_MIN_HEIGHT (18) // minimal height (for SpinEdit)
#define CONTROLS_SPIN_BUTTON_SIZE (8) // default size of button (16 x 8) (for SpinEdit)
//--- Combo
#define CONTROLS_COMBO_BUTTON_X_OFF (2) // X offset of button from right (for ComboBox)
#define CONTROLS_COMBO_MIN_HEIGHT (18) // minimal height (for ComboBox)
#define CONTROLS_COMBO_ITEM_HEIGHT (18) // height of combo box item (for ComboBox)
#define CONTROLS_COMBO_ITEMS_VIEW (18) // number of items in combo box (for ComboBox)
//--- ListView
#define CONTROLS_LIST_ITEM_HEIGHT (18) // height of list item (for ListView)
#define CONTROLS_LIST_ITEM_CLICK (19)
//--- Dialog
#define CONTROLS_DIALOG_CAPTION_HEIGHT (22) // height of dialog header
#define CONTROLS_DIALOG_BUTTON_OFF (3) // offset of dialog buttons
#define CONTROLS_DIALOG_CLIENT_OFF (2) // offset of dialog client area
#define CONTROLS_DIALOG_MINIMIZE_LEFT (10) // left coordinate of dialog in minimized state
#define CONTROLS_DIALOG_MINIMIZE_TOP (10) // top coordinate of dialog in minimized state
#define CONTROLS_DIALOG_MINIMIZE_WIDTH (100) // width of dialog in minimized state
#define CONTROLS_DIALOG_MINIMIZE_HEIGHT (4*CONTROLS_BORDER_WIDTH+CONTROLS_DIALOG_CAPTION_HEIGHT) // height of dialog in minimized state
//+------------------------------------------------------------------+
//| Macro |
//+------------------------------------------------------------------+
//--- check properties
#define IS_CAN_DBL_CLICK ((m_prop_flags&WND_PROP_FLAG_CAN_DBL_CLICK)!=0)
#define IS_CAN_DRAG ((m_prop_flags&WND_PROP_FLAG_CAN_DRAG)!=0)
#define IS_CLICKS_BY_PRESS ((m_prop_flags&WND_PROP_FLAG_CLICKS_BY_PRESS)!=0)
#define IS_CAN_LOCK ((m_prop_flags&WND_PROP_FLAG_CAN_LOCK)!=0)
#define IS_READ_ONLY ((m_prop_flags&WND_PROP_FLAG_READ_ONLY)!=0)
//--- check state
#define IS_ENABLED ((m_state_flags&WND_STATE_FLAG_ENABLE)!=0)
#define IS_VISIBLE ((m_state_flags&WND_STATE_FLAG_VISIBLE)!=0)
#define IS_ACTIVE ((m_state_flags&WND_STATE_FLAG_ACTIVE)!=0)
//+------------------------------------------------------------------+
//| Macro of event handling map |
//+------------------------------------------------------------------+
#define INTERNAL_EVENT (-1)
//--- beginning of map
#define EVENT_MAP_BEGIN(class_name) bool class_name::OnEvent(const int id,const long& lparam,const double& dparam,const string& sparam) {
//--- end of map
#define EVENT_MAP_END(parent_class_name) return(parent_class_name::OnEvent(id,lparam,dparam,sparam)); }
//--- event handling by numeric ID
#define ON_EVENT(event,control,handler) if(id==(event+CHARTEVENT_CUSTOM) && lparam==control.Id()) { handler(); return(true); }
//--- event handling by numeric ID by pointer of control
#define ON_EVENT_PTR(event,control,handler) if(control!=NULL && id==(event+CHARTEVENT_CUSTOM) && lparam==control.Id()) { handler(); return(true); }
//--- event handling without ID analysis
#define ON_NO_ID_EVENT(event,handler) if(id==(event+CHARTEVENT_CUSTOM)) { return(handler()); }
//--- event handling by row ID
#define ON_NAMED_EVENT(event,control,handler) if(id==(event+CHARTEVENT_CUSTOM) && sparam==control.Name()) { handler(); return(true); }
//--- handling of indexed event
#define ON_INDEXED_EVENT(event,controls,handler) { int total=ArraySize(controls); for(int i=0;i<total;i++) if(id==(event+CHARTEVENT_CUSTOM) && lparam==controls[i].Id()) return(handler(i)); }
//--- handling of external event
#define ON_EXTERNAL_EVENT(event,handler) if(id==(event+CHARTEVENT_CUSTOM)) { handler(lparam,dparam,sparam); return(true); }
//+------------------------------------------------------------------+
//| Events |
//+------------------------------------------------------------------+
#define CUSTOM_SPACING (15)
#define ON_CLICK (0) // clicking on control event
#define ON_DBL_CLICK (1) // double clicking on control event
#define ON_SHOW (2) // showing control event
#define ON_HIDE (3) // hiding control event
#define ON_CHANGE (4) // changing control event
#define ON_START_EDIT (5) // start of editing event
#define ON_END_EDIT (6) // end of editing event
#define ON_SCROLL_INC (7) // increment of scrollbar event
#define ON_SCROLL_DEC (8) // decrement of scrollbar event
#define ON_MOUSE_FOCUS_SET (9) // the "mouse cursor entered the control" event
#define ON_MOUSE_FOCUS_KILL (10) // the "mouse cursor exited the control" event
#define ON_DRAG_START (11) // the "control dragging start" event
#define ON_DRAG_PROCESS (12) // the "control is being dragged" event
#define ON_DRAG_END (13) // the "control dragging end" event
#define ON_BRING_TO_TOP (14) // the "mouse events priority increase" event
#define ON_CLICK_LIST_ITEM (123)
#define ON_CLICK_COMBOBOX_ITEM (17)
#define ON_CLICK_COMBOBOX_BUTTON (28)
#define ON_APP_CLOSE (100) // "closing the application" event
//+------------------------------------------------------------------+
+971
View File
@@ -0,0 +1,971 @@
//+------------------------------------------------------------------+
//| Dialog.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include "WndContainer.mqh"
#include "WndClient.mqh"
#include "Panel.mqh"
#include "Edit.mqh"
#include "BmpButton.mqh"
#include <Charts\Chart.mqh>
//+------------------------------------------------------------------+
//| Resources |
//+------------------------------------------------------------------+
#resource "res\\Close.bmp"
#resource "res\\Restore.bmp"
#resource "res\\Turn.bmp"
//+------------------------------------------------------------------+
//| Class CDialog |
//| Usage: base class to create dialog boxes |
//| and indicator panels |
//+------------------------------------------------------------------+
class CDialog : public CWndContainer
{
private:
//--- dependent controls
CPanel m_white_border; // the "white border" object
CPanel m_background; // the background object
CEdit m_caption; // the window title object
CBmpButton m_button_close; // the "Close" button object
CWndClient m_client_area; // the client area object
protected:
//--- flags
bool m_panel_flag; // the "panel in a separate window" flag
//--- flags
bool m_minimized; // "create in minimized state" flag
//--- additional areas
CRect m_min_rect; // minimal area coordinates
CRect m_norm_rect; // normal area coordinates
public:
CDialog(void);
~CDialog(void);
//--- create
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
//--- chart event handler
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
//--- set up
string Caption(void) const { return(m_caption.Text()); }
bool Caption(const string text) { return(m_caption.Text(text)); }
//--- fill
bool Add(CWnd *control);
bool Add(CWnd &control);
//--- methods for working with files
virtual bool Save(const int file_handle);
virtual bool Load(const int file_handle);
protected:
//--- create dependent controls
virtual bool CreateWhiteBorder(void);
virtual bool CreateBackground(void);
virtual bool CreateCaption(void);
virtual bool CreateButtonClose(void);
virtual bool CreateClientArea(void);
//--- handlers of the dependent controls events
virtual void OnClickCaption(void);
virtual void OnClickButtonClose(void);
//--- access properties of caption
void CaptionAlignment(const int flags,const int left,const int top,const int right,const int bottom)
{ m_caption.Alignment(flags,left,top,right,bottom); }
//--- access properties of client area
bool ClientAreaVisible(const bool visible) { return(m_client_area.Visible(visible)); }
int ClientAreaLeft(void) const { return(m_client_area.Left()); }
int ClientAreaTop(void) const { return(m_client_area.Top()); }
int ClientAreaRight(void) const { return(m_client_area.Right()); }
int ClientAreaBottom(void) const { return(m_client_area.Bottom()); }
int ClientAreaWidth(void) const { return(m_client_area.Width()); }
int ClientAreaHeight(void) const { return(m_client_area.Height()); }
//--- handlers of drag
virtual bool OnDialogDragStart(void);
virtual bool OnDialogDragProcess(void);
virtual bool OnDialogDragEnd(void);
};
//+------------------------------------------------------------------+
//| Common handler of events |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CDialog)
ON_EVENT(ON_CLICK,m_button_close,OnClickButtonClose)
ON_EVENT(ON_CLICK,m_caption,OnClickCaption)
ON_EVENT(ON_DRAG_START,m_caption,OnDialogDragStart)
ON_EVENT_PTR(ON_DRAG_PROCESS,m_drag_object,OnDialogDragProcess)
ON_EVENT_PTR(ON_DRAG_END,m_drag_object,OnDialogDragEnd)
EVENT_MAP_END(CWndContainer)
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CDialog::CDialog(void) : m_panel_flag(false),
m_minimized(false)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CDialog::~CDialog(void)
{
}
//+------------------------------------------------------------------+
//| Create a control |
//+------------------------------------------------------------------+
bool CDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
{
//--- call method of parent class
if(!CWndContainer::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
//--- create dependent controls
if(!m_panel_flag && !CreateWhiteBorder())
return(false);
if(!CreateBackground())
return(false);
if(!CreateCaption())
return(false);
if(!CreateButtonClose())
return(false);
if(!CreateClientArea())
return(false);
//--- set up additional areas
m_norm_rect.SetBound(m_rect);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Add control to the client area (by pointer) |
//+------------------------------------------------------------------+
bool CDialog::Add(CWnd *control)
{
return(m_client_area.Add(control));
}
//+------------------------------------------------------------------+
//| Add control to the client area (by reference) |
//+------------------------------------------------------------------+
bool CDialog::Add(CWnd &control)
{
return(m_client_area.Add(control));
}
//+------------------------------------------------------------------+
//| Save |
//+------------------------------------------------------------------+
bool CDialog::Save(const int file_handle)
{
//--- check
if(file_handle==INVALID_HANDLE)
return(false);
//--- save
FileWriteStruct(file_handle,m_norm_rect);
FileWriteInteger(file_handle,m_min_rect.left);
FileWriteInteger(file_handle,m_min_rect.top);
FileWriteInteger(file_handle,m_minimized);
//--- result
return(CWndContainer::Save(file_handle));
}
//+------------------------------------------------------------------+
//| Load |
//+------------------------------------------------------------------+
bool CDialog::Load(const int file_handle)
{
if(file_handle==INVALID_HANDLE)
return(false);
//--- load
if(!FileIsEnding(file_handle))
{
FileReadStruct(file_handle,m_norm_rect);
int left=FileReadInteger(file_handle);
int top=FileReadInteger(file_handle);
m_min_rect.Move(left,top);
m_minimized=FileReadInteger(file_handle);
}
//--- result
return(CWndContainer::Load(file_handle));
}
//+------------------------------------------------------------------+
//| Create "white border" |
//+------------------------------------------------------------------+
bool CDialog::CreateWhiteBorder(void)
{
//--- coordinates
int x1=0;
int y1=0;
int x2=Width();
int y2=Height();
//--- create
if(!m_white_border.Create(m_chart_id,m_name+"Border",m_subwin,x1,y1,x2,y2))
return(false);
if(!m_white_border.ColorBackground(CONTROLS_DIALOG_COLOR_BG))
return(false);
if(!m_white_border.ColorBorder(CONTROLS_DIALOG_COLOR_BORDER_LIGHT))
return(false);
if(!CWndContainer::Add(m_white_border))
return(false);
m_white_border.Alignment(WND_ALIGN_CLIENT,0,0,0,0);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Create background |
//+------------------------------------------------------------------+
bool CDialog::CreateBackground(void)
{
int off=(m_panel_flag) ? 0:CONTROLS_BORDER_WIDTH;
//--- coordinates
int x1=off;
int y1=off;
int x2=Width()-off;
int y2=Height()-off;
//--- create
if(!m_background.Create(m_chart_id,m_name+"Back",m_subwin,x1,y1,x2,y2))
return(false);
if(!m_background.ColorBackground(CONTROLS_DIALOG_COLOR_BG))
return(false);
color border=(m_panel_flag) ? CONTROLS_DIALOG_COLOR_BG : CONTROLS_DIALOG_COLOR_BORDER_DARK;
if(!m_background.ColorBorder(border))
return(false);
if(!CWndContainer::Add(m_background))
return(false);
m_background.Alignment(WND_ALIGN_CLIENT,off,off,off,off);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Create window title |
//+------------------------------------------------------------------+
bool CDialog::CreateCaption(void)
{
int off=(m_panel_flag) ? 0:2*CONTROLS_BORDER_WIDTH;
//--- coordinates
int x1=off;
int y1=off;
int x2=Width()-off;
int y2=y1+CONTROLS_DIALOG_CAPTION_HEIGHT;
//--- create
if(!m_caption.Create(m_chart_id,m_name+"Caption",m_subwin,x1,y1,x2,y2))
return(false);
if(!m_caption.Color(CONTROLS_DIALOG_COLOR_CAPTION_TEXT))
return(false);
if(!m_caption.ColorBackground(CONTROLS_DIALOG_COLOR_BG))
return(false);
if(!m_caption.ColorBorder(CONTROLS_DIALOG_COLOR_BG))
return(false);
if(!m_caption.ReadOnly(true))
return(false);
if(!m_caption.Text(m_name))
return(false);
if(!CWndContainer::Add(m_caption))
return(false);
m_caption.Alignment(WND_ALIGN_WIDTH,off,0,off,0);
if(!m_panel_flag)
m_caption.PropFlags(WND_PROP_FLAG_CAN_DRAG);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Create the "Close" button |
//+------------------------------------------------------------------+
bool CDialog::CreateButtonClose(void)
{
int off=(m_panel_flag) ? 0 : 2*CONTROLS_BORDER_WIDTH;
//--- coordinates
int x1=Width()-off-(CONTROLS_BUTTON_SIZE+CONTROLS_DIALOG_BUTTON_OFF);
int y1=off+CONTROLS_DIALOG_BUTTON_OFF;
int x2=x1+CONTROLS_BUTTON_SIZE;
int y2=y1+CONTROLS_BUTTON_SIZE;
//--- create
if(!m_button_close.Create(m_chart_id,m_name+"Close",m_subwin,x1,y1,x2,y2))
return(false);
if(!m_button_close.BmpNames("::res\\Close.bmp"))
return(false);
if(!CWndContainer::Add(m_button_close))
return(false);
m_button_close.Alignment(WND_ALIGN_RIGHT,0,0,off+CONTROLS_DIALOG_BUTTON_OFF,0);
//--- change caption
CaptionAlignment(WND_ALIGN_WIDTH,off,0,off+(CONTROLS_BUTTON_SIZE+CONTROLS_DIALOG_BUTTON_OFF),0);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Create client area |
//+------------------------------------------------------------------+
bool CDialog::CreateClientArea(void)
{
int off=(m_panel_flag) ? 0:2*CONTROLS_BORDER_WIDTH;
//--- coordinates
int x1=off+CONTROLS_DIALOG_CLIENT_OFF;
int y1=off+CONTROLS_DIALOG_CAPTION_HEIGHT;
int x2=Width()-(off+CONTROLS_DIALOG_CLIENT_OFF);
int y2=Height()-(off+CONTROLS_DIALOG_CLIENT_OFF);
//--- create
if(!m_client_area.Create(m_chart_id,m_name+"Client",m_subwin,x1,y1,x2,y2))
return(false);
if(!m_client_area.ColorBackground(CONTROLS_DIALOG_COLOR_CLIENT_BG))
return(false);
if(!m_client_area.ColorBorder(CONTROLS_DIALOG_COLOR_CLIENT_BORDER))
return(false);
CWndContainer::Add(m_client_area);
m_client_area.Alignment(WND_ALIGN_CLIENT,x1,y1,x1,x1);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Handler of click on the window title |
//+------------------------------------------------------------------+
void CDialog::OnClickCaption(void)
{
}
//+------------------------------------------------------------------+
//| Handler of click on the "Close" button |
//+------------------------------------------------------------------+
void CDialog::OnClickButtonClose(void)
{
Visible(false);
}
//+------------------------------------------------------------------+
//| Start dragging the dialog box |
//+------------------------------------------------------------------+
bool CDialog::OnDialogDragStart(void)
{
if(m_drag_object==NULL)
{
m_drag_object=new CDragWnd;
if(m_drag_object==NULL)
return(false);
}
//--- calculate coordinates
int x1=Left()-CONTROLS_DRAG_SPACING;
int y1=Top()-CONTROLS_DRAG_SPACING;
int x2=Right()+CONTROLS_DRAG_SPACING;
int y2=Bottom()+CONTROLS_DRAG_SPACING;
//--- create
m_drag_object.Create(m_chart_id,"",m_subwin,x1,y1,x2,y2);
m_drag_object.PropFlags(WND_PROP_FLAG_CAN_DRAG);
//--- constraints
CChart chart;
chart.Attach(m_chart_id);
m_drag_object.Limits(-CONTROLS_DRAG_SPACING,-CONTROLS_DRAG_SPACING,
chart.WidthInPixels()+CONTROLS_DRAG_SPACING,
chart.HeightInPixels(m_subwin)+CONTROLS_DRAG_SPACING);
chart.Detach();
//--- set mouse params
m_drag_object.MouseX(m_caption.MouseX());
m_drag_object.MouseY(m_caption.MouseY());
m_drag_object.MouseFlags(m_caption.MouseFlags());
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Continue dragging the dialog box |
//+------------------------------------------------------------------+
bool CDialog::OnDialogDragProcess(void)
{
//--- checking
if(m_drag_object==NULL)
return(false);
//--- calculate coordinates
int x=m_drag_object.Left()+50;
int y=m_drag_object.Top()+50;
//--- move dialog
Move(x,y);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| End dragging the dialog box |
//+------------------------------------------------------------------+
bool CDialog::OnDialogDragEnd(void)
{
if(m_drag_object!=NULL)
{
m_caption.MouseFlags(m_drag_object.MouseFlags());
delete m_drag_object;
m_drag_object=NULL;
}
//--- set up additional areas
if(m_minimized)
m_min_rect.SetBound(m_rect);
else
m_norm_rect.SetBound(m_rect);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Class CAppDialog |
//| Usage: main dialog box of MQL5 application |
//+------------------------------------------------------------------+
class CAppDialog : public CDialog
{
private:
//--- dependent controls
CBmpButton m_button_minmax; // the "Minimize/Maximize" button object
//--- variables
string m_program_name; // name of program
string m_instance_id; // unique string ID
ENUM_PROGRAM_TYPE m_program_type; // type of program
string m_indicator_name;
int m_deinit_reason;
//--- for mouse
int m_subwin_Yoff; // subwindow Y offset
CWnd* m_focused_wnd; // pointer to object that has mouse focus
CWnd* m_top_wnd; // pointer to object that has priority over mouse events handling
protected:
CChart m_chart; // object to access chart
public:
CAppDialog(void);
~CAppDialog(void);
//--- main application dialog creation and destroy
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
virtual void Destroy(const int reason=REASON_PROGRAM);
//--- chart event handler
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
//--- dialog run
bool Run(void);
//--- chart events processing
void ChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
//--- set up
void Minimized(const bool flag) { m_minimized=flag; }
//--- to save/restore state
void IniFileSave(void);
void IniFileLoad(void);
virtual string IniFileName(void) const;
virtual string IniFileExt(void) const { return(".dat"); }
virtual bool Load(const int file_handle);
virtual bool Save(const int file_handle);
private:
bool CreateCommon(const long chart,const string name,const int subwin);
bool CreateExpert(const int x1,const int y1,const int x2,const int y2);
bool CreateIndicator(const int x1,const int y1,const int x2,const int y2);
protected:
//--- create dependent controls
virtual bool CreateButtonMinMax(void);
//--- handlers of the dependent controls events
virtual void OnClickButtonClose(void);
virtual void OnClickButtonMinMax(void);
//--- external event handlers
virtual void OnAnotherApplicationClose(const long &lparam,const double &dparam,const string &sparam);
//--- methods
virtual bool Rebound(const CRect &rect);
virtual void Minimize(void);
virtual void Maximize(void);
string CreateInstanceId(void);
string ProgramName(void) const { return(m_program_name); }
void SubwinOff(void);
};
//+------------------------------------------------------------------+
//| Common handler of events |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CAppDialog)
ON_EVENT(ON_CLICK,m_button_minmax,OnClickButtonMinMax)
ON_EXTERNAL_EVENT(ON_APP_CLOSE,OnAnotherApplicationClose)
EVENT_MAP_END(CDialog)
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CAppDialog::CAppDialog(void) : m_program_type(WRONG_VALUE),
m_deinit_reason(WRONG_VALUE),
m_subwin_Yoff(0),
m_focused_wnd(NULL),
m_top_wnd(NULL)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CAppDialog::~CAppDialog(void)
{
}
//+------------------------------------------------------------------+
//| Application dialog initialization function |
//+------------------------------------------------------------------+
bool CAppDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
{
if(!CreateCommon(chart,name,subwin))
return(false);
//---
switch(m_program_type)
{
case PROGRAM_EXPERT:
if(!CreateExpert(x1,y1,x2,y2))
return(false);
break;
case PROGRAM_INDICATOR:
if(!CreateIndicator(x1,y1,x2,y2))
return(false);
break;
default:
Print("CAppDialog: invalid program type");
return(false);
}
//--- Title of dialog window
if(!Caption(m_program_name))
return(false);
//--- create dependent controls
if(!CreateButtonMinMax())
return(false);
//--- get subwindow offset
SubwinOff();
//--- if flag is set, minimize the dialog
if(m_minimized)
Minimize();
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Initialize common area |
//+------------------------------------------------------------------+
bool CAppDialog::CreateCommon(const long chart,const string name,const int subwin)
{
//--- save parameters
m_chart_id =chart;
m_name =name;
m_subwin =subwin;
m_program_name =name;
m_deinit_reason=WRONG_VALUE;
//--- get unique ID
m_instance_id=CreateInstanceId();
//--- initialize chart object
m_chart.Attach(chart);
//--- determine type of program
m_program_type=(ENUM_PROGRAM_TYPE)MQL5InfoInteger(MQL5_PROGRAM_TYPE);
//--- specify object and mouse events
if(!m_chart.EventObjectCreate() || !m_chart.EventObjectDelete() || !m_chart.EventMouseMove())
{
Print("CAppDialog: object events specify error");
m_chart.Detach();
return(false);
}
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Initialize in Expert Advisor |
//+------------------------------------------------------------------+
bool CAppDialog::CreateExpert(const int x1,const int y1,const int x2,const int y2)
{
//--- EA works only in main window
m_subwin=0;
//--- geometry for the minimized state
m_min_rect.SetBound(CONTROLS_DIALOG_MINIMIZE_LEFT,
CONTROLS_DIALOG_MINIMIZE_TOP,
CONTROLS_DIALOG_MINIMIZE_LEFT+CONTROLS_DIALOG_MINIMIZE_WIDTH,
CONTROLS_DIALOG_MINIMIZE_TOP+CONTROLS_DIALOG_MINIMIZE_HEIGHT);
//--- call method of the parent class
if(!CDialog::Create(m_chart.ChartId(),m_instance_id,m_subwin,x1,y1,x2,y2))
{
Print("CAppDialog: expert dialog create error");
m_chart.Detach();
return(false);
}
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Initialize in Indicator |
//+------------------------------------------------------------------+
bool CAppDialog::CreateIndicator(const int x1,const int y1,const int x2,const int y2)
{
int width=m_chart.WidthInPixels();
//--- geometry for the minimized state
m_min_rect.LeftTop(0,0);
m_min_rect.Width(width);
m_min_rect.Height(CONTROLS_DIALOG_MINIMIZE_HEIGHT-2*CONTROLS_BORDER_WIDTH);
//--- determine subwindow
m_subwin=ChartWindowFind();
if(m_subwin==-1)
{
Print("CAppDialog: find subwindow error");
m_chart.Detach();
return(false);
}
//---
int total=ChartIndicatorsTotal(m_chart.ChartId(),m_subwin);
m_indicator_name=ChartIndicatorName(m_chart.ChartId(),m_subwin,total-1);
//--- if subwindow number is 0 (main window), then our program is
//--- not an indicator panel, but is an indicator with built-in settings dialog
//--- dialog of such an indicator should behave as an Expert Advisor dialog
if(m_subwin==0)
return(CreateExpert(x1,y1,x2,y2));
//--- if subwindow number is not 0, then our program is an indicator panel
//--- check if subwindow is not occupied by other indicators
if(total!=1)
{
Print("CAppDialog: subwindow busy");
ChartIndicatorDelete(m_chart.ChartId(),m_subwin,ChartIndicatorName(m_chart.ChartId(),m_subwin,total-1));
m_chart.Detach();
return(false);
}
//--- resize subwindow by dialog height
if(!IndicatorSetInteger(INDICATOR_HEIGHT,(y2-y1)+1))
{
Print("CAppDialog: subwindow resize error");
ChartIndicatorDelete(m_chart.ChartId(),m_subwin,ChartIndicatorName(m_chart.ChartId(),m_subwin,total-1));
m_chart.Detach();
return(false);
}
//--- indicator short name
m_indicator_name=m_program_name+IntegerToString(m_subwin);
if(!IndicatorSetString(INDICATOR_SHORTNAME,m_indicator_name))
{
Print("CAppDialog: shortname error");
ChartIndicatorDelete(m_chart.ChartId(),m_subwin,ChartIndicatorName(m_chart.ChartId(),m_subwin,total-1));
m_chart.Detach();
return(false);
}
//--- set flag
m_panel_flag=true;
//--- call method of the parent class
if(!CDialog::Create(m_chart.ChartId(),m_instance_id,m_subwin,0,0,width,y2-y1))
{
Print("CAppDialog: indicator dialog create error");
ChartIndicatorDelete(m_chart.ChartId(),m_subwin,ChartIndicatorName(m_chart.ChartId(),m_subwin,total-1));
m_chart.Detach();
return(false);
}
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Application dialog deinitialization function |
//+------------------------------------------------------------------+
void CAppDialog::Destroy(const int reason)
{
//--- destroyed already?
if(m_deinit_reason!=WRONG_VALUE)
return;
//---
m_deinit_reason=reason;
IniFileSave();
//--- detach chart object from chart
m_chart.Detach();
//--- call parent destroy
CDialog::Destroy();
//---
if(reason==REASON_PROGRAM)
{
if(m_program_type==PROGRAM_EXPERT)
ExpertRemove();
if(m_program_type==PROGRAM_INDICATOR)
ChartIndicatorDelete(m_chart_id,m_subwin,m_indicator_name);
}
//--- send message
EventChartCustom(CONTROLS_SELF_MESSAGE,ON_APP_CLOSE,m_subwin,0.0,m_program_name);
}
//+------------------------------------------------------------------+
//| Calculate subwindow offset |
//+------------------------------------------------------------------+
void CAppDialog::SubwinOff(void)
{
m_subwin_Yoff=m_chart.SubwindowY(m_subwin);
}
//+------------------------------------------------------------------+
//| Create the "Minimize/Maximize" button |
//+------------------------------------------------------------------+
bool CAppDialog::CreateButtonMinMax(void)
{
int off=(m_panel_flag) ? 0:2*CONTROLS_BORDER_WIDTH;
//--- coordinates
int x1=Width()-off-2*(CONTROLS_BUTTON_SIZE+CONTROLS_DIALOG_BUTTON_OFF);
int y1=off+CONTROLS_DIALOG_BUTTON_OFF;
int x2=x1+CONTROLS_BUTTON_SIZE;
int y2=y1+CONTROLS_BUTTON_SIZE;
//--- create
if(!m_button_minmax.Create(m_chart_id,m_name+"MinMax",m_subwin,x1,y1,x2,y2))
return(false);
if(!m_button_minmax.BmpNames("::res\\Turn.bmp","::res\\Restore.bmp"))
return(false);
if(!CWndContainer::Add(m_button_minmax))
return(false);
m_button_minmax.Locking(true);
m_button_minmax.Alignment(WND_ALIGN_RIGHT,0,0,off+CONTROLS_BUTTON_SIZE+2*CONTROLS_DIALOG_BUTTON_OFF,0);
//--- change caption
CaptionAlignment(WND_ALIGN_WIDTH,off,0,off+2*(CONTROLS_BUTTON_SIZE+CONTROLS_DIALOG_BUTTON_OFF),0);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Charts event processing |
//+------------------------------------------------------------------+
void CAppDialog::ChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
int mouse_x=(int)lparam;
int mouse_y=(int)dparam-m_subwin_Yoff;
//--- separate mouse events from others
switch(id)
{
case CHARTEVENT_CHART_CHANGE:
//--- assumed that the CHARTEVENT_CHART_CHANGE event can handle only the application dialog
break;
case CHARTEVENT_OBJECT_CLICK:
//--- we won't handle the CHARTEVENT_OBJECT_CLICK event, as we are working with the CHARTEVENT_MOUSE_MOVE events
return;
case CHARTEVENT_CUSTOM+ON_MOUSE_FOCUS_SET:
//--- the CHARTEVENT_CUSTOM + ON_MOUSE_FOCUS_SET event
if(CheckPointer(m_focused_wnd)!=POINTER_INVALID)
{
//--- if there is an element with focus, try to take its focus away
if(!m_focused_wnd.MouseFocusKill(lparam))
return;
}
m_focused_wnd=ControlFind(lparam);
return;
case CHARTEVENT_CUSTOM+ON_BRING_TO_TOP:
m_top_wnd=ControlFind(lparam);
return;
case CHARTEVENT_MOUSE_MOVE:
//--- the CHARTEVENT_MOUSE_MOVE event
if(CheckPointer(m_top_wnd)!=POINTER_INVALID)
{
//--- if a priority element already exists, pass control to it
if(m_top_wnd.OnMouseEvent(mouse_x,mouse_y,(int)StringToInteger(sparam)))
{
//--- event handled
m_chart.Redraw();
return;
}
}
if(OnMouseEvent(mouse_x,mouse_y,(int)StringToInteger(sparam)))
m_chart.Redraw();
return;
default:
//--- call event processing and redraw chart if event handled
if(OnEvent(id,lparam,dparam,sparam))
m_chart.Redraw();
return;
}
//--- if event was not handled, try to handle the CHARTEVENT_CHART_CHANGE event
if(id==CHARTEVENT_CHART_CHANGE)
{
//--- if subwindow number is not 0, and dialog subwindow has changed its number, then restart
if(m_subwin!=0 && m_subwin!=ChartWindowFind())
{
long fiction=1;
OnAnotherApplicationClose(fiction,dparam,sparam);
}
//--- if subwindow height is less that dialog height, minimize application window (always)
if(m_chart.HeightInPixels(m_subwin)<Height()+CONTROLS_BORDER_WIDTH)
{
m_button_minmax.Pressed(true);
Minimize();
m_chart.Redraw();
}
//--- if chart width is less that dialog width, and subwindow number is not 0, try to modify dialog width
if(m_chart.WidthInPixels()!=Width() && m_subwin!=0)
{
Width(m_chart.WidthInPixels());
m_chart.Redraw();
}
//--- get subwindow offset
SubwinOff();
return;
}
}
//+------------------------------------------------------------------+
//| Run application |
//+------------------------------------------------------------------+
bool CAppDialog::Run(void)
{
//--- redraw chart for dialog invalidate
m_chart.Redraw();
//--- here we begin to assign IDs to controls
if(Id(m_subwin*CONTROLS_MAXIMUM_ID)>CONTROLS_MAXIMUM_ID)
{
Print("CAppDialog: too many objects");
return(false);
}
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Stop application |
//+------------------------------------------------------------------+
void CAppDialog::OnClickButtonClose(void)
{
//--- destroy application
Destroy();
}
//+------------------------------------------------------------------+
//| Handler of click on the "Minimize/Maximize" button |
//+------------------------------------------------------------------+
void CAppDialog::OnClickButtonMinMax(void)
{
if(m_button_minmax.Pressed())
Minimize();
else
Maximize();
//--- get subwindow offset
SubwinOff();
}
//+------------------------------------------------------------------+
//| Resize |
//+------------------------------------------------------------------+
bool CAppDialog::Rebound(const CRect &rect)
{
if(!Move(rect.LeftTop()))
return(false);
if(!Size(rect.Size()))
return(false);
//--- resize subwindow
if(m_program_type==PROGRAM_INDICATOR && !IndicatorSetInteger(INDICATOR_HEIGHT,rect.Height()+1))
{
Print("CAppDialog: subwindow resize error");
return(false);
}
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Minimize dialog window |
//+------------------------------------------------------------------+
void CAppDialog::Minimize(void)
{
//--- set flag
m_minimized=true;
//--- resize
Rebound(m_min_rect);
//--- hide client area
ClientAreaVisible(false);
}
//+------------------------------------------------------------------+
//| Restore dialog window |
//+------------------------------------------------------------------+
void CAppDialog::Maximize(void)
{
//--- reset flag
m_minimized=false;
//--- resize
Rebound(m_norm_rect);
//--- show client area
ClientAreaVisible(true);
}
//+------------------------------------------------------------------+
//| Create unique prefix for object names |
//+------------------------------------------------------------------+
string CAppDialog::CreateInstanceId(void)
{
return(IntegerToString(rand(),5,'0'));
}
//+------------------------------------------------------------------+
//| Handler of the ON_APP_CLOSE external event |
//+------------------------------------------------------------------+
void CAppDialog::OnAnotherApplicationClose(const long &lparam,const double &dparam,const string &sparam)
{
//--- exit if we are in the main window
if(m_subwin==0)
return;
//--- exit if external program was closed in main window
if(lparam==0)
return;
//--- get subwindow offset
SubwinOff();
//--- exit if external program was closed in subwindow with greater number
if(lparam>=m_subwin)
return;
//--- after all the checks we must change the subwindow
//--- get the new number of subwindow
m_subwin=ChartWindowFind();
//--- change short name
m_indicator_name=m_program_name+IntegerToString(m_subwin);
IndicatorSetString(INDICATOR_SHORTNAME,m_indicator_name);
//--- change dialog title
Caption(m_program_name);
//--- reassign IDs
Run();
}
//+------------------------------------------------------------------+
//| Save the current state of the program |
//+------------------------------------------------------------------+
void CAppDialog::IniFileSave(void)
{
string filename=IniFileName()+IniFileExt();
int handle=FileOpen(filename,FILE_WRITE|FILE_BIN|FILE_ANSI);
//---
if(handle!=INVALID_HANDLE)
{
Save(handle);
FileClose(handle);
}
}
//+------------------------------------------------------------------+
//| Read the previous state of the program |
//+------------------------------------------------------------------+
void CAppDialog::IniFileLoad(void)
{
string filename=IniFileName()+IniFileExt();
int handle=FileOpen(filename,FILE_READ|FILE_BIN|FILE_ANSI);
//---
if(handle!=INVALID_HANDLE)
{
Load(handle);
FileClose(handle);
}
}
//+------------------------------------------------------------------+
//| Generate the filename |
//+------------------------------------------------------------------+
string CAppDialog::IniFileName(void) const
{
string name;
//---
name=(m_indicator_name!=NULL) ? m_indicator_name : m_program_name;
//---
name+="_"+Symbol();
name+="_Ini";
//---
return(name);
}
//+------------------------------------------------------------------+
//| Load data |
//+------------------------------------------------------------------+
bool CAppDialog::Load(const int file_handle)
{
if(CDialog::Load(file_handle))
{
if(m_minimized)
{
m_button_minmax.Pressed(true);
Minimize();
}
else
{
m_button_minmax.Pressed(false);
Maximize();
}
int prev_deinit_reason=FileReadInteger(file_handle);
if(prev_deinit_reason==REASON_CHARTCLOSE || prev_deinit_reason==REASON_CLOSE)
{
//--- if the previous time program ended after closing the chart window,
//--- delete object left since the last start of the program
string prev_instance_id=IntegerToString(FileReadInteger(file_handle),5,'0');
if(prev_instance_id!=m_instance_id)
{
long chart_id=m_chart.ChartId();
int total=ObjectsTotal(chart_id,m_subwin);
for(int i=total-1;i>=0;i--)
{
string obj_name=ObjectName(chart_id,i,m_subwin);
if(StringFind(obj_name,prev_instance_id)==0)
ObjectDelete(chart_id,obj_name);
}
}
}
return(true);
}
//--- failure
return(false);
}
//+------------------------------------------------------------------+
//| Save data |
//+------------------------------------------------------------------+
bool CAppDialog::Save(const int file_handle)
{
if(CDialog::Save(file_handle))
{
FileWriteInteger(file_handle,m_deinit_reason);
FileWriteInteger(file_handle,(int)StringToInteger(m_instance_id));
return(true);
}
//--- failure
return(false);
}
//+------------------------------------------------------------------+
+10
View File
@@ -0,0 +1,10 @@
//+------------------------------------------------------------------+
//| EAF.mqh |
//| Copyright 2022, Anatoli Kazharski |
//| https://www.mql5.com/ru/users/tol64 |
//+------------------------------------------------------------------+
// Unzip the archive you downloaded from the library page and
// place the library files in similar directories
//+------------------------------------------------------------------+
+43
View File
@@ -0,0 +1,43 @@
//+------------------------------------------------------------------+
//| EnumToArray.mqh |
//| Copyright (c) 2022, MetaQuotes Ltd. |
//| https://www.mql5.com/ |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Convert enum E elements into array of ints (correponding to IDs) |
//| Return number of elements in the enum E |
//+------------------------------------------------------------------+
template<typename E>
int EnumToArray(E /*dummy*/, int &values[],
const int start = INT_MIN, const int stop = INT_MAX)
{
const static string t = "::";
ArrayResize(values, 0);
int count = 0;
for(int i = start; i < stop && !IsStopped(); i++)
{
E e = (E)i;
if(StringFind(EnumToString(e), t) == -1)
{
ArrayResize(values, count + 1);
values[count++] = i;
}
}
return count;
}
//+------------------------------------------------------------------+
//| Shorthand version of enum E elements detection as array of ints |
//+------------------------------------------------------------------+
template<typename E>
int EnumToArray(int &values[],
const int start = INT_MIN, const int stop = INT_MAX)
{
static E e;
return EnumToArray(e, values, start, stop);
}
//+------------------------------------------------------------------+
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+144
View File
@@ -0,0 +1,144 @@
//+------------------------------------------------------------------+
//| License.mqh |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| defines |
//+------------------------------------------------------------------+
#define LICENSED_TRADE_MODES {ACCOUNT_TRADE_MODE_DEMO}//{ACCOUNT_TRADE_MODE_CONTEST,ACCOUNT_TRADE_MODE_DEMO}
#define LICENSED_EXPIRY_DATE D'2025.06.01'
#define LICENSED_EXPIRY_DAYS 30
#define LICENSED_EXPIRY_DATE_START D'2025.05.01'
#define LICENSED_EXPIRY_DATE_START_COMPILE_TIME __DATETIME__
#define LICENSED_PRIVATE_KEY "Activation Key E"
class License
{
protected:
string M_ProductName;
long m_AccountLogin;
int m_UserID;
datetime m_Expiry;
virtual string LicencePath();
bool FileGen(string data);
public:
License();
~License();
string GeneratePasscode(string data);
void ClinetProgram(string NameExpert, int UserID, datetime Expiry, long LoginAccount = -1);
};
License::License()
{
}
License::~License()
{
}
//+------------------------------------------------------------------+
//| DLL imports |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| EX5 imports |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| create hash |
//+------------------------------------------------------------------+
string License::GeneratePasscode(string data)
{
uchar dataChar[];
StringToCharArray( data, dataChar, 0, StringLen( data ) );
uchar cryptChar[];
CryptEncode( CRYPT_HASH_SHA256, dataChar, dataChar, cryptChar );
uchar resCharArray[];
ArrayResize(resCharArray, ArraySize(cryptChar));
ArrayCopy(resCharArray, cryptChar, 0, 0, ArraySize(cryptChar));
uchar base64Result[];
CryptEncode(CRYPT_BASE64, resCharArray, resCharArray, base64Result);
string result = CharArrayToString(base64Result);
return result;
}
//+------------------------------------------------------------------+
//| create file name to hash |
//+------------------------------------------------------------------+
string License::LicencePath() {return ("License\\"+M_ProductName+"\\"+GeneratePasscode(IntegerToString(m_AccountLogin)+"_"+IntegerToString(m_UserID))+"lic");}
//+------------------------------------------------------------------+
//| set to name prognam, login number, expirytion, user id |
//+------------------------------------------------------------------+
void License::ClinetProgram(string NameExpert, int UserID, datetime Expiry, long LoginAccount = -1)
{
if(LoginAccount < 0) {LoginAccount = AccountInfoInteger(ACCOUNT_LOGIN);}
m_AccountLogin = LoginAccount;
M_ProductName = NameExpert;
m_UserID = UserID;
m_Expiry = Expiry;
}
//+------------------------------------------------------------------+
//| create file to hash |
//+------------------------------------------------------------------+
bool License::FileGen(string data)
{
string licencePath = LicencePath();
int handle = FileOpen( licencePath, FILE_WRITE | FILE_BIN | FILE_ANSI );
if ( handle == INVALID_HANDLE ) {
PrintFormat( "Could not create licence file %s", licencePath );
return ( false );
}
return true;
}
+767
View File
@@ -0,0 +1,767 @@
//+------------------------------------------------------------------+
//| MatrixNet.mqh |
//| Copyright (c) 2023, Marketeer |
//| https://www.mql5.com/ru/articles/12187/ |
//+------------------------------------------------------------------+
#include <Graphics/Graphic.mqh>
#define PUSH(A,V) (A[ArrayResize(A, ArrayRange(A, 0) + 1, ArrayRange(A, 0) * 2) - 1] = V)
// In your source code you can enable RPROP mode (recommended)
// by placing the following macro in front of #include <MatrixNet.mqh>
//
// #define BATCH_PROP
//+------------------------------------------------------------------+
//| Main class for backpropagation NN on matrices |
//+------------------------------------------------------------------+
class MatrixNet
{
protected:
const int n; // number of layers with weights (excluding input layer)
matrix weights[/* n */];
matrix outputs[/* n + 1 */];
ENUM_ACTIVATION_FUNCTION af; // default activation function for all layers
ENUM_ACTIVATION_FUNCTION of; // output layer activation function (if specified)
bool ready;
int dropOutRate;
public:
// data stats and custom info
struct Stats
{
double bestLoss;
int bestEpoch;
int trainingSet;
int validationSet;
int epochsDone;
};
Stats getStats() const
{
return stats;
}
protected:
// save best weights every time we got new minimum of loss
matrix bestWeights[];
Stats stats;
#ifdef BATCH_PROP
matrix speed[];
matrix deltas[];
#else
double speed;
#endif
void allocate()
{
ArrayResize(weights, n);
ArrayResize(outputs, n + 1);
ArrayResize(bestWeights, n);
dropOutRate = 0;
#ifdef BATCH_PROP
ArrayResize(speed, n);
ArrayResize(deltas, n);
plus = 1.1;
minus = 0.1;
max = 50;
min = 0.0;
#endif
}
template<typename T>
struct SubArray
{
T data[];
};
class DropOutState
{
SubArray<uint> indices[];
matrix weights[];
const int percent;
public:
DropOutState(const int p = 10 /* subject of practical selection */): percent(p) { }
bool restoreState(matrix &parent[], const bool cleanup = true)
{
const int n = ArraySize(parent);
if(ArraySize(weights) == n)
{
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < ArraySize(indices[i].data); ++j)
{
parent[i].Flat(indices[i].data[j], weights[i].Flat(indices[i].data[j]));
}
if(cleanup) ArrayResize(indices[i].data, 0);
}
return true;
}
return false;
}
bool switchState(matrix &parent[])
{
const int n = ArraySize(parent);
if(ArraySize(weights) == 0)
{
ArrayResize(weights, n);
ArrayResize(indices, n);
}
else if(!restoreState(parent))
{
return false;
}
for(int i = 0; i < n; ++i)
{
weights[i].Assign(parent[i]); // save current state
const int m = (int)(parent[i].Rows() * parent[i].Cols());
int k = 0;
while(k++ < m * percent / 100)
{
const uint p = (rand() | (rand() << 16)) % m;
parent[i].Flat(p, 0);
PUSH(indices[i].data, p);
}
}
return true;
}
};
public:
MatrixNet(const int &layers[], const ENUM_ACTIVATION_FUNCTION f1 = AF_TANH,
const ENUM_ACTIVATION_FUNCTION f2 = AF_NONE):
ready(false), af(f1), of(f2), n(ArraySize(layers) - 1)
{
if(n < 2) return;
allocate();
for(int i = 1; i <= n; ++i)
{
// NB: weights are transposed, that is [row][column] hold [synapse][neuron]
weights[i - 1].Init(layers[i - 1] + 1, layers[i]);
#ifdef BATCH_PROP
speed[i - 1] = weights[i - 1];
deltas[i - 1] = weights[i - 1];
#endif
}
ready = true;
randomize();
}
MatrixNet(const matrix &w[], const ENUM_ACTIVATION_FUNCTION f1 = AF_TANH,
const ENUM_ACTIVATION_FUNCTION f2 = AF_NONE):
ready(false), af(f1), of(f2), n(ArraySize(w))
{
if(n < 2) return;
allocate();
for(int i = 0; i < n; ++i)
{
weights[i] = w[i];
#ifdef BATCH_PROP
speed[i] = weights[i];
deltas[i] = weights[i];
#endif
}
ready = true;
}
bool isReady() const
{
return ready;
}
void enableDropOut(const uint percent = 10 /* 0 means disable */)
{
dropOutRate = (int)percent;
}
void setActivationFunction(const ENUM_ACTIVATION_FUNCTION f1, ENUM_ACTIVATION_FUNCTION f2 = AF_NONE)
{
af = f1;
of = f2;
}
ENUM_ACTIVATION_FUNCTION getActivationFunction(const bool output = false) const
{
return output ? of : af;
}
bool getWeights(matrix &array[]) const
{
if(!ready) return false;
ArrayResize(array, n);
for(int i = 0; i < n; ++i)
{
array[i] = weights[i];
}
return true;
}
bool setWeights(matrix &array[])
{
if(!ready) return false;
if(ArraySize(array) != n)
{
PrintFormat("Number of layers mismatches: got %d, expected %d",
ArraySize(array), n);
return false;
}
for(int i = 0; i < n; ++i)
{
if(array[i].Rows() != weights[i].Rows()
|| array[i].Cols() != weights[i].Cols())
{
PrintFormat("%d-th layer dimensions mismatch: got %dx%d, expected %dx%d",
i, array[i].Rows(), array[i].Cols(), weights[i].Rows(), weights[i].Cols());
return false;
}
}
ArraySwap(array, weights);
return true;
}
bool getBestWeights(matrix &array[]) const
{
if(!ready) return false;
if(!n || !bestWeights[0].Rows()) return false;
ArrayResize(array, n);
for(int i = 0; i < n; ++i)
{
array[i] = bestWeights[i];
}
return true;
}
// NB: change values to appropriate distribution for specific activation function
void randomize(const double from = -0.5, const double to = +0.5)
{
if(!ready) return;
for(int i = 0; i < n; ++i)
{
weights[i].Random(from, to);
}
}
double train(const matrix &data, const matrix &target,
const matrix &validation, const matrix &check,
const int epochs = 1000, const double accuracy = 0.001,
const ENUM_LOSS_FUNCTION lf = LOSS_MSE)
{
if(!ready) return NaN();
#ifdef BATCH_PROP
for(int i = 0; i < n; ++i)
{
speed[i].Fill(accuracy); // will adjust the speeds on the fly
deltas[i].Fill(0);
}
#else
speed = accuracy;
#endif
double mse = DBL_MAX;
double msev = DBL_MAX;
double msema = 0; // averaged training MSE
double msemap = 0; // averaged training MSE on previous epoch
double msevma = 0; // averaged validation MSE
double msevmap = 0; // averaged validation MSE on previous epoch
double ema = 0; // exponentional averaging coefficient
int p = 0, grow = 0; // ema period
const int scale = (int)(data.Rows() / (validation.Rows() + 1)) + 1;
p = (int)sqrt(epochs); // FIXME: rule of thumb - reconsider as appropriate
ema = 2.0 / (p + 1);
PrintFormat("EMA for early stopping: %d (%f)", p, ema);
stats.bestLoss = DBL_MAX;
stats.bestEpoch = -1;
DropOutState state(dropOutRate);
int ep = 0;
for(; ep < epochs; ep++)
{
// NB: on each epoch entire dataset is processed as is,
// no batches or shuffling - implement yourself
if(validation.Rows() && check.Rows())
{
// if validation is enabled, run it before normal/training pass
msev = test(validation, check, lf);
// smooth error stat through epochs
msevma = (msevma ? msevma : msev) * (1 - ema) + ema * msev;
}
if(dropOutRate > 0)
{
state.restoreState(weights);
}
mse = test(data, target, lf); // invokes feedForward(data)
msema = (msema ? msema : mse) * (1 - ema) + ema * mse;
const double candidate = (msev != DBL_MAX) ? msev : mse;
if(candidate < stats.bestLoss)
{
stats.bestLoss = candidate;
stats.bestEpoch = ep;
// get all 'weights' (which can be partially dropped) into 'bestWeights'
for(int i = 0; i < n; ++i)
{
bestWeights[i].Assign(weights[i]);
}
}
if(!progress(ep, epochs, mse, msev, msema, msevma))
{
PrintFormat("Interrupted by user at epoch %d", ep);
break;
}
if(!MathIsValidNumber(mse))
{
PrintFormat("NaN at epoch %d", ep);
break; // will return NaN as error indication
}
if(ep > p && candidate > stats.bestLoss * 10)
{
PrintFormat("Too big errors at epoch %d", ep);
break;
}
if(msema > msemap)
{
if(++grow > p)
{
PrintFormat("Stop by growing error at epoch %d", ep);
break;
}
}
else
{
grow = 0;
}
if(msevmap != 0 && ep > p && msevma > msevmap + scale * (msemap - msema))
{
// skip first p epochs to accumulate values for smoothing
PrintFormat("Stop by validation at %d, v: %f > %f, t: %f vs %f", ep, msevma, msevmap, msema, msemap);
break;
}
msevmap = msevma;
msemap = msema;
if(mse <= accuracy)
{
PrintFormat("Done by accuracy limit %f at epoch %d", accuracy, ep);
break;
}
if(dropOutRate > 0)
{
state.switchState(weights);
}
if(!backProp(target))
{
mse = NaN(); // error flag
break;
}
}
if(ep == epochs)
{
PrintFormat("Done by epoch limit %d with accuracy %f", ep, mse);
}
stats.trainingSet = (int)data.Rows();
stats.validationSet = (int)validation.Rows();
stats.epochsDone = ep;
if(dropOutRate > 0) state.restoreState(weights);
return mse;
}
double train(const matrix &data, const matrix &target,
const int epochs = 1000, const double accuracy = 0.001,
const ENUM_LOSS_FUNCTION lf = LOSS_MSE)
{
matrix dummy = {}, fake = {};
return train(data, target, dummy, fake, epochs, accuracy, lf);
}
virtual bool progress(const int epoch, const int total,
const double error, const double valid = DBL_MAX,
const double ma = DBL_MAX, const double mav = DBL_MAX)
{
static uint trap;
if(GetTickCount() > trap) // by default log every second
{
PrintFormat("Epoch %d of %d, loss %.5f%s%s%s", epoch, total, error,
ma == DBL_MAX ? "" : StringFormat(" ma(%.5f)", ma),
valid == DBL_MAX ? "" : StringFormat(", validation %.5f", valid),
valid == DBL_MAX ? "" : StringFormat(" v.ma(%.5f)", mav));
trap = GetTickCount() + 1000;
}
return !IsStopped(); // true keeps running, false will break the training loop
}
bool feedForward(const matrix &data)
{
if(!ready) return false;
if(data.Cols() != weights[0].Rows() - 1)
{
PrintFormat("Column number in data %d <> Inputs layer size %d",
data.Cols(), weights[0].Rows() - 1);
return false;
}
outputs[0] = data;
for(int i = 0; i < n; ++i)
{
// extend each layer with 1 neuron for bias (except for the last layer)
if(!outputs[i].Resize(outputs[i].Rows(), weights[i].Rows()) ||
!outputs[i].Col(vector::Ones(outputs[i].Rows()), weights[i].Rows() - 1))
return false;
// propagate signal from i-th layer to (i+1)-th layer
matrix temp = outputs[i].MatMul(weights[i]);
if(!temp.Activation(outputs[i + 1], i < n - 1 ? af : of))
return false;
}
return true;
}
matrix getResults(const int layer = -1) const
{
static const matrix empty = {};
if(!ready) return empty;
if(layer == -1) return outputs[n];
if(layer < -1 || layer > n) return empty;
return outputs[layer];
}
/*
LEGEND for error (loss) backpropagation
last layer:
loss = (y - t) * derivative(y)
other layers:
loss = loss[y[+1]] * w'[y[+1]] * derivative(y)
update:
weight += niu * loss * y[-1]
where y is a neuron state in current layer, or
a reference to connected neuron
from previous layer y[-1] or next layer y[+1]
NB: lines marked by //* comprise a bugfix released after the article:
it turned out that the method Derivative() accepts input values of activation functions,
not output values of activation functions as it was initially supposed
*/
bool backProp(const matrix &target)
{
if(!ready) return false;
if(target.Rows() != outputs[n].Rows() ||
target.Cols() != outputs[n].Cols())
return false;
// output layer
matrix temp;
//*if(!outputs[n].Derivative(temp, of))
//* return false;
if(!outputs[n - 1].MatMul(weights[n - 1]).Derivative(temp, of))
return false;
matrix loss = (outputs[n] - target) * temp; // data record per row
for(int i = n - 1; i >= 0; --i) // for each layer except output
{
//*// remove unusable pseudo-errors for neurons, added as constant bias source
//*// (in all layers except for the last (where it wasn't added))
//*if(i < n - 1) loss.Resize(loss.Rows(), loss.Cols() - 1);
#ifdef BATCH_PROP
matrix delta = speed[i] * outputs[i].Transpose().MatMul(loss);
adjustSpeed(speed[i], delta * deltas[i]);
deltas[i] = delta;
#else
matrix delta = speed * outputs[i].Transpose().MatMul(loss);
#endif
// NB: i-th index in outputs[] corresponds to
// the layer of neurons defined by (i-1)-th index in weights[],
// because input layer (outputs[0]) does not have weights,
// in other words, weights[0] produce outputs[1],
// weights[1] produce outputs[2], etc.
//*if(!outputs[i].Derivative(temp, af))
//* return false;
//*loss = loss.MatMul(weights[i].Transpose()) * temp;
if(i > 0) // backpropagate loss to previous layers
{
if(!outputs[i - 1].MatMul(weights[i - 1]).Derivative(temp, af))
return false;
matrix mul = loss.MatMul(weights[i].Transpose());
// remove unusable pseudo-errors for neurons, added as constant bias source
// (in all layers except for the last (where it wasn't added))
mul.Resize(mul.Rows(), mul.Cols() - 1);
loss = mul * temp;
}
weights[i] -= delta;
}
return true;
}
double test(const matrix &data, const matrix &target, const ENUM_LOSS_FUNCTION lf = LOSS_MSE)
{
if(!ready || !feedForward(data)) return NaN();
return outputs[n].Loss(target, lf);
}
static double NaN() // used to signal an error packed in double
{
return MathArcsin(2.0); // usefull to trace a problem via breakpoint
}
#ifdef BATCH_PROP
void setupSpeedAdjustment(const double up, const double down,
const double high, const double low)
{
plus = up;
minus = down;
max = high;
min = low;
}
protected:
double plus;
double minus;
double max;
double min;
void adjustSpeed(matrix &subject, const matrix &product)
{
for(int i = 0; i < (int)product.Rows(); ++i)
{
for(int j = 0; j < (int)product.Cols(); ++j)
{
if(product[i][j] > 0)
{
subject[i][j] *= plus;
if(subject[i][j] > max) subject[i][j] = max;
}
else if(product[i][j] < 0)
{
subject[i][j] *= minus;
if(subject[i][j] < min) subject[i][j] = min;
}
}
}
}
#endif
};
//+------------------------------------------------------------------+
//| Helper custom graphic with published work area |
//+------------------------------------------------------------------+
class CGraphicView: public CGraphic
{
public:
int getRight() const
{
return m_right;
}
int getLeft() const
{
return m_left;
}
int getTop() const
{
return m_up;
}
int getBottom() const
{
return m_down;
}
};
//+-------------------------------------------------------------------+
//| Backpropagation NN on matrices with visualization of MSE progress |
//+-------------------------------------------------------------------+
class MatrixNetVisual: public MatrixNet
{
CGraphicView graphic;
CCurve *c[5];
double p[], x[], y[], z[], q[], b[];
const string objname;
const double nan;
double amplitude;
// prepare chart object for drawing
void graph()
{
ulong width = ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
ulong height = ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
bool res = false;
if(ObjectFind(0, objname) >= 0)
res = graphic.Attach(0, objname);
else
res = graphic.Create(0, objname, 0, 0, 0, (int)(width - 0), (int)(height - 0));
if(!res)
return;
c[0] = graphic.CurveAdd(p, x, CURVE_LINES, "Training");
c[1] = graphic.CurveAdd(p, y, CURVE_LINES, "Validation");
c[2] = graphic.CurveAdd(p, z, CURVE_LINES, "Val.EMA");
c[3] = graphic.CurveAdd(p, q, CURVE_LINES, "Train.EMA");
c[4] = graphic.CurveAdd(p, b, CURVE_POINTS, "Best/Minimum");
ArrayResize(b, 1);
amplitude = 0;
graphic.XAxis().AutoScale(false);
graphic.YAxis().AutoScale(false);
}
void plot()
{
c[0].Update(p, x);
c[1].Update(p, y);
c[2].Update(p, z);
c[3].Update(p, q);
double point[1] = {stats.bestEpoch};
b[0] = stats.bestLoss;
c[4].Update(point, b);
const int size = ArraySize(p) - 1;
graphic.CalculateMaxMinValues();
graphic.XAxis().Min(0);
graphic.YAxis().Min(0);
// find max values on the fly at every last added point
const double range = y[size] != DBL_MAX ? MathMax(y[size], x[size]) : x[size];
if(range > amplitude)
{
amplitude = range;
double ystep = MathPow(10, MathCeil(MathLog10(amplitude))) / 20;
if(ystep != 0 && amplitude / ystep < 5) ystep /= 2;
graphic.YAxis().Max(ystep != 0 ? ystep * (MathCeil(amplitude / ystep)) : 1);
graphic.YAxis().DefaultStep(ystep);
}
double xstep = MathPow(10, MathCeil(MathLog10(p[size]))) / 20;
if(xstep != 0 && p[size] / xstep < 5) xstep /= 2;
graphic.XAxis().Max(xstep != 0 ? xstep * (MathCeil(p[size] / xstep)) : 1);
graphic.XAxis().DefaultStep(xstep);
graphic.CurvePlotAll();
graphic.TextAdd(graphic.Width() - graphic.getRight() - 5, graphic.getTop() + 5,
"MSE error (Loss) by Epoch (Cycle)", clrBlack, TA_RIGHT | TA_TOP);
graphic.Update();
}
public:
MatrixNetVisual(const int &layers[], const ENUM_ACTIVATION_FUNCTION f1 = AF_TANH,
const ENUM_ACTIVATION_FUNCTION f2 = AF_NONE): MatrixNet(layers, f1, f2), objname("BPNNERROR"), nan(NaN())
{
graph();
}
MatrixNetVisual(const matrix &w[], const ENUM_ACTIVATION_FUNCTION f1 = AF_TANH,
const ENUM_ACTIVATION_FUNCTION f2 = AF_NONE): MatrixNet(w, f1, f2), objname("BPNNERROR"), nan(NaN())
{
graph();
}
~MatrixNetVisual()
{
if(!MQLInfoInteger(MQL_TESTER))
{
graphic.Destroy();
}
}
CGraphicView *view() const
{
return (CGraphicView *)&graphic;
}
virtual bool progress(const int epoch, const int total,
const double error, const double valid = DBL_MAX,
const double ma = DBL_MAX, const double mav = DBL_MAX) override
{
// accumulate and draw graph of error, valid, ma values
PUSH(p, epoch);
PUSH(x, error);
if(valid != DBL_MAX) PUSH(y, valid); else PUSH(y, nan);
if(ma != DBL_MAX) PUSH(q, ma); else PUSH(q, nan);
if(mav != DBL_MAX) PUSH(z, mav); else PUSH(z, nan);
plot();
return MatrixNet::progress(epoch, total, error, valid, ma, mav);
}
};
/* EXAMPLE:
bool CreateData(matrix &data, matrix &target, const int count)
{
if(!data.Init(count, 3) || !target.Init(count, 1)) return false;
data.Random(-10, 10);
vector X1 = MathPow(data.Col(0) + data.Col(1) + data.Col(2), 2);
vector X2 = MathPow(data.Col(0), 2) + MathPow(data.Col(1), 2) + MathPow(data.Col(2), 2);
if(!target.Col(X1 / X2 / 3, 0)) return false;
return true;
}
void OnStart()
{
const int layers[] = {3, 21, 15, 1};
MatrixNetVisual net(layers);
matrix data, target;
CreateData(data, target, 100);
matrix valid, test;
CreateData(valid, test, 25);
// NB: in practice you should normalize and clean up data from outliers
// before training (here we generate artificially ideal data)
Print(net.train(data, target, valid, test, 1000, 0.0001));
//Print(net.train(data, target, 1000, 0.00001));
matrix w[];
if(net.getBestWeights(w))
{
// for(int i = 0; i < ArraySize(w); ++i) Print(w[i]); // debug
MatrixNet net2(w);
if(net2.isReady())
{
Print("Copy: ", net2.test(data, target));
}
}
}
*/
//+-------------------------------------------------------------------+
+116
View File
@@ -0,0 +1,116 @@
//+------------------------------------------------------------------+
//| MatrixNetStore.mqh |
//| Copyright (c) 2023, Marketeer |
//| https://www.mql5.com/ru/articles/12187/ |
//+------------------------------------------------------------------+
#include "MatrixNet.mqh"
//+------------------------------------------------------------------+
//| General storage interface for custom data |
//+------------------------------------------------------------------+
class Storage
{
public:
virtual bool store(const int h) = 0;
virtual bool restore(const int h) = 0;
};
//+-----------------------------------------------------------------------+
//| MatrixNet writer/reader with the storage interface invocation. |
//| By default handles all internal data of NN (structure, size, weights) |
//+-----------------------------------------------------------------------+
class MatrixNetStore
{
static string signature;
public:
void static setSignature(const string s)
{
signature = s;
}
string static getSignature()
{
return signature;
}
template<typename M> // M is a MatrixNet
static M *load(const string filename, Storage *storage = NULL, const int flags = 0)
{
int h = FileOpen(filename, FILE_READ | FILE_BIN | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_ANSI | flags);
if(h == INVALID_HANDLE) return NULL;
const string header = FileReadString(h, StringLen(signature));
if(header != signature)
{
FileClose(h);
Print("Incorrect file header");
return NULL;
}
const ENUM_ACTIVATION_FUNCTION f1 = (ENUM_ACTIVATION_FUNCTION)FileReadInteger(h);
const ENUM_ACTIVATION_FUNCTION f2 = (ENUM_ACTIVATION_FUNCTION)FileReadInteger(h);
const int size = FileReadInteger(h);
matrix w[];
ArrayResize(w, size);
for(int i = 0; i < size; ++i)
{
const int rows = FileReadInteger(h);
const int cols = FileReadInteger(h);
double a[];
FileReadArray(h, a, 0, rows * cols);
w[i].Swap(a);
w[i].Reshape(rows, cols);
}
if(storage)
{
if(!storage.restore(h)) Print("External info wasn't read");
}
M *m = new M(w, f1, f2);
FileClose(h);
return m;
}
template<typename M> // M is a MatrixNet
static bool save(const string filename, const M &net, Storage *storage = NULL, const int flags = 0)
{
matrix w[];
if(!net.getBestWeights(w))
{
if(!net.getWeights(w))
{
return false;
}
}
int h = FileOpen(filename, FILE_WRITE | FILE_BIN | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_ANSI | flags);
if(h == INVALID_HANDLE) return false;
FileWriteString(h, signature);
FileWriteInteger(h, net.getActivationFunction());
FileWriteInteger(h, net.getActivationFunction(true));
FileWriteInteger(h, ArraySize(w));
for(int i = 0; i < ArraySize(w); ++i)
{
matrix m = w[i];
FileWriteInteger(h, (int)m.Rows());
FileWriteInteger(h, (int)m.Cols());
double a[];
m.Swap(a);
FileWriteArray(h, a);
}
if(storage)
{
if(!storage.store(h)) Print("External info wasn't saved");
}
FileClose(h);
return true;
}
};
static string MatrixNetStore::signature = "BPNNMS/1.0";
//+-----------------------------------------------------------------------+
+317
View File
@@ -0,0 +1,317 @@
//+------------------------------------------------------------------+
//| MovingAverages.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Simple Moving Average |
//+------------------------------------------------------------------+
double SimpleMA(const int position,const int period,const double &price[])
{
double result=0.0;
//--- check period
if(period>0 && period<=(position+1))
{
for(int i=0; i<period; i++)
result+=price[position-i];
result/=period;
}
return(result);
}
//+------------------------------------------------------------------+
//| Exponential Moving Average |
//+------------------------------------------------------------------+
double ExponentialMA(const int position,const int period,const double prev_value,const double &price[])
{
double result=0.0;
//--- check period
if(period>0)
{
double pr=2.0/(period+1.0);
result=price[position]*pr+prev_value*(1-pr);
}
return(result);
}
//+------------------------------------------------------------------+
//| Smoothed Moving Average |
//+------------------------------------------------------------------+
double SmoothedMA(const int position,const int period,const double prev_value,const double &price[])
{
double result=0.0;
//--- check period
if(period>0 && period<=(position+1))
{
if(position==period-1)
{
for(int i=0; i<period; i++)
result+=price[position-i];
result/=period;
}
result=(prev_value*(period-1)+price[position])/period;
}
return(result);
}
//+------------------------------------------------------------------+
//| Linear Weighted Moving Average |
//+------------------------------------------------------------------+
double LinearWeightedMA(const int position,const int period,const double &price[])
{
double result=0.0;
//--- check period
if(period>0 && period<=(position+1))
{
double sum =0.0;
int wsum=0;
for(int i=period; i>0; i--)
{
wsum+=i;
sum +=price[position-i+1]*(period-i+1);
}
result=sum/wsum;
}
return(result);
}
//+------------------------------------------------------------------+
//| Simple moving average on price array |
//+------------------------------------------------------------------+
int SimpleMAOnBuffer(const int rates_total,const int prev_calculated,const int begin,const int period,const double& price[],double& buffer[])
{
//--- check period
if(period<=1 || period>(rates_total-begin))
return(0);
//--- save as_series flags
bool as_series_price=ArrayGetAsSeries(price);
bool as_series_buffer=ArrayGetAsSeries(buffer);
ArraySetAsSeries(price,false);
ArraySetAsSeries(buffer,false);
//--- calculate start position
int start_position;
if(prev_calculated==0) // first calculation or number of bars was changed
{
//--- set empty value for first bars
start_position=period+begin;
for(int i=0; i<start_position-1; i++)
buffer[i]=0.0;
//--- calculate first visible value
double first_value=0;
for(int i=begin; i<start_position; i++)
first_value+=price[i];
buffer[start_position-1]=first_value/period;
}
else
start_position=prev_calculated-1;
//--- main loop
for(int i=start_position; i<rates_total; i++)
buffer[i]=buffer[i-1]+(price[i]-price[i-period])/period;
//--- restore as_series flags
ArraySetAsSeries(price,as_series_price);
ArraySetAsSeries(buffer,as_series_buffer);
//---
return(rates_total);
}
//+------------------------------------------------------------------+
//| Exponential moving average on price array |
//+------------------------------------------------------------------+
int ExponentialMAOnBuffer(const int rates_total,const int prev_calculated,const int begin,const int period,const double& price[],double& buffer[])
{
//--- check period
if(period<=1 || period>(rates_total-begin))
return(0);
//--- save and clear 'as_series' flags
bool as_series_price=ArrayGetAsSeries(price);
bool as_series_buffer=ArrayGetAsSeries(buffer);
ArraySetAsSeries(price,false);
ArraySetAsSeries(buffer,false);
//--- calculate start position
int start_position;
double smooth_factor=2.0/(1.0+period);
if(prev_calculated==0) // first calculation or number of bars was changed
{
//--- set empty value for first bars
for(int i=0; i<begin; i++)
buffer[i]=0.0;
//--- calculate first visible value
start_position=period+begin;
buffer[begin] =price[begin];
for(int i=begin+1; i<start_position; i++)
buffer[i]=price[i]*smooth_factor+buffer[i-1]*(1.0-smooth_factor);
}
else
start_position=prev_calculated-1;
//--- main loop
for(int i=start_position; i<rates_total; i++)
buffer[i]=price[i]*smooth_factor+buffer[i-1]*(1.0-smooth_factor);
//--- restore as_series flags
ArraySetAsSeries(price,as_series_price);
ArraySetAsSeries(buffer,as_series_buffer);
//---
return(rates_total);
}
//+------------------------------------------------------------------+
//| Linear weighted moving average on price array classic |
//+------------------------------------------------------------------+
int LinearWeightedMAOnBuffer(const int rates_total,const int prev_calculated,const int begin,const int period,const double& price[],double& buffer[])
{
//--- check period
if(period<=1 || period>(rates_total-begin))
return(0);
//--- save as_series flags
bool as_series_price=ArrayGetAsSeries(price);
bool as_series_buffer=ArrayGetAsSeries(buffer);
ArraySetAsSeries(price,false);
ArraySetAsSeries(buffer,false);
//--- calculate start position
int i,start_position;
if(prev_calculated<=period+begin+2) // first calculation or number of bars was changed
{
//--- set empty value for first bars
start_position=period+begin;
for(i=0; i<start_position; i++)
buffer[i]=0.0;
}
else
start_position=prev_calculated-2;
//--- calculate first visible value
double sum=0.0,lsum=0.0;
int l,weight=0;
for(i=start_position-period,l=1; i<start_position; i++,l++)
{
sum +=price[i]*l;
lsum +=price[i];
weight+=l;
}
buffer[start_position-1]=sum/weight;
//--- main loop
for(i=start_position; i<rates_total; i++)
{
sum =sum-lsum+price[i]*period;
lsum =lsum-price[i-period]+price[i];
buffer[i]=sum/weight;
}
//--- restore as_series flags
ArraySetAsSeries(price,as_series_price);
ArraySetAsSeries(buffer,as_series_buffer);
//---
return(rates_total);
}
//+------------------------------------------------------------------+
//| Linear weighted moving average on price array fast |
//+------------------------------------------------------------------+
int LinearWeightedMAOnBuffer(const int rates_total,const int prev_calculated,const int begin,const int period,const double& price[],double& buffer[],int &weight_sum)
{
//--- check period
if(period<=1 || period>(rates_total-begin))
return(0);
//--- save as_series flags
bool as_series_price=ArrayGetAsSeries(price);
bool as_series_buffer=ArrayGetAsSeries(buffer);
ArraySetAsSeries(price,false);
ArraySetAsSeries(buffer,false);
//--- calculate start position
int start_position;
if(prev_calculated==0) // first calculation or number of bars was changed
{
//--- set empty value for first bars
start_position=period+begin;
for(int i=0; i<start_position; i++)
buffer[i]=0.0;
//--- calculate first visible value
double first_value=0;
int wsum =0;
for(int i=begin,k=1; i<start_position; i++,k++)
{
first_value+=k*price[i];
wsum +=k;
}
buffer[start_position-1]=first_value/wsum;
weight_sum=wsum;
}
else
start_position=prev_calculated-1;
//--- main loop
for(int i=start_position; i<rates_total; i++)
{
double sum=0;
for(int j=0; j<period; j++)
sum+=(period-j)*price[i-j];
buffer[i]=sum/weight_sum;
}
//--- restore as_series flags
ArraySetAsSeries(price,as_series_price);
ArraySetAsSeries(buffer,as_series_buffer);
//---
return(rates_total);
}
//+------------------------------------------------------------------+
//| Smoothed moving average on price array |
//+------------------------------------------------------------------+
int SmoothedMAOnBuffer(const int rates_total,const int prev_calculated,const int begin,const int period,const double& price[],double& buffer[])
{
//--- check period
if(period<=1 || period>(rates_total-begin))
return(0);
//--- save as_series flags
bool as_series_price=ArrayGetAsSeries(price);
bool as_series_buffer=ArrayGetAsSeries(buffer);
ArraySetAsSeries(price,false);
ArraySetAsSeries(buffer,false);
//--- calculate start position
int start_position;
if(prev_calculated==0) // first calculation or number of bars was changed
{
//--- set empty value for first bars
start_position=period+begin;
for(int i=0; i<start_position-1; i++)
buffer[i]=0.0;
//--- calculate first visible value
double first_value=0;
for(int i=begin; i<start_position; i++)
first_value+=price[i];
buffer[start_position-1]=first_value/period;
}
else
start_position=prev_calculated-1;
//--- main loop
for(int i=start_position; i<rates_total; i++)
buffer[i]=(buffer[i-1]*(period-1)+price[i])/period;
//--- restore as_series flags
ArraySetAsSeries(price,as_series_price);
ArraySetAsSeries(buffer,as_series_buffer);
//---
return(rates_total);
}
//+------------------------------------------------------------------+
+33
View File
@@ -0,0 +1,33 @@
//+------------------------------------------------------------------+
//| Object.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include "StdLibErr.mqh"
//+------------------------------------------------------------------+
//| Class CObject. |
//| Purpose: Base class for storing elements. |
//+------------------------------------------------------------------+
class CObject
{
private:
CObject *m_prev; // previous item of list
CObject *m_next; // next item of list
public:
CObject(void): m_prev(NULL),m_next(NULL) { }
~CObject(void) { }
//--- methods to access protected data
CObject *Prev(void) const { return(m_prev); }
void Prev(CObject *node) { m_prev=node; }
CObject *Next(void) const { return(m_next); }
void Next(CObject *node) { m_next=node; }
//--- methods for working with files
virtual bool Save(const int file_handle) { return(true); }
virtual bool Load(const int file_handle) { return(true); }
//--- method of identifying the object
virtual int Type(void) const { return(0); }
//--- method of comparing the objects
virtual int Compare(const CObject *node,const int mode=0) const { return(0); }
};
//+------------------------------------------------------------------+
+10
View File
@@ -0,0 +1,10 @@
//+------------------------------------------------------------------+
//| StdLibErr.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#define ERR_USER_INVALID_HANDLE 1
#define ERR_USER_INVALID_BUFF_NUM 2
#define ERR_USER_ITEM_NOT_FOUND 3
#define ERR_USER_ARRAY_IS_EMPTY 1000
//+------------------------------------------------------------------+
BIN
View File
Binary file not shown.
+1592
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+200
View File
@@ -0,0 +1,200 @@
//+------------------------------------------------------------------+
//| VirtualKeys.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Virtual keys copied from winuser.h |
//+------------------------------------------------------------------+
//
// Virtual Keys, Standard Set
//
#define VK_LBUTTON 0x01
#define VK_RBUTTON 0x02
#define VK_CANCEL 0x03
#define VK_MBUTTON 0x04
#define VK_XBUTTON1 0x05
#define VK_XBUTTON2 0x06
// 0x07 : unassigned
#define VK_BACK 0x08
#define VK_TAB 0x09
// 0x0A - 0x0B : reserved
#define VK_CLEAR 0x0C
#define VK_RETURN 0x0D
#define VK_SHIFT 0x10
#define VK_CONTROL 0x11
#define VK_MENU 0x12
#define VK_PAUSE 0x13
#define VK_CAPITAL 0x14
#define VK_KANA 0x15
#define VK_HANGUL 0x15
#define VK_JUNJA 0x17
#define VK_FINAL 0x18
#define VK_HANJA 0x19
#define VK_KANJI 0x19
#define VK_ESCAPE 0x1B
#define VK_CONVERT 0x1C
#define VK_NONCONVERT 0x1D
#define VK_ACCEPT 0x1E
#define VK_MODECHANGE 0x1F
#define VK_SPACE 0x20
#define VK_PRIOR 0x21
#define VK_NEXT 0x22
#define VK_END 0x23
#define VK_HOME 0x24
#define VK_LEFT 0x25
#define VK_UP 0x26
#define VK_RIGHT 0x27
#define VK_DOWN 0x28
#define VK_SELECT 0x29
#define VK_PRINT 0x2A
#define VK_EXECUTE 0x2B
#define VK_SNAPSHOT 0x2C
#define VK_INSERT 0x2D
#define VK_DELETE 0x2E
#define VK_HELP 0x2F
// VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39)
// 0x40 : unassigned
// VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A)
#define VK_LWIN 0x5B
#define VK_RWIN 0x5C
#define VK_APPS 0x5D
// 0x5E : reserved
#define VK_SLEEP 0x5F
#define VK_NUMPAD0 0x60
#define VK_NUMPAD1 0x61
#define VK_NUMPAD2 0x62
#define VK_NUMPAD3 0x63
#define VK_NUMPAD4 0x64
#define VK_NUMPAD5 0x65
#define VK_NUMPAD6 0x66
#define VK_NUMPAD7 0x67
#define VK_NUMPAD8 0x68
#define VK_NUMPAD9 0x69
#define VK_MULTIPLY 0x6A
#define VK_ADD 0x6B
#define VK_SEPARATOR 0x6C
#define VK_SUBTRACT 0x6D
#define VK_DECIMAL 0x6E
#define VK_DIVIDE 0x6F
#define VK_F1 0x70
#define VK_F2 0x71
#define VK_F3 0x72
#define VK_F4 0x73
#define VK_F5 0x74
#define VK_F6 0x75
#define VK_F7 0x76
#define VK_F8 0x77
#define VK_F9 0x78
#define VK_F10 0x79
#define VK_F11 0x7A
#define VK_F12 0x7B
#define VK_F13 0x7C
#define VK_F14 0x7D
#define VK_F15 0x7E
#define VK_F16 0x7F
#define VK_F17 0x80
#define VK_F18 0x81
#define VK_F19 0x82
#define VK_F20 0x83
#define VK_F21 0x84
#define VK_F22 0x85
#define VK_F23 0x86
#define VK_F24 0x87
// 0x88 - 0x8F : unassigned
#define VK_NUMLOCK 0x90
#define VK_SCROLL 0x91
// 0x92 - 0x96 : OEM specific
// 0x97 - 0x9F : unassigned
#define VK_LSHIFT 0xA0
#define VK_RSHIFT 0xA1
#define VK_LCONTROL 0xA2
#define VK_RCONTROL 0xA3
#define VK_LMENU 0xA4
#define VK_RMENU 0xA5
#define VK_BROWSER_BACK 0xA6
#define VK_BROWSER_FORWARD 0xA7
#define VK_BROWSER_REFRESH 0xA8
#define VK_BROWSER_STOP 0xA9
#define VK_BROWSER_SEARCH 0xAA
#define VK_BROWSER_FAVORITES 0xAB
#define VK_BROWSER_HOME 0xAC
#define VK_VOLUME_MUTE 0xAD
#define VK_VOLUME_DOWN 0xAE
#define VK_VOLUME_UP 0xAF
#define VK_MEDIA_NEXT_TRACK 0xB0
#define VK_MEDIA_PREV_TRACK 0xB1
#define VK_MEDIA_STOP 0xB2
#define VK_MEDIA_PLAY_PAUSE 0xB3
#define VK_LAUNCH_MAIL 0xB4
#define VK_LAUNCH_MEDIA_SELECT 0xB5
#define VK_LAUNCH_APP1 0xB6
#define VK_LAUNCH_APP2 0xB7
// 0xB8 - 0xB9 : reserved
#define VK_OEM_1 0xBA
#define VK_OEM_PLUS 0xBB
#define VK_OEM_COMMA 0xBC
#define VK_OEM_MINUS 0xBD
#define VK_OEM_PERIOD 0xBE
#define VK_OEM_2 0xBF
#define VK_OEM_3 0xC0
// 0xC1 - 0xD7 : reserved
// 0xD8 - 0xDA : unassigned
#define VK_OEM_4 0xDB
#define VK_OEM_5 0xDC
#define VK_OEM_6 0xDD
#define VK_OEM_7 0xDE
#define VK_OEM_8 0xDF
// 0xE0 : reserved
// 0xE1 : OEM specific
#define VK_OEM_102 0xE2
// 0xE3 - 0xE4 : OEM specific
#define VK_PROCESSKEY 0xE5
// 0xE6 : OEM specific
#define VK_PACKET 0xE7
// 0xE8 : unassigned
// 0xE9 - 0xF5 : OEM specific
#define VK_ATTN 0xF6
#define VK_CRSEL 0xF7
#define VK_EXSEL 0xF8
#define VK_EREOF 0xF9
#define VK_PLAY 0xFA
#define VK_ZOOM 0xFB
#define VK_NONAME 0xFC
#define VK_PA1 0xFD
#define VK_OEM_CLEAR 0xFE
// 0xFF : reserved
//+------------------------------------------------------------------+
+28
View File
@@ -0,0 +1,28 @@
//+------------------------------------------------------------------+
//| errhandlingapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winnt.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
void RaiseException(uint exception_code,uint exception_flags,uint number_of_arguments,const ulong &arguments[]);
int UnhandledExceptionFilter(EXCEPTION_POINTERS &exception_info);
PVOID SetUnhandledExceptionFilter(PVOID top_level_exception_filter);
uint GetLastError(void);
void SetLastError(uint err_code);
uint GetErrorMode(void);
uint SetErrorMode(uint mode);
PVOID AddVectoredExceptionHandler(uint first,PVOID handler);
uint RemoveVectoredExceptionHandler(PVOID handle);
PVOID AddVectoredContinueHandler(uint first,PVOID handler);
uint RemoveVectoredContinueHandler(PVOID handle);
void RestoreLastError(uint err_code);
void RaiseFailFastException(EXCEPTION_RECORD &exception_record,CONTEXT &context_record,uint flags);
void FatalAppExitW(uint action,const string message_text);
uint GetThreadErrorMode(void);
int SetThreadErrorMode(uint new_mode,uint& old_mode);
#import
+146
View File
@@ -0,0 +1,146 @@
//+------------------------------------------------------------------+
//| fileapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
//---
enum STREAM_INFO_LEVELS
{
FindStreamInfoStandard,
FindStreamInfoMaxInfoLevel
};
//---
struct BY_HANDLE_FILE_INFORMATION
{
uint dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
uint dwVolumeSerialNumber;
uint nFileSizeHigh;
uint nFileSizeLow;
uint nNumberOfLinks;
uint nFileIndexHigh;
uint nFileIndexLow;
};
//---
struct CREATEFILE2_EXTENDED_PARAMETERS
{
uint dwSize;
uint dwFileAttributes;
uint dwFileFlags;
uint dwSecurityQosFlags;
PVOID lpSecurityAttributes;
HANDLE hTemplateFile;
};
//---
struct FILE_ATTRIBUTE_DATA
{
uint dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
uint nFileSizeHigh;
uint nFileSizeLow;
};
//---
struct FIND_STREAM_DATA
{
long StreamSize;
short cStreamName[MAX_PATH+36];
};
//---
struct FIND_DATAW
{
uint dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
uint nFileSizeHigh;
uint nFileSizeLow;
uint dwReserved0;
uint dwReserved1;
short cFileName[MAX_PATH];
short cAlternateFileName[14];
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int AreFileApisANSI(void);
int CompareFileTime(FILETIME &file_time1,FILETIME &file_time2);
int CreateDirectoryW(const string path_name,PVOID security_attributes);
HANDLE CreateFile2(const string file_name,uint desired_access,uint share_mode,uint creation_disposition,CREATEFILE2_EXTENDED_PARAMETERS &create_ex_params);
HANDLE CreateFileW(const string file_name,uint desired_access,uint share_mode,PVOID security_attributes,uint creation_disposition,uint flags_and_attributes,HANDLE template_file);
int DefineDosDeviceW(uint flags,const string device_name,const string target_path);
int DeleteFileW(const string file_name);
int DeleteVolumeMountPointW(const string volume_mount_point);
int FileTimeToLocalFileTime(FILETIME &file_time,FILETIME &local_file_time);
int FindClose(HANDLE find_file);
int FindCloseChangeNotification(HANDLE change_handle);
HANDLE FindFirstChangeNotificationW(const string path_name,int watch_subtree,uint notify_filter);
HANDLE FindFirstFileExW(const string file_name,FINDEX_INFO_LEVELS info_level_id,FIND_DATAW &find_file_data,FINDEX_SEARCH_OPS search_op,PVOID search_filter,uint additional_flags);
HANDLE FindFirstFileNameW(const string file_name,uint flags,uint &StringLength,ushort &LinkName[]);
HANDLE FindFirstFileW(const string file_name,FIND_DATAW &find_file_data);
HANDLE FindFirstStreamW(const string file_name,STREAM_INFO_LEVELS InfoLevel,FIND_STREAM_DATA &find_stream_data,uint flags);
HANDLE FindFirstVolumeW(ushort &volume_name[],uint &buffer_length);
int FindNextChangeNotification(HANDLE change_handle);
int FindNextFileNameW(HANDLE find_stream,uint &StringLength,ushort &LinkName[]);
int FindNextFileW(HANDLE find_file,FIND_DATAW &find_file_data);
int FindNextStreamW(HANDLE find_stream,FIND_STREAM_DATA &find_stream_data);
int FindNextVolumeW(HANDLE find_volume,ushort &volume_name[],uint &buffer_length);
int FindVolumeClose(HANDLE find_volume);
int FlushFileBuffers(HANDLE file);
uint GetCompressedFileSizeW(const string file_name,uint &file_size_high);
int GetDiskFreeSpaceExW(const string directory_name,ulong &free_bytes_available_to_caller,ulong &total_number_of_bytes,ulong &total_number_of_free_bytes);
int GetDiskFreeSpaceW(const string root_path_name,uint &sectors_per_cluster,uint &bytes_per_sector,uint &number_of_free_clusters,uint &total_number_of_clusters);
uint GetDriveTypeW(const string root_path_name);
int GetFileAttributesExW(const string file_name,GET_FILEEX_INFO_LEVELS info_level_id,FILE_ATTRIBUTE_DATA &file_information);
uint GetFileAttributesW(const string file_name);
int GetFileInformationByHandle(HANDLE file,BY_HANDLE_FILE_INFORMATION &file_information);
uint GetFileSize(HANDLE file,uint &file_size_high);
int GetFileSizeEx(HANDLE file,long &file_size);
int GetFileTime(HANDLE file,FILETIME &creation_time,FILETIME &last_access_time,FILETIME &last_write_time);
uint GetFileType(HANDLE file);
uint GetFinalPathNameByHandleW(HANDLE file,ushort &file_path[],uint file_path,uint flags);
uint GetFullPathNameW(const string file_name,uint buffer_length,ushort &buffer[],ushort &file_part[]);
uint GetLogicalDrives(void);
uint GetLogicalDriveStringsW(uint buffer_length,ushort &buffer[]);
uint GetLongPathNameW(const string short_path,string &long_path,uint buffer);
uint GetShortPathNameW(const string long_path,string &short_path,uint buffer);
uint GetTempFileNameW(const string path_name,const string prefix_string,uint unique,ushort &temp_file_name[]);
uint GetTempPathW(uint buffer_length,ushort &buffer[]);
int GetVolumeInformationByHandleW(HANDLE file,ushort &volume_name_buffer[],uint volume_name_size,uint &volume_serial_number,uint &maximum_component_length,uint &file_system_flags,ushort &file_system_name_buffer[],uint file_system_name_size);
int GetVolumeInformationW(const string root_path_name,ushort &volume_name_buffer[],uint volume_name_size,uint &volume_serial_number,uint &maximum_component_length,uint &file_system_flags,ushort &file_system_name_buffer[],uint file_system_name_size);
int GetVolumeNameForVolumeMountPointW(const string volume_mount_point,string volume_name,uint buffer_length);
int GetVolumePathNamesForVolumeNameW(const string volume_name,string volume_path_names,uint buffer_length,uint &return_length);
int GetVolumePathNameW(const string file_name,ushort &volume_path_name[],uint buffer_length);
int LocalFileTimeToFileTime(FILETIME &local_file_time,FILETIME &file_time);
int LockFile(HANDLE file,uint file_offset_low,uint file_offset_high,uint number_of_bytes_to_lock_low,uint number_of_bytes_to_lock_high);
int LockFileEx(HANDLE file,uint flags,uint reserved,uint number_of_bytes_to_lock_low,uint number_of_bytes_to_lock_high,OVERLAPPED &overlapped);
uint QueryDosDeviceW(const string device_name,ushort &target_path[],uint max);
int ReadFile(HANDLE file,ushort &buffer[],uint number_of_bytes_to_read,uint &number_of_bytes_read,OVERLAPPED &overlapped);
int ReadFile(HANDLE file,ushort &buffer[],uint number_of_bytes_to_read,uint &number_of_bytes_read,PVOID overlapped);
int ReadFileScatter(HANDLE file,FILE_SEGMENT_ELEMENT &segment_array[],uint number_of_bytes_to_read,uint &reserved,OVERLAPPED &overlapped);
int ReadFileScatter(HANDLE file,FILE_SEGMENT_ELEMENT &segment_array[],uint number_of_bytes_to_read,uint &reserved,PVOID overlapped);
int RemoveDirectoryW(const string path_name);
int SetEndOfFile(HANDLE file);
void SetFileApisToANSI(void);
void SetFileApisToOEM(void);
int SetFileAttributesW(const string file_name,uint file_attributes);
int SetFileInformationByHandle(HANDLE file,FILE_INFO_BY_HANDLE_CLASS FileInformationClass,FILE_INFO &file_information,uint buffer_size);
int SetFileIoOverlappedRange(HANDLE FileHandle,uchar &OverlappedRangeStart,uint Length);
uint SetFilePointer(HANDLE file,long distance_to_move,long &distance_to_move_high,uint move_method);
int SetFilePointerEx(HANDLE file,long distance_to_move,long &new_file_pointer,uint move_method);
int SetFileTime(HANDLE file,FILETIME &creation_time,FILETIME &last_access_time,FILETIME &last_write_time);
int SetFileValidData(HANDLE file,long ValidDataLength);
int UnlockFile(HANDLE file,uint file_offset_low,uint file_offset_high,uint number_of_bytes_to_unlock_low,uint number_of_bytes_to_unlock_high);
int UnlockFileEx(HANDLE file,uint reserved,uint number_of_bytes_to_unlock_low,uint number_of_bytes_to_unlock_high,OVERLAPPED &overlapped);
int WriteFile(HANDLE file,const ushort &buffer[],uint number_of_bytes_to_write,uint &number_of_bytes_written,OVERLAPPED &overlapped);
int WriteFile(HANDLE file,const ushort &buffer[],uint number_of_bytes_to_write,uint &number_of_bytes_written,PVOID overlapped);
int WriteFileGather(HANDLE file,FILE_SEGMENT_ELEMENT &segment_array[],uint number_of_bytes_to_write,uint &reserved,OVERLAPPED &overlapped);
int WriteFileGather(HANDLE file,FILE_SEGMENT_ELEMENT &segment_array[],uint number_of_bytes_to_write,uint &reserved,PVOID overlapped);
#import
//+------------------------------------------------------------------+
+21
View File
@@ -0,0 +1,21 @@
//+------------------------------------------------------------------+
//| handleapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int CloseHandle(HANDLE object);
int DuplicateHandle(HANDLE source_process_handle,HANDLE source_handle,HANDLE target_process_handle,HANDLE &target_handle,uint desired_access,int inherit_handle,uint options);
int GetHandleInformation(HANDLE object,uint& flags);
int SetHandleInformation(HANDLE object,uint mask,uint flags);
#import
#import "kernelbase.dll"
int CompareObjectHandles(HANDLE first_object_handle, HANDLE second_object_handle);
#import
//+------------------------------------------------------------------+
+47
View File
@@ -0,0 +1,47 @@
//+------------------------------------------------------------------+
//| libloaderapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
//---
struct ENUMUILANG
{
uint NumOfEnumUILang;
uint SizeOfEnumUIBuffer;
PVOID EnumUIBuffer;
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int DisableThreadLibraryCalls(HANDLE lib_module);
HANDLE FindResourceExW(HANDLE module,const string type,const string name,ushort language);
int FindStringOrdinal(uint find_string_ordinal_flags,const string string_source,int source,const string string_value,int value,int ignore_case);
int FreeLibrary(HANDLE lib_module);
void FreeLibraryAndExitThread(HANDLE lib_module,uint exit_code);
int FreeResource(HANDLE res_data);
uint GetModuleFileNameW(HANDLE module,ushort &filename[],uint size);
HANDLE GetModuleHandleW(const string module_name);
int GetModuleHandleExW(uint flags,const string module_name,HANDLE &module);
PVOID GetProcAddress(HANDLE module,uchar &proc_name[]);
HANDLE LoadLibraryExW(const string lib_file_name,HANDLE file,uint flags);
HANDLE LoadResource(HANDLE module,HANDLE res_info);
PVOID LockResource(HANDLE res_data);
uint SizeofResource(HANDLE module,HANDLE res_info);
PVOID AddDllDirectory(const string new_directory);
int RemoveDllDirectory(PVOID cookie);
int SetDefaultDllDirectories(uint directory_flags);
int EnumResourceLanguagesExW(HANDLE module,const string type,const string name,PVOID enum_func,long param,uint flags,ushort lang_id);
int EnumResourceNamesExW(HANDLE module,const string type,PVOID enum_func,long param,uint flags,ushort lang_id);
int EnumResourceTypesExW(HANDLE module,PVOID enum_func,long param,uint flags,ushort lang_id);
HANDLE FindResourceW(HANDLE module,const string name,const string type);
HANDLE LoadLibraryW(const string lib_file_name);
int EnumResourceNamesW(HANDLE module,const string type,PVOID enum_func,long param);
#import
#import "user32.dll"
int LoadStringW(HANDLE instance,uint id,string buffer,int buffer_max);
#import
//+------------------------------------------------------------------+
+85
View File
@@ -0,0 +1,85 @@
//+------------------------------------------------------------------+
//| memoryapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winnt.mqh>
//---
enum MEMORY_RESOURCE_NOTIFICATION_TYPE
{
LowMemoryResourceNotification,
HighMemoryResourceNotification
};
//---
enum OFFER_PRIORITY
{
VmOfferPriorityVeryLow=1,
VmOfferPriorityLow,
VmOfferPriorityBelowNormal,
VmOfferPriorityNormal
};
//---
enum WIN32_MEMORY_INFORMATION_CLASS
{
MemoryRegionInfo
};
//---
struct WIN32_MEMORY_RANGE_ENTRY
{
PVOID VirtualAddress;
ulong NumberOfBytes;
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int AllocateUserPhysicalPages(HANDLE hProcess,ulong &NumberOfPages,ulong &PageArray[]);
int AllocateUserPhysicalPagesNuma(HANDLE hProcess,ulong &NumberOfPages,ulong &PageArray[],uint nndPreferred);
HANDLE CreateFileMappingFromApp(HANDLE hFile,PVOID SecurityAttributes,uint PageProtection,ulong MaximumSize,const string Name);
HANDLE CreateFileMappingNumaW(HANDLE hFile,PVOID lpFileMappingAttributes,uint flProtect,uint dwMaximumSizeHigh,uint dwMaximumSizeLow,const string lpName,uint nndPreferred);
HANDLE CreateFileMappingW(HANDLE hFile,PVOID lpFileMappingAttributes,uint flProtect,uint dwMaximumSizeHigh,uint dwMaximumSizeLow,const string lpName);
HANDLE CreateMemoryResourceNotification(MEMORY_RESOURCE_NOTIFICATION_TYPE NotificationType);
uint DiscardVirtualMemory(PVOID VirtualAddress,ulong Size);
int FlushViewOfFile(const PVOID lpBaseAddress,ulong dwNumberOfBytesToFlush);
int FreeUserPhysicalPages(HANDLE hProcess,ulong &NumberOfPages,ulong &PageArray[]);
ulong GetLargePageMinimum(void);
int GetMemoryErrorHandlingCapabilities(uint &Capabilities);
int GetProcessWorkingSetSizeEx(HANDLE hProcess,ulong &lpMinimumWorkingSetSize,ulong &lpMaximumWorkingSetSize,uint &Flags);
int GetSystemFileCacheSize(ulong &lpMinimumFileCacheSize,ulong &lpMaximumFileCacheSize,uint &lpFlags);
uint GetWriteWatch(uint dwFlags,PVOID lpBaseAddress,ulong dwRegionSize,PVOID &lpAddresses[],uint &lpdwCount,uint &lpdwGranularity);
int MapUserPhysicalPages(PVOID VirtualAddress,ulong &NumberOfPages,ulong &PageArray[]);
PVOID MapViewOfFile(HANDLE hFileMappingObject,uint dwDesiredAccess,uint dwFileOffsetHigh,uint dwFileOffsetLow,ulong dwNumberOfBytesToMap);
PVOID MapViewOfFileEx(HANDLE hFileMappingObject,uint dwDesiredAccess,uint dwFileOffsetHigh,uint dwFileOffsetLow,ulong dwNumberOfBytesToMap,PVOID lpBaseAddress);
PVOID MapViewOfFileFromApp(HANDLE hFileMappingObject,uint DesiredAccess,ulong FileOffset,ulong NumberOfBytesToMap);
uint OfferVirtualMemory(PVOID VirtualAddress,ulong Size,OFFER_PRIORITY Priority);
HANDLE OpenFileMappingW(uint dwDesiredAccess,int bInheritHandle,const string lpName);
int PrefetchVirtualMemory(HANDLE hProcess,uint &NumberOfEntries,WIN32_MEMORY_RANGE_ENTRY &VirtualAddresses,uint Flags);
int QueryMemoryResourceNotification(HANDLE ResourceNotificationHandle,int &ResourceState);
int ReadProcessMemory(HANDLE hProcess,const PVOID lpBaseAddress,PVOID lpBuffer,ulong nSize,ulong &lpNumberOfBytesRead);
uint ReclaimVirtualMemory(const PVOID VirtualAddress,ulong Size);
PVOID RegisterBadMemoryNotification(PVOID Callback);
uint ResetWriteWatch(PVOID lpBaseAddress,ulong dwRegionSize);
int SetProcessWorkingSetSizeEx(HANDLE hProcess,ulong dwMinimumWorkingSetSize,ulong dwMaximumWorkingSetSize,uint Flags);
int SetSystemFileCacheSize(ulong MinimumFileCacheSize,ulong MaximumFileCacheSize,uint Flags);
int UnmapViewOfFile(const PVOID lpBaseAddress);
int UnmapViewOfFileEx(PVOID BaseAddress,uint UnmapFlags);
int UnregisterBadMemoryNotification(PVOID RegistrationHandle);
PVOID VirtualAlloc(PVOID lpAddress,ulong dwSize,uint flAllocationType,uint flProtect);
PVOID VirtualAllocEx(HANDLE hProcess,PVOID lpAddress,ulong dwSize,uint flAllocationType,uint flProtect);
PVOID VirtualAllocExNuma(HANDLE hProcess,PVOID lpAddress,ulong dwSize,uint flAllocationType,uint flProtect,uint nndPreferred);
int VirtualFree(PVOID lpAddress,ulong dwSize,uint dwFreeType);
int VirtualFreeEx(HANDLE hProcess,PVOID lpAddress,ulong dwSize,uint dwFreeType);
int VirtualLock(PVOID lpAddress,ulong dwSize);
int VirtualProtect(PVOID lpAddress,ulong dwSize,uint flNewProtect,uint &lpflOldProtect);
int VirtualProtectEx(HANDLE hProcess,PVOID lpAddress,ulong dwSize,uint flNewProtect,uint &lpflOldProtect);
ulong VirtualQuery(const PVOID lpAddress,MEMORY_BASIC_INFORMATION &lpBuffer,ulong dwLength);
ulong VirtualQueryEx(HANDLE hProcess,const PVOID lpAddress,MEMORY_BASIC_INFORMATION &lpBuffer,ulong dwLength);
int VirtualUnlock(PVOID lpAddress,ulong dwSize);
int WriteProcessMemory(HANDLE hProcess,PVOID lpBaseAddress,PVOID lpBuffer,ulong nSize,ulong &lpNumberOfBytesWritten);
int WriteProcessMemory(HANDLE hProcess,PVOID lpBaseAddress,uchar &lpBuffer[],ulong nSize,ulong &lpNumberOfBytesWritten);
int WriteProcessMemory(HANDLE hProcess,uchar &lpBaseAddress[],PVOID lpBuffer,ulong nSize,ulong &lpNumberOfBytesWritten);
int WriteProcessMemory(HANDLE hProcess,uchar &lpBaseAddress[],uchar &lpBuffer[],ulong nSize,ulong &lpNumberOfBytesWritten);
#import
//+------------------------------------------------------------------+
+27
View File
@@ -0,0 +1,27 @@
//+------------------------------------------------------------------+
//| processenv.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int SetEnvironmentStringsW(string new_environment);
HANDLE GetStdHandle(uint std_handle);
int SetStdHandle(uint std_handle,HANDLE handle);
int SetStdHandleEx(uint std_handle,HANDLE handle,HANDLE &prev_value);
string GetCommandLineW(void);
string GetEnvironmentStringsW(void);
int FreeEnvironmentStringsW(string v);
uint GetEnvironmentVariableW(const string name,ushort &buffer[],uint size);
int SetEnvironmentVariableW(const string name,const string value);
uint ExpandEnvironmentStringsW(const string src,string dst,uint size);
int SetCurrentDirectoryW(const string path_name);
uint GetCurrentDirectoryW(uint buffer_length,ushort &buffer[]);
uint GetCurrentDirectoryW(uint buffer_length,string &buffer);
uint SearchPathW(const string path,const string file_name,const string extension,uint buffer_length,ushort &buffer[],string &file_part);
int NeedCurrentDirectoryForExePathW(const string exe_name);
#import
+202
View File
@@ -0,0 +1,202 @@
//+------------------------------------------------------------------+
//| processthreadsapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winnt.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//---
enum THREAD_INFORMATION_CLASS
{
ThreadMemoryPriority,
ThreadAbsoluteCpuPriority,
ThreadDynamicCodePolicy,
ThreadPowerThrottling,
ThreadInformationClassMax
};
//---
enum PROCESS_INFORMATION_CLASS
{
ProcessMemoryPriority,
ProcessMemoryExhaustionInfo,
ProcessAppMemoryInfo,
ProcessInPrivateInfo,
ProcessPowerThrottling,
ProcessReservedValue1,
ProcessTelemetryCoverageInfo,
ProcessProtectionLevelInfo,
ProcessInformationClassMax
};
//---
enum PROCESS_MEMORY_EXHAUSTION_TYPE
{
PMETypeFailFastOnCommitFailure,
PMETypeMax
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//---
struct PROCESS_INFORMATION
{
HANDLE hProcess;
HANDLE hThread;
uint dwProcessId;
uint dwThreadId;
};
//---
struct STARTUPINFOW
{
uint cb;
string lpReserved;
string lpDesktop;
string lpTitle;
uint dwX;
uint dwY;
uint dwXSize;
uint dwYSize;
uint dwXCountChars;
uint dwYCountChars;
uint dwFillAttribute;
uint dwFlags;
ushort wShowWindow;
ushort cbReserved2;
PVOID lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
};
//---
struct MEMORY_PRIORITY_INFORMATION
{
uint MemoryPriority;
};
//---
struct THREAD_POWER_THROTTLING_STATE
{
uint Version;
uint ControlMask;
uint StateMask;
};
//---
struct APP_MEMORY_INFORMATION
{
ulong AvailableCommit;
ulong PrivateCommitUsage;
ulong PeakPrivateCommitUsage;
ulong TotalCommitUsage;
};
//---
struct PROCESS_MEMORY_EXHAUSTION_INFO
{
ushort Version;
ushort Reserved;
PROCESS_MEMORY_EXHAUSTION_TYPE Type;
ulong Value;
};
//---
struct PROCESS_POWER_THROTTLING_STATE
{
uint Version;
uint ControlMask;
uint StateMask;
};
//---
struct PROCESS_PROTECTION_LEVEL_INFORMATION
{
uint ProtectionLevel;
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
uint QueueUserAPC(PVOID apc,HANDLE thread,ulong data);
int GetProcessTimes(HANDLE process,FILETIME &creation_time,FILETIME &exit_time,FILETIME &kernel_time,FILETIME &user_time);
HANDLE GetCurrentProcess(void);
uint GetCurrentProcessId(void);
void ExitProcess(uint exit_code);
int TerminateProcess(HANDLE process,uint exit_code);
int GetExitCodeProcess(HANDLE process,uint &exit_code);
int SwitchToThread(void);
HANDLE CreateThread(PVOID thread_attributes,ulong stack_size,PVOID start_address,PVOID parameter,uint creation_flags,uint &thread_id);
HANDLE CreateRemoteThread(HANDLE process,PVOID thread_attributes,ulong stack_size,PVOID start_address,PVOID parameter,uint creation_flags,uint &thread_id);
HANDLE GetCurrentThread(void);
uint GetCurrentThreadId(void);
HANDLE OpenThread(uint desired_access,int inherit_handle,uint thread_id);
int SetThreadPriority(HANDLE thread,int priority);
int SetThreadPriorityBoost(HANDLE thread,int disable_priority_boost);
int GetThreadPriorityBoost(HANDLE thread,int &disable_priority_boost);
int GetThreadPriority(HANDLE thread);
void ExitThread(uint exit_code);
int TerminateThread(HANDLE thread,uint exit_code);
int GetExitCodeThread(HANDLE thread,uint &exit_code);
uint SuspendThread(HANDLE thread);
uint ResumeThread(HANDLE thread);
uint TlsAlloc(void);
PVOID TlsGetValue(uint tls_index);
int TlsSetValue(uint tls_index,PVOID tls_value);
int TlsFree(uint tls_index);
int CreateProcessW(const string application_name,string command_line,PVOID process_attributes,PVOID thread_attributes,int inherit_handles,uint creation_flags,PVOID environment,const string current_directory,STARTUPINFOW &startup_info,PROCESS_INFORMATION &process_information);
int SetProcessShutdownParameters(uint level,uint flags);
uint GetProcessVersion(uint process_id);
void GetStartupInfoW(STARTUPINFOW &startup_info);
int SetPriorityClass(HANDLE process,uint priority_class);
uint GetPriorityClass(HANDLE process);
int SetThreadStackGuarantee(ulong stack_size_in_bytes);
int ProcessIdToSessionId(uint process_id,uint &session_id);
uint GetProcessId(HANDLE process);
uint GetThreadId(HANDLE thread);
void FlushProcessWriteBuffers(void);
uint GetProcessIdOfThread(HANDLE thread);
int InitializeProcThreadAttributeList(PVOID attribute_list,uint attribute_count,uint flags,ulong &size);
void DeleteProcThreadAttributeList(PVOID attribute_list);
int SetProcessAffinityUpdateMode(HANDLE process,uint flags);
int QueryProcessAffinityUpdateMode(HANDLE process,uint &flags);
int UpdateProcThreadAttribute(PVOID attribute_list,uint flags,uint attribute,PVOID value,ulong size,PVOID previous_value,ulong &return_size);
HANDLE CreateRemoteThreadEx(HANDLE process,PVOID thread_attributes,ulong stack_size,PVOID start_address,PVOID parameter,uint creation_flags,PVOID attribute_list,uint &thread_id);
void GetCurrentThreadStackLimits(ulong &low_limit,ulong &high_limit);
int GetThreadContext(HANDLE thread,CONTEXT &context);
int GetProcessMitigationPolicy(HANDLE process,PROCESS_MITIGATION_POLICY mitigation_policy,PVOID buffer,ulong length);
int SetThreadContext(HANDLE thread,const CONTEXT &context);
int SetProcessMitigationPolicy(PROCESS_MITIGATION_POLICY mitigation_policy,PVOID buffer,ulong length);
int FlushInstructionCache(HANDLE process,const PVOID base_address,ulong size);
int GetThreadTimes(HANDLE thread,FILETIME &creation_time,FILETIME &exit_time,FILETIME &kernel_time,FILETIME &user_time);
HANDLE OpenProcess(uint desired_access,int inherit_handle,uint process_id);
int IsProcessorFeaturePresent(uint processor_feature);
int GetProcessHandleCount(HANDLE process,uint &handle_count);
uint GetCurrentProcessorNumber(void);
int SetThreadIdealProcessorEx(HANDLE thread,PROCESSOR_NUMBER &ideal_processor,PROCESSOR_NUMBER &previous_ideal_processor);
int GetThreadIdealProcessorEx(HANDLE thread,PROCESSOR_NUMBER &ideal_processor);
void GetCurrentProcessorNumberEx(PROCESSOR_NUMBER &proc_number);
int GetProcessPriorityBoost(HANDLE process,int &disable_priority_boost);
int SetProcessPriorityBoost(HANDLE process,int disable_priority_boost);
int GetThreadIOPendingFlag(HANDLE thread,int &io_is_pending);
int GetSystemTimes(FILETIME &idle_time,FILETIME &kernel_time,FILETIME &user_time);
int GetThreadInformation(HANDLE thread,THREAD_INFORMATION_CLASS thread_information_class,PVOID thread_information,uint thread_information_size);
int SetThreadInformation(HANDLE thread,THREAD_INFORMATION_CLASS thread_information_class,PVOID thread_information,uint thread_information_size);
int IsProcessCritical(HANDLE process,int &critical);
int SetProtectedPolicy(const GUID &policy_guid,ulong policy_value,ulong &old_policy_value);
int QueryProtectedPolicy(const GUID &policy_guid,ulong &policy_value);
uint SetThreadIdealProcessor(HANDLE thread,uint ideal_processor);
int SetProcessInformation(HANDLE process,PROCESS_INFORMATION_CLASS process_information_class,PVOID process_information,uint process_information_size);
int GetProcessInformation(HANDLE process,PROCESS_INFORMATION_CLASS process_information_class,PVOID process_information,uint process_information_size);
int GetSystemCpuSetInformation(SYSTEM_CPU_SET_INFORMATION &information,uint buffer_length,ulong returned_length,HANDLE process,uint flags);
int GetProcessDefaultCpuSets(HANDLE process,ulong &cpu_set_ids,uint cpu_set_id_count,ulong required_id_count);
int SetProcessDefaultCpuSets(HANDLE process,const uint &cpu_set_ids,uint cpu_set_id_count);
int GetThreadSelectedCpuSets(HANDLE thread,ulong &cpu_set_ids,uint cpu_set_id_count,ulong required_id_count);
int SetThreadSelectedCpuSets(HANDLE thread,const uint &cpu_set_ids,uint cpu_set_id_count);
int GetProcessShutdownParameters(uint &level,uint &flags);
int SetThreadDescription(HANDLE thread,const string thread_description);
int GetThreadDescription(HANDLE thread,string &thread_description);
#import
#import "advapi32.dll"
int CreateProcessAsUserW(HANDLE token,const string application_name,string command_line,PVOID process_attributes,PVOID thread_attributes,int inherit_handles,uint creation_flags,PVOID environment,const string current_directory,STARTUPINFOW &startup_info,PROCESS_INFORMATION &process_information);
int SetThreadToken(HANDLE thread,HANDLE token);
int OpenProcessToken(HANDLE process_handle,uint desired_access,HANDLE &token_handle);
int OpenThreadToken(HANDLE thread_handle,uint desired_access,int open_as_self,HANDLE &token_handle);
#import
//+------------------------------------------------------------------+
+119
View File
@@ -0,0 +1,119 @@
//+------------------------------------------------------------------+
//| securitybaseapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winnt.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "advapi32.dll"
int AccessCheck(SECURITY_DESCRIPTOR &security_descriptor,HANDLE client_token,uint desired_access,GENERIC_MAPPING &generic_mapping,PRIVILEGE_SET &privilege_set,uint &privilege_set_length,uint &granted_access,int &access_status);
int AccessCheckAndAuditAlarmW(const string subsystem_name,PVOID handle_id,string object_type_name,string object_name,SECURITY_DESCRIPTOR &security_descriptor,uint desired_access,GENERIC_MAPPING &generic_mapping,int object_creation,uint &granted_access,int &access_status,int &generate_on_close);
int AccessCheckByType(SECURITY_DESCRIPTOR &security_descriptor,SID &principal_self_sid,HANDLE client_token,uint desired_access,OBJECT_TYPE_LIST &object_type_list,uint object_type_list_length,GENERIC_MAPPING &generic_mapping,PRIVILEGE_SET &privilege_set,uint &privilege_set_length,uint &granted_access,int &access_status);
int AccessCheckByTypeResultList(SECURITY_DESCRIPTOR &security_descriptor,SID &principal_self_sid,HANDLE client_token,uint desired_access,OBJECT_TYPE_LIST &object_type_list,uint object_type_list_length,GENERIC_MAPPING &generic_mapping,PRIVILEGE_SET &privilege_set,uint &privilege_set_length,uint &granted_access_list,uint &access_status_list);
int AccessCheckByTypeAndAuditAlarmW(const string subsystem_name,PVOID handle_id,const string object_type_name,const string object_name,SECURITY_DESCRIPTOR &security_descriptor,SID &principal_self_sid,uint desired_access,AUDIT_EVENT_TYPE audit_type,uint flags,OBJECT_TYPE_LIST &object_type_list,uint object_type_list_length,GENERIC_MAPPING &generic_mapping,int object_creation,uint &granted_access,int &access_status,int &generate_on_close);
int AccessCheckByTypeResultListAndAuditAlarmW(const string subsystem_name,PVOID handle_id,const string object_type_name,const string object_name,SECURITY_DESCRIPTOR &security_descriptor,SID &principal_self_sid,uint desired_access,AUDIT_EVENT_TYPE audit_type,uint flags,OBJECT_TYPE_LIST &object_type_list,uint object_type_list_length,GENERIC_MAPPING &generic_mapping,int object_creation,uint &granted_access_list,uint &access_status_list,int &generate_on_close);
int AccessCheckByTypeResultListAndAuditAlarmByHandleW(const string subsystem_name,PVOID handle_id,HANDLE client_token,const string object_type_name,const string object_name,SECURITY_DESCRIPTOR &security_descriptor,SID &principal_self_sid,uint desired_access,AUDIT_EVENT_TYPE audit_type,uint flags,OBJECT_TYPE_LIST &object_type_list,uint object_type_list_length,GENERIC_MAPPING &generic_mapping,int object_creation,uint &granted_access_list,uint &access_status_list,int &generate_on_close);
int AddAccessAllowedAce(ACL &acl,uint ace_revision,uint access_mask,SID &sid);
int AddAccessAllowedAceEx(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,SID &sid);
int AddAccessAllowedObjectAce(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,GUID &object_type_guid,GUID &inherited_object_type_guid,SID &sid);
int AddAccessDeniedAce(ACL &acl,uint ace_revision,uint access_mask,SID &sid);
int AddAccessDeniedAceEx(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,SID &sid);
int AddAccessDeniedObjectAce(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,GUID &object_type_guid,GUID &inherited_object_type_guid,SID &sid);
int AddAce(ACL &acl,uint ace_revision,uint starting_ace_index,PVOID ace_list,uint ace_list_length);
int AddAuditAccessAce(ACL &acl,uint ace_revision,uint access_mask,SID &sid,int audit_success,int audit_failure);
int AddAuditAccessAceEx(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,SID &sid,int audit_success,int audit_failure);
int AddAuditAccessObjectAce(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,GUID &object_type_guid,GUID &inherited_object_type_guid,SID &sid,int audit_success,int audit_failure);
int AddMandatoryAce(ACL &acl,uint ace_revision,uint ace_flags,uint mandatory_policy,SID &label_sid);
int AdjustTokenGroups(HANDLE token_handle,int reset_to_default,TOKEN_GROUPS &new_state,uint buffer_length,TOKEN_GROUPS &previous_state,uint &return_length);
int AdjustTokenPrivileges(HANDLE token_handle,int disable_all_privileges,TOKEN_PRIVILEGES &new_state,uint buffer_length,TOKEN_PRIVILEGES &previous_state,uint &return_length);
int AllocateAndInitializeSid(SID_IDENTIFIER_AUTHORITY &identifier_authority,uchar sub_authority_count,uint sub_authority0,uint sub_authority1,uint sub_authority2,uint sub_authority3,uint sub_authority4,uint sub_authority5,uint sub_authority6,uint sub_authority7,SID &sid);
int AllocateLocallyUniqueId(LUID &luid);
int AreAllAccessesGranted(uint granted_access,uint desired_access);
int AreAnyAccessesGranted(uint granted_access,uint desired_access);
int CheckTokenMembership(HANDLE token_handle,SID &sid_to_check,int &is_member);
int ConvertToAutoInheritPrivateObjectSecurity(SECURITY_DESCRIPTOR &parent_descriptor,SECURITY_DESCRIPTOR &current_security_descriptor,SECURITY_DESCRIPTOR &new_security_descriptor,GUID &object_type,uchar is_directory_object,GENERIC_MAPPING &generic_mapping);
int CopySid(uint destination_sid_length,SID &destination_sid,SID &source_sid);
int CreatePrivateObjectSecurity(SECURITY_DESCRIPTOR &parent_descriptor,SECURITY_DESCRIPTOR &creator_descriptor,SECURITY_DESCRIPTOR &new_descriptor,int is_directory_object,HANDLE token,GENERIC_MAPPING &generic_mapping);
int CreatePrivateObjectSecurityEx(SECURITY_DESCRIPTOR &parent_descriptor,SECURITY_DESCRIPTOR &creator_descriptor,SECURITY_DESCRIPTOR &new_descriptor,GUID &object_type,int is_container_object,uint auto_inherit_flags,HANDLE token,GENERIC_MAPPING &generic_mapping);
int CreatePrivateObjectSecurityWithMultipleInheritance(SECURITY_DESCRIPTOR &parent_descriptor,SECURITY_DESCRIPTOR &creator_descriptor,SECURITY_DESCRIPTOR &new_descriptor,GUID &object_types,uint guid_count,int is_container_object,uint auto_inherit_flags,HANDLE token,GENERIC_MAPPING &generic_mapping);
int CreateRestrictedToken(HANDLE existing_token_handle,uint flags,uint disable_sid_count,SID_AND_ATTRIBUTES &sids_to_disable,uint delete_privilege_count,LUID_AND_ATTRIBUTES &privileges_to_delete,uint restricted_sid_count,SID_AND_ATTRIBUTES &sids_to_restrict,HANDLE &new_token_handle);
int CreateWellKnownSid(WELL_KNOWN_SID_TYPE well_known_sid_type,SID &domain_sid,SID &sid,uint &sid);
int EqualDomainSid(SID &sid1,SID &sid2,int &equal);
int DeleteAce(ACL &acl,uint ace_index);
int DestroyPrivateObjectSecurity(SECURITY_DESCRIPTOR &object_descriptor);
int DuplicateToken(HANDLE existing_token_handle,SECURITY_IMPERSONATION_LEVEL impersonation_level,HANDLE &duplicate_token_handle);
int DuplicateTokenEx(HANDLE existing_token,uint desired_access,PVOID token_attributes,SECURITY_IMPERSONATION_LEVEL impersonation_level,TOKEN_TYPE token_type,HANDLE &new_token);
int EqualPrefixSid(SID &sid1,SID &sid2);
int EqualSid(SID &sid1,SID &sid2);
int FindFirstFreeAce(ACL &acl,PVOID &ace);
PVOID FreeSid(SID &sid);
int GetAce(ACL &acl,uint ace_index,PVOID &ace);
int GetAclInformation(ACL &acl,PVOID acl_information,uint acl_information_length,ACL_INFORMATION_CLASS acl_information_class);
int GetFileSecurityW(const string file_name,uint requested_information,SECURITY_DESCRIPTOR &security_descriptor,uint length,uint &length_needed);
int GetKernelObjectSecurity(HANDLE handle,uint requested_information,SECURITY_DESCRIPTOR &security_descriptor,uint length,uint &length_needed);
uint GetLengthSid(SID &sid);
int GetPrivateObjectSecurity(SECURITY_DESCRIPTOR &object_descriptor,uint security_information,SECURITY_DESCRIPTOR &resultant_descriptor,uint descriptor_length,uint &return_length);
int GetSecurityDescriptorControl(SECURITY_DESCRIPTOR &security_descriptor,ushort &control,uint &revision);
int GetSecurityDescriptorDacl(SECURITY_DESCRIPTOR &security_descriptor,int &dacl_present,ACL &dacl,int &dacl_defaulted);
int GetSecurityDescriptorGroup(SECURITY_DESCRIPTOR &security_descriptor,SID &group,int &group_defaulted);
uint GetSecurityDescriptorLength(SECURITY_DESCRIPTOR &security_descriptor);
int GetSecurityDescriptorOwner(SECURITY_DESCRIPTOR &security_descriptor,SID &owner,int &owner_defaulted);
uint GetSecurityDescriptorRMControl(SECURITY_DESCRIPTOR &security_descriptor,uchar &rm_control);
int GetSecurityDescriptorSacl(SECURITY_DESCRIPTOR &security_descriptor,int &sacl_present,ACL &sacl,int &sacl_defaulted);
PVOID GetSidIdentifierAuthority(SID &sid);
uint GetSidLengthRequired(uchar sub_authority_count);
PVOID GetSidSubAuthority(SID &sid,uint sub_authority);
PVOID GetSidSubAuthorityCount(SID &sid);
int GetTokenInformation(HANDLE token_handle,TOKEN_INFORMATION_CLASS token_information_class,PVOID &token_information,uint token_information_length,uint &return_length);
int GetWindowsAccountDomainSid(SID &sid,SID &domain_sid,uint &domain_sid);
int ImpersonateAnonymousToken(HANDLE thread_handle);
int ImpersonateLoggedOnUser(HANDLE token);
int ImpersonateSelf(SECURITY_IMPERSONATION_LEVEL impersonation_level);
int InitializeAcl(ACL &acl,uint acl_length,uint acl_revision);
int InitializeSecurityDescriptor(SECURITY_DESCRIPTOR &security_descriptor,uint revision);
int InitializeSid(SID &sid,SID_IDENTIFIER_AUTHORITY &identifier_authority,uchar sub_authority_count);
int IsTokenRestricted(HANDLE token_handle);
int IsValidAcl(ACL &acl);
int IsValidSecurityDescriptor(SECURITY_DESCRIPTOR &security_descriptor);
int IsValidSid(SID &sid);
int IsWellKnownSid(SID &sid,WELL_KNOWN_SID_TYPE well_known_sid_type);
int MakeAbsoluteSD(SECURITY_DESCRIPTOR &self_relative_security_descriptor,SECURITY_DESCRIPTOR &absolute_security_descriptor,uint &absolute_security_descriptor_size,ACL &dacl,uint &dacl_size,ACL &sacl,uint &sacl_size,SID &owner,uint &owner_size,SID &primary_group,uint &primary_group_size);
int MakeSelfRelativeSD(SECURITY_DESCRIPTOR &absolute_security_descriptor,SECURITY_DESCRIPTOR &self_relative_security_descriptor,uint &buffer_length);
void MapGenericMask(uint &access_mask,GENERIC_MAPPING &generic_mapping);
int ObjectCloseAuditAlarmW(const string subsystem_name,PVOID handle_id,int generate_on_close);
int ObjectDeleteAuditAlarmW(const string subsystem_name,PVOID handle_id,int generate_on_close);
int ObjectOpenAuditAlarmW(const string subsystem_name,PVOID handle_id,string object_type_name,string object_name,SECURITY_DESCRIPTOR &security_descriptor,HANDLE client_token,uint desired_access,uint granted_access,PRIVILEGE_SET &privileges,int object_creation,int access_granted,int &generate_on_close);
int ObjectPrivilegeAuditAlarmW(const string subsystem_name,PVOID handle_id,HANDLE client_token,uint desired_access,PRIVILEGE_SET &privileges,int access_granted);
int PrivilegeCheck(HANDLE client_token,PRIVILEGE_SET &required_privileges,int &result);
int PrivilegedServiceAuditAlarmW(const string subsystem_name,const string service_name,HANDLE client_token,PRIVILEGE_SET &privileges,int access_granted);
void QuerySecurityAccessMask(uint security_information,uint &desired_access);
int RevertToSelf(void);
int SetAclInformation(ACL &acl,PVOID acl_information,uint acl_information_length,ACL_INFORMATION_CLASS acl_information_class);
int SetFileSecurityW(const string file_name,uint security_information,SECURITY_DESCRIPTOR &security_descriptor);
int SetKernelObjectSecurity(HANDLE handle,uint security_information,SECURITY_DESCRIPTOR &security_descriptor);
int SetPrivateObjectSecurity(uint security_information,SECURITY_DESCRIPTOR &modification_descriptor,SECURITY_DESCRIPTOR &objects_security_descriptor,GENERIC_MAPPING &generic_mapping,HANDLE token);
int SetPrivateObjectSecurityEx(uint security_information,SECURITY_DESCRIPTOR &modification_descriptor,SECURITY_DESCRIPTOR &objects_security_descriptor,uint auto_inherit_flags,GENERIC_MAPPING &generic_mapping,HANDLE token);
void SetSecurityAccessMask(uint security_information,uint &desired_access);
int SetSecurityDescriptorControl(SECURITY_DESCRIPTOR &security_descriptor,ushort control_bits_of_interest,ushort control_bits_to_set);
int SetSecurityDescriptorDacl(SECURITY_DESCRIPTOR &security_descriptor,int dacl_present,ACL &dacl,int dacl_defaulted);
int SetSecurityDescriptorGroup(SECURITY_DESCRIPTOR &security_descriptor,SID &group,int group_defaulted);
int SetSecurityDescriptorOwner(SECURITY_DESCRIPTOR &security_descriptor,SID &owner,int owner_defaulted);
uint SetSecurityDescriptorRMControl(SECURITY_DESCRIPTOR &security_descriptor,uchar &rm_control);
int SetSecurityDescriptorSacl(SECURITY_DESCRIPTOR &security_descriptor,int sacl_present,ACL &sacl,int sacl_defaulted);
int SetTokenInformation(HANDLE token_handle,TOKEN_INFORMATION_CLASS token_information_class,PVOID token_information,uint token_information_length);
int CveEventWrite(const string cve_id,const string additional_details);
#import
#import "kernel32.dll"
int AddResourceAttributeAce(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,SID &sid,CLAIM_SECURITY_ATTRIBUTES_INFORMATION &attribute_info,uint &return_length);
int AddScopedPolicyIDAce(ACL &acl,uint ace_revision,uint ace_flags,uint access_mask,SID &sid);
int CheckTokenCapability(HANDLE token_handle,SID &capability_sid_to_check,int &has_capability);
int GetAppContainerAce(ACL &acl,uint starting_ace_index,PVOID &app_container_ace,uint &app_container_ace_index);
int CheckTokenMembershipEx(HANDLE token_handle,SID &sid_to_check,uint flags,int &is_member);
int SetCachedSigningLevel(HANDLE &source_files,uint source_file_count,uint flags,HANDLE target_file);
int GetCachedSigningLevel(HANDLE file,ulong flags,ulong signing_level,uchar &thumbprint[],ulong thumbprint_size,ulong thumbprint_algorithm);
#import
//+------------------------------------------------------------------+
+95
View File
@@ -0,0 +1,95 @@
//+------------------------------------------------------------------+
//| sysinfoapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winbase.mqh>
//---
enum COMPUTER_NAME_FORMAT
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified,
ComputerNameMax
};
//---
struct DUMMYSTRUCTNAME
{
uint dwOemId;
ushort wProcessorArchitecture;
ushort wReserved;
};
//---
struct MEMORYSTATUSEX
{
uint dwLength;
uint dwMemoryLoad;
ulong ullTotalPhys;
ulong ullAvailPhys;
ulong ullTotalPageFile;
ulong ullAvailPageFile;
ulong ullTotalVirtual;
ulong ullAvailVirtual;
ulong ullAvailExtendedVirtual;
};
//---
struct SYSTEM_INFO
{
uint dwOemId;
uint dwPageSize;
PVOID lpMinimumApplicationAddress;
PVOID lpMaximumApplicationAddress;
ulong dwActiveProcessorMask;
uint dwNumberOfProcessors;
uint dwProcessorType;
uint dwAllocationGranularity;
ushort wProcessorLevel;
ushort wProcessorRevision;
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int GlobalMemoryStatusEx(MEMORYSTATUSEX &buffer);
void GetSystemInfo(SYSTEM_INFO &system_info);
void GetSystemTime(SYSTEMTIME &system_time);
void GetSystemTimeAsFileTime(FILETIME &system_time_as_file_time);
void GetLocalTime(SYSTEMTIME &system_time);
uint GetVersion(void);
int SetLocalTime(const SYSTEMTIME &system_time);
uint GetTickCount(void);
ulong GetTickCount64(void);
int GetSystemTimeAdjustment(uint &time_adjustment,uint &time_increment,int &time_adjustment_disabled);
uint GetSystemDirectoryW(ushort &buffer[],uint size);
uint GetWindowsDirectoryW(ushort &buffer[],uint size);
uint GetSystemWindowsDirectoryW(ushort &buffer[],uint size);
int GetComputerNameExW(COMPUTER_NAME_FORMAT name_type,ushort &buffer[],uint &size);
int SetComputerNameExW(COMPUTER_NAME_FORMAT name_type,const string buffer);
int SetSystemTime(const SYSTEMTIME &system_time);
int GetVersionExW(OSVERSIONINFOW &version_information);
int GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION &buffer[],uint &returned_length);
int GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship_type,SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX &buffer[],uint &returned_length);
void GetNativeSystemInfo(SYSTEM_INFO &system_info);
void GetSystemTimePreciseAsFileTime(FILETIME &system_time_as_file_time);
int GetProductInfo(uint os_major_version,uint os_minor_version,uint sp_major_version,uint sp_minor_version,uint &returned_product_type);
uint EnumSystemFirmwareTables(uint firmware_table_provider_signature,PVOID &firmware_table_enum_buffer,uint buffer_size);
uint EnumSystemFirmwareTables(uint firmware_table_provider_signature,uchar &firmware_table_enum_buffer[],uint buffer_size);
uint GetSystemFirmwareTable(uint firmware_table_provider_signature,uint firmware_table_id,PVOID firmware_table_buffer,uint buffer_size);
uint GetSystemFirmwareTable(uint firmware_table_provider_signature,uint firmware_table_id,uchar &firmware_table_buffer[],uint buffer_size);
int DnsHostnameToComputerNameExW(const string hostname,ushort &computer_name[],uint &size);
int GetPhysicallyInstalledSystemMemory(ulong &total_memory_in_kilobytes);
int SetComputerNameEx2W(COMPUTER_NAME_FORMAT name_type,uint flags,const string buffer);
int SetSystemTimeAdjustment(uint time_adjustment,int time_adjustment_disabled);
int InstallELAMCertificateInfo(HANDLE elam_file);
int GetProcessorSystemCycleTime(ushort group,PVOID &buffer,uint &returned_length);
int GetProcessorSystemCycleTime(ushort group,SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION &buffer[],uint &returned_length);
int SetComputerNameW(const string computer_name);
#import
//+------------------------------------------------------------------+
+21
View File
@@ -0,0 +1,21 @@
//+------------------------------------------------------------------+
//| winapi.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include "windef.mqh"
#include "winnt.mqh"
#include "fileapi.mqh"
#include "winbase.mqh"
#include "winuser.mqh"
#include "wingdi.mqh"
#include "winreg.mqh"
#include "handleapi.mqh"
#include "processthreadsapi.mqh"
#include "securitybaseapi.mqh"
#include "errhandlingapi.mqh"
#include "sysinfoapi.mqh"
#include "processenv.mqh"
#include "libloaderapi.mqh"
#include "memoryapi.mqh"
//+------------------------------------------------------------------+
+814
View File
@@ -0,0 +1,814 @@
//+------------------------------------------------------------------+
//| WinBase.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winnt.mqh>
#include <WinAPI\fileapi.mqh>
//---
#define OFS_MAXPATHNAME 128
#define HW_PROFILE_GUIDLEN 39
#define MAX_PROFILE_LEN 80
#define RESTART_MAX_CMD_LINE 1024
//---
enum COPYFILE2_COPY_PHASE
{
COPYFILE2_PHASE_NONE=0,
COPYFILE2_PHASE_PREPARE_SOURCE,
COPYFILE2_PHASE_PREPARE_DEST,
COPYFILE2_PHASE_READ_SOURCE,
COPYFILE2_PHASE_WRITE_DESTINATION,
COPYFILE2_PHASE_SERVER_COPY,
COPYFILE2_PHASE_NAMEGRAFT_COPY,
COPYFILE2_PHASE_MAX
};
//---
enum COPYFILE2_MESSAGE_ACTION
{
COPYFILE2_PROGRESS_CONTINUE=0,
COPYFILE2_PROGRESS_CANCEL,
COPYFILE2_PROGRESS_STOP,
COPYFILE2_PROGRESS_QUIET,
COPYFILE2_PROGRESS_PAUSE
};
//---
enum COPYFILE2_MESSAGE_TYPE
{
COPYFILE2_CALLBACK_NONE=0,
COPYFILE2_CALLBACK_CHUNK_STARTED,
COPYFILE2_CALLBACK_CHUNK_FINISHED,
COPYFILE2_CALLBACK_STREAM_STARTED,
COPYFILE2_CALLBACK_STREAM_FINISHED,
COPYFILE2_CALLBACK_POLL_CONTINUE,
COPYFILE2_CALLBACK_ERROR,
COPYFILE2_CALLBACK_MAX
};
//---
enum DEP_SYSTEM_POLICY_TYPE
{
DEPPolicyAlwaysOff=0,
DEPPolicyAlwaysOn,
DEPPolicyOptIn,
DEPPolicyOptOut,
DEPTotalPolicyCount
};
//---
enum FILE_ID_TYPE
{
FileIdType,
ObjectIdType,
ExtendedFileIdType,
MaximumFileIdType
};
//---
enum PRIORITY_HINT
{
IoPriorityHintVeryLow=0,
IoPriorityHintLow,
IoPriorityHintNormal,
MaximumIoPriorityHintType
};
//---
enum PROC_THREAD_ATTRIBUTE_NUM
{
ProcThreadAttributeParentProcess=0,
ProcThreadAttributeHandleList=2,
ProcThreadAttributeGroupAffinity=3,
ProcThreadAttributePreferredNode=4,
ProcThreadAttributeIdealProcessor=5,
ProcThreadAttributeUmsThread=6,
ProcThreadAttributeMitigationPolicy=7,
ProcThreadAttributeSecurityCapabilities=9,
ProcThreadAttributeProtectionLevel=11,
ProcThreadAttributeJobList=13,
ProcThreadAttributeChildProcessPolicy=14,
ProcThreadAttributeAllApplicationPackagesPolicy=15,
ProcThreadAttributeWin32kFilter=16,
ProcThreadAttributeSafeOpenPromptOriginClaim=17,
ProcThreadAttributeDesktopAppPolicy=18
};
//---
struct ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA
{
PVOID lpInformation;
PVOID lpSectionBase;
uint ulSectionLength;
PVOID lpSectionGlobalDataBase;
uint ulSectionGlobalDataLength;
};
//---
struct ACTCTX_SECTION_KEYED_DATA
{
uint cbSize;
uint ulDataFormatVersion;
PVOID lpData;
uint ulLength;
PVOID lpSectionGlobalData;
uint ulSectionGlobalDataLength;
PVOID lpSectionBase;
uint ulSectionTotalLength;
HANDLE hActCtx;
uint ulAssemblyRosterIndex;
uint ulFlags;
ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA AssemblyMetadata;
};
//---
struct ACTCTX_SECTION_KEYED_DATA_2600
{
uint cbSize;
uint ulDataFormatVersion;
PVOID lpData;
uint ulLength;
PVOID lpSectionGlobalData;
uint ulSectionGlobalDataLength;
PVOID lpSectionBase;
uint ulSectionTotalLength;
HANDLE hActCtx;
uint ulAssemblyRosterIndex;
};
//---
struct ACTCTXW
{
uint cbSize;
uint dwFlags;
PVOID lpSource;
ushort wProcessorArchitecture;
ushort wLangId;
PVOID lpAssemblyDirectory;
PVOID lpResourceName;
PVOID lpApplicationName;
HANDLE hModule;
};
//---
struct ACTIVATION_CONTEXT_BASIC_INFORMATION
{
HANDLE hActCtx;
uint dwFlags;
};
//---
struct DCB
{
uint DCBlength;
uint BaudRate;
uint Flags;
ushort wReserved;
ushort XonLim;
ushort XoffLim;
uchar ByteSize;
uchar Parity;
uchar StopBits;
char XonChar;
char XoffChar;
char ErrorChar;
char EofChar;
char EvtChar;
ushort wReserved1;
};
//---
struct COMMCONFIG
{
uint dwSize;
ushort wVersion;
ushort wReserved;
DCB dcb;
uint dwProviderSubType;
uint dwProviderOffset;
uint dwProviderSize;
short wcProviderData[2];
};
//---
struct COMMPROP
{
ushort wPacketLength;
ushort wPacketVersion;
uint dwServiceMask;
uint dwReserved1;
uint dwMaxTxQueue;
uint dwMaxRxQueue;
uint dwMaxBaud;
uint dwProvSubType;
uint dwProvCapabilities;
uint dwSettableParams;
uint dwSettableBaud;
ushort wSettableData;
ushort wSettableStopParity;
uint dwCurrentTxQueue;
uint dwCurrentRxQueue;
uint dwProvSpec1;
uint dwProvSpec2;
short wcProvChar[1];
};
//---
struct COMMTIMEOUTS
{
uint ReadIntervalTimeout;
uint ReadTotalTimeoutMultiplier;
uint ReadTotalTimeoutConstant;
uint WriteTotalTimeoutMultiplier;
uint WriteTotalTimeoutConstant;
};
//---
struct COMSTAT
{
uint cbInQue;
uint cbOutQue;
};
//---
struct COPYFILE2_EXTENDED_PARAMETERS
{
uint dwSize;
uint dwCopyFlags;
PVOID pfCancel;
PVOID pProgressRoutine;
PVOID pvCallbackContext;
};
//---
struct EVENTLOG_FULL_INFORMATION
{
uint dwFull;
};
//---
struct FILE_ALIGNMENT_INFO: public FILE_INFO
{
uint AlignmentRequirement;
};
//---
struct FILE_ALLOCATION_INFO: public FILE_INFO
{
long AllocationSize;
};
//---
struct FILE_ATTRIBUTE_TAG_INFO: public FILE_INFO
{
uint FileAttributes;
uint ReparseTag;
};
//---
struct FILE_BASIC_INFO: public FILE_INFO
{
long CreationTime;
long LastAccessTime;
long LastWriteTime;
long ChangeTime;
uint FileAttributes;
};
//---
struct FILE_COMPRESSION_INFO: public FILE_INFO
{
long CompressedFileSize;
ushort CompressionFormat;
uchar CompressionUnitShift;
uchar ChunkShift;
uchar ClusterShift;
uchar Reserved[3];
};
//---
struct FILE_DISPOSITION_INFO: public FILE_INFO
{
uchar DeleteFile;
};
//---
struct FILE_DISPOSITION_INFO_EX: public FILE_INFO
{
uint Flags;
};
//---
struct FILE_END_OF_FILE_INFO: public FILE_INFO
{
long EndOfFile;
};
//---
struct FILE_FULL_DIR_INFO: public FILE_INFO
{
uint NextEntryOffset;
uint FileIndex;
long CreationTime;
long LastAccessTime;
long LastWriteTime;
long ChangeTime;
long EndOfFile;
long AllocationSize;
uint FileAttributes;
uint FileNameLength;
uint EaSize;
short FileName[1];
};
//---
struct FILE_ID_BOTH_DIR_INFO: public FILE_INFO
{
uint NextEntryOffset;
uint FileIndex;
long CreationTime;
long LastAccessTime;
long LastWriteTime;
long ChangeTime;
long EndOfFile;
long AllocationSize;
uint FileAttributes;
uint FileNameLength;
uint EaSize;
char ShortNameLength;
short ShortName[12];
long FileId;
short FileName[1];
};
//---
struct FILE_ID_EXTD_DIR_INFO: public FILE_INFO
{
uint NextEntryOffset;
uint FileIndex;
long CreationTime;
long LastAccessTime;
long LastWriteTime;
long ChangeTime;
long EndOfFile;
long AllocationSize;
uint FileAttributes;
uint FileNameLength;
uint EaSize;
uint ReparsePointTag;
FILE_ID_128 FileId;
short FileName[1];
};
//---
struct FILE_ID_INFO: public FILE_INFO
{
ulong VolumeSerialNumber;
FILE_ID_128 FileId;
};
//---
struct FILE_IO_PRIORITY_HINT_INFO: public FILE_INFO
{
PRIORITY_HINT PriorityHint;
};
//---
struct FILE_NAME_INFO
{
uint FileNameLength;
short FileName[2];
};
//---
struct FILE_STANDARD_INFO: public FILE_INFO
{
long AllocationSize;
long EndOfFile;
uint NumberOfLinks;
uchar DeletePending;
uchar Directory;
};
//---
struct FILE_STORAGE_INFO: public FILE_INFO
{
uint LogicalBytesPerSector;
uint PhysicalBytesPerSectorForAtomicity;
uint PhysicalBytesPerSectorForPerformance;
uint FileSystemEffectivePhysicalBytesPerSectorForAtomicity;
uint Flags;
uint ByteOffsetForSectorAlignment;
uint ByteOffsetForPartitionAlignment;
};
//---
struct FILE_STREAM_INFO: public FILE_INFO
{
uint NextEntryOffset;
uint StreamNameLength;
long StreamSize;
long StreamAllocationSize;
short StreamName[1];
};
//---
struct HW_PROFILE_INFOW
{
uint dwDockInfo;
short szHwProfileGuid[HW_PROFILE_GUIDLEN];
short szHwProfileName[MAX_PROFILE_LEN];
};
//---
struct JIT_DEBUG_INFO
{
uint dwSize;
uint dwProcessorArchitecture;
uint dwThreadID;
uint dwReserved0;
ulong lpExceptionAddress;
ulong lpExceptionRecord;
ulong lpContextRecord;
};
//---
struct MEMORYSTATUS
{
uint dwLength;
uint dwMemoryLoad;
ulong dwTotalPhys;
ulong dwAvailPhys;
ulong dwTotalPageFile;
ulong dwAvailPageFile;
ulong dwTotalVirtual;
ulong dwAvailVirtual;
};
//---
struct OFSTRUCT
{
uchar cBytes;
uchar fFixedDisk;
ushort nErrCode;
ushort Reserved1;
ushort Reserved2;
char szPathName[OFS_MAXPATHNAME];
};
//---
struct OPERATION_END_PARAMETERS
{
uint Version;
uint OperationId;
uint Flags;
};
//---
struct OPERATION_START_PARAMETERS
{
uint Version;
uint OperationId;
uint Flags;
};
//---
struct SYSTEM_POWER_STATUS
{
uchar ACLineStatus;
uchar BatteryFlag;
uchar BatteryLifePercent;
uchar SystemStatusFlag;
uint BatteryLifeTime;
uint BatteryFullLifeTime;
};
//---
struct UMS_SCHEDULER_STARTUP_INFO
{
uint UmsVersion;
PVOID CompletionList;
PVOID SchedulerProc;
PVOID SchedulerParam;
};
//---
struct WIN32_STREAM_ID
{
uint dwStreamId;
uint dwStreamAttributes;
long Size;
uint dwStreamNameSize;
};
//---
struct UMS_SYSTEM_THREAD_INFORMATION
{
uint UmsVersion;
uint ThreadUmsFlags;
};
//---
struct FILE_ID_DESCRIPTOR
{
uint dwSize;
FILE_ID_TYPE Type;
long FileId;
};
//---
struct SYSTEMTIME
{
ushort wYear;
ushort wMonth;
ushort wDayOfWeek;
ushort wDay;
ushort wHour;
ushort wMinute;
ushort wSecond;
ushort wMilliseconds;
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "kernel32.dll"
int ActivateActCtx(HANDLE act_ctx,PVOID &cookie);
int ActivateActCtx(ACTCTXW &act_ctx,PVOID &cookie);
ushort AddAtomW(const string str);
int AddIntegrityLabelToBoundaryDescriptor(HANDLE &BoundaryDescriptor,SID &IntegrityLabel);
void AddRefActCtx(HANDLE act_ctx);
void AddRefActCtx(ACTCTXW &act_ctx);
int AddSecureMemoryCacheCallback(PVOID call_back);
void ApplicationRecoveryFinished(int success);
int ApplicationRecoveryInProgress(int &cancelled);
int BackupRead(HANDLE file,uchar &buffer[],uint number_of_bytes_to_read,uint &number_of_bytes_read,int abort,int process_security,PVOID &context);
int BackupSeek(HANDLE file,uint low_bytes_to_seek,uint high_bytes_to_seek,uint &low_byte_seeked,uint &high_byte_seeked,PVOID &context);
int BackupWrite(HANDLE file,uchar &buffer[],uint number_of_bytes_to_write,uint &number_of_bytes_written,int abort,int process_security,PVOID &context);
HANDLE BeginUpdateResourceW(const string file_name,int delete_existing_resources);
int BindIoCompletionCallback(HANDLE FileHandle,PVOID Function,uint Flags);
int BuildCommDCBAndTimeoutsW(const string def,DCB &lpDCB,COMMTIMEOUTS &comm_timeouts);
int BuildCommDCBW(const string def,DCB &lpDCB);
int CancelDeviceWakeupRequest(HANDLE device);
int CancelTimerQueueTimer(HANDLE TimerQueue,HANDLE Timer);
int CheckNameLegalDOS8Dot3W(const string name,char &oem_name[],uint oem_name_size,int &name_contains_spaces,int &name_legal);
int ClearCommBreak(HANDLE file);
int ClearCommError(HANDLE file,uint &errors,COMSTAT &stat);
int CommConfigDialogW(const string name,HANDLE wnd,COMMCONFIG &lpCC);
int ConvertFiberToThread(void);
PVOID ConvertThreadToFiber(PVOID parameter);
PVOID ConvertThreadToFiberEx(PVOID parameter,uint flags);
int CopyContext(CONTEXT &Destination,uint ContextFlags,CONTEXT &Source);
int CopyFile2(const string existing_file_name,const string new_file_name,COPYFILE2_EXTENDED_PARAMETERS &extended_parameters);
int CopyFileExW(const string existing_file_name,const string new_file_name,PVOID progress_routine,PVOID data,int &cancel,uint copy_flags);
int CopyFileTransactedW(const string existing_file_name,const string new_file_name,PVOID progress_routine,PVOID data,int &cancel,uint copy_flags,HANDLE transaction);
int CopyFileW(const string existing_file_name,const string new_file_name,int fail_if_exists);
HANDLE CreateActCtxW(const ACTCTXW &act_ctx);
int CreateDirectoryExW(const string template_directory,const string new_directory,PVOID security_attributes);
int CreateDirectoryTransactedW(const string template_directory,const string new_directory,PVOID security_attributes,HANDLE transaction);
PVOID CreateFiber(ulong stack_size,PVOID start_address,PVOID parameter);
PVOID CreateFiberEx(ulong stack_commit_size,ulong stack_reserve_size,uint flags,PVOID start_address,PVOID parameter);
HANDLE CreateFileTransactedW(const string file_name,uint desired_access,uint share_mode,PVOID security_attributes,uint creation_disposition,uint flags_and_attributes,HANDLE template_file,HANDLE transaction,ushort &mini_version,PVOID extended_parameter);
int CreateHardLinkTransactedW(const string file_name,const string existing_file_name,PVOID security_attributes,HANDLE transaction);
int CreateHardLinkW(const string file_name,const string existing_file_name,PVOID security_attributes);
int CreateJobSet(uint NumJob,JOB_SET_ARRAY &UserJobSet,uint Flags);
HANDLE CreateMailslotW(const string name,uint max_message_size,uint read_timeout,PVOID security_attributes);
uchar CreateSymbolicLinkTransactedW(const string symlink_file_name,const string target_file_name,uint flags,HANDLE transaction);
uchar CreateSymbolicLinkW(const string symlink_file_name,const string target_file_name,uint flags);
uint CreateTapePartition(HANDLE device,uint partition_method,uint count,uint size);
int CreateUmsCompletionList(PVOID &UmsCompletionList);
int CreateUmsThreadContext(PVOID &ums_thread);
int DeactivateActCtx(uint flags,ulong cookie);
int DebugBreakProcess(HANDLE Process);
int DebugSetProcessKillOnExit(int KillOnExit);
ushort DeleteAtom(ushort atom);
void DeleteFiber(PVOID fiber);
int DeleteFileTransactedW(const string file_name,HANDLE transaction);
int DeleteTimerQueue(HANDLE TimerQueue);
int DeleteUmsCompletionList(PVOID UmsCompletionList);
int DeleteUmsThreadContext(PVOID UmsThread);
int DequeueUmsCompletionListItems(PVOID UmsCompletionList,uint WaitTimeOut,PVOID &UmsThreadList);
uint DisableThreadProfiling(HANDLE PerformanceDataHandle);
int DnsHostnameToComputerNameW(const string hostname,ushort &computer_name[],uint &size);
int DosDateTimeToFileTime(ushort fat_date,ushort fat_time,FILETIME &file_time);
uint EnableThreadProfiling(HANDLE ThreadHandle,uint Flags,ulong HardwareCounters,HANDLE &PerformanceDataHandle);
int EndUpdateResourceW(HANDLE update,int discard);
int EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO &SchedulerStartupInfo);
int EnumResourceLanguagesW(HANDLE module,const string type,const string name,PVOID enum_func,long param);
int EnumResourceTypesW(HANDLE module,PVOID enum_func,long param);
uint EraseTape(HANDLE device,uint erase_type,int immediate);
int EscapeCommFunction(HANDLE file,uint func);
int ExecuteUmsThread(PVOID UmsThread);
void FatalExit(int ExitCode);
int FileTimeToDosDateTime(FILETIME &file_time,ushort &fat_date,ushort &fat_time);
int FindActCtxSectionGuid(uint flags,const GUID &extension_guid[],uint section_id,const GUID &guid_to_find[],ACTCTX_SECTION_KEYED_DATA &ReturnedData);
int FindActCtxSectionStringW(uint flags,const GUID &extension_guid[],uint section_id,const string string_to_find,ACTCTX_SECTION_KEYED_DATA &ReturnedData);
ushort FindAtomW(const string str);
HANDLE FindFirstFileNameTransactedW(const string file_name,uint flags,uint &StringLength,string LinkName,HANDLE transaction);
HANDLE FindFirstFileTransactedW(const string file_name,FINDEX_INFO_LEVELS info_level_id,FIND_DATAW &find_file_data,FINDEX_SEARCH_OPS search_op,PVOID search_filter,uint additional_flags,HANDLE transaction);
HANDLE FindFirstStreamTransactedW(const string file_name,STREAM_INFO_LEVELS InfoLevel,FIND_STREAM_DATA &find_stream_data,uint flags,HANDLE transaction);
HANDLE FindFirstVolumeMountPointW(const string root_path_name,ushort &volume_mount_point[],uint buffer_length);
int FindNextVolumeMountPointW(HANDLE find_volume_mount_point,string volume_mount_point,uint buffer_length);
int FindVolumeMountPointClose(HANDLE find_volume_mount_point);
uint FormatMessageW(uint flags,const uchar &source[],uint message_id,uint language_id,ushort &buffer[],uint size,PVOID &Arguments[]);
uint GetActiveProcessorCount(ushort GroupNumber);
ushort GetActiveProcessorGroupCount(void);
int GetApplicationRecoveryCallback(HANDLE process,PVOID &recovery_callback,PVOID &parameter,uint &ping_interval,uint &flags);
int GetApplicationRestartSettings(HANDLE process,ushort &commandline[],uint &size,uint &flags);
uint GetAtomNameW(ushort atom,ushort &buffer[],int size);
int GetBinaryTypeW(const string application_name,uint &binary_type);
int GetCommConfig(HANDLE comm_dev,COMMCONFIG &lpCC,uint &size);
int GetCommMask(HANDLE file,uint &evt_mask);
int GetCommModemStatus(HANDLE file,uint &modem_stat);
int GetCommProperties(HANDLE file,COMMPROP &comm_prop);
int GetCommState(HANDLE file,DCB &lpDCB);
int GetCommTimeouts(HANDLE file,COMMTIMEOUTS &comm_timeouts);
uint GetCompressedFileSizeTransactedW(const string file_name,uint &file_size_high,HANDLE transaction);
int GetComputerNameW(ushort &buffer[],uint &size);
int GetCurrentActCtx(HANDLE &act_ctx);
int GetCurrentActCtx(ACTCTXW &act_ctx);
PVOID GetCurrentUmsThread(void);
int GetDefaultCommConfigW(const string name,COMMCONFIG &lpCC,uint &size);
int GetDevicePowerState(HANDLE device,int &on);
uint GetDllDirectoryW(uint buffer_length,ushort &buffer[]);
ulong GetEnabledXStateFeatures(void);
int GetFileAttributesTransactedW(const string file_name,GET_FILEEX_INFO_LEVELS info_level_id,PVOID file_information,HANDLE transaction);
int GetFileBandwidthReservation(HANDLE file,uint &period_milliseconds,uint &bytes_per_period,int &discardable,uint &transfer_size,uint &num_outstanding_requests);
int GetFileInformationByHandleEx(HANDLE file,FILE_INFO_BY_HANDLE_CLASS FileInformationClass,PVOID file_information,uint buffer_size);
int GetFileInformationByHandleEx(HANDLE file,FILE_INFO_BY_HANDLE_CLASS FileInformationClass,uchar &file_information[],uint buffer_size);
uint GetFirmwareEnvironmentVariableExW(const string name,const string guid,PVOID buffer,uint size,uint &attribubutes);
uint GetFirmwareEnvironmentVariableW(const string name,const string guid,PVOID buffer,uint size);
int GetFirmwareType(FIRMWARE_TYPE &FirmwareType);
uint GetFullPathNameTransactedW(const string file_name,uint buffer_length,string buffer,string &file_part,HANDLE transaction);
uint GetLongPathNameTransactedW(const string short_path,string long_path,uint buffer,HANDLE transaction);
int GetMailslotInfo(HANDLE mailslot,uint &max_message_size,uint &next_size,uint &message_count,uint &read_timeout);
uint GetMaximumProcessorCount(ushort GroupNumber);
ushort GetMaximumProcessorGroupCount(void);
int GetNamedPipeClientProcessId(HANDLE Pipe,uint &ClientProcessId);
int GetNamedPipeClientSessionId(HANDLE Pipe,uint &ClientSessionId);
int GetNamedPipeServerProcessId(HANDLE Pipe,uint &ServerProcessId);
int GetNamedPipeServerSessionId(HANDLE Pipe,uint &ServerSessionId);
PVOID GetNextUmsListItem(PVOID UmsContext);
int GetNumaAvailableMemoryNode(uchar Node,ulong &AvailableBytes);
int GetNumaAvailableMemoryNodeEx(ushort Node,ulong &AvailableBytes);
int GetNumaNodeNumberFromHandle(HANDLE file,ushort &NodeNumber);
int GetNumaNodeProcessorMask(uchar Node,ulong &ProcessorMask);
int GetNumaProcessorNode(uchar Processor,uchar &NodeNumber);
int GetNumaProcessorNodeEx(PROCESSOR_NUMBER &Processor,ushort &NodeNumber);
int GetNumaProximityNode(uint ProximityId,uchar &NodeNumber);
uint GetPrivateProfileIntW(const string app_name,const string key_name,int default_value,const string file_name);
uint GetPrivateProfileSectionNamesW(string return_buffer,uint size,const string file_name);
uint GetPrivateProfileSectionW(const string app_name,string returned_string,uint size,const string file_name);
uint GetPrivateProfileStringW(const string app_name,const string key_name,const string default_value,string returned_string,uint size,const string file_name);
int GetPrivateProfileStructW(const string section,const string key,PVOID struct_obj,uint size_struct,const string file);
int GetProcessAffinityMask(HANDLE process,ulong &process_affinity_mask,ulong &system_affinity_mask);
int GetProcessDEPPolicy(HANDLE process,uint &flags,int &permanent);
int GetProcessIoCounters(HANDLE process,IO_COUNTERS &io_counters);
int GetProcessWorkingSetSize(HANDLE process,ulong &minimum_working_set_size,ulong &maximum_working_set_size);
uint GetProfileIntW(const string app_name,const string key_name,int default_value);
uint GetProfileSectionW(const string app_name,string returned_string,uint size);
uint GetProfileStringW(const string app_name,const string key_name,const string default_value,string returned_string,uint size);
DEP_SYSTEM_POLICY_TYPE GetSystemDEPPolicy(void);
int GetSystemPowerStatus(SYSTEM_POWER_STATUS &system_power_status);
int GetSystemRegistryQuota(uint &quota_allowed,uint &quota_used);
uint GetTapeParameters(HANDLE device,uint operation,uint &size,PVOID tape_information);
uint GetTapePosition(HANDLE device,uint position_type,uint &partition,uint &offset_low,uint &offset_high);
uint GetTapeStatus(HANDLE device);
int GetThreadSelectorEntry(HANDLE thread,uint selector,LDT_ENTRY &selector_entry);
int GetUmsCompletionListEvent(PVOID UmsCompletionList,HANDLE &UmsCompletionEvent);
int GetUmsSystemThreadInformation(HANDLE ThreadHandle,UMS_SYSTEM_THREAD_INFORMATION &SystemThreadInfo);
int GetXStateFeaturesMask(CONTEXT &Context,ulong &FeatureMask);
ushort GlobalAddAtomExW(const string str,uint Flags);
ushort GlobalAddAtomW(const string str);
HANDLE GlobalAlloc(uint flags,ulong bytes);
ulong GlobalCompact(uint min_free);
ushort GlobalDeleteAtom(ushort atom);
ushort GlobalFindAtomW(const string str);
void GlobalFix(HANDLE mem);
uint GlobalFlags(HANDLE mem);
HANDLE GlobalFree(HANDLE mem);
uint GlobalGetAtomNameW(ushort atom,ushort &buffer[],int size);
HANDLE GlobalHandle(const PVOID mem);
PVOID GlobalLock(HANDLE mem);
void GlobalMemoryStatus(MEMORYSTATUS &buffer);
HANDLE GlobalReAlloc(HANDLE mem,ulong bytes,uint flags);
ulong GlobalSize(HANDLE mem);
void GlobalUnfix(HANDLE mem);
int GlobalUnlock(HANDLE mem);
int GlobalUnWire(HANDLE mem);
PVOID GlobalWire(HANDLE mem);
int InitAtomTable(uint size);
int InitializeContext(uchar &Buffer[],uint ContextFlags,CONTEXT &Context,uint &ContextLength);
int InitializeContext(PVOID Buffer,uint ContextFlags,CONTEXT &Context,uint &ContextLength);
int IsBadCodePtr(PVOID lpfn);
int IsBadHugeReadPtr(PVOID lp,ulong ucb);
int IsBadHugeWritePtr(PVOID lp,ulong ucb);
int IsBadReadPtr(PVOID lp,ulong ucb);
int IsBadStringPtrW(const string lpsz,ulong max);
int IsBadWritePtr(PVOID lp,ulong ucb);
int IsNativeVhdBoot(int &NativeVhdBoot);
int IsSystemResumeAutomatic(void);
HANDLE LoadPackagedLibrary(const string lib_file_name,uint Reserved);
HANDLE LocalAlloc(uint flags,ulong bytes);
ulong LocalCompact(uint min_free);
uint LocalFlags(HANDLE mem);
HANDLE LocalFree(HANDLE mem);
HANDLE LocalHandle(const PVOID mem);
PVOID LocalLock(HANDLE mem);
HANDLE LocalReAlloc(HANDLE mem,ulong bytes,uint flags);
ulong LocalShrink(HANDLE mem,uint new_size);
ulong LocalSize(HANDLE mem);
int LocalUnlock(HANDLE mem);
PVOID LocateXStateFeature(CONTEXT &Context,uint FeatureId,uint &Length);
string lstrcatW(ushort &string1[],const string string2);
int lstrcmpiW(const string string1,const string string2);
int lstrcmpW(const string string1,const string string2);
string lstrcpynW(ushort &string1[],const string string2,int max_length);
string lstrcpyW(ushort &string1[],const string string2);
int lstrlenW(const string str);
int MapUserPhysicalPagesScatter(PVOID &VirtualAddresses[],ulong NumberOfPages,ulong &PageArray[]);
PVOID MapViewOfFileExNuma(HANDLE file_mapping_object,uint desired_access,uint file_offset_high,uint file_offset_low,ulong number_of_bytes_to_map,PVOID base_address,uint preferred);
int MoveFileExW(const string existing_file_name,const string new_file_name,uint flags);
int MoveFileTransactedW(const string existing_file_name,const string new_file_name,PVOID progress_routine,PVOID data,uint flags,HANDLE transaction);
int MoveFileW(const string existing_file_name,const string new_file_name);
int MoveFileWithProgressW(const string existing_file_name,const string new_file_name,PVOID progress_routine,PVOID data,uint flags);
int MulDiv(int number,int numerator,int denominator);
HANDLE OpenFileById(HANDLE volume_hint,FILE_ID_DESCRIPTOR &file_id,uint desired_access,uint share_mode,PVOID security_attributes,uint flags_and_attributes);
int PowerClearRequest(HANDLE PowerRequest,POWER_REQUEST_TYPE RequestType);
HANDLE PowerCreateRequest(REASON_CONTEXT &Context);
int PowerSetRequest(HANDLE PowerRequest,POWER_REQUEST_TYPE RequestType);
uint PrepareTape(HANDLE device,uint operation,int immediate);
int PulseEvent(HANDLE event);
int PurgeComm(HANDLE file,uint flags);
int QueryActCtxSettingsW(uint flags,HANDLE act_ctx,const string name_space,const string name,string buffer,ulong buffer,ulong &written_or_required);
int QueryActCtxSettingsW(uint flags,ACTCTXW &act_ctx,const string name_space,const string name,string buffer,ulong buffer,ulong &written_or_required);
int QueryActCtxW(uint flags,HANDLE act_ctx,PVOID sub_instance,uint info_class,PVOID buffer,ulong buffer,ulong &written_or_required);
int QueryActCtxW(uint flags,ACTCTXW &act_ctx,PVOID sub_instance,uint info_class,PVOID buffer,ulong buffer,ulong &written_or_required);
int QueryFullProcessImageNameW(HANDLE process,uint flags,string exe_name,uint &size);
uint QueryThreadProfiling(HANDLE ThreadHandle,uchar &Enabled);
int QueryUmsThreadInformation(PVOID UmsThread,RTL_UMS_THREAD_INFO_CLASS UmsThreadInfoClass,PVOID UmsThreadInformation,uint UmsThreadInformationLength,uint &ReturnLength);
int ReadDirectoryChangesExW(HANDLE directory,PVOID buffer,uint buffer_length,int watch_subtree,uint notify_filter,uint &bytes_returned,OVERLAPPED &overlapped,PVOID completion_routine,READ_DIRECTORY_NOTIFY_INFORMATION_CLASS ReadDirectoryNotifyInformationClass);
int ReadDirectoryChangesW(HANDLE directory,PVOID buffer,uint buffer_length,int watch_subtree,uint notify_filter,uint &bytes_returned,OVERLAPPED &overlapped,PVOID completion_routine);
uint ReadThreadProfilingData(HANDLE PerformanceDataHandle,uint Flags,PERFORMANCE_DATA &PerformanceData);
int RegisterApplicationRecoveryCallback(PVOID recovey_callback,PVOID parameter,uint ping_interval,uint flags);
int RegisterApplicationRestart(const string commandline,uint flags);
int RegisterWaitForSingleObject(HANDLE &new_wait_object,HANDLE object,PVOID Callback,PVOID Context,uint milliseconds,uint flags);
void ReleaseActCtx(HANDLE act_ctx);
void ReleaseActCtx(ACTCTXW &act_ctx);
int RemoveDirectoryTransactedW(const string path_name,HANDLE transaction);
int RemoveSecureMemoryCacheCallback(PVOID call_back);
HANDLE ReOpenFile(HANDLE original_file,uint desired_access,uint share_mode,uint flags_and_attributes);
int ReplaceFileW(const string replaced_file_name,const string replacement_file_name,const string backup_file_name,uint replace_flags,PVOID exclude,PVOID reserved);
int ReplacePartitionUnit(string TargetPartition,string SparePartition,uint Flags);
int RequestDeviceWakeup(HANDLE device);
int RequestWakeupLatency(LATENCY_TIME latency);
void RestoreLastError(uint err_code);
int SetCommBreak(HANDLE file);
int SetCommConfig(HANDLE comm_dev,COMMCONFIG &lpCC,uint size);
int SetCommMask(HANDLE file,uint evt_mask);
int SetCommState(HANDLE file,DCB &lpDCB);
int SetCommTimeouts(HANDLE file,COMMTIMEOUTS &comm_timeouts);
int SetDefaultCommConfigW(const string name,COMMCONFIG &lpCC,uint size);
int SetDllDirectoryW(const string path_name);
int SetFileAttributesTransactedW(const string file_name,uint file_attributes,HANDLE transaction);
int SetFileBandwidthReservation(HANDLE file,uint period_milliseconds,uint bytes_per_period,int discardable,uint &transfer_size,uint &num_outstanding_requests);
int SetFileCompletionNotificationModes(HANDLE FileHandle,uchar Flags);
int SetFileShortNameW(HANDLE file,const string short_name);
int SetFirmwareEnvironmentVariableExW(const string name,const string guid,PVOID value,uint size,uint attributes);
int SetFirmwareEnvironmentVariableW(const string name,const string guid,PVOID value,uint size);
uint SetHandleCount(uint number);
int SetMailslotInfo(HANDLE mailslot,uint read_timeout);
int SetMessageWaitingIndicator(HANDLE msg_indicator,uint msg_count);
int SetProcessAffinityMask(HANDLE process,PVOID process_affinity_mask);
int SetProcessDEPPolicy(uint flags);
int SetProcessWorkingSetSize(HANDLE process,ulong minimum_working_set_size,ulong maximum_working_set_size);
int SetSearchPathMode(uint flags);
int SetSystemPowerState(int suspend,int force);
uint SetTapeParameters(HANDLE device,uint operation,PVOID tape_information);
uint SetTapePosition(HANDLE device,uint position_method,uint partition,uint offset_low,uint offset_high,int immediate);
PVOID SetThreadAffinityMask(HANDLE thread,PVOID thread_affinity_mask);
uint SetThreadExecutionState(uint flags);
HANDLE SetTimerQueueTimer(HANDLE TimerQueue,PVOID Callback,PVOID Parameter,uint DueTime,uint Period,int PreferIo);
int SetUmsThreadInformation(PVOID UmsThread,RTL_UMS_THREAD_INFO_CLASS UmsThreadInfoClass,PVOID UmsThreadInformation,uint UmsThreadInformationLength);
int SetupComm(HANDLE file,uint in_queue,uint out_queue);
int SetVolumeLabelW(const string root_path_name,const string volume_name);
int SetVolumeMountPointW(const string volume_mount_point,const string volume_name);
int SetXStateFeaturesMask(CONTEXT &Context,ulong FeatureMask);
uint SignalObjectAndWait(HANDLE object_to_signal,HANDLE object_to_wait_on,uint milliseconds,int alertable);
void SwitchToFiber(PVOID fiber);
int TransmitCommChar(HANDLE file,char symbol);
int UmsThreadYield(PVOID SchedulerParam);
int UnregisterApplicationRecoveryCallback(void);
int UnregisterApplicationRestart(void);
int UnregisterWait(HANDLE WaitHandle);
int UpdateResourceW(HANDLE update,const string type,const string name,ushort &language,PVOID data,uint cb);
int VerifyVersionInfoW(OSVERSIONINFOEXW &version_information,uint type_mask,ulong condition_mask);
int WaitCommEvent(HANDLE file,uint &evt_mask,OVERLAPPED &overlapped);
uchar Wow64EnableWow64FsRedirection(uchar Wow64FsEnableRedirection);
int Wow64GetThreadContext(HANDLE thread,CONTEXT &context);
int Wow64GetThreadSelectorEntry(HANDLE thread,uint selector,LDT_ENTRY &selector_entry);
int Wow64SetThreadContext(HANDLE thread,CONTEXT &context);
uint Wow64SuspendThread(HANDLE thread);
int WritePrivateProfileSectionW(const string app_name,const string str,const string file_name);
int WritePrivateProfileStringW(const string app_name,const string key_name,const string str,const string file_name);
int WritePrivateProfileStructW(const string section,const string key,PVOID struct_obj,uint size_struct,const string file);
int WriteProfileSectionW(const string app_name,const string str);
int WriteProfileStringW(const string app_name,const string key_name,const string str);
uint WriteTapemark(HANDLE device,uint tapemark_type,uint tapemark_count,int immediate);
uint WTSGetActiveConsoleSessionId(void);
int ZombifyActCtx(HANDLE act_ctx);
int ZombifyActCtx(ACTCTXW &act_ctx);
#import
#import "advapi32.dll"
int AddConditionalAce(ACL &acl,uint ace_revision,uint AceFlags,uchar AceType,uint AccessMask,SID &sid,string ConditionStr,uint &ReturnLength);
int BackupEventLogW(HANDLE event_log,const string backup_file_name);
int ClearEventLogW(HANDLE event_log,const string backup_file_name);
void CloseEncryptedFileRaw(PVOID context);
int CloseEventLog(HANDLE event_log);
int DecryptFileW(const string file_name,uint reserved);
int DeregisterEventSource(HANDLE event_log);
int EncryptFileW(const string file_name);
int FileEncryptionStatusW(const string file_name,uint &status);
int GetCurrentHwProfileW(HW_PROFILE_INFOW &hw_profile_info);
int GetEventLogInformation(HANDLE event_log,uint info_level,PVOID buffer,uint buf_size,uint &bytes_needed);
int GetNumberOfEventLogRecords(HANDLE event_log,uint &NumberOfRecords);
int GetOldestEventLogRecord(HANDLE event_log,uint &OldestRecord);
int GetUserNameW(string buffer,uint &buffer);
int IsTextUnicode(PVOID lpv,int size,int &result);
int IsTokenUntrusted(HANDLE TokenHandle);
int LogonUserExW(const string username,const string domain,const string password,uint logon_type,uint logon_provider,HANDLE &token,PVOID &logon_sid,PVOID &profile_buffer,uint &profile_length,QUOTA_LIMITS &quota_limits);
int LogonUserW(const string username,const string domain,const string password,uint logon_type,uint logon_provider,HANDLE &token);
int LookupAccountNameW(const string system_name,const string account_name,SID &Sid,uint &sid,string ReferencedDomainName,uint &referenced_domain_name,SID_NAME_USE &use);
int LookupAccountSidW(const string system_name,SID &Sid,string Name,uint &name,string ReferencedDomainName,uint &referenced_domain_name,SID_NAME_USE &use);
int LookupPrivilegeDisplayNameW(const string system_name,const string name,string display_name,uint &display_name,uint &language_id);
int LookupPrivilegeNameW(const string system_name,LUID &luid,string name,uint &name);
int LookupPrivilegeValueW(const string system_name,const string name,LUID &luid);
int NotifyChangeEventLog(HANDLE event_log,HANDLE event);
HANDLE OpenBackupEventLogW(const string lpUNCServerName,const string file_name);
uint OpenEncryptedFileRawW(const string file_name,uint flags,PVOID &context);
HANDLE OpenEventLogW(const string lpUNCServerName,const string source_name);
int OperationEnd(OPERATION_END_PARAMETERS &OperationEndParams);
int OperationStart(OPERATION_START_PARAMETERS &OperationStartParams);
uint ReadEncryptedFileRaw(PVOID export_callback,PVOID callback_context,PVOID context);
int ReadEventLogW(HANDLE event_log,uint read_flags,uint record_offset,PVOID buffer,uint number_of_bytes_to_read,uint &bytes_read,uint &min_number_of_bytes_needed);
HANDLE RegisterEventSourceW(const string lpUNCServerName,const string source_name);
int ReportEventW(HANDLE event_log,ushort &type,ushort &category,uint dwEventID,SID &user_sid,ushort &num_strings,uint data_size,const string &strings[],PVOID raw_data);
uint WriteEncryptedFileRaw(PVOID import_callback,PVOID callback_context,PVOID context);
#import
//+------------------------------------------------------------------+
+325
View File
@@ -0,0 +1,325 @@
//+------------------------------------------------------------------+
//| windef.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#define HANDLE long
#define PVOID long
//---
#define ANYSIZE_ARRAY 1
#define MAX_BREAKPOINTS 8
#define MAX_WATCHPOINTS 2
#define MAX_HW_COUNTERS 16
#define MAX_PATH 260
#define EXCEPTION_MAXIMUM_PARAMETERS 15
//---
enum LATENCY_TIME
{
LT_DONT_CARE,
LT_LOWEST_LATENCY
};
//---
enum GET_FILEEX_INFO_LEVELS
{
GetFileExInfoStandard,
GetFileExMaxInfoLevel
};
//---
enum FINDEX_INFO_LEVELS
{
FindExInfoStandard,
FindExInfoBasic,
FindExInfoMaxInfoLevel
};
//---
enum FINDEX_SEARCH_OPS
{
FindExSearchNameMatch,
FindExSearchLimitToDirectories,
FindExSearchLimitToDevices,
FindExSearchMaxSearchOp
};
//---
enum DPI_AWARENESS
{
DPI_AWARENESS_INVALID=-1,
DPI_AWARENESS_UNAWARE=0,
DPI_AWARENESS_SYSTEM_AWARE=1,
DPI_AWARENESS_PER_MONITOR_AWARE=2
};
//---
enum DPI_HOSTING_BEHAVIOR
{
DPI_HOSTING_BEHAVIOR_INVALID=-1,
DPI_HOSTING_BEHAVIOR_DEFAULT=0,
DPI_HOSTING_BEHAVIOR_MIXED=1
};
//---
enum FILE_INFO_BY_HANDLE_CLASS
{
FileBasicInfo=0,
FileStandardInfo=1,
FileNameInfo=2,
FileRenameInfo=3,
FileDispositionInfo= 4,
FileAllocationInfo = 5,
FileEndOfFileInfo=6,
FileStreamInfo=7,
FileCompressionInfo=8,
FileAttributeTagInfo=9,
FileIdBothDirectoryInfo=10,
FileIdBothDirectoryRestartInfo=11,
FileIoPriorityHintInfo = 12,
FileRemoteProtocolInfo = 13,
FileFullDirectoryInfo=14,
FileFullDirectoryRestartInfo=15,
FileStorageInfo=16,
FileAlignmentInfo=17,
FileIdInfo=18,
FileIdExtdDirectoryInfo=19,
FileIdExtdDirectoryRestartInfo=20,
MaximumFileInfoByHandlesClass
};
//---
enum READ_DIRECTORY_NOTIFY_INFORMATION_CLASS
{
ReadDirectoryNotifyInformation=1,
ReadDirectoryNotifyExtendedInformation
};
//---
enum WELL_KNOWN_SID_TYPE
{
WinNullSid=0,
WinWorldSid= 1,
WinLocalSid= 2,
WinCreatorOwnerSid= 3,
WinCreatorGroupSid= 4,
WinCreatorOwnerServerSid=5,
WinCreatorGroupServerSid= 6,
WinNtAuthoritySid=7,
WinDialupSid=8,
WinNetworkSid=9,
WinBatchSid=10,
WinInteractiveSid=11,
WinServiceSid=12,
WinAnonymousSid=13,
WinProxySid=14,
WinEnterpriseControllersSid=15,
WinSelfSid=16,
WinAuthenticatedUserSid=17,
WinRestrictedCodeSid= 18,
WinTerminalServerSid= 19,
WinRemoteLogonIdSid=20,
WinLogonIdsSid=21,
WinLocalSystemSid=22,
WinLocalServiceSid=23,
WinNetworkServiceSid=24,
WinBuiltinDomainSid=25,
WinBuiltinAdministratorsSid=26,
WinBuiltinUsersSid=27,
WinBuiltinGuestsSid=28,
WinBuiltinPowerUsersSid=29,
WinBuiltinAccountOperatorsSid=30,
WinBuiltinSystemOperatorsSid=31,
WinBuiltinPrintOperatorsSid=32,
WinBuiltinBackupOperatorsSid=33,
WinBuiltinReplicatorSid=34,
WinBuiltinPreWindows2000CompatibleAccessSid=35,
WinBuiltinRemoteDesktopUsersSid=36,
WinBuiltinNetworkConfigurationOperatorsSid=37,
WinAccountAdministratorSid=38,
WinAccountGuestSid=39,
WinAccountKrbtgtSid=40,
WinAccountDomainAdminsSid=41,
WinAccountDomainUsersSid=42,
WinAccountDomainGuestsSid=43,
WinAccountComputersSid=44,
WinAccountControllersSid=45,
WinAccountCertAdminsSid=46,
WinAccountSchemaAdminsSid=47,
WinAccountEnterpriseAdminsSid=48,
WinAccountPolicyAdminsSid=49,
WinAccountRasAndIasServersSid=50,
WinNTLMAuthenticationSid=51,
WinDigestAuthenticationSid=52,
WinSChannelAuthenticationSid=53,
WinThisOrganizationSid=54,
WinOtherOrganizationSid=55,
WinBuiltinIncomingForestTrustBuildersSid=56,
WinBuiltinPerfMonitoringUsersSid=57,
WinBuiltinPerfLoggingUsersSid=58,
WinBuiltinAuthorizationAccessSid=59,
WinBuiltinTerminalServerLicenseServersSid=60,
WinBuiltinDCOMUsersSid=61,
WinBuiltinIUsersSid=62,
WinIUserSid=63,
WinBuiltinCryptoOperatorsSid=64,
WinUntrustedLabelSid=65,
WinLowLabelSid=66,
WinMediumLabelSid=67,
WinHighLabelSid=68,
WinSystemLabelSid=69,
WinWriteRestrictedCodeSid=70,
WinCreatorOwnerRightsSid=71,
WinCacheablePrincipalsGroupSid=72,
WinNonCacheablePrincipalsGroupSid=73,
WinEnterpriseReadonlyControllersSid=74,
WinAccountReadonlyControllersSid=75,
WinBuiltinEventLogReadersGroup=76,
WinNewEnterpriseReadonlyControllersSid=77,
WinBuiltinCertSvcDComAccessGroup=78,
WinMediumPlusLabelSid=79,
WinLocalLogonSid=80,
WinConsoleLogonSid=81,
WinThisOrganizationCertificateSid= 82,
WinApplicationPackageAuthoritySid= 83,
WinBuiltinAnyPackageSid=84,
WinCapabilityInternetClientSid=85,
WinCapabilityInternetClientServerSid=86,
WinCapabilityPrivateNetworkClientServerSid=87,
WinCapabilityPicturesLibrarySid=88,
WinCapabilityVideosLibrarySid=89,
WinCapabilityMusicLibrarySid=90,
WinCapabilityDocumentsLibrarySid=91,
WinCapabilitySharedUserCertificatesSid=92,
WinCapabilityEnterpriseAuthenticationSid=93,
WinCapabilityRemovableStorageSid=94,
WinBuiltinRDSRemoteAccessServersSid=95,
WinBuiltinRDSEndpointServersSid=96,
WinBuiltinRDSManagementServersSid=97,
WinUserModeDriversSid=98,
WinBuiltinHyperVAdminsSid=99,
WinAccountCloneableControllersSid=100,
WinBuiltinAccessControlAssistanceOperatorsSid=101,
WinBuiltinRemoteManagementUsersSid=102,
WinAuthenticationAuthorityAssertedSid=103,
WinAuthenticationServiceAssertedSid=104,
WinLocalAccountSid=105,
WinLocalAccountAndAdministratorSid=106,
WinAccountProtectedUsersSid=107,
WinCapabilityAppointmentsSid=108,
WinCapabilityContactsSid=109,
WinAccountDefaultSystemManagedSid=110,
WinBuiltinDefaultSystemManagedGroupSid=111,
WinBuiltinStorageReplicaAdminsSid=112,
WinAccountKeyAdminsSid=113,
WinAccountEnterpriseKeyAdminsSid=114,
WinAuthenticationKeyTrustSid=115,
WinAuthenticationKeyPropertyMFASid=116,
WinAuthenticationKeyPropertyAttestationSid=117,
WinAuthenticationFreshKeyAuthSid=118,
WinBuiltinDeviceOwnersSid=119
};
//---
union FILE_SEGMENT_ELEMENT
{
PVOID Buffer;
ulong Alignment;
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//---
struct REASON_CONTEXT
{
uint Version;
uint Flags;
PVOID Reason;
};
//---
struct OVERLAPPED
{
PVOID Internal;
PVOID InternalHigh;
uint Offset;
uint OffsetHigh;
HANDLE hEvent;
};
//---
struct LDT_ENTRY
{
ushort LimitLow;
ushort BaseLow;
uchar BaseMid;
uchar Flags1;
uchar Flags2;
uchar BaseHi;
};
//---
struct GUID
{
ulong Data1;
ushort Data2;
ushort Data3;
uchar Data4[8];
};
//---
struct FILETIME
{
uint dwLowDateTime;
uint dwHighDateTime;
};
//---
struct POINT
{
int x;
int y;
};
//---
struct POINTL
{
int x;
int y;
};
//---
struct POINTS
{
short x;
short y;
};
//---
struct RECT
{
int left;
int top;
int right;
int bottom;
};
//---
struct RECTL
{
int left;
int top;
int right;
int bottom;
};
//---
struct SIZE
{
int cx;
int cy;
};
//---
struct FILE_INFO
{
};
//---
struct CLAIM_SECURITY_ATTRIBUTE_V1
{
PVOID Name;
ushort ValueType;
ushort Reserved;
uint Flags;
uint ValueCount;
PVOID Values;
};
//---
struct CLAIM_SECURITY_ATTRIBUTES_INFORMATION
{
ushort Version;
ushort Reserved;
uint AttributeCount;
PVOID Attribute;
};
//+------------------------------------------------------------------+
+2080
View File
File diff suppressed because it is too large Load Diff
+3642
View File
File diff suppressed because it is too large Load Diff
+77
View File
@@ -0,0 +1,77 @@
//+------------------------------------------------------------------+
//| winreg.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#include <WinAPI\windef.mqh>
#include <WinAPI\winnt.mqh>
//---
struct VALENTW
{
PVOID ve_valuename;
uint ve_valuelen;
uchar offset1[4];
PVOID ve_valueptr;
uint ve_type;
uchar offset2[4];
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#import "advapi32.dll"
int AbortSystemShutdownW(string machine_name);
uint CheckForHiberboot(uchar &hiberboot,uchar clear_flag);
uint InitiateShutdownW(string machine_name,string message,uint grace_period,uint shutdown_flags,uint reason);
int InitiateSystemShutdownExW(string machine_name,string message,uint timeout,int force_apps_closed,int reboot_after_shutdown,uint reason);
int InitiateSystemShutdownW(string machine_name,string message,uint timeout,int force_apps_closed,int reboot_after_shutdown);
int RegCloseKey(HANDLE key);
int RegConnectRegistryExW(const string machine_name,HANDLE key,uint Flags,HANDLE &result);
int RegConnectRegistryW(const string machine_name,HANDLE key,HANDLE &result);
int RegCopyTreeW(HANDLE key_src,const string sub_key,HANDLE key_dest);
int RegCreateKeyExW(HANDLE key,const string sub_key,PVOID reserved,string class_name,uint options,uint desired,PVOID security_attributes,HANDLE &result,uint &disposition);
int RegCreateKeyTransactedW(HANDLE key,const string sub_key,PVOID reserved,string class_name,uint options,uint desired,PVOID security_attributes,HANDLE &result,uint &disposition,HANDLE transaction,PVOID extended_parameter);
int RegCreateKeyW(HANDLE key,const string sub_key,HANDLE &result);
int RegDeleteKeyExW(HANDLE key,const string sub_key,uint desired,PVOID reserved);
int RegDeleteKeyTransactedW(HANDLE key,const string sub_key,uint desired,PVOID reserved,HANDLE transaction,PVOID extended_parameter);
int RegDeleteKeyValueW(HANDLE key,const string sub_key,const string value_name);
int RegDeleteKeyW(HANDLE key,const string sub_key);
int RegDeleteTreeW(HANDLE key,const string sub_key);
int RegDeleteValueW(HANDLE key,const string value_name);
int RegDisablePredefinedCache(void);
int RegDisablePredefinedCacheEx(void);
int RegDisableReflectionKey(HANDLE base);
int RegEnableReflectionKey(HANDLE base);
int RegEnumKeyExW(HANDLE key,uint index,ushort &name[],uint &name_size,PVOID reserved,ushort &class_name[],uint &class_size,FILETIME &last_write_time);
int RegEnumKeyW(HANDLE key,uint index,ushort &name[],uint &name_size);
int RegEnumValueW(HANDLE key,uint index,ushort &value_name[],uint &value_name_size,PVOID reserved,uint &type,uchar &data[],uint &data_size);
int RegFlushKey(HANDLE key);
int RegGetKeySecurity(HANDLE key,uint SecurityInformation,SECURITY_DESCRIPTOR &security_descriptor,uint &security_descriptor_size);
int RegGetValueW(HANDLE key,const string sub_key,const string value,uint flags,uint &type,uchar &data[],uint &data_size);
int RegLoadAppKeyW(const string file,HANDLE &result,uint desired,uint options,PVOID reserved);
int RegLoadKeyW(HANDLE key,const string sub_key,const string file);
int RegLoadMUIStringW(HANDLE key,const string value,ushort &out_buf[],uint &out_buf_size,uint &data,uint flags,const string directory);
int RegNotifyChangeKeyValue(HANDLE key,int watch_subtree,uint notify_filter,HANDLE event,int asynchronous);
int RegOpenCurrentUser(uint desired,HANDLE &result);
int RegOpenKeyExW(HANDLE key,const string sub_key,uint options,uint desired,HANDLE &result);
int RegOpenKeyTransactedW(HANDLE key,const string sub_key,uint options,uint desired,HANDLE &result,HANDLE transaction,PVOID extended_paremeter);
int RegOpenKeyW(HANDLE key,const string sub_key,HANDLE &result);
int RegOpenUserClassesRoot(HANDLE token,uint options,uint desired,HANDLE &result);
int RegOverridePredefKey(HANDLE key,HANDLE new_key);
int RegQueryInfoKeyW(HANDLE key,string class_name,uint &class_size,PVOID reserved,uint &sub_keys,uint &max_sub_key_len,uint &max_class_len,uint &values,uint &max_value_name_len,uint &max_value_len,uint &security_descriptor,FILETIME &last_write_time);
int RegQueryMultipleValuesW(HANDLE key,VALENTW &val_list[],uint num_vals,ushort &value_buf[],uint &totsize);
int RegQueryReflectionKey(HANDLE base,int &is_reflection_disabled);
int RegQueryValueExW(HANDLE key,const string value_name,PVOID reserved,uint &type,uchar &data[],uint &data_size);
int RegQueryValueW(HANDLE key,const string sub_key,uchar &data[],uint &data_size);
int RegRenameKey(HANDLE key,const string sub_key_name,const string new_key_name);
int RegReplaceKeyW(HANDLE key,const string sub_key,const string new_file,const string old_file);
int RegRestoreKeyW(HANDLE key,const string file,uint flags);
int RegSaveKeyExW(HANDLE key,const string file,PVOID security_attributes,uint flags);
int RegSaveKeyW(HANDLE key,const string file,PVOID security_attributes);
int RegSetKeySecurity(HANDLE key,uint SecurityInformation,SECURITY_DESCRIPTOR &security_descriptor);
int RegSetKeyValueW(HANDLE key,const string sub_key,const string value_name,uint type,const uchar &data[],uint data);
int RegSetValueExW(HANDLE key,const string value_name,PVOID reserved,uint type,const uchar &data[],uint data_size);
int RegSetValueW(HANDLE key,const string sub_key,uint type,const ushort &data[],uint data_size);
int RegUnLoadKeyW(HANDLE key,const string sub_key);
#import
//+------------------------------------------------------------------+
+1825
View File
File diff suppressed because it is too large Load Diff
+108
View File
@@ -0,0 +1,108 @@
//+------------------------------------------------------------------+
//| ChartObjectsTxtControls.mqh |
//| Copyright 2000-2024, MetaQuotes Ltd. |
//+------------------------------------------------------------------+
#include "ChartObject.mqh"
// Global variable to store the edit control state
bool isEditing = false;
string textControlName = "MyText"; // Name of your text control
//+------------------------------------------------------------------+
//| Custom function for checking mouse over the text control |
//+------------------------------------------------------------------+
bool IsMouseOverTextControl(int x, int y) {
// Get the position and size of the text control
long chart_id = ChartID();
double price = Bid; // Example price, can be customized
datetime time = TimeCurrent(); // Example time, can be customized
// Get coordinates of the text control
double textX, textY, textWidth, textHeight;
if (!ObjectGetTextControlCoordinates(chart_id, textControlName, textX, textY, textWidth, textHeight)) {
return false; // If we cannot get the coordinates, return false
}
// Check if mouse coordinates are within the text control area
return (x >= textX && x <= textX + textWidth && y >= textY && y <= textY + textHeight);
}
//+------------------------------------------------------------------+
//| Function to remove focus from the text control |
//+------------------------------------------------------------------+
void RemoveFocusFromTextControl() {
isEditing = false; // Reset editing state
// Logic to update the chart if necessary
// You may want to refresh the chart or do other operations here
}
//+------------------------------------------------------------------+
//| OnMouseMove event handler |
//+------------------------------------------------------------------+
void OnMouseMove(int x, int y) {
if (!isEditing) return; // Exit if not in editing mode
// Check if mouse is over the text control
if (!IsMouseOverTextControl(x, y)) {
// Exit edit mode
RemoveFocusFromTextControl();
}
}
//+------------------------------------------------------------------+
//| OnClick event handler |
//+------------------------------------------------------------------+
void OnClick() {
// Logic to check if the text control was clicked
if (ObjectFind(ChartID(), textControlName) != -1) {
// If clicked on the text control, set editing state
isEditing = true;
}
}
//+------------------------------------------------------------------+
//| Function to create the text control |
//+------------------------------------------------------------------+
bool CreateTextControl() {
long chart_id = ChartID();
if (!ObjectCreate(chart_id, textControlName, OBJ_TEXT, 0, TimeCurrent(), Bid)) {
return false;
}
ObjectSetInteger(chart_id, textControlName, OBJPROP_FONTSIZE, 12);
ObjectSetString(chart_id, textControlName, OBJPROP_FONT, "Arial");
ObjectSetInteger(chart_id, textControlName, OBJPROP_COLOR, clrWhite);
ObjectSetInteger(chart_id, textControlName, OBJPROP_XSIZE, 100); // Width
ObjectSetInteger(chart_id, textControlName, OBJPROP_YSIZE, 20); // Height
return true;
}
//+------------------------------------------------------------------+
//| Custom function to get text control coordinates |
//+------------------------------------------------------------------+
bool ObjectGetTextControlCoordinates(long chart_id, const string name, double &x, double &y, double &width, double &height) {
// Retrieve properties of the text object
x = ObjectGetDouble(chart_id, name, OBJPROP_X); // X position
y = ObjectGetDouble(chart_id, name, OBJPROP_Y); // Y position
width = ObjectGetInteger(chart_id, name, OBJPROP_XSIZE); // Width
height = ObjectGetInteger(chart_id, name, OBJPROP_YSIZE); // Height
return true;
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit() {
CreateTextControl(); // Create the text control when the expert initializes
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
ObjectDelete(ChartID(), textControlName); // Clean up text control on deinitialization
}
//+------------------------------------------------------------------+
Binary file not shown.
BIN
View File
Binary file not shown.
+314
View File
@@ -0,0 +1,314 @@
//+------------------------------------------------------------------+
//| SampleSignal.mqh |
//| Copyright 2010, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
//+------------------------------------------------------------------+
//| include files |
//+------------------------------------------------------------------+
#include <Expert\ExpertSignal.mqh>
// wizard description start
//+------------------------------------------------------------------+
//| Description of the class |
//| Title=Signal on crossing of the price and the MA |
//| entering on the back movement |
//| Type=Signal |
//| Name=Sample |
//| Class=CSampleSignal |
//| Page= |
//| Parameter=PeriodMA,int,12 |
//| Parameter=ShiftMA,int,0 |
//| Parameter=MethodMA,ENUM_MA_METHOD,MODE_EMA |
//| Parameter=AppliedMA,ENUM_APPLIED_PRICE,PRICE_CLOSE |
//| Parameter=Limit,double,0.0 |
//| Parameter=StopLoss,double,50.0 |
//| Parameter=TakeProfit,double,50.0 |
//| Parameter=Expiration,int,10 |
//+------------------------------------------------------------------+
// wizard description end
//+------------------------------------------------------------------+
//| CSampleSignal. |
//| Purpose: Class of trading signal generator when price |
//| crosses moving average, |
//| entering on the subsequent back movement. |
//| It is derived from the CExpertSignal class. |
//+------------------------------------------------------------------+
class CSampleSignal : public CExpertSignal
{
protected:
CiMA m_MA; // object to access the values of the moving average
CiOpen m_open; // object to access the bar open prices
CiClose m_close; // object to access the bar close prices
//--- Setup parameters
int m_period_ma; // averaging period of the MA
int m_shift_ma; // shift of the MA along the time axis
ENUM_MA_METHOD m_method_ma; // averaging method of the MA
ENUM_APPLIED_PRICE m_applied_ma; // averaging object of the MA
double m_limit; // level to place a pending order relative to the MA
double m_stop_loss; // level to place a stop loss order relative to the open price
double m_take_profit; // level to place a take profit order relative to the open price
int m_expiration; // lifetime of a pending order in bars
public:
CSampleSignal();
//--- Methods to set the parameters
void PeriodMA(int value) { m_period_ma=value; }
void ShiftMA(int value) { m_shift_ma=value; }
void MethodMA(ENUM_MA_METHOD value) { m_method_ma=value; }
void AppliedMA(ENUM_APPLIED_PRICE value) { m_applied_ma=value; }
void Limit(double value) { m_limit=value; }
void StopLoss(double value) { m_stop_loss=value; }
void TakeProfit(double value) { m_take_profit=value; }
void Expiration(int value) { m_expiration=value; }
//---Method to validate the parameters
virtual bool ValidationSettings();
//--- Method to validate the parameters
virtual bool InitIndicators(CIndicators* indicators);
//--- Methods to generate signals to enter the market
virtual bool CheckOpenLong(double& price,double& sl,double& tp,datetime& expiration);
virtual bool CheckOpenShort(double& price,double& sl,double& tp,datetime& expiration);
//--- Methods to generate signals of pending order modification
virtual bool CheckTrailingOrderLong(COrderInfo* order,double& price);
virtual bool CheckTrailingOrderShort(COrderInfo* order,double& price);
protected:
//--- Object initialization method
bool InitMA(CIndicators* indicators);
bool InitOpen(CIndicators* indicators);
bool InitClose(CIndicators* indicators);
//--- Methods to access object data
double MA(int index) { return(m_MA.Main(index)); }
double Open(int index) { return(m_open.GetData(index)); }
double Close(int index) { return(m_close.GetData(index)); }
};
//+------------------------------------------------------------------+
//| CSampleSignal Constructor. |
//| INPUT: No. |
//| OUTPUT: No. |
//| REMARK: No. |
//+------------------------------------------------------------------+
void CSampleSignal::CSampleSignal()
{
//--- Setting the default values
m_period_ma =12;
m_shift_ma =0;
m_method_ma =MODE_EMA;
m_applied_ma =PRICE_CLOSE;
m_limit =0.0;
m_stop_loss =50.0;
m_take_profit=50.0;
m_expiration =10;
}
//+------------------------------------------------------------------+
//| Validation of parameters. |
//| INPUT: No. |
//| OUTPUT: true if the settings are correct, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::ValidationSettings()
{
//--- Validation of parameters
if(m_period_ma<=0)
{
printf(__FUNCTION__+": the MA period must be greater than zero");
return(false);
}
//--- Successful completion
return(true);
}
//+------------------------------------------------------------------+
//| Initialization of indicators and timeseries. |
//| INPUT: indicators - pointer to the object - collection of |
//| indicators and timeseries. |
//| OUTPUT: true in case of success, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::InitIndicators(CIndicators* indicators)
{
//--- Validation of the pointer
if(indicators==NULL) return(false);
//--- Initialization of the moving average
if(!InitMA(indicators)) return(false);
//--- Initialization of the timeseries of open prices
if(!InitOpen(indicators)) return(false);
//--- Initialization of the timeseries of close prices
if(!InitClose(indicators)) return(false);
//--- Successful completion
return(true);
}
//+------------------------------------------------------------------+
//| Initialization of the moving average |
//| INPUT: indicators - pointer to the object - collection of |
//| indicators and timeseries. |
//| OUTPUT: true in case of success, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::InitMA(CIndicators* indicators)
{
//--- Initialization of the MA object
if(!m_MA.Create(m_symbol.Name(),m_period,m_period_ma,m_shift_ma,m_method_ma,m_applied_ma))
{
printf(__FUNCTION__+": object initialization error");
return(false);
}
m_MA.BufferResize(3+m_shift_ma);
//--- Adding an object to the collection
if(!indicators.Add(GetPointer(m_MA)))
{
printf(__FUNCTION__+": object adding error");
return(false);
}
//--- Successful completion
return(true);
}
//+------------------------------------------------------------------+
//| Initialization of the timeseries of open prices. |
//| INPUT: indicators - pointer to the object - collection of |
//| indicators and timeseries. |
//| OUTPUT: true in case of success, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::InitOpen(CIndicators* indicators)
{
//--- Initialization of the timeseries object
if(!m_open.Create(m_symbol.Name(),m_period))
{
printf(__FUNCTION__+": object initialization error");
return(false);
}
//--- Adding an object to the collection
if(!indicators.Add(GetPointer(m_open)))
{
printf(__FUNCTION__+": object adding error");
return(false);
}
//--- Successful completion
return(true);
}
//+------------------------------------------------------------------+
//| Initialization of the timeseries of close prices. |
//| INPUT: indicators - pointer to the object - collection of |
//| indicators and timeseries. |
//| OUTPUT: true in case of success, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::InitClose(CIndicators* indicators)
{
//--- Initialization of the timeseries object
if(!m_close.Create(m_symbol.Name(),m_period))
{
printf(__FUNCTION__+": object initialization error");
return(false);
}
//--- Adding an object to the collection
if(!indicators.Add(GetPointer(m_close)))
{
printf(__FUNCTION__+": object adding error");
return(false);
}
//--- Successful completion
return(true);
}
//+------------------------------------------------------------------+
//| Check whether a Buy condition is fulfilled |
//| INPUT: price - variable for open price |
//| sl - variable for stop loss price, |
//| tp - variable for take profit price |
//| expiration - variable for expiration time. |
//| OUTPUT: true if the condition is fulfilled, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::CheckOpenLong(double& price,double& sl,double& tp,datetime& expiration)
{
//--- Preparing the data
double spread=m_symbol.Ask()-m_symbol.Bid();
double ma =MA(1);
double unit =PriceLevelUnit();
//--- Checking the condition
if(Open(1)<ma && Close(1)>ma && ma>MA(2))
{
price=m_symbol.NormalizePrice(ma-m_limit*unit+spread);
sl =m_symbol.NormalizePrice(price-m_stop_loss*unit);
tp =m_symbol.NormalizePrice(price+m_take_profit*unit);
expiration+=m_expiration*PeriodSeconds(m_period);
//--- Condition is fulfilled
return(true);
}
//--- Condition is not fulfilled
return(false);
}
//+------------------------------------------------------------------+
//| Check whether a Sell condition is fulfilled. |
//| INPUT: price - variable for open price, |
//| sl - variable for stop loss, |
//| tp - variable for take profit |
//| expiration - variable for expiration time. |
//| OUTPUT: true if the condition is fulfilled, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::CheckOpenShort(double& price,double& sl,double& tp,datetime& expiration)
{
//--- Preparing the data
double ma =MA(1);
double unit=PriceLevelUnit();
//--- Checking the condition
if(Open(1)>ma && Close(1)<ma && ma<MA(2))
{
price=m_symbol.NormalizePrice(ma+m_limit*unit);
sl =m_symbol.NormalizePrice(price+m_stop_loss*unit);
tp =m_symbol.NormalizePrice(price-m_take_profit*unit);
expiration+=m_expiration*PeriodSeconds(m_period);
//--- Condition is fulfilled
return(true);
}
//--- Condition is not fulfilled
return(false);
}
//+------------------------------------------------------------------+
//| Check whether the condition of modification |
//| of a Buy order is fulfilled. |
//| INPUT: order - pointer at the object-order, |
//| price - a variable for the new open price. |
//| OUTPUT: true if the condition is fulfilled, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::CheckTrailingOrderLong(COrderInfo* order,double& price)
{
//--- Checking the pointer
if(order==NULL) return(false);
//--- Preparing the data
double spread =m_symbol.Ask()-m_symbol.Bid();
double ma =MA(1);
double unit =PriceLevelUnit();
double new_price=m_symbol.NormalizePrice(ma-m_limit*unit+spread);
//--- Checking the condition
if(order.PriceOpen()==new_price) return(false);
price=new_price;
//--- Condition is fulfilled
return(true);
}
//+------------------------------------------------------------------+
//| Check whether the condition of modification |
//| of a Sell order is fulfilled. |
//| INPUT: order - pointer at the object-order, |
//| price - a variable for the new open price. |
//| OUTPUT: true if the condition is fulfilled, otherwise false. |
//| REMARK: No. |
//+------------------------------------------------------------------+
bool CSampleSignal::CheckTrailingOrderShort(COrderInfo* order,double& price)
{
//--- Checking the pointer
if(order==NULL) return(false);
//--- Preparing the data
double ma =MA(1);
double unit=PriceLevelUnit();
double new_price=m_symbol.NormalizePrice(ma+m_limit*unit);
//--- Checking the condition
if(order.PriceOpen()==new_price) return(false);
price=new_price;
//--- Condition is fulfilled
return(true);
}
//+------------------------------------------------------------------+
+3478
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
+13
View File
@@ -0,0 +1,13 @@
class test_color
{
public:
color col_inds;
void testcol()
{
col_inds = C'8,235,243';
}
};
Binary file not shown.