### FileMove Example Setup Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_arquivo.html Example script setup for demonstrating the FileMove function, including input parameters for source and destination file names and directories. ```mql5 //--- mosta a janela dos parâmetros de entrada quando lançado o script #property script_show_inputs //--- parâmetros de entrada input string InpSrcName="data.txt"; input string InpDstName="newdata.txt"; input string InpSrcDirectory="SomeFolder"; input string InpDstDirectory="OtherFolder"; //+------------------------------------------------------------------+ ``` -------------------------------- ### MQL5 Indicator Setup Example Source: https://mql5docs.onrender.com/indicadores_t%C3%A9cnicos.html This example demonstrates the basic setup for an MQL5 indicator, including properties like copyright, version, description, and indicator-specific settings such as plots, labels, types, and colors. ```mq5 #property copyright "Copyright 2000-2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property description "O indicador demonstra como obter dados" #property description "de buffers do indicador para o indicador técnico iCCI." #property description "Um símbolo e o prazo utilizado para o cálculo do indicador," #property description "são definidos pelos parâmetros de símbolo e período." #property description "O método de criação do manipulador é definido através do parâme #property indicator_separate_window #property indicator_buffers 1 ``` ```mq5 #property indicator_plots 1 //--- plotar iCCI #property indicator_label1 "iCCI" #property indicator_type1 DRAW_LINE #property indicator_color1 clrLightSeaGreen #property indicator_style1 STYLE_SOLID #property indicator_width1 1 //--- níveis horizontais na janela de indicador #property indicator_level1 -100.0 #property indicator_level2 100.0 ``` -------------------------------- ### iBWMFI Indicator Example Setup Source: https://mql5docs.onrender.com/indicadores_t%C3%A9cnicos.html Example MQL5 code demonstrating the setup for the iBWMFI indicator, including property declarations for indicator buffers, plots, and labels. This code defines how the indicator will be displayed and its data will be managed. ```mq5 #property copyright "Copyright 2000-2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property description "O indicador demonstra como obter dados" #property description "de buffers do indicador para o indicador técnico iBWMFI." #property description "Um símbolo e o prazo utilizado para o cálculo do indicador," #property description "são definidos pelos parâmetros de símbolo e período." #property description "O método de criação do manipulador é definido através do parâme #property indicator_separate_window #property indicator_buffers 2 #property indicator_plots 1 //--- plotar iBWMFI #property indicator_label1 "iBWMFI" #property indicator_type1 DRAW_COLOR_HISTOGRAM #property indicator_color1 clrLime,clrSaddleBrown,clrBlue,clrPink ``` -------------------------------- ### MQL5 Indicator Example Setup Source: https://mql5docs.onrender.com/indicadores_t%C3%A9cnicos.html Example MQL5 code demonstrating how to obtain indicator data for iRSI. It sets up properties for the indicator, including copyright, link, version, description, and display window. ```mq5 #property copyright "Copyright 2000-2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property description "O indicador demonstra como obter dados" #property description "de buffers do indicador para o indicador técnico iRSI." #property description "Um símbolo e o prazo utilizado para o cálculo do indicador," #property description "são definidos pelos parâmetros de símbolo e período." #property description "O método de criação do manipulador é definido através do parâme #property description "Todos os outros parâmetros são similares ao padrão Relative Str #property indicator_separate_window ``` -------------------------------- ### Socket Creation and Connection Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_rede.html Example demonstrating how to create a socket, connect to a server, send a GET request, and handle TLS certificate information. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The desired username for the new account. - **email** (string) - Required - The email address for the new account. - **password** (string) - Required - The password for the new account. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201 Created) - **userId** (string) - The unique identifier for the newly created user. - **message** (string) - A confirmation message. #### Response Example ```json { "userId": "usr_12345abcde", "message": "User created successfully." } ``` ``` -------------------------------- ### MQL Example: Preparing for Text Drawing with TextOut Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_objeto.html This example demonstrates the initial setup for using `TextOut`, including defining image dimensions, color format, and creating a `OBJ_BITMAP_LABEL` object to hold the graphic resource. ```MQL //--- largura e altura da tela (usado para o desenho) #define IMG_WIDTH 200 #define IMG_HEIGHT 200 //--- exibir a janela de parâmetro antes de lançar o script #property script_show_inputs //--- permite definir o formato de cor input ENUM_COLOR_FORMAT clr_format=COLOR_FORMAT_XRGB_NOALPHA; //--- array de desenho (buffer) uint ExtImg[IMG_WIDTH*IMG_HEIGHT]; //+------------------------------------------------------------------+ //| Programa Script da função start (iniciar)  | //+------------------------------------------------------------------+ void OnStart() { //--- criar o objeto OBJ_BITMAP_LABEL para desenhar ObjectCreate(0,"RELÓGIO",OBJ_BITMAP_LABEL,0,0,0); //--- especificar o nome do recurso gráfico para escrever no objeto RELÓGIO ObjectSetString(0,"RELÓGIO",OBJPROP_BMPFILE,"::IMG"); //--- variáveis auxiliares double a; // seta no canto uint nm=2700; // minutos no canto uint nh=2700*12; // horas no canto uint w,h; // variáveis para receber string de tamanhos de texto ``` -------------------------------- ### Network Connection Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_rede.html Example script demonstrating how to create a socket, connect to a server, send an HTTP GET request, and receive the response. ```APIDOC ## Network Connection Example ### Description This script demonstrates establishing a network connection, sending an HTTP GET request, and receiving the response using MQL5 network functions. ### Script Logic 1. Creates a socket using `SocketCreate()`. 2. Connects to a specified address and port using `SocketConnect()`. 3. Checks if the connection is secured by TLS using `SocketTlsCertificate()` and prints certificate details if available. 4. Sends an HTTP GET request to the server using `HTTPSend()`. 5. Receives the server's response using `HTTPRecv()`. 6. Prints connection status, certificate information, and request/response messages. 6. Closes the socket using `SocketClose()` upon completion or error. ### Example Usage ```mql5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { int socket=SocketCreate(); //--- check the handle if(socket!=INVALID_HANDLE) { //--- if everything is in order, connect if(SocketConnect(socket,Address,Port,1000)) { Print("Connected to ",Address,":",Port); string subject,issuer,serial,thumbprint; datetime expiration; //--- if the connection is protected by a certificate, display its data if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration)) { Print("TLS Certificate:"); Print(" Subject: ",subject); Print(" Issuer: ",issuer); Print(" Serial: ",serial); Print(" Thumbprint: ",thumbprint); Print(" Expiration: ",expiration); ExtTLS=true; // Assuming ExtTLS is a global or accessible variable } //--- send a GET request to the server if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n",39,ExtTLS)) { Print("GET request sent"); //--- read the response if(!HTTPRecv(socket,1000)) Print("Failed to get response, error ",GetLastError()); } else Print("Failed to send GET request, error ",GetLastError()); } else { Print("Failed connection to ",Address,":",Port,", error ",GetLastError()); } //--- close the socket after use SocketClose(socket); } else Print("Could not create socket, error ",GetLastError()); } //+------------------------------------------------------------------+ ``` ``` -------------------------------- ### Demo_FileReadLong Indicator Setup Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_arquivo.html Indicator properties and global variables for the Demo_FileReadLong example, including file name and directory inputs. ```mq5 //+------------------------------------------------------------------+ //| Demo_FileReadLong.mq5 | //| Copyright 2013, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2013, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" #property indicator_buffers 1 #property indicator_plots 1 //---- Plotar Etiqueta1 #property indicator_label1 "Volume" #property indicator_type1 DRAW_LINE #property indicator_color1 clrYellow #property indicator_style1 STYLE_SOLID #property indicator_width1 2 #property indicator_separate_window //--- paramêtros para leitura de dados input string InpFileName="Volume.bin"; // file name input string InpDirectoryName="Data"; // directory name //--- variáveis globais int ind=0; int size=0; ``` -------------------------------- ### Indicator Properties Setup Example Source: https://mql5docs.onrender.com/indicadores_customizados.html This example demonstrates setting various properties for a custom indicator, including separate window display, min/max values, horizontal levels, line width, color, and style. It also shows how to set text labels for the levels and a short name for the indicator using IndicatorSetString. ```mql5 #property indicator_separate_window #property indicator_minimum 0 #property indicator_maximum 100 //--- visualiza três níveis horizontais na janela separada #property indicator_level1 20 #property indicator_level2 50 #property indicator_level3 80 //--- definir a espessura dos níveis horizontais #property indicator_levelwidth 5 //--- definir a cor dos níveis horizontais #property indicator_levelcolor clrAliceBlue //--- definir o estilo dos níveis horizontais #property indicator_levelstyle STYLE_DOT //+------------------------------------------------------------------+ //| Função de inicialização do indicador customizado  | //+------------------------------------------------------------------+ int OnInit() { //--- definir as descrições dos níveis horizontais IndicatorSetString(INDICATOR_LEVELTEXT,0,"Primeiro Nível (índice 0)"); IndicatorSetString(INDICATOR_LEVELTEXT,1,"Segundo Nível (índice 1)"); IndicatorSetString(INDICATOR_LEVELTEXT,2,"Terceiro Nível (índice 2)"); //--- define o mome abreviado para o indicador IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetInteger() Demo"); return(INIT_SUCCEEDED); ``` -------------------------------- ### ChartScreenShot Example Setup Source: https://mql5docs.onrender.com/opera%C3%A7%C3%B5es_de_gr%C3%A1ficos.html Defines constants for image width and height used in ChartScreenShot calls. Ensure these values are appropriate for your desired output. ```mql5 #property description "O Expert Advisor demonstra como criar uma série de captura de t #property description gráfico usando a função ChartScreenShot(). Por conveniência, o #property description "mostrando sobre o gráfico. A altura e a largura das imagens são #define WIDTH 800 // ChartScreenShot() para Chamar a largura da imagem #define HEIGHT 600 // ChartScreenShot() para Chamar a altura da imagem ``` -------------------------------- ### Example: HTTP GET Request with TLS Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_rede.html Demonstrates creating a socket, connecting to a server, establishing a TLS connection if available, sending an HTTP GET request, and receiving the response. Closes the socket afterward. Ensure Address and Port are defined. ```mql5 void OnStart() { int socket=SocketCreate(); //--- verifica o identificador if(socket!=INVALID_HANDLE) { //--- se tudo estiver em ordem, conecte-se if(SocketConnect(socket,Address,Port,1000)) { Print("Conectado a ",Address,":",Port); string subject,issuer,serial,thumbprint; datetime expiration; //--- se a conexão estiver protegida por um certificado, exibe seus dados if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration)) { Print("Certificado TLS:"); Print(" Proprietário: ",subject); Print(" Emissor: ",issuer); Print(" Número: ",serial); Print(" Impressão digital: ",thumbprint); Print(" Expiração: ",expiration); ExtTLS=true; } //--- envia um pedido GET ao servidor if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r")) { Print("Solicitação GET enviada"); //--- leia a resposta if(!HTTPRecv(socket,1000)) Print("Falha ao obter resposta, erro ",GetLastError()); } else Print("Falha ao enviar solicitação GET, erro ",GetLastError()); } else { Print("Falhou conexão a ",Address,":",Port,", erro ",GetLastError()); } //--- fecha o soquete após ser usado SocketClose(socket); } else Print("Não foi possível criar o soquete, erro ",GetLastError()); } ``` -------------------------------- ### MQL5 Indicator Initialization Example Source: https://mql5docs.onrender.com/s%C3%A9ries_temporais_e_acesso_a_indicadores.html Sets up an MQL5 custom indicator, defining its properties, buffers, and initial settings. This snippet is part of the OnInit() function, responsible for indicator setup. ```mql5 #property indicator_separate_window #property indicator_buffers 1 #property indicator_plots 1 //---- plotar Spread #property indicator_label1 "Spread" #property indicator_type1 DRAW_HISTOGRAM #property indicator_color1 clrRed #property indicator_style1 STYLE_SOLID #property indicator_width1 1 //--- parâmetros de entrada input int bars=3000; //--- buffers do indicador double SpreadBuffer[]; //+------------------------------------------------------------------+ //| Função de inicialização do indicador customizado I've been asked to document code snippets. I will provide the JSON output based on the schema you provided. I will ensure that all code examples are copied verbatim and properly escaped. I will also group similar code snippets into the `codeList` where appropriate. I will not include any extra text or markdown in my response. I will only output valid JSON. The provided text does not contain any explicit code blocks or delimited code cells that can be extracted as code snippets. Therefore, the `codeSnippets` array will be empty. The page title, description, and summary will be generated based on the available text, but without any code examples to document. ``` -------------------------------- ### MQL5 Script Example for FileSeek Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_arquivo.html A basic MQL5 script setup with input parameters for filename, directory, and encoding type, intended to demonstrate file operations like FileSeek. ```mql5 //+------------------------------------------------------------------+ //| Demo_FileSeek.mq5 | //| Copyright 2013, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2013, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" //--- mosta a janela dos parâmetros de entrada quando lançado o script #property script_show_inputs //--- parâmetros de entrada input string InpFileName="file.txt"; // nome do arquivo input string InpDirectoryName="Data"; // nome do diretório input int InpEncodingType=FILE_ANSI; // ANSI=32 ou UNICODE=64 ``` ``` -------------------------------- ### Array Resizing and Sizing Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_para_array.html Demonstrates how to resize one-dimensional and multidimensional arrays, both with and without memory backup. It also shows how to get the size of an array and its dimensions. ```mql5 void OnStart() { //--- criar arrays double one_dim[]; double four_dim[][10][5][2]; //--- tamanhos int one_dim_size=25; int reserve=20; int four_dim_size=5; //--- variáveis auxiliares int size; //--- alocar memória sem fazer backup ArrayResize(one_dim,one_dim_size); ArrayResize(four_dim,four_dim_size); //--- 1. array unidimensional Print("+==========================================================+"); Print("Tamanhos de arrays:"); Print("1. Array unidimensional"); size=ArraySize(one_dim); PrintFormat("Tamanho dimensão zero = %d, Tamanho array = %d",one_dim_size,size); //--- 2. array multidimensional Print("2. Array multidimensional"); size=ArraySize(four_dim); PrintFormat("Tamanho dimensão zero = %d, Tamanho array = %d",four_dim_size,size); //--- tamanhos de dimensões int d_1=ArrayRange(four_dim,1); int d_2=ArrayRange(four_dim,2); int d_3=ArrayRange(four_dim,3); ``` ```mql5 Print("Verificar:"); Print("Dimensão zero = Tamanho de array / (Primeira dimensão * Segunda dimensão * PrintFormat("%d = %d / (%d * %d * %d)",size/(d_1*d_2*d_3),size,d_1,d_2,d_3); //--- 3. array unidimensional com backup de memória Print("3. Array unidimensional com backup de memória"); //--- dobro do valor one_dim_size*=2; //--- alocar memória com o backup ArrayResize(one_dim,one_dim_size,reserve); //--- imprimir o tamanho size=ArraySize(one_dim); PrintFormat("Tamanho com o backup = %d, Atual tamanho do array = %d",one_dim_size+r ``` -------------------------------- ### iDEMA Indicator Example Setup Source: https://mql5docs.onrender.com/indicadores_t%C3%A9cnicos.html This code snippet sets up the properties for a demo indicator that demonstrates how to obtain data from the iDEMA technical indicator's buffers. ```mq5 #property copyright "Copyright 2000-2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property description "O indicador demonstra como obter dados" #property description "de buffers do indicador para o indicador técnico iDEMA." #property description "Um símbolo e o prazo utilizado para o cálculo do indicador, ``` -------------------------------- ### Example Usage of DatabaseExport Source: https://mql5docs.onrender.com/trabalhar_com_bancos_de_dados.html Illustrates a basic setup for using the DatabaseExport function within an MQL5 script. This snippet shows the input parameter declaration and the start of the OnStart function. ```mql5 input int InpRates=100; //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { } ``` -------------------------------- ### MQL5 OnStart Function for Object Demonstration Source: https://mql5docs.onrender.com/elementos_b%C3%A1sicos_da_linguagem.html The main entry point for the script, demonstrating various ways to declare, create, and pass objects and object pointers, including arrays. ```mql5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- declaramos o objeto como uma variável com criação automática Foo foo1; //--- variante de passagem de objeto por referência PrintObject(foo1); //--- declaramos um ponteiro para um objeto e o criamos usando o operador 'new' Foo *foo2=new Foo("foo2"); //--- variante de passagem de um ponteiro para um objeto por referência PrintObject(foo2); // o ponteiro para o objeto é convertido automaticamente pelo co //--- declaramos um array de objetos Foo Foo foo_objects[5]; //--- variante de passagem de array de objetos PrintObjectsArray(foo_objects); // função separada para passagem de array de objeto //--- declaramos um array de ponteiros para objetos do tipo Foo Foo *foo_pointers[5]; for(int i=0;i<5;i++) foo_pointers[i]=new Foo("foo_pointer"); //--- variante de passagem de array de ponteiros PrintPointersArray(foo_pointers); // função separada para passagem de array de pont //--- antes de concluir o trabalho, sempre devemos excluir os objetos criados como pon delete(foo2); //--- removemos o array de ponteiros int size=ArraySize(foo_pointers); for(int i=0;i<5;i++) delete(foo_pointers[i]); //--- } ``` -------------------------------- ### Example Usage and Plotting Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Demonstrates how to create instances of CGeneralizedBellShapedMembershipFunction, define wrapper functions to get their values, and plot them using the CGraphic class. Includes setup for the graphic object and its axes. ```cpp //+------------------------------------------------------------------+ //| GeneralizedBellShapedMembershipFunction.mq5 | //| Copyright 2000-2024, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #include #include //--- Create membership functions CGeneralizedBellShapedMembershipFunction func1(5, 1, 3); CGeneralizedBellShapedMembershipFunction func2(5, 2, 3); CGeneralizedBellShapedMembershipFunction func3(5, 3, 3); //--- Create wrappers for membership functions double GeneralizedBellShapedMembershipFunction1(double x) { return(func1.GetValue(x)); double GeneralizedBellShapedMembershipFunction2(double x) { return(func2.GetValue(x)); double GeneralizedBellShapedMembershipFunction3(double x) { return(func3.GetValue(x)); //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- create graphic CGraphic graphic; if(!graphic.Create(0,"GeneralizedBellShapedMembershipFunction",0,30,30,780,380)) { graphic.Attach(0,"GeneralizedBellShapedMembershipFunction"); } graphic.HistoryNameWidth(70); graphic.BackgroundMain("GeneralizedBellShapedMembershipFunction"); graphic.BackgroundMainSize(16); //--- create curve graphic.CurveAdd(GeneralizedBellShapedMembershipFunction1,0.0,10.0,0.1,CURVE_LINES, graphic.CurveAdd(GeneralizedBellShapedMembershipFunction2,0.0,10.0,0.1,CURVE_LINES, graphic.CurveAdd(GeneralizedBellShapedMembershipFunction3,0.0,10.0,0.1,CURVE_LINES, //--- sets the X-axis properties graphic.XAxis().AutoScale(false); graphic.XAxis().Min(0.0); graphic.XAxis().Max(10.0); graphic.XAxis().DefaultStep(1.0); //--- sets the Y-axis properties graphic.YAxis().AutoScale(false); graphic.YAxis().Min(0.0); graphic.YAxis().Max(1.1); graphic.YAxis().DefaultStep(0.2); //--- plot graphic.CurvePlotAll(); graphic.Update(); } ``` -------------------------------- ### OnStart Function Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_comuns.html Demonstrates the usage of CMyList and CItem classes. It creates dynamic and automatic items, inserts them into the list, and then destroys the list. This example illustrates dynamic memory management and list manipulation. ```cpp void OnStart() { CMyList list; CItem items[10]; CItem* item; //--- item=new CItem; if(item!=NULL) { item.Initialize(100,"dinâmico"); item.PrintMe(); list.InsertToBegin(item); } //--- for(int i=0; i<10; i++) { items[i].Initialize(i,"automático"); items[i].PrintMe(); item=GetPointer(items[i]); if(CheckPointer(item)!=POINTER_INVALID) list.InsertToBegin(item); } //--- item=new CItem; if(item!=NULL) { item.Initialize(200,"dinâmico"); item.PrintMe(); list.InsertToBegin(item); } //--- list.Destroy(); //--- } ``` -------------------------------- ### Example OnInit Function for an EA Source: https://mql5docs.onrender.com/manipula%C3%A7%C3%A3o_de_eventos.html This example demonstrates a typical OnInit function for an Expert Advisor, including input parameters and basic initialization logic. ```mql5 //--- input parameters input int ma_period=20; // período de média móvel //--- identificador do indicador usado no Expert Advisor int indicator_handle; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- verificamos se o valor ma_period é correto ``` -------------------------------- ### Get Last Order Ticket Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_negocia%C3%A7%C3%A3o.html Example snippet showing how to get the ticket number of the last order from the trading history within the OnTrade function. ```cpp //+------------------------------------------------------------------+ //| Função Trade | //+------------------------------------------------------------------+ void OnTrade() { //--- receber ticket da última ordem do histórico comercial da semana ulong last_order=GetLastOrderTicket(); ``` -------------------------------- ### File Reading Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_arquivo.html Example script demonstrating how to open a binary file for reading and print its path. It includes input parameters for the file name and directory. ```mql5 //--- mosta a janela dos parâmetros de entrada quando lançado o script #property script_show_inputs //--- paramêtros para leitura de dados input string InpFileName="Trend.bin"; // file name input string InpDirectoryName="Data"; // nome do diretório //+------------------------------------------------------------------+ //| Programa Script da função start (iniciar)  | //+------------------------------------------------------------------+ void OnStart() { //--- abre o arquivo ResetLastError(); int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN|FILE_ if(file_handle!=INVALID_HANDLE) { PrintFormat("%s arquivo está disponível para leitura",InpFileName); PrintFormat("Caminho do arquivo: %s\Files\",TerminalInfoString(TERMINAL_DATA_P //--- variáveis ​adicionais int str_size; string str; ``` -------------------------------- ### TrapezoidMembershipFunction Example Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html An example demonstrating the usage of CTrapezoidMembershipFunction and CGraphic for plotting. It includes necessary includes and setup for membership functions. ```mq5 //+------------------------------------------------------------------+ //| TrapezoidMembershipFunction.mq5 | //| Copyright 2000-2024, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #include #include //--- Create membership functions ``` -------------------------------- ### MQL5 OnStart Function for Pointer Verification Example Source: https://mql5docs.onrender.com/elementos_b%C3%A1sicos_da_linguagem.html Illustrates the creation of an uninitialized object within the OnStart function, setting the stage for pointer verification examples. ```mql5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- criamos um objeto não inicializado ``` -------------------------------- ### A (Get) Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Retrieves the start parameter of the fuzzy set. ```APIDOC ## A (Get) ### Description Retrieves the start parameter of the fuzzy set. ### Method `double A()` ### Return Value Start parameter of the fuzzy set. ``` -------------------------------- ### MQL5 OnInit Function Example Source: https://mql5docs.onrender.com/manipula%C3%A7%C3%A3o_de_eventos.html Example of the OnInit() function for an Expert Advisor (EA). It prints the build number and demonstrates how to retrieve the deinitialization reason using both _UninitReason and UninitializeReason(). Use this for EA initialization logic. ```mql5 input int fake_parameter=3; // parâmetro inútil //+----------´--------------------------------------------------------+ //| Expert initialization function | //+----------´--------------------------------------------------------+ int OnInit() { //--- Obtemos o número da compilação do programa Print(__FUNCTION__," Build #",__MQLBUILD__); //--- Código de motivo de reinicialização pode ser obtido na OnInit() Print(__FUNCTION__," Ao reinicializar o EA, você pode obter o código de motivo da d //--- Primeira maneira de obter o código de motivo de desinicialização Print(__FUNCTION__," _UninitReason = ",getUninitReasonText(_UninitReason)); //--- Segunda maneira de obter o código de motivo de desinicialização Print(__FUNCTION__," UninitializeReason() = ",getUninitReasonText(UninitializeReaso //--- return(INIT_SUCCEEDED); } ``` -------------------------------- ### Initialize Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Inicializa o programa OpenCL. Pode opcionalmente mostrar o log de inicialização. ```APIDOC ## Initialize ### Description Inicializa o programa OpenCL. Pode opcionalmente mostrar o log de inicialização. ### Method `bool Initialize(string program, bool show_log = true)` ### Parameters #### Path Parameters - `program` (string) - Identificador de programa OpenCL. - `show_log` (bool) - Ativar o registro de mensagens no diário (padrão: true). ### Return Value Retorna `true`, se a inicialização for bem-sucedida. Caso contrário, retorna `false`. ``` -------------------------------- ### HTTPSend and HTTPRecv Example Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_rede.html Example demonstrating how to send an HTTP GET request and receive a response using MQL5 socket functions. ```APIDOC ## POST /api/users ### Description This endpoint is used to create a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": 123, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### A (Get Method) Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Retrieves the start parameter of the decreasing range. ```APIDOC ## A (Get Method) ### Description Retrieves the start parameter of the decreasing range. ### Method GET ### Endpoint /A ### Return Value - **double**: The start parameter of the decreasing range. ``` -------------------------------- ### Script Example for File Operations Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_arquivo.html An example script demonstrating how to initiate file operations by setting input parameters and preparing to search for files. It includes setting a default array size for file names. ```MQL5 //--- mostrar a janela de parâmetros de entrada quando do lançamento do script #property script_show_inputs //--- data para arquivos antigos input datetime InpFilesDate=D'2013.01.01 00:00'; //+------------------------------------------------------------------+ //| Programa Script da função start (iniciar)  | //+------------------------------------------------------------------+ void OnStart() { string file_name; // variável para armazenar os nomes dos arquivos string filter="*.txt"; // filtrar parar pesquisar os arquivos datetime create_date; // data de criação do arquivo string files[]; // lista de nome dos arquivos int def_size=25; // tamanho do array por padrão int size=0; // número de arquivos //--- alocar memória para o array ArrayResize(files,def_size); //--- receber o manipulador de pesquisa na raiz da pasta local ``` -------------------------------- ### P_ShapedMembershipFunction Example Script Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html An example script demonstrating the creation and plotting of P_ShapedMembershipFunction objects. It includes necessary includes and setup for the CGraphic class. ```MQL5 //+------------------------------------------------------------------+ //| P_ShapedMembershipFunction.mq5 | //| Copyright 2016, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #include #include //--- Create membership functions CP_ShapedMembershipFunction func1(0,0.5,3,9); CP_ShapedMembershipFunction func2(0,4,5.5,9); CP_ShapedMembershipFunction func3(0,6,7,9); //--- Create wrappers for membership functions double P_ShapedMembershipFunction1(double x) { return(func1.GetValue(x)); } double P_ShapedMembershipFunction2(double x) { return(func2.GetValue(x)); } double P_ShapedMembershipFunction3(double x) { return(func3.GetValue(x)); } //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- create graphic CGraphic graphic; if(!graphic.Create(0,"P_ShapedMembershipFunction",0,30,30,780,380)) { graphic.Attach(0,"P_ShapedMembershipFunction"); } graphic.HistoryNameWidth(70); graphic.BackgroundMain("P_ShapedMembershipFunction"); graphic.BackgroundMainSize(16); //--- create curve graphic.CurveAdd(P_ShapedMembershipFunction1,0.0,10.0,0.1,CURVE_LINES,"[0, 0.5, 3, graphic.CurveAdd(P_ShapedMembershipFunction2,0.0,10.0,0.1,CURVE_LINES,"[0, 4, 5.5, graphic.CurveAdd(P_ShapedMembershipFunction3,0.0,10.0,0.1,CURVE_LINES,"[0, 6, 7, 9] //--- sets the X-axis properties graphic.XAxis().AutoScale(false); graphic.XAxis().Min(0.0); graphic.XAxis().Max(10.0); graphic.XAxis().DefaultStep(1.0); //--- sets the Y-axis properties graphic.YAxis().AutoScale(false); graphic.YAxis().Min(0.0); graphic.YAxis().Max(1.1); graphic.YAxis().DefaultStep(0.2); //--- plot graphic.CurvePlotAll(); graphic.Update(); } ``` -------------------------------- ### Example Socket Connection and HTTPSend Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_rede.html This example demonstrates setting up a socket connection and sending a request. The Address must be added to the allowed list in the terminal settings for the example to function. ```mql5 //+------------------------------------------------------------------+ //| SocketExample.mq5 | //| Copyright 2018, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2000-2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property description "Para o exemplo funcionar, adicione Address à lista de permitido #property script_show_inputs input string Address="www.mql5.com"; input int Port =80; bool ExtTLS =false; //+------------------------------------------------------------------+ //| Enviando comandos para o servidor | //+------------------------------------------------------------------+ bool HTTPSend(int socket,string request) { char req[]; int len=StringToCharArray(request,req)-1; ``` -------------------------------- ### Example: Get Chart Window Number for Indicator Source: https://mql5docs.onrender.com/opera%C3%A7%C3%B5es_de_gr%C3%A1ficos.html Example script demonstrating how to retrieve the chart window number for an indicator using its short name. This example assumes the indicator's short name is provided as an input parameter. ```mql5 #property script_show_inputs //--- parâmetros de entrada input string shortname="MACD(12,26,9)"; //+------------------------------------------------------------------+ //| Retorna o múmero da janela do gráfico com este indicador | //+------------------------------------------------------------------+ ``` -------------------------------- ### Matrix and Vector Initialization Example in MQL5 Source: https://mql5docs.onrender.com/m%C3%A9todos_matriciais_e_vetoriais.html Provides an example of creating and initializing a matrix and a vector using custom range functions in MQL5. ```MQL5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- int size_m=3, size_k=4; matrix m(size_m,size_k,MatrixArange,-2.,0.1); // primeiro cria uma matriz não-inici Print("matrix m \n",m); // em seguida, a função MatrixArange matrixf m_float(5,5,MatrixArange,-2.f,0.1f); // após a criação de uma matriz do ti Print("matrix m_float \n",m_float); vector v(size_k,VectorArange,-10.0); // após a criação de um vetor, Vector Print("vector v \n",v); } ``` -------------------------------- ### Get Time Series Data by Start Time Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Retrieves time series data elements starting from a specified time. Returns the number of elements retrieved or -1 on error. ```MQL5 int GetData( datetime start_time, // starting time int count, // number of elements double& buffer // target array ) const ``` -------------------------------- ### MQL5 DLL Integration Example Source: https://mql5docs.onrender.com/m%C3%A9todos_matriciais_e_vetoriais.html Example demonstrating how to import and use MQL5 matrix/vector functions from a DLL. ```APIDOC ## MQL5 DLL Integration Example ### Description This section provides examples of how MQL5 matrices and vectors can be integrated with DLLs, including function signatures in both MQL5 and C++. ### MQL5 Import Example ```mql5 #import "mmlib.dll" bool sgemm(uint flags, matrix &C, const matrix &A, const matrix &B); #import ``` ### C++ Export Example ```cpp extern "C" __declspec(dllexport) bool sgemm(UINT flags, float *C, const float *A, const float *B, UINT rowsA, UINT colsA, UINT rowsB, UINT colsB, UINT rowsC, UINT colsC); ``` ### Important Note When passing matrices and vectors to DLLs, it is essential to also pass their sizes (dimensions) to ensure correct data processing. ``` -------------------------------- ### Get Data by Start Time Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Retrieves a specified number of data elements from an indicator buffer starting from a given datetime. Returns the count of received elements or -1 on error. ```MQL5 int GetData( const datetime start_time, const int count, const int buffer_num, double& buffer[] ) const ``` -------------------------------- ### Get Data by Start Position Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Retrieves a specified number of data elements from an indicator buffer starting from a given position. Returns the count of received elements or -1 on error. ```MQL5 int GetData( const int start_pos, const int count, const int buffer_num, double& buffer[] ) const ``` -------------------------------- ### OnInit Function Source: https://mql5docs.onrender.com/biblioteca_padr%C3%A3o.html Initializes the MQL5 program, creates the application dialog, and starts its execution. Returns INIT_FAILED on error. ```cpp //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- create application dialog if(!ExtDialog.Create(0,"Controls",0,40,40,380,344)) return(INIT_FAILED); //--- run application ExtDialog.Run(); //--- succeed return(INIT_SUCCEEDED); } ``` -------------------------------- ### MQL5 Socket Example Script Header Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_rede.html Basic MQL5 script structure with socket example setup. Requires adding the server address to the allowed list for the script to function properly. ```mql5 //+------------------------------------------------------------------+ //| SocketExample.mq5 | //| Copyright 2018, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2000-2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property description "Para o exemplo funcionar, adicione Address à lista de permitido" #property script_show_inputs input string Address="www.mql5.com"; input int Port =80; ``` -------------------------------- ### MQL5 Script Example for File Operations Source: https://mql5docs.onrender.com/fun%C3%A7%C3%B5es_de_arquivo.html Example script demonstrating input parameters for symbol data retrieval and file writing. Includes parameters for symbol name, timeframe, indicator settings, date range, and file output. ```mql5 //+------------------------------------------------------------------+ //| Demo_FileWriteDouble.mq5 | //| Copyright 2013, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2013, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" //--- mostrar a janela de parâmetros de entrada quando do lançamento do script #property script_show_inputs //--- parâmetros para a recepção de dados a partir do terminal input string InpSymbolName="EURJPY"; // par de moedas input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_M15; // período de tempo input int InpMAPeriod=10; // período suavizado input int InpMAShift=0; // deslocacamente de indica input ENUM_MA_METHOD InpMAMethod=MODE_SMA; // tipo de suavização input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // tipo de preço input datetime InpDateStart=D'2013.01.01 00:00'; // data de início da cópia //--- parâmetros para escrever dados no arquivo input string InpFileName="MA.csv"; // file name input string InpDirectoryName="Data"; // nome do diretório //+------------------------------------------------------------------+ //| Programa Script da função start (iniciar)  | //+------------------------------------------------------------------+ void OnStart() { ```