Here's a breakdown of how this trading script works, in plain language:
This script is designed to automatically trade currencies in the Forex market, using a strategy based on the Relative Strength Index (RSI) and a Simple Moving Average (SMA). Think of it as a robot that tries to identify when a currency is likely to go up or down, and then places trades accordingly.
Here's the process:
-
Initialization: When the script starts, it first sets up some basic settings. These include:
- Lot Size: How big each trade should be. This can be a fixed amount, or calculated based on the account balance.
- Stop Loss & Take Profit: These are safety nets. The stop loss automatically closes a trade if it goes too far in the wrong direction, limiting losses. The take profit automatically closes a trade when it reaches a certain profit target.
- Slippage: The acceptable difference between the requested price and the actual price a trade is executed at.
- Money Management: If enabled, the script will automatically calculate the appropriate lot size for each trade based on the account balance and risk tolerance.
- RSI Period: a number that defines how many days to look back when calculating the RSI
-
The Core Strategy (Daily Analysis): The script focuses on analyzing daily price movements. Each day, it looks at the following:
-
RSI Calculation: The script calculates the RSI (Relative Strength Index) for the past three days. The RSI is a number between 0 and 100 that tells you if an asset is overbought (likely to go down soon) or oversold (likely to go up soon).
-
SMA Calculation: The script calculates the 200-day SMA (Simple Moving Average) from yesterday's close price. The SMA is a trend indicator to know if the general price trend is upwards or downwards
-
Buy Signal:
- The script checks if the RSI value has been decreasing over the last three days, moving towards an oversold condition.
- It also checks if the closing price yesterday was above the 200-day SMA (indicating an upward trend).
- If both conditions are true, the script considers this a "buy signal," meaning it thinks the currency is likely to go up.
-
Sell Signal:
- The script checks if the RSI value has been increasing over the last three days, moving towards an overbought condition.
- It also checks if the closing price yesterday was below the 200-day SMA (indicating a downward trend).
- If both conditions are true, the script considers this a "sell signal," meaning it thinks the currency is likely to go down.
-
-
Managing Existing Trades: Before placing any new trades, the script checks if there are any open trades.
- Closing Trades Based on RSI Extremes: If a buy trade is open and the RSI is now very high (overbought), the script closes the buy trade. Similarly, if a sell trade is open and the RSI is very low (oversold), it closes the sell trade. This is because extreme RSI values often signal a trend reversal.
- Closing Trades based on the SMA: If a buy trade is open and the price is below the 200-day SMA (indicating an trend downside), the script closes the buy trade. Similarly, if a sell trade is open and the price is above the 200-day SMA, it closes the sell trade. This is because the trend changed from when the trade started
- Trailing Stop: The script uses the Parabolic SAR indicator to dynamically adjust the stop loss of open trades, "trailing" it as the price moves in a profitable direction. This helps to lock in profits while still allowing the trade to potentially gain more.
-
Placing New Trades:
- Buy Order: If the script detects a buy signal and there are no buy orders currently open, it first closes any open sell orders. Then, it places a buy order.
- Sell Order: If the script detects a sell signal and there are no sell orders currently open, it first closes any open buy orders. Then, it places a sell order.
In Summary: This script is an automated Forex trading system that uses the RSI and SMA indicators to generate buy and sell signals, manages existing trades with trailing stops and RSI/SMA conditions, and includes basic money management features. It aims to automatically profit from currency price fluctuations.
//+---------------------------------------------------------------------------------+
//| |
//| RSI-R2.mq4 - Ver 1.3 @ 04/19/2007 by Bluto |
//| |
//| Rev 1.1 - Enhanced Money Mgmt & Optimized RSI Periods Per Pairs |
//| |
//| Rev 1.2 - Enhanced RSI_Period handler to allow usage of either pre-determined |
//| internal optimized RSI_Period values set in the int init() function |
//| or default RSI_Period value via the boolean UseDefaultRSI_Period |
//| extern variable. |
//| Set UseDefaultRSI_Period = true to use default RSI_Period value when | |
//| performing your own optimizations of RSI_Period via backtesting. |
//| |
//| Rev 1.3 Added test of Price-Close vs. 200SMA to exit a trade that is moving |
//| in the wrong direction. | |
//+---------------------------------------------------------------------------------+
/*In layman's terms, this is how the RSI-R2 Ver 1.1 EA works:
With each new tick, the EA is called and control passes to the init_start() mainline function.
First, we perform the money management option via the "Calc_Money_Management()" function call if the value of the UseMoneyMgmt variable is set to true. This function calculates the appropriate lot size to use based on available equity and the "RiskPercent" setting. If money management is disabled, the value of the default "LotSize" variable is used.
-Then-
Using a daily timeframe, first, get the closing value of RSI three days ago (RSI_Day_1), the closing value of RSI two days ago (RSI_Day_2) and the value of RSI one day ago (RSI_Day_3) . Also, get the closing value of a 200-day simple moving average one day ago (SMA200_Day3). We will analyze the behavior of a short term RSI over the prior three days as our primary buy/sell trigger.
-Then-
Check for Buy Signal: We're looking for a decreasing value of RSI over the past three days into a deeper oversold status as price remains above SMA200.
If the value of RSI_Day_1 < 65 and the value of RSI_Day_2 < RSI_Day_1 and the value of RSI_Day_3 < RSI_Day_2 and the value of Closing Price from one day ago is > SMA200_Day3, we have a Buy signal, so set the boolean Buy Flag (Buy_Mode) to True, otherwise set it to false.
-Then-
Check for Sell Signal: We're looking for an increasing value of RSI over the past three days into a deeper overbought status as price remains below SMA200.
If the value of RSI_Day_1 > 35 and the value of RSI_Day_2 > RSI_Day_1 and the value of RSI_Day_3 > RSI_Day_2 and the value of Closing Price from one day ago is < SMA200_Day3, we have a Sell signal, so set the boolean Sell Flag (Sell_Mode) to True, otherwise set it to false.
-Then-
Before we act on any potential signals that may have fired, we do some housekeeping on any order that may already be open. The EA only allows one sell or one buy order to be open at a time. If we have an open Buy order in progress and the value of RSI_Day_3 > 75, we close the order because RSI is entering extreme overbought status (reversal coming?) If we have an open sell order and the value of RSI_Day_3 < 25, we close the order because RSI is entering extreme oversold status.
The order closures would actually happen on the opening bar of day 4 since we're on a D1 timeframe.
We then update trailing stop using Parabolic SAR. Managing these stops can cause an order to stop out if things get nasty.
-Then-
We now act on any new buy/sell signals:
If we have a new buy signal and there isn't a buy order already open (OpenBuyOrders = 0), we check first to see if a sell order may be open and if so, we close it. Then we simply open a newa buy order and increment the open buy order counter (OpenBuyOrders++). The counter keeps us from opening multiple buy orders since we only want one.
If we have a new sell signal and there isn't a sellorder already open (OpenSellOrders = 0), we check first to see if a buy order may be open and if so, we close it. Then we simply open a new sell order and increment the open sell order counter (OpenSellOrders++). The counter keeps us from opening multiple sell orders since we only want one.
That's it. Control then passes back to MT4 via the last statement of "return(0)" in the init_start() routine until the next tick occurs and calls the EA at which point we repeat the entire process again.
I hope that this helps clarify what the EA is doing under the hood.
-bluto
*/
#property copyright "Bluto"
#property link "None"
extern double LotSize=10;
extern int Slippage=3;
extern double StopLoss=0;
extern double TakeProfit=700;
extern double RiskPercent=2.0;
extern bool UseMoneyMgmt=false;
extern bool BrokerPermitsFractionalLots = true;
extern bool UseDefaultRSI_Period = false;
extern int RSI_Period = 4;
extern double RSI_Overbought_Value = 75.0;
extern double RSI_Oversold_Value = 25.0;
int MagicNumber = 0;
int ticket;
int OpenBuyOrders = 0;
int OpenSellOrders = 0;
int i;
bool Buy_Mode = false, Sell_Mode = false;
double RSI_Day_1 = 0, RSI_Day_2 = 0, RSI_Day_3 = 0, SMA200_Day3 = 0;
double MM_MinLotSize = 0;
double MM_MaxLotSize = 0;
double MM_LotStep = 0;
double MM_Decimals = 0;
double MM_OrderLotSize = 0;
int MM_AcctLeverage = 0;
int MM_CurrencyLotSize = 0;
int init()
{
if (Symbol()=="AUDCADm" || Symbol()=="AUDCAD") {MagicNumber=200001;if(UseDefaultRSI_Period==false){RSI_Period=5;}}
if (Symbol()=="AUDJPYm" || Symbol()=="AUDJPY") {MagicNumber=200002;if(UseDefaultRSI_Period==false){RSI_Period=7;}}
if (Symbol()=="AUDNZDm" || Symbol()=="AUDNZD") {MagicNumber=200003;if(UseDefaultRSI_Period==false){RSI_Period=6;}}
if (Symbol()=="AUDUSDm" || Symbol()=="AUDUSD") {MagicNumber=200004;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="CHFJPYm" || Symbol()=="CHFJPY") {MagicNumber=200005;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="EURAUDm" || Symbol()=="EURAUD") {MagicNumber=200006;if(UseDefaultRSI_Period==false){RSI_Period=2;}}
if (Symbol()=="EURCADm" || Symbol()=="EURCAD") {MagicNumber=200007;if(UseDefaultRSI_Period==false){RSI_Period=3;}}
if (Symbol()=="EURCHFm" || Symbol()=="EURCHF") {MagicNumber=200008;if(UseDefaultRSI_Period==false){RSI_Period=3;}}
if (Symbol()=="EURGBPm" || Symbol()=="EURGBP") {MagicNumber=200009;if(UseDefaultRSI_Period==false){RSI_Period=2;}}
if (Symbol()=="EURJPYm" || Symbol()=="EURJPY") {MagicNumber=200010;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="EURUSDm" || Symbol()=="EURUSD") {MagicNumber=200011;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="GBPCHFm" || Symbol()=="GBPCHF") {MagicNumber=200012;if(UseDefaultRSI_Period==false){RSI_Period=6;}}
if (Symbol()=="GBPJPYm" || Symbol()=="GBPJPY") {MagicNumber=200013;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="GBPUSDm" || Symbol()=="GBPUSD") {MagicNumber=200014;if(UseDefaultRSI_Period==false){RSI_Period=3;}}
if (Symbol()=="NZDJPYm" || Symbol()=="NZDJPY") {MagicNumber=200015;if(UseDefaultRSI_Period==false){RSI_Period=6;}}
if (Symbol()=="NZDUSDm" || Symbol()=="NZDUSD") {MagicNumber=200016;if(UseDefaultRSI_Period==false){RSI_Period=7;}}
if (Symbol()=="USDCHFm" || Symbol()=="USDCHF") {MagicNumber=200017;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="USDJPYm" || Symbol()=="USDJPY") {MagicNumber=200018;if(UseDefaultRSI_Period==false){RSI_Period=4;}}
if (Symbol()=="USDCADm" || Symbol()=="USDCAD") {MagicNumber=200019;if(UseDefaultRSI_Period==false){RSI_Period=2;}}
if (MagicNumber==0) {MagicNumber = 200999;}
return(0);
}
int deinit()
{
return(0);
}
int start()
{
Calc_Money_Management();
SMA200_Day3 = iMA(NULL,PERIOD_D1,200, 0, MODE_SMA, PRICE_CLOSE, 1);
RSI_Day_1 = iRSI(NULL, PERIOD_D1, RSI_Period, PRICE_CLOSE, 3);
RSI_Day_2 = iRSI(NULL, PERIOD_D1, RSI_Period, PRICE_CLOSE, 2);
RSI_Day_3 = iRSI(NULL, PERIOD_D1, RSI_Period, PRICE_CLOSE, 1);
if (RSI_Day_1 < 65 && RSI_Day_2 < RSI_Day_1 && RSI_Day_3 < RSI_Day_2 && Close[1] > SMA200_Day3)
{
Buy_Mode=true;
} else {
Buy_Mode=false;
}
if (RSI_Day_1 > 35 && RSI_Day_2 > RSI_Day_1 && RSI_Day_3 > RSI_Day_2 && Close[1] < SMA200_Day3)
{
Sell_Mode=true;
} else {
Sell_Mode=false;
}
if (OpenBuyOrders == 1 && (RSI_Day_3 > RSI_Overbought_Value || Close[1] < SMA200_Day3))
{
CloseLongs(MagicNumber);
OpenBuyOrders = 0;
}
if (OpenSellOrders == 1 && (RSI_Day_3 < RSI_Oversold_Value || Close[1] > SMA200_Day3))
{
CloseShorts(MagicNumber);
OpenSellOrders = 0;
}
//----- Count number of existing open buy & sell orders; update trailing stops.
OpenBuyOrders=0;
OpenSellOrders=0;
// Manage Paraolic SAR
for (i = 0; i <= OrdersTotal(); i++)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == MagicNumber))
{
if (OrderType() == OP_BUY)
{
OpenBuyOrders++;
if ((iSAR(NULL,0,0.02,0.2,1) > OrderStopLoss()) && (Bid > iSAR(NULL,0,0.02,0.2,1)) && (OrderOpenPrice() < iSAR(NULL,0,0.02,0.2,1)) && (iSAR(NULL,0,0.02,0.2,1) > iSAR(NULL,0,0.02,0.2,2)))
{
OrderModify(OrderTicket(),OrderOpenPrice(),iSAR(NULL,0,0.02,0.2,1),OrderTakeProfit(),0,Blue);
Print("Order # ",OrderTicket()," updated at ",Hour(),":",Minute(),":",Seconds());
return(0);
}
}
if (OrderType() == OP_SELL)
{
OpenSellOrders++;
if ((iSAR(NULL,0,0.02,0.2,1) < OrderStopLoss()) && (Ask < iSAR(NULL,0,0.02,0.2,1)) && (OrderOpenPrice() > iSAR(NULL,0,0.02,0.2,1)) && (iSAR(NULL,0,0.02,0.2,1) < iSAR(NULL,0,0.02,0.2,2)))
{
OrderModify(OrderTicket(),OrderOpenPrice(),iSAR(NULL,0,0.02,0.2,1),OrderTakeProfit(),0,Blue);
Print("Order # ",OrderTicket()," updated at ",Hour(),":",Minute(),":",Seconds());
return(0);
}
}
}
}
//----- Generic order handler.
//----- If we have a new buy signal, close existing sell orders; if we have a new sell signal, close existing buy orders; reset order counters.
//----- Next, create new buy or sell order.
if (Buy_Mode==true && OpenBuyOrders==0)
{
if(OpenSellOrders > 0)
{
CloseShorts(MagicNumber);
OpenSellOrders = 0;
}
if(OpenBuyOrders == 0)
{
ticket = OpenPendingOrder(OP_BUY,MM_OrderLotSize,Ask,Slippage,Bid,StopLoss,TakeProfit,"RSI-R2",MagicNumber,0,Lime);
if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError());
return(0);
}
else
{
OpenBuyOrders++;
}
}
}
if (Sell_Mode==true && OpenSellOrders==0)
{
if(OpenBuyOrders > 0)
{
CloseLongs(MagicNumber);
OpenBuyOrders = 0;
}
if (OpenSellOrders == 0)
{
ticket = OpenPendingOrder(OP_SELL,MM_OrderLotSize,Bid,Slippage,Ask,StopLoss,TakeProfit,"RSI-R2",MagicNumber,0,HotPink);
if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError());
return(0);
}
else
{
OpenSellOrders++;
}
}
}
return(0);
}
//----- Order Processing Functions
void CloseLongs(int MagicNumber)
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES)==false)
continue;
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_BUY)
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
}//for
}
void CloseShorts(int MagicNumber)
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES)==false)
continue;
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_SELL)
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
}//for
}
int OpenPendingOrder(int pType,double pLots,double pLevel,int sp, double pr, int sl, int tp,string pComment,int pMagic,datetime pExpiration,color pColor)
{
int ticket=0;
int err=0;
int c = 0;
int NumberOfTries = 10;
switch (pType)
{
case OP_BUY:
for(c = 0 ; c < NumberOfTries ; c++)
{
RefreshRates();
ticket=OrderSend(Symbol(),OP_BUY,pLots,Ask,sp,StopLong(Bid,sl),TakeLong(Bid,tp),pComment,pMagic,pExpiration,pColor);
if (ticket > 0) break;
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
Print("Error Code= ", err);
break;
}
}
}
break;
case OP_SELL:
for(c = 0 ; c < NumberOfTries ; c++)
{
RefreshRates();
ticket=OrderSend(Symbol(),OP_SELL,pLots,Bid,sp,StopShort(Ask,sl),TakeShort(Ask,tp),pComment,pMagic,pExpiration,pColor);
if (ticket > 0) break;
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
Print("Error Code= ", err);
break;
}
}
}
break;
}
return(ticket);
}
double StopLong(double price,int stop)
{
if(stop==0)
return(0);
else
return(price-(stop*Point));
}
double StopShort(double price,int stop)
{
if(stop==0)
return(0);
else
return(price+(stop*Point));
}
double TakeLong(double price,int take)
{
if(take==0)
return(0);
else
return(price+(take*Point));
}
double TakeShort(double price,int take)
{
if(take==0)
return(0);
else
return(price-(take*Point));
}
void Calc_Money_Management()
{
MM_AcctLeverage = AccountLeverage();
MM_MinLotSize = MarketInfo(Symbol(),MODE_MINLOT);
MM_MaxLotSize = MarketInfo(Symbol(),MODE_MAXLOT);
MM_LotStep = MarketInfo(Symbol(),MODE_LOTSTEP);
MM_CurrencyLotSize = MarketInfo(Symbol(),MODE_LOTSIZE);
if(MM_LotStep == 0.01) {MM_Decimals = 2;}
if(MM_LotStep == 0.1) {MM_Decimals = 1;}
if(BrokerPermitsFractionalLots == true)
{
if (UseMoneyMgmt == true)
{
MM_OrderLotSize = AccountEquity() * (RiskPercent * 0.01) / (MM_CurrencyLotSize / MM_AcctLeverage);
MM_OrderLotSize = StrToDouble(DoubleToStr(MM_OrderLotSize,MM_Decimals));
if (MM_OrderLotSize < MM_MinLotSize) {MM_OrderLotSize = MM_MinLotSize;}
if (MM_OrderLotSize > MM_MaxLotSize) {MM_OrderLotSize = MM_MaxLotSize;}
}
else
{
MM_OrderLotSize = LotSize;
if (MM_OrderLotSize < MM_MinLotSize) {MM_OrderLotSize = MM_MinLotSize;}
if (MM_OrderLotSize > MM_MaxLotSize) {MM_OrderLotSize = MM_MaxLotSize;}
}
}
else
{
if (UseMoneyMgmt == true)
{
MM_OrderLotSize = AccountEquity() * (RiskPercent * 0.01) / (MM_CurrencyLotSize / MM_AcctLeverage);
MM_OrderLotSize = MathRound(MM_OrderLotSize);
if (MM_OrderLotSize < MM_MinLotSize) {MM_OrderLotSize = MM_MinLotSize;}
if (MM_OrderLotSize > MM_MaxLotSize) {MM_OrderLotSize = MM_MaxLotSize;}
}
else
{
MM_OrderLotSize = LotSize;
if (MM_OrderLotSize < MM_MinLotSize) {MM_OrderLotSize = MM_MinLotSize;}
if (MM_OrderLotSize > MM_MaxLotSize) {MM_OrderLotSize = MM_MaxLotSize;}
}
}
return(0);
}
Comments