### Python MetaTrader5 copy_rates_from_pos Example Source: https://www.mql5.com/en/docs/python_metatrader5/mt5copyratesfrompos_py Demonstrates how to initialize MetaTrader5, retrieve 10 daily bars for GBPUSD starting from the current position, and then process and display the data. It shows how to get raw rate data and convert it into a pandas DataFrame for easier analysis. ```python from datetime import datetime import MetaTrader5 as mt5 # display data on the MetaTrader 5 package print("MetaTrader5 package author: ", mt5.__author__) print("MetaTrader5 package version: ", mt5.__version__) # import the 'pandas' module for displaying data obtained in the tabular form import pandas as pd pd.set_option('display.max_columns', 500) # number of columns to be displayed pd.set_option('display.width', 1500) # max table width to display # establish connection to MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() # get 10 GBPUSD D1 bars from the current day rates = mt5.copy_rates_from_pos("GBPUSD", mt5.TIMEFRAME_D1, 0, 10) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() # display each element of obtained data in a new line print("Display obtained data 'as is'") for rate in rates: print(rate) # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the datetime format rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s') # display data print("\nDisplay dataframe with data") print(rates_frame) ``` -------------------------------- ### Get Terminal Build and 64-bit Status Source: https://www.mql5.com/en/docs/check/terminalinfodouble This example demonstrates how to retrieve the terminal's build number and whether it is a 64-bit version using TerminalInfoInteger. It then prints this information to the journal. ```mql5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- get the build number of the running terminal and its "64-bit terminal" property int build = TerminalInfoInteger(TERMINAL_BUILD); bool x64 = TerminalInfoInteger(TERMINAL_X64); //--- print the obtained terminal data in the journal PrintFormat("MetaTrader 5 %s build %d", (x64 ? "x64" : "x32"), build); /* result: MetaTrader 5 x64 build 4330 */ } ``` -------------------------------- ### Simple Custom Indicator Example Source: https://www.mql5.com/en/docs/customind A basic custom indicator demonstrating indicator properties, buffer mapping with SetIndexBuffer, and the OnCalculate function structure. Use this as a starting point for creating your own indicators. ```mql5 #property indicator_chart_window #property indicator_buffers 1 #property indicator_plots 1 //---- plot Label1 #property indicator_label1 "Label1" #property indicator_type1 DRAW_LINE #property indicator_color1 clrRed #property indicator_style1 STYLE_SOLID #property indicator_width1 1 //--- indicator buffers double Label1Buffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ void OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA); //--- } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const int begin, const double &price[]) { //--- Print("begin = ",begin," prev_calculated = ",prev_calculated," rates_total = ",rates_total); //--- return value of prev_calculated for next call return(rates_total); } ``` -------------------------------- ### Python MetaTrader5 terminal_info() Example Source: https://www.mql5.com/en/docs/python_metatrader5/mt5terminalinfo_py This snippet demonstrates how to initialize a connection to MetaTrader 5, retrieve terminal information, and display it in different formats including a named tuple, a dictionary, and a Pandas DataFrame. It also shows how to display package version and author information. Ensure MetaTrader5 is installed and initialized before use. ```python import MetaTrader5 as mt5 import pandas as pd # display data on the MetaTrader 5 package print("MetaTrader5 package author: ",mt5.__author__) print("MetaTrader5 package version: ",mt5.__version__) # establish connection to the MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed, error code =",mt5.last_error()) quit() # display data on MetaTrader 5 version print(mt5.version()) # display info on the terminal settings and status terminal_info=mt5.terminal_info() if terminal_info!=None: # display the terminal data 'as is' print(terminal_info) # display data in the form of a list print("Show terminal_info()._asdict():") terminal_info_dict = mt5.terminal_info()._asdict() for prop in terminal_info_dict: print(" {}={}".format(prop, terminal_info_dict[prop])) print() # convert the dictionary into DataFrame and print df=pd.DataFrame(list(terminal_info_dict.items()),columns=['property','value']) print("terminal_info() as dataframe:") print(df) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() ``` -------------------------------- ### OnStart Function Signature Source: https://www.mql5.com/en/docs/basis/function/events The OnStart() function is the Start event handler for scripts. It must be of void type with no parameters. ```mql5 void OnStart(); ``` -------------------------------- ### Install Supporting Packages Source: https://www.mql5.com/en/docs/python_metatrader5 Install essential Python libraries like matplotlib for plotting and pandas for data manipulation. These are commonly used with MetaTrader5 data. ```bash pip install matplotlib ``` ```bash pip install pandas ``` -------------------------------- ### Install MetaTrader5 Package Source: https://www.mql5.com/en/docs/python_metatrader5 Install the MetaTrader5 package for Python using pip. This is the first step to enable integration. ```bash pip install MetaTrader5 ``` -------------------------------- ### Object Creation and Initialization Examples Source: https://www.mql5.com/en/docs/basis/types/classes Demonstrates various ways to create and initialize objects of a class using different constructors, including default, parametric, and copy constructors. Also shows dynamic object creation and pointer handling. ```mql5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { // CFoo foo; // This variant cannot be used - a default constructor is not set //--- Possible options to create the CFoo object CFoo foo1(TimeCurrent()); // An explicit call of a parametric constructor CFoo foo2(); // An explicit call of a parametric constructor with a default parameter CFoo foo3=D'2009.09.09'; // An implicit call of a parametric constructor CFoo foo40(foo1); // An explicit call of a copy constructor CFoo foo41=foo1; // An implicit call of a copy constructor CFoo foo5; // An explicit call of a default constructor (if there is no default constructor, // then a parametric constructor with a default value is called) //--- Possible options to receive CFoo pointers CFoo *pfoo6=new CFoo(); // Dynamic creation of an object and receiving of a pointer to it CFoo *pfoo7=new CFoo(TimeCurrent());// Another option of dynamic object creation CFoo *pfoo8=GetPointer(foo1); // Now pfoo8 points to object foo1 CFoo *pfoo9=pfoo7; // pfoo9 and pfoo7 point to one and the same object // CFoo foo_array[3]; // This option cannot be used - a default constructor is not specified //--- Show the value of m_call_time Print("foo1.m_call_time=",foo1.ToString()); Print("foo2.m_call_time=",foo2.ToString()); Print("foo3.m_call_time=",foo3.ToString()); Print("foo4.m_call_time=",foo4.ToString()); Print("foo5.m_call_time=",foo5.ToString()); Print("pfoo6.m_call_time=",pfoo6.ToString()); Print("pfoo7.m_call_time=",pfoo7.ToString()); Print("pfoo8.m_call_time=",pfoo8.ToString()); Print("pfoo9.m_call_time=",pfoo9.ToString()); //--- Delete dynamically created arrays delete pfoo6; delete pfoo7; //delete pfoo8; // You do not need to delete pfoo8 explicitly, since it points to the automatically created object foo1 //delete pfoo9; // You do not need to delete pfoo9 explicitly. since it points to the same object as pfoo7 } ``` -------------------------------- ### Using Resources from Another EX5 Program (with path) Source: https://www.mql5.com/en/docs/runtime/resources Shows how to use a resource from a different EX5 file by specifying the path to the EX5 file and the resource name, separated by '::'. ```mql ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"\\\Scripts\\\Draw_Triangles_Script.ex5::Files\\\triangle.bmp"); ``` -------------------------------- ### Get Terminal Directory Path Source: https://www.mql5.com/en/docs/runtime/resources Retrieves the path to the directory where the MetaTrader 5 client terminal is started. ```mql5 //--- Folder, in which terminal data are stored string terminal_path=TerminalInfoString(TERMINAL_PATH); ``` -------------------------------- ### Get Trade Request Textual Description Source: https://www.mql5.com/en/docs/constants/structures/mqltradetransaction This function provides a textual description of a MqlTradeRequest object, starting with the action type and symbol. ```mql string RequestDescription(const MqlTradeRequest &request) { //--- string desc=EnumToString(request.action)+"\r\n"; desc+="Symbol: "+request.symbol+"\r\n"; ``` -------------------------------- ### Correct Resource Inclusion Examples Source: https://www.mql5.com/en/docs/runtime/resources Demonstrates correct ways to specify resource paths. Ensure paths adhere to length limits and character restrictions. Resources are compressed automatically. ```mql5 #resource "\\Images\\euro.bmp" // euro.bmp is located in terminal_data_directory\MQL5\Images\ ``` ```mql5 #resource "picture.bmp" // picture.bmp is located in the same directory as the source file ``` ```mql5 #resource "Resource\\map.bmp" // the resource is located in source_file_directory\Resource\map.bmp ``` -------------------------------- ### MQL5 Script for OpenCL Program Creation and Execution Source: https://www.mql5.com/en/docs/opencl/clprogramcreate Demonstrates the initialization of OpenCL objects, including context, program, kernel, and buffer creation, followed by execution. ```MQL5 //--- #define ARRAY_SIZE 100 // size of the array #define TOTAL_ARRAYS 5 // total arrays //--- OpenCL handles int cl_ctx; // OpenCL context handle int cl_prg; // OpenCL program handle int cl_krn; // OpenCL kernel handle int cl_mem; // OpenCL buffer handle //--- double DataArray1[]; // data array for CPU calculation double DataArray2[]; // data array for GPU calculation //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ int OnStart() { //--- initialize OpenCL objects //--- create OpenCL context if((cl_ctx=CLContextCreate())==INVALID_HANDLE) { Print("OpenCL not found. Error=",GetLastError()); return(1); } //--- create OpenCL program if((cl_prg=CLProgramCreate(cl_ctx,cl_src))==INVALID_HANDLE) { CLContextFree(cl_ctx); Print("OpenCL program create failed. Error=",GetLastError()); return(1); } //--- create OpenCL kernel if((cl_krn=CLKernelCreate(cl_prg,"Test_GPU"))==INVALID_HANDLE) { CLProgramFree(cl_prg); CLContextFree(cl_ctx); Print("OpenCL kernel create failed. Error=",GetLastError()); return(1); } //--- create OpenCL buffer if((cl_mem=CLBufferCreate(cl_ctx,ARRAY_SIZE*TOTAL_ARRAYS*sizeof(double),CL_MEM_READ_WRITE))==INVALID_HANDLE) { CLKernelFree(cl_krn); CLProgramFree(cl_prg); CLContextFree(cl_ctx); ``` -------------------------------- ### Python MT5 copy_ticks_range Example Source: https://www.mql5.com/en/docs/python_metatrader5/mt5copyticksrange_py Demonstrates how to retrieve tick data for a symbol within a specific date range using the copy_ticks_range function. It includes necessary imports and setup for MetaTrader 5. ```python from datetime import datetime import MetaTrader5 as mt5 # connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() # get the last tick on EURUSD H1 symbol = "EURUSD" date_from = datetime(2023, 10, 26, 10, 0, 0) date_to = datetime(2023, 10, 26, 11, 0, 0) # get ticks for the specified range ticks = mt5.copy_ticks_range(symbol, date_from, date_to, mt5.COPY_TICKS_ALL) # deinitialize MetaTrader 5 mt5.shutdown() if ticks is None: print("copy_ticks_range failed, error code =", mt5.last_error()) elif len(ticks) == 0: print("no ticks found for the specified range") else: # create DataFrame from the obtained data ticks_frame = mt5.copy_ticks_range(symbol, date_from, date_to, mt5.COPY_TICKS_ALL) print(ticks_frame) # display only last 5 ticks from the array print("Last 5 ticks:") print(ticks_frame[-5:]) ``` -------------------------------- ### Using Resources from Another EX5 Program (without path) Source: https://www.mql5.com/en/docs/runtime/resources Demonstrates using a resource from another EX5 file without specifying the EX5 file's path. The system searches for the EX5 file in the same directory as the calling program. ```mql ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"Draw_Triangles_Script.ex5::Files\\\triangle.bmp"); ``` -------------------------------- ### Script Program Start Function with Resource Manipulation Source: https://www.mql5.com/en/docs/runtime/resources Demonstrates using resource variables to display and modify images, create new graphical resources, and apply them to objects. Includes error handling for unavailable resources. ```MQL5 //+------------------------------------------------------------------+ //| Script program start function | //+------------------------------------------------------------------+ void OnStart() { //--- output the size of the image [width, height] stored in euro resource variable Print(ArrayRange(euro,1),", ",ArrayRange(euro,0)); //--- change the image in euro - draw the red horizontal stripe in the middle for(int x=0;x