rsi_expert_v2.0
Download scriptThis automated trading script is designed to manage currency or asset trades by combining two primary technical analysis indicators: the Relative Strength Index (RSI) and Moving Averages (MA). It functions as a systematic "Expert Advisor" that monitors market conditions and executes trades based on specific mathematical triggers.
Core Trading Logic
The script operates on a dual-confirmation system. For a trade to be executed, it generally looks for agreement between the following two components:
-
RSI Momentum (The Trigger): The script monitors the RSI, which measures the speed and change of price movements. It looks for "oversold" or "overbought" conditions.
- A Buy signal is generated when the RSI moves from below a bottom threshold to above it.
- A Sell signal is generated when the RSI moves from above a top threshold to below it.
-
Moving Average Trend (The Filter): The script uses two Moving Averages (a "Fast" one and a "Slow" one) to determine the overall direction of the market. Depending on the user's settings, this acts as a filter:
- Forward Mode: It only allows trades that align with the current trend (e.g., buying only when the fast average is above the slow one).
- Reverse Mode: It looks for trades that go against the current trend.
- Off Mode: It ignores the moving averages entirely and relies solely on the RSI.
Trade Execution and Management
When both the RSI and Moving Average conditions are met simultaneously, the script takes action:
- Automatic Entry: It opens a new position (Buy or Sell) based on the detected direction.
- Opposite Position Closing: If a new Buy signal appears, the script automatically closes any existing Sell positions (and vice versa).
- Lot Management: The user can choose how much capital to risk per trade using three methods:
- Fixed: Always trades the same specific amount.
- Float: Calculates the trade size based on a percentage of the available account balance.
- Martin: A "Martingale" approach where it doubles the lot size of the previous order if that order resulted in a loss.
Safety and Optimization Features
- Trailing Stop: The script includes a "Trailing Stop" mechanism. This automatically moves the Stop Loss of an open trade as the price moves in your favor, helping to lock in profits while maintaining room for further gains.
- Error Handling: It contains robust logic to handle common trading issues, such as market slippage, "busy" servers, or insufficient funds, attempting to retry operations automatically when these occur.
- Validation Check: Upon startup, the script performs a self-check. If the user has entered impossible parameters (such as setting a "Slow" Moving Average that is actually faster than the "Fast" one), the script will alert the user and disable itself to prevent erratic behavior.
//+------------------------------------------------------------------+
//| RSI_Expert_v2.0.mq4 |
//| Joni |
//| JoniH88@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Joni"
#property link "JoniH88@mail.ru"
#property version "2.00"
#property description "JoniH88@mail.ru"
#property strict
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum enum_ma_trade
{
OFF, //Îòêëþ÷åíà
FORWARD, //Ïðÿìàÿ
REVERS //Îáðàòíàÿ
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum enum_lot
{
FIX,//Ôèêñèðîâàííûé
FLOAT,//Ïðîöåíò îò áàëàíñà
MARTIN
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum enum_trade
{
UP,
DOWN,
ALWAYS,
FOUL
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum enum_order
{
BUY_MINUS,
PLUS,
SELL_MINUS,
};
input string RSI = "--=========RSI==========--";
input int periodRSI = 21; //Ïåðèîä:
input double levelUpRSI = 70.0; //Âåðõíèé óðîâåíü:
input double levelDownRSI = 30.0; //Íèæíèé óðîâåíü:
input ENUM_APPLIED_PRICE priceRSI = PRICE_CLOSE; //Ïðèìåíèòü ê:
input string FastMovingAverage="--====Fast Moving Average=====--";
input int periodFastMA = 50; //Ïåðèîä:
input ENUM_MA_METHOD modeFastMA = MODE_SMA; //Ìåòîä ÌÀ:
input ENUM_APPLIED_PRICE priceFastMA = PRICE_CLOSE; //Ïðèìåíèòü ê:
input string SlowMovingAverage="--====Slow Moving Average=====--";
input int periodSlowMA = 200; //Ïåðèîä:
input ENUM_MA_METHOD modeSlowMA = MODE_SMA; //Ìåòîä ÌÀ:
input ENUM_APPLIED_PRICE priceSlowMA = PRICE_CLOSE; //Ïðèìåíèòü ê:
input string Expert = "--======Expert Settings======--";
input enum_ma_trade typeTradeMA = FORWARD; //Òîðãîâëÿ ïî MA
input enum_lot typeLot = FIX; //Òèï ëîòà
input double lotPoz = 10; //Ðàçìåð ëîòà â ïðîöåíòàõ îò áàëàíñà
input double lot = 0.01; //Ëîò
input int SL = 0; //Stop Loss (â ïóíêòàõ)
input int TP = 0; //Take Profit (â ïóíêòàõ)
input int stepTrall = 0; //Òðåéëèã ñòîï (â ïóíêòàõ)
input int Slippage = 3; //Ïðîñêàëüçîâàíèå (â ïóíêòàõ)
input int magic = 25;
datetime gBar;
int gSlippage;
double gPoint;
bool gTradeEnable;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit()
{
Comment("");
gTradeEnable=true;
checkingSet();
if(Digits==5) gPoint=0.0001;
else
{
if(Digits==3) gPoint=0.01;
else gPoint=Point;
}
gSlippage=(int)NormalizeDouble(Slippage*gPoint/Point,0);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTick()
{
if(gTradeEnable)
{
if(gBar!=Time[0])
{
gBar=Time[0];
trade(1);
trall(stepTrall);
}
} else {
Comment("Ñîâåòíèê íå òîðãóåò");
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void trade(int _numBar)
{
int _typeTrade=typeTrade();
double _lot=calcLot(_typeTrade);
if(_typeTrade==1)
{
if(_lot>0) openOrder(OP_BUY,_lot,SL,TP);
closeAllSell();
}
if(_typeTrade==-1)
{
if(_lot>0) openOrder(OP_SELL,_lot,SL,TP);
closeAllBuy();
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int typeTrade()
{
enum_trade tradeRsi= tradeRsi();
enum_trade tradeMa = tradeMa();
if(tradeRsi == UP && (tradeMa == UP || tradeMa == ALWAYS)) return 1;
if(tradeRsi == DOWN && (tradeMa == DOWN || tradeMa == ALWAYS)) return -1;
return 0;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum_trade tradeRsi()
{
double rsi_1 = iRSI(Symbol(), PERIOD_CURRENT, periodRSI, PRICE_CLOSE, 1);
double rsi_2 = iRSI(Symbol(), PERIOD_CURRENT, periodRSI, PRICE_CLOSE, 2);
if(rsi_1 > levelDownRSI && rsi_2 < levelDownRSI) return UP;
if(rsi_1 < levelUpRSI && rsi_2 > levelUpRSI) return DOWN;
return FOUL;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum_trade tradeMa()
{
double maFast = iMA(Symbol(), PERIOD_CURRENT, periodFastMA, 0, modeFastMA, priceFastMA, 1);
double maSlow = iMA(Symbol(), PERIOD_CURRENT, periodSlowMA, 0, modeSlowMA, priceSlowMA, 1);
switch(typeTradeMA)
{
case OFF:
return ALWAYS;
case FORWARD:
if(maFast > maSlow) return UP;
if(maFast < maSlow) return DOWN;
break;
case REVERS:
if(maFast < maSlow) return UP;
if(maFast > maSlow) return DOWN;
break;
}
return FOUL;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double calcLot(int _typeTrade)
{
double _lot=0.01;
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
double needForOneLot=MarketInfo(Symbol(),MODE_MARGINREQUIRED); //Ðàçìåð ñâîáîäíûõ ñðåäñòâ, íåîáõîäèìûõ äëÿ îòêðûòèÿ 1 ëîòà íà ïîêóïêó
if(typeLot==FLOAT)
{
_lot=AccountFreeMargin()*lotPoz/100.0/needForOneLot;
if(_lot<minLot)
{
_lot=0;
}
if(_lot>maxLot)
{
_lot=maxLot;
}
} else if(typeLot==MARTIN) {
if((typeLastOrder()==BUY_MINUS && _typeTrade>0) || (typeLastOrder()==SELL_MINUS && _typeTrade<0))
{
_lot=sizeLotLastOrder()*2;
}
}
return _lot;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void trall(int step)
{
if(MarketInfo(Symbol(), MODE_STOPLEVEL) > step * gPoint / Point) return;
int ordersTotal=OrdersTotal();
for(int i=ordersTotal-1; i>=0; i --)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic)
{
setSl(step);
}
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void setSl(int sl)
{
double _sl=0.0;
if(OrderType()==OP_BUY)
{
_sl=ND(Bid -(double)sl*gPoint);
if(_sl <= OrderStopLoss()) return;
}
if(OrderType()==OP_SELL)
{
_sl=ND(Ask+(double)sl*gPoint);
//Print("sl = ", sl, " ordersl = ", OrderStopLoss());
if(OrderStopLoss() != 0.0 && _sl >= OrderStopLoss()) return;
}
bool f=OrderModify(OrderTicket(),OrderOpenPrice(),_sl,OrderTakeProfit(),0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum_order typeLastOrder()
{
if(OrderSelect(OrdersTotal()-1,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic)
{
if(OrderType()==OP_BUY)
{
if(OrderProfit() >= 0) return PLUS;
else return BUY_MINUS;
} else if(OrderType()==OP_SELL) {
if(OrderProfit() >= 0) return PLUS;
else return SELL_MINUS;
}
}
}
return PLUS;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double sizeLotLastOrder()
{
if(OrderSelect(OrdersTotal()-1,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic)
return OrderLots();
}
return 0;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void closeAllBuy()
{
int i;
int ordersTotal=OrdersTotal();
for(i=ordersTotal-1; i>=0; i --)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUY)
{
if(OrderStopLoss()==0 || OrderStopLoss()-OrderOpenPrice()<0) closeOpder(OP_BUY);
}
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void closeAllSell()
{
int i;
int ordersTotal=OrdersTotal();
for(i=ordersTotal-1; i>=0; i --)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_SELL)
{
if(OrderStopLoss()==0 || OrderOpenPrice()-OrderStopLoss()<0) closeOpder(OP_SELL);
}
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int openOrder(int cmd,double lots,int _stop_loss,int _take_profit)
{
double sl = 0;
double tp = 0;
int ticket= 0;
int error = 0;
RefreshRates();
ResetLastError();
while(true)
{
if(cmd==OP_SELL)
{
if(_stop_loss==0) sl=0;
else sl=NormalizeDouble(Ask+_stop_loss*gPoint,Digits);
if(_take_profit==0) tp=0;
else tp= NormalizeDouble(Ask-_take_profit * gPoint,Digits);
ticket = OrderSend(Symbol(),OP_SELL,lots,NormalizeDouble(Bid,Digits),gSlippage,sl,tp,NULL,magic,0,Red);
}
if(cmd==OP_BUY)
{
if(_stop_loss==0) sl=0;
else sl=NormalizeDouble(Bid-_stop_loss*gPoint,Digits);
if(_take_profit==0) tp=0;
else tp= NormalizeDouble(Bid+_take_profit * gPoint,Digits);
ticket = OrderSend(Symbol(),OP_BUY,lots,NormalizeDouble(Ask,Digits),gSlippage,sl,tp,NULL,magic,0,Blue);
}
if(ticket>0) break;
error=GetLastError();
switch(error)
{
case 135: Print("Öåíà èçìåíèëàñü. Ïðîáóþ åù¸ ...");
RefreshRates();
continue;
case 136: Print("Íåò öåí. Æäó íîâûé òèê ...");
while(RefreshRates()==false)
Sleep(1);
continue;
case 146: Print("Ïîäñèñòåìà òîðãîâëè çàíÿòà. Ïðîáóþ åù¸ ...");
Sleep(500);
RefreshRates();
continue;
case 138: Print("Öåíà óñòàðåëà. Ïðîáóþ åù¸ ...");
Sleep(500);
RefreshRates();
continue;
case 129: Print("Íåïðàâèëüíàÿ öåíà ïðè ïîïûòêå îòêðûòü îðäåð. Ïðîáóþ åù¸ ...");
Sleep(5000);
RefreshRates();
continue;
}
switch(error) // Êðèòè÷åñêèå îøèáêè
{
case 2 : Print("Îáùàÿ îøèáêà.");
break;
case 5 : Print("Ñòàðàÿ âåðñèÿ êëèåíòñêîãî òåðìèíàëà.");
break;
case 64: Print("Ñ÷åò çàáëîêèðîâàí.");
break;
case 133:Print("Òîðãîâëÿ çàïðåùåíà");
break;
case 130:Print("Ñëèøêîì ìàëåíüêèé ÑË èëè ÒÏ");
break;
case 134:Print("Íå õâàòàåò ñðåäñòâ");
break;
default: Print("Âîçíèêëà îøèáêà: ",error);// Äðóãèå âàðèàíòû
}
break; // Âûõîä èç öèêëà
}
return ticket;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void closeAll()
{
int i;
int ordersTotal=OrdersTotal();
if(ordersTotal>0)
{
for(i=ordersTotal-1; i>=0; i --)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_SELL)
{
if(OrderStopLoss()==0 || OrderOpenPrice()-OrderStopLoss()<0) closeOpder(OP_SELL);
}
if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUY)
{
if(OrderStopLoss()==0 || OrderStopLoss()-OrderOpenPrice()<0) closeOpder(OP_BUY);
}
}
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void closeOpder(int cmd)
{
bool er=false;
int error=0;
RefreshRates();
ResetLastError();
while(true)
{
if(cmd==OP_BUY)
{
er = OrderClose(OrderTicket(),OrderLots(),Bid,gSlippage,Blue);
}
if(cmd==OP_SELL)
{
er = OrderClose(OrderTicket(),OrderLots(),Ask,gSlippage,Red);
}
if(er == true) break;
error = GetLastError();
switch(error) // Ïðåîäîëèìûå îøèáêè
{
case 135: Print("Öåíà èçìåíèëàñü. Ïðîáóþ åù¸ ...");
RefreshRates();
continue;
case 136: Print("Íåò öåí. Æäó íîâûé òèê ...");
while(RefreshRates()==false)
Sleep(1);
continue;
case 146: Print("Ïîäñèñòåìà òîðãîâëè çàíÿòà. Ïðîáóþ åù¸ ...");
Sleep(500);
RefreshRates();
continue;
case 129: Print("Íåïðàâèëüíàÿ öåíà ïðè ïîïûòêå çàêðûòü îðäåð. Ïðîáóþ åù¸...");
Sleep(5000);
RefreshRates();
continue;
}
switch(error)
{
case 2 : Print("Îáùàÿ îøèáêà.");
break;
case 5 : Print("Ñòàðàÿ âåðñèÿ êëèåíòñêîãî òåðìèíàëà.");
break;
case 64: Print("Ñ÷åò çàáëîêèðîâàí.");
break;
case 133: Print("Òîðãîâëÿ çàïðåùåíà");
break;
default: Print("Âîçíèêëà îøèáêà: ",error);
}
break;
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double ND(double value)
{
return NormalizeDouble(value, Digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum enum_error
{
ERROR_RSI,
ERROR_MA
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void checkingSet()
{
if(levelUpRSI<=levelDownRSI)
{
gTradeEnable=false;
showError(ERROR_RSI);
}
if(periodSlowMA<=periodFastMA)
{
gTradeEnable = false;
showError(ERROR_MA);
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void showError(enum_error error)
{
switch(error)
{
case ERROR_RSI:
MessageBox("Íåâåðíî âûñòàâëåíû óðîâíè RSI!\nÏîæàëóéñòà, óñòàíîâèòå âåðõíèé óðîâåíü âûøå íèæíåãî");
break;
case ERROR_MA:
MessageBox("Íåâåðíî âûñòàâëåíû ïåðèîäû ÌÀ!\nÏîæàëóéñòà, óâåëè÷òå ïåðèîä ìåäëåííîé ÌÀ\nèëè óìåíüøèòå ïåðèîä áûñòðîé ÌÀ");
break;
}
}
//+------------------------------------------------------------------+
Comments