0% found this document useful (0 votes)
39 views4 pages

MultiBot Trading Strategy Script

The document is a MetaTrader 5 Expert Advisor script designed for automated trading using multiple indicators including RSI, Stochastic, and MACD. It includes parameters for risk management, trade entry conditions based on bullish and bearish divergences, and functions for opening and closing orders. The script initializes indicators, checks for new ticks, and executes trades based on defined trading signals and risk-reward ratios.

Uploaded by

Le Loi Phong
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views4 pages

MultiBot Trading Strategy Script

The document is a MetaTrader 5 Expert Advisor script designed for automated trading using multiple indicators including RSI, Stochastic, and MACD. It includes parameters for risk management, trade entry conditions based on bullish and bearish divergences, and functions for opening and closing orders. The script initializes indicators, checks for new ticks, and executes trades based on defined trading signals and risk-reward ratios.

Uploaded by

Le Loi Phong
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

//+------------------------------------------------------------------+

//| MultiBot.mq5|
//| Copyright 2023, MetaQuotes Software Corp.|
//| [Link] |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023"
#property version "1.00"
#property strict

//--- Input parameters


input double RiskPerTrade = 1.0; // Risk per trade (%)
input double RewardRatio = 2.0; // Risk-Reward Ratio
input int RSIPeriod = 9; // RSI Period
input int StochKPeriod = 10; // Stochastic %K Period
input int StochDPeriod = 3; // Stochastic %D Period
input int StochSlowing = 3; // Stochastic Slowing
input int FastEMA = 5; // MACD Fast EMA
input int SlowEMA = 13; // MACD Slow EMA
input int SignalSMA = 5; // MACD Signal SMA

//--- Global variables


int rsiHandle, stochHandle, macdHandle;
double rsiBuffer[], stochKBuffer[], stochDBuffer[], macdBuffer[], signalBuffer[];
datetime lastBarTime;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit() {
// Khởi tạo các chỉ báo
rsiHandle = iRSI(_Symbol, _Period, RSIPeriod, PRICE_CLOSE);
stochHandle = iStochastic(_Symbol, _Period, StochKPeriod, StochDPeriod,
StochSlowing, MODE_SMA, STO_LOWHIGH);
macdHandle = iMACD(_Symbol, _Period, FastEMA, SlowEMA, SignalSMA, PRICE_CLOSE);

// Kiểm tra lỗi khởi tạo


if (rsiHandle == INVALID_HANDLE || stochHandle == INVALID_HANDLE || macdHandle
== INVALID_HANDLE) {
Print("Lỗi khởi tạo chỉ báo!");
return(INIT_FAILED);
}

// Khai báo buffer


ArraySetAsSeries(rsiBuffer, true);
ArraySetAsSeries(stochKBuffer, true);
ArraySetAsSeries(stochDBuffer, true);
ArraySetAsSeries(macdBuffer, true);
ArraySetAsSeries(signalBuffer, true);

lastBarTime = 0;
return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
IndicatorRelease(rsiHandle);
IndicatorRelease(stochHandle);
IndicatorRelease(macdHandle);
}

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick() {
// Kiểm tra nến mới
if (lastBarTime == iTime(_Symbol, _Period, 0)) return;
lastBarTime = iTime(_Symbol, _Period, 0);

// Lấy dữ liệu chỉ báo


CopyBuffer(rsiHandle, 0, 0, 3, rsiBuffer);
CopyBuffer(stochHandle, 0, 0, 3, stochKBuffer);
CopyBuffer(stochHandle, 1, 0, 3, stochDBuffer);
CopyBuffer(macdHandle, 0, 0, 3, macdBuffer);
CopyBuffer(macdHandle, 1, 0, 3, signalBuffer);

// Điều kiện vào lệnh


bool buySignal = false;
bool sellSignal = false;

// Kiểm tra phân kỳ tăng/giảm


bool bullishDivergence = CheckBullishDivergence();
bool bearishDivergence = CheckBearishDivergence();

// Tín hiệu BUY


if (rsiBuffer[1] < 30 && stochKBuffer[1] < 20 && macdBuffer[1] > signalBuffer[1]
&& bullishDivergence) {
buySignal = true;
}

// Tín hiệu SELL


if (rsiBuffer[1] > 70 && stochKBuffer[1] > 80 && macdBuffer[1] < signalBuffer[1]
&& bearishDivergence) {
sellSignal = true;
}

// Đóng lệnh đối nghịch (nếu có)


CloseOppositeOrders(buySignal, sellSignal);

// Mở lệnh mới
if (buySignal) {
OpenOrder(ORDER_TYPE_BUY);
} else if (sellSignal) {
OpenOrder(ORDER_TYPE_SELL);
}
}

