📈

Creating a Trade Copier for Metatrader 5

Aug 20, 2024

Trade Copier Program for Metatrader 5

Overview

  • Creating a trade copier program for Metatrader 5
  • The program will operate between two Metatrader terminals with different accounts.
  • One terminal acts as "master" and the other as "slave".
  • The master terminal will send commands (open/close trades) to the slave terminal.

Development Environment Setup

  1. Open Metacodes Language Editor.
  2. Create a new Expert Advisor program (e.g., trade copier youtube).
  3. Delete comments and unneeded functions (like onTick).

File Sharing Mechanism

  • Use a shared folder for file storage accessible by both terminals.
  • Define file name for trade information (e.g., mqlinfo string.bin).
  • Include necessary libraries:
    • trail.mqh for position handling.
    • arraylong.mqh for ticket storage.

Mode Enumeration

  • Define an enumeration for operating modes:
    • mode master
    • mode slave
  • Set default mode to slave.

Timer Setup

  • Use event set timer for a recurring event (e.g., every 500 milliseconds).
  • Remember to kill the timer in onDeinit.

Master Terminal Logic

  1. Opening/Creating File: Use file open to write to the shared file.
  2. Position Handling:
    • If no open positions, delete the file.
    • Loop through all open positions and write their properties (ticket, symbol, volume, type, SL, TP) to the file.
  3. Closing the File after processing.

Slave Terminal Logic

  1. File Handling: Open the shared file in read mode.
  2. Reading Positions:
    • Loop until the end of the file, read trades and their properties.
  3. Position Comparison:
    • Loop through existing slave positions, check if they match master positions using position ticket stored as a comment.
    • If not found, open the position on the slave terminal.
  4. Updating Positions: Check and update SL and TP if they differ from those in the master.
  5. Closing Unmatched Positions: Loop through slave positions, close those not found in the master.

Compilation and Testing

  • Compile the code in the MetaEditor.
  • Drag and drop the newly created Expert Advisor onto a chart in both terminals.
  • Ensure the master is set to mode master and the slave to mode slave.

Performance Demonstration

  • Open positions on the master terminal to see them copied to the slave.
  • Changes in SL and TP on the master are reflected on the slave.
  • Note: Opening a position on the slave that isn't on the master will be closed by the program.

Code Summary

  • The program contains about 99 lines of code.
  • Easily modifiable for additional features like adjusting lot sizes, using FTP servers, etc.

Conclusion

  • This tutorial introduced a basic trade copier for Metatrader 5.
  • Encouragement to subscribe for more programming tutorials and trading automation content.