- Do you know how to write a trading robot in MetaTrader 5 and run it with high stability?
- Technical introduction to MetaTrader 5 and MQL5
- Basic structure of EA in MQL5
- Sending orders and managing positions
- Practical example — Cross Moving Average Robot
- Installing and running MetaTrader 5 on a server (VPS / Cloud)
- Testing, optimizing, and deploying robots
- Choosing a location and configuring a VPS for traders
- Security, monitoring and practical tips
- Summary and technical proposal
- Frequently Asked Questions
Do you know how to write a trading robot in MetaTrader 5 and run it with high stability?
This step-by-step guide will help you get familiar with the environment. MetaTrader 5 and programming language MQL5 It covers writing, testing, and deploying an Expert Advisor (EA). It also includes practical tips on running it 24/7 on a VPS/cloud server, choosing a location with the lowest ping, security, and monitoring to ensure your robot runs in a real-world environment with stability and low latency.
Technical introduction to MetaTrader 5 and MQL5
MetaTrader 5 (MT5) It is an advanced platform that MQL5 It is used as a programming language for writing Expert Advisors (EAs), indicators, and scripts. Structure MQL5 It is similar to C++ and the class CTrade It is provided for sending orders and managing trades.
Prerequisites: Installation MetaTrader 5/MetaEditor, access to the broker's data feed or demo/real account, and in the server environment, it is recommended to use a VPS with low ping and high uptime.
Basic structure of EA in MQL5
A simple EA includes the following main functions:
- OnInit(): for initialization
- OnDeinit(): For cleaning
- OnTick(): A function that is executed for each price tick
#include <Trade\Trade.mqh>
CTrade trade;
int OnInit() {
// initialization
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason) {
// cleanup resources
}
void OnTick() {
// trading logic
}
Sending orders and managing positions
In MQL5 From class CTrade Used to submit an order. The following example shows a simple market buy and prints a possible error.
double lot = 0.1;
if(trade.Buy(lot, _Symbol)) {
Print("BUY executed");
} else {
Print("Error Buy: ", GetLastError());
}To close a position, you can take the ticket and use the method PositionClose Use:
ulong ticket = PositionGetTicket(0);
if(trade.PositionClose(ticket)) {
Print("Position closed");
}
Practical example — Cross Moving Average Robot
Logic: Buy when the fast moving average crosses the slow average from below upwards; vice versa for sell. This basic example can be supplemented with risk management, SL/TP, trailing stop and market time filter.
input int FastPeriod = 10;
input int SlowPeriod = 50;
double FastMA, SlowMA;
int OnInit() {
return INIT_SUCCEEDED;
}
void OnTick() {
FastMA = iMA(_Symbol, PERIOD_M1, FastPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
SlowMA = iMA(_Symbol, PERIOD_M1, SlowPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
double prevFast = iMA(_Symbol, PERIOD_M1, FastPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
double prevSlow = iMA(_Symbol, PERIOD_M1, SlowPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
if(prevFast < prevSlow && FastMA > SlowMA) {
trade.Buy(0.1, _Symbol);
} else if(prevFast > prevSlow && FastMA < SlowMA) {
trade.Sell(0.1, _Symbol);
}
}
Installing and running MetaTrader 5 on a server (VPS / Cloud)
To run bots 24/7, it is recommended to use a VPS or cloud server. Two common routes:
- Windows Server (Common suggestion for MT5)
- Linux + Wine (To reduce cost, but some versions may be incompatible)
Windows VPS — Recommended Settings
Recommended tips for Windows Server:
- Installation Windows Server 2019/2022
- Enabling RDP with Network Level Authentication
- Installation MetaTrader 5 and MetaEditor
- Manage Automatic Updates manually to prevent unwanted reboots
Linux + Wine — Sample Commands (Ubuntu)
If you want to run MT5 on Linux, the following sample commands can get you started. Some brokers or plugins may have issues under Wine; thorough testing is recommended.
sudo apt update && sudo apt install -y wine winetricks xvfb xrdp
# create a dedicated mt5 user
sudo useradd -m mt5user
sudo passwd mt5user
# run mt5 installer under the user with a virtual framebuffer
sudo -u mt5user xvfb-run wine mt5setup.exe
RDP security and secure access
To protect access to the server, it is recommended to:
- Change the default RDP port, Enable NLA and use VPN or SSH tunnel for RDP connection
- Restrict access with firewall and whitelist valid IPs
- Installation fail2ban To protect against brute-force
sudo ufw allow from 203.0.113.0/24 to any port 3389 proto tcp
sudo ufw enable
Testing, optimizing, and deploying robots
Strategy Tester MT5 has Backtest, Optimization and Forward testing capabilities. You can use Genetic Algorithm to optimize parameters and benefit from high-quality data (tick data).
- Use real tick data to get results that are close to reality.
- Test on a VPS and demo account for at least a few weeks before running on a live account.
Risk assessment methods
Methods you should use to measure risk and sustainability:
- Walk-forward analysis: Testing on different intervals to avoid overfitting.
- Monte Carlo: To measure stability based on simulating changes in transaction execution.
- Review metrics: CAGR, Sharpe Ratio, Max Drawdown, Profit Factor.
CI/CD and automated deployment
For EA code management and automated deployment, you can use GitLab or GitHub and set up a Runner on your VPS to automate the process of compiling and transferring the EX5 file.
Example script to copy EX5 file to terminal folder:
# copy the compiled EA to MetaTrader 5 Experts folder
cp MyEA.ex5 "/home/mt5user/.wine/drive_c/Program Files/MetaTrader 5/MQL5/Experts/"
# restart terminal or signal reloadYou can also use APIs or ZeroMQ to communicate between a Python service and MT5 to pass AI/ML data to the EA.
Choosing a location and configuring a VPS for traders
For traders, ping/latency and network stability are critical. Location selection should be based on proximity to the broker's servers or target market.
Comparison of key locations
- London/Manchester/Frankfurt/Amsterdam: Great for European brokers and European ECN markets.
- New York/Washington: Suitable for American brokers and fast execution in the NY market.
- Singapore/Tokyo/Hong Kong: Provides low ping for brokers and Asian markets.
- Best practice: Find the broker IP or AS and choose the data center that has the shortest BGP path.
Our company has more than 85 global locations Offers the ability to choose the closest data center to the broker server.
Recommended VPS configuration for trading
- CPU: 2-4 cores with fixed legs and high clocks.
- RAM: 4-8GB basic; 8-16GB for heavy EAs.
- Storage: NVMe SSD for fast I/O.
- Network: 1Gbps or higher; fixed latency and ports with BGP and anti-DDoS.
- Features: Snapshots, automatic backups, 24/7 monitoring, anti-DDoS server, and reliable SLA.
For AI-based strategies or heavy analysis, you may need a server with GPUs to run ML models and then send signals to MT5.
Security, monitoring and practical tips
System and network protection
- Enable local firewall (Windows Firewall or ufw/iptables).
- Use VPN or IP whitelist for RDP access.
- Install antivirus and File Integrity Monitoring for the folder
MQL5.
Monitoring and Alert
Setting up a monitoring service (e.g. Prometheus + Grafana) is important for checking the CPU, Memory, Network and health of the MT5 terminal.
Sending an alert to email/Slack/Telegram in case of a connection loss or critical error is recommended.
Preventing slippage and ricochet
- Choose a VPS with lower ping and a location close to the broker.
- Using Market vs. Limit orders and setting Max Slippage In EA or MetaTrader settings.
- Enable auto-reconnect in the EA to prevent losing trades in case of disconnection.
Summary and technical proposal
This guide covers the basics. MQL5 Testing, optimization, and deployment on VPS were discussed, and practical tips for security and choosing the right location were discussed.
If you need a server with 85+ global locationsWhether you have anti-DDoS servers, NVMe, and BGP networking, or need GPUs for AI strategies, our support team is ready to respond 24/7 to recommend the most appropriate configuration based on your broker and strategy.