//+------------------------------------------------------------------+
//| Kiểm tra phân kỳ tăng |
//+------------------------------------------------------------------+
bool CheckBullishDivergence() {
// So sánh đáy giá và đáy RSI
double priceLow1 = iLow(_Symbol, _Period, 1);
double priceLow2 = iLow(_Symbol, _Period, 2);
double rsiLow1 = rsiBuffer[1];
double rsiLow2 = rsiBuffer[2];
if (priceLow1 < priceLow2 && rsiLow1 > rsiLow2) return true;
return false;
}

//+------------------------------------------------------------------+
//| Kiểm tra phân kỳ giảm |
//+------------------------------------------------------------------+
bool CheckBearishDivergence() {
// So sánh đỉnh giá và đỉnh RSI
double priceHigh1 = iHigh(_Symbol, _Period, 1);
double priceHigh2 = iHigh(_Symbol, _Period, 2);
double rsiHigh1 = rsiBuffer[1];
double rsiHigh2 = rsiBuffer[2];

if (priceHigh1 > priceHigh2 && rsiHigh1 < rsiHigh2) return true;


return false;
}

//+------------------------------------------------------------------+
//| Mở lệnh |
//+------------------------------------------------------------------+
void OpenOrder(ENUM_ORDER_TYPE orderType) {
double sl = 0, tp = 0;
double price = (orderType == ORDER_TYPE_BUY) ? Ask : Bid;

// Tính toán SL và TP
if (orderType == ORDER_TYPE_BUY) {
sl = price - CalculateSL();
tp = price + CalculateTP(sl, price);
} else {
sl = price + CalculateSL();
tp = price - CalculateTP(sl, price);
}

// Tính lot size dựa trên rủi ro


double lotSize = CalculateLotSize(sl, price);

// Gửi lệnh
if (lotSize > 0) {
int ticket = OrderSend(_Symbol, orderType, lotSize, price, 3, sl, tp,
"MultiBot", 0, clrNONE);
if (ticket < 0) Print("Lỗi mở lệnh: ", GetLastError());
}
}

//+------------------------------------------------------------------+
//| Tính toán SL |
//+------------------------------------------------------------------+
double CalculateSL() {
// Dựa trên ATR hoặc mức cố định (ví dụ: 50 pips)
return 50 * _Point;
}

//+------------------------------------------------------------------+
//| Tính toán TP dựa trên Risk-Reward Ratio |
//+------------------------------------------------------------------+
double CalculateTP(double sl, double entryPrice) {
double risk = MathAbs(entryPrice - sl);
return risk * RewardRatio;
}

//+------------------------------------------------------------------+
//| Tính toán Lot Size |
//+------------------------------------------------------------------+
double CalculateLotSize(double sl, double entryPrice) {
double riskAmount = AccountBalance() * RiskPerTrade / 100;
double riskPips = MathAbs(entryPrice - sl) / _Point;
double pipValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double lotSize = riskAmount / (riskPips * pipValue);
lotSize = NormalizeDouble(lotSize, 2);
return lotSize;
}

//+------------------------------------------------------------------+
//| Đóng lệnh đối nghịch |
//+------------------------------------------------------------------+
void CloseOppositeOrders(bool buySignal, bool sellSignal) {
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol() == _Symbol) {
if (buySignal && OrderType() == ORDER_TYPE_SELL)
OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrRed);
if (sellSignal && OrderType() == ORDER_TYPE_BUY)
OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrRed);
}
}
}
}
//+------------------------------------------------------------------+

Common questions

Powered by AI

MultiBot includes error handling mechanisms like checking for INVALID_HANDLE after initializing indicators to detect and respond to initialization failures, ensuring these are logged and preventing continuation if these conditions are met. Additionally, when opening trades, it checks if the ticket number is valid (greater than 0) post-trade execution and logs errors using GetLastError to capture any trading operation issues. These mechanisms help in identifying and rectifying faults swiftly, maintaining the script's reliability in operational environments .

MultiBot interacts with the MetaTrader platform by utilizing platform-specific functions such as OrderSend for executing trades and OrderSelect, OrderClose for managing open positions. These functions allow for direct interaction with the trading environment to open new orders with calculated lot size, entry price, stop-loss, and take-profit levels based on the defined strategy parameters, ensuring seamless integration with MetaTrader's trading functionalities .

For a buy order, the stop-loss (SL) is set at the entry price minus a fixed amount (50 pips calculated as 50 * _Point), and the take-profit (TP) is the SL distance multiplied by the Risk-Reward Ratio (2.0) and added to the entry price. Conversely, for a sell order, SL is set above the entry price, and TP is subtracted based on the same multipliers. This method ensures that the potential reward is always twice the risk taken .

Setting ArraySetAsSeries for indicator data buffers in MultiBot is significant because it ensures that arrays are indexed in the correct sequence for processing, where the most recent data point is at index zero. This allows easy access to the latest indicator values without reordering the array data manually. By doing so, it simplifies the logic for evaluating trading signals and prevents possible errors that could arise from incorrectly ordered data during dynamic market conditions .

When a new tick occurs, MultiBot first checks if a new candle (bar) is being formed by comparing the current bar time to the last recorded time. It retrieves buffer data for RSI, Stochastic, and MACD indicators to assess conditions for buy or sell signals. It evaluates these conditions by using existing data points to check for bullish or bearish divergences. Based on these calculations and prescribed conditions, it determines if a buy or sell signal is present, and proceeds to close any opposing orders before opening a new order if the signals suffice .

MultiBot calculates the lot size required for a trade using the current account balance, risk percentage per trade (RiskPerTrade), and the pip value of the symbol being traded. By computing the dollar risk amount based on account balance and open price's pip value, it divides this risk by the pip distance to the stop-loss, thereby normalizing the lot size to a two-decimal value. This ensures the leverage is effectively utilized without exceeding risk limits .

The MultiBot system determines a buy signal by checking if certain conditions are met: the RSI value is below 30, the Stochastic %K value is below 20, the MACD value is greater than the MACD signal line, and there is evidence of bullish divergence, characterized by a higher low in RSI compared to price making a lower low .

The implementation of both bullish and bearish divergence checks offers the advantage of detecting market reversals to generate timely trading signals, enhancing the versatility and responsiveness of the strategy. However, potential downsides include susceptibility to false positives during volatile or choppy market conditions, which could lead to premature or incorrect trade entries. Consequently, while these indicators can significantly improve trading results by capturing key reversals, they also require complementary filters to minimize noise and avoid unnecessary trades in ranging markets .

Essential parameters used in MultiBot include RiskPerTrade, RewardRatio, RSIPeriod, StochKPeriod, StochDPeriod, StochSlowing, FastEMA, SlowEMA, and SignalSMA. They are initialized in the OnInit function, which also sets up the indicator handles (rsiHandle, stochHandle, macdHandle) for RSI, Stochastic, and MACD by using appropriate MetaTrader functions .

The divergence checking method in MultiBot uses RSI to identify bullish divergence when price forms a lower low but RSI forms a higher low, and bearish divergence when price forms a higher high but RSI forms a lower high. This approach is robust as it combines price action with momentum indicator discrepancies to anticipate potential reversals. Such divergences are often precursors to trend changes, thus providing a solid basis for generating trading signals and enhancing decision accuracy by confirming the underlying momentum shift before executing trades .

You might also like