Okay, here's a breakdown of what this MetaTrader script does, explained in plain language for someone who isn't a programmer.
In Essence
This script is designed to automatically trade on the Forex market (currency exchange). It's like having a robot that watches the market and makes buy or sell decisions based on a specific set of rules. It's goal is to make profits.
Key Components and How They Work
-
Settings (The "Extern" Variables): Think of these as the control panel for the robot. They determine how it behaves. You, as the user, can adjust these settings to customize the trading strategy. Here's what some of them do:
-
Minsum
: This is the minimum amount of money you need in your trading account for the robot to keep working. If your account balance drops below this, the robot stops trading to prevent further losses. -
Lots
: This is the size of the trades the robot will make. A "lot" is a standard unit in Forex trading. -
SLoss
&TakeProfit
: These are safety nets.SLoss
is the Stop Loss (maximum amount you're willing to lose on a single trade), andTakeProfit
is the target profit amount for a trade. -
MM
&Risk
: MM stands for Money Management. If this is turned "On" (True), the robot will automatically adjust the trade size (Lots
) based on how much money you have in your account and how much risk you're willing to take on each trade. -
Slippage
: This is a tolerance for price changes. In fast-moving markets, the price might change slightly between when the robot decides to trade and when the trade actually happens. Slippage allows for a small amount of price difference. -
Magic
: This is a unique identifier. It helps the robot keep track of its own trades and not interfere with trades you might make manually or trades from other robots. -
MA_1
,MA_2
,MA_3
: These are settings related to Moving Averages. Moving Averages are a way to smooth out price data to identify trends. The numbers refer to the periods the Moving Averages are calculated over. -
fast
,slow
,signal
: These are parameters for an indicator called "OsMA," which is used to measure the difference between two moving averages. -
RVI_Per
,RVI_max
,RVI_min
: These are parameters for an indicator called "RVI" (Relative Vigor Index) which measures the strength of a trend. -
Trailing
&Tmfrm
,Bars_n
,Indent
: This activates a Trailing Stop mechanism. Which automatically adjusts the Stop Loss level as the trade becomes more profitable, locking in gains.
-
-
Indicators: The script uses several technical indicators to analyze the market. Indicators use math formulas on past price and volume data to give trade suggestions.
- Moving Averages (MA): Help identify the general direction of the price trend.
- OsMA: Measures the difference between two moving averages, and the "signal" setting is a moving average of this difference. This helps identify overbought and oversold conditions.
- Relative Vigor Index (RVI): Gauges the strength of a trend.
-
Trading Logic: The heart of the script is the
start()
function. This is where the robot makes its trading decisions. The basic idea is:- Check Conditions: It looks at the current values of the indicators and compares them to the settings you've defined.
- Buy or Sell: If all the conditions are met for a buy or sell signal, the robot will place an order.
- Money Management: Before placing an order, it checks if money management is enabled and calculates the appropriate trade size.
- Order Placement: When its time to place an order, the script sends the parameters to the broker, which actually buys or sells the currency.
- Check if Funds are adequate. Before doing anything, it verifies that there are enought funds on the account to operate.
-
Trailing Stop: If the
Trailing
setting is on, the robot constantly monitors open trades. As a trade becomes profitable, it moves the Stop Loss order closer to the current price, securing profits. -
Order Management: The script has functions to:
- Close Orders: It can close open trades if certain conditions are met.
- Modify Orders: It can change the Stop Loss or Take Profit levels of existing trades.
Simplified Example of How it Decides to Buy
Imagine the robot is set to buy when:
- The OsMA indicator is positive.
- The RVI Indicator is above a minimum level
- A set of moving averages are in a specific order.
- Some calculations are below a limit.
If all of these conditions are true, the robot will place a "Buy" order.
Important Considerations
- Risk: Forex trading involves risk, and this robot is not a guaranteed money-maker. It can lose money if the market moves against its trades.
- Customization: The settings can be adjusted to create different trading strategies, but it takes knowledge of Forex trading to use the script effectively.
- Backtesting: It's important to test any trading robot on historical data (backtesting) to see how it would have performed in the past. This is not a guarantee of future performance, but it can help you understand the robot's strengths and weaknesses.
In short, this script automates a Forex trading strategy based on technical indicators and user-defined settings. It tries to identify profitable trading opportunities and manage risk, but it's crucial to understand the risks involved and to use the script responsibly.
//<=====================================================================+||
// JS_SISTEM.mq4 ||
// © 2009,||
// Ïèøó òîðãîâûå ñèñòåìû js_sergey@list.ru ||
//<=====================================================================+||
#define major 1
#define minor 0
//======================================================================||
extern string SS1 = " ÍÀÑÒÐÎÉÊÈ ÌÌ ";
extern double Minsum = 100; //-$- îñòàíîâêà ðàáîòû ñîâåòíèêà
extern double Lots = 0.1;//Ìèíèìàëüíûé ëîò
extern int SLoss = 700; //StopLoss avto Otstup
extern int TakeProfit = 4000; //Ìàêñèìàëüíûé ïðîôèò
extern bool MM = False;//Óïðàâëåíèå êàïèòàëîì True-âêë
extern double Risk = 2; //Ïðîöåíò ñâîáîäíûõ ñðåäñòâ
extern int Slippage = 30; //Ïðîñêàëüçûâàíèå öåíû
extern int Magic = 12321;
//======================================================================||
extern string SS2 = " MA ÍÀÑÒÐÎÉÊÈ ";
extern int Razk = 280;//EURUSD-280: GBRUSD-390:
extern int MA_1 = 55;
extern int MA_2 = 89;
extern int MA_3 = 144;
//======================================================================||
extern string SS3 = " OsMA ÍÀÑÒÐÎÉÊÈ ";
extern int fast = 13;
extern int slow = 55;
extern int signal = 21;
//======================================================================||
extern string SS4 = " RVI ÍÀÑÒÐÎÉÊÈ ";
extern int RVI_Per = 45;
extern double RVI_max = 0.05;
extern double RVI_min = -0.05;
//======================================================================||
extern string SS5 = "ÒÐÅÉËÈÍÃ ÒÅÍÈ";
extern bool Trailing = True;
extern int Tmfrm = 30; // ïåðèîä, ïî áàðàì êîòîðîãî ñëåäóåò òðàëèòü
extern int Bars_n = 13; // êîë-âî áàðîâ, ïî êîòîðûì ñëåäóåò òðàëèòü
extern int Indent = 10; // îòñòóï îò òåíè áàðà, íà êîòîðîì ðàçìåùàåòñÿ ñòîïëîññ
//======================================================================||
extern string SS6 = " --- UseSound ---";
extern bool UseSound = True; // Èñïîëüçîâàòü çâóêîâîé ñèãíàë
extern string Sound_o = "ok.wav"; // Íàèìåíîâàíèå çâóêîâîãî ôàéëà
//======================================================================||
#include <stdlib.mqh>
#include <stderror.mqh>
double new_extremum;
int AvgRange;
string comm;
double s1[];
//======================================================================||
int deinit()
{
ObjectDelete("time");
return(0);
}
void start()
{
if(AccountFreeMargin()<Minsum) // äåíüãè êîí÷èëèñü
{
Print("äåíüãè êîí÷èëèñü = ", AccountFreeMargin());
return(0);
}
//=======================================================================================================================
if (Trailing) TrailPositions();
double OsMA1 = iOsMA(NULL,0,fast,slow,signal,PRICE_CLOSE,0);
double RVI_M = iRVI(NULL,0,RVI_Per,MODE_MAIN,0);
double RVI_S = iRVI(NULL,0,RVI_Per,MODE_MAIN,1);
double ima_S = iMA(NULL,0,5,0,3,0,0);
double ima_a = iMA(NULL,0,MA_1,0,3,0,0);
double ima_b = iMA(NULL,0,MA_2,0,3,0,0);
double ima_c = iMA(NULL,0,MA_3,0,3,0,0);
int rash_1 = (ima_a - ima_c)/Point;
int rash_2 = (ima_c - ima_a)/Point;
int rash_3 = (ima_S - ima_c)/Point;
int rash_4 = (ima_c - ima_S)/Point;
int StopLosb = rash_3+SLoss;
int StopLoss = rash_4+SLoss;
//========ManiMenedjment=================================================================================================
if(MM){if(Risk<0.1||Risk>100){Comment("Invalid Risk Value.");
return(0);}
else{Lots=MathFloor((AccountFreeMargin()*AccountLeverage()*(Risk/(SLoss+(Ask-Bid))*100.0)*Point*100.0)/(Ask*MarketInfo(Symbol(),
MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);}}
if(MM==false){Lots=Lots;}
//=====×àñû==============================================================================================================
double f;
int m,s,k;
m=Time[0]+Period()*60-CurTime();
f=m/60.0;
s=m%60;
m=(m-m%60)/60;
ObjectDelete("time");
if(ObjectFind("time") != 0)
{
ObjectCreate("time", OBJ_TEXT, 0, Time[0], Close[0]+ 0.0005);
ObjectSetText("time"," "+m+":"+s,8, "Arial", DodgerBlue);
}
else
{
ObjectMove("time", 0, Time[0], Close[0]+0.0005);
}
//=======================================================================================================================
int BuyCnt = 0;
int SellCnt = 0;
int cnt = OrdersTotal();
for (int i=0; i < cnt; i++)
{
if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (OrderSymbol() != Symbol()) continue;
if (OrderMagicNumber() != Magic) continue;
int type = OrderType();
if (type == OP_BUY) BuyCnt++;
if (type == OP_SELL) SellCnt++;
}
double price, sl, tp;
//=======================================================================================================================
if (OsMA1>0.0 && RVI_M>RVI_S && RVI_S>=RVI_max && ima_a>ima_b && ima_b>ima_c && rash_1<Razk)
{
if (BuyCnt > 0) return;
if (CloseOrders(OP_SELL) > 0) return;
price = Ask;
sl = If(StopLosb > 0, price - StopLosb*Point,0);
tp = If(TakeProfit > 0, price + TakeProfit*Point,0);
Buy(Symbol(), GetLots(), price, sl, tp, Magic);
return;
}
//======================================================================================================================
if (OsMA1<0.0 && RVI_M<RVI_S && RVI_S<=RVI_min && ima_a<ima_b && ima_b<ima_c && rash_2<Razk)
{
if (SellCnt > 0) return;
if (CloseOrders(OP_BUY) > 0) return;
price = Bid;
sl = If(StopLoss > 0, price + StopLoss*Point,0);
tp = If(TakeProfit > 0, price - TakeProfit*Point,0);
Sell(Symbol(), GetLots(), price, sl, tp, Magic);
return;
}}
//======================================================================================================================
double If(bool cond, double if_true, double if_false)
{
if (cond) return (if_true);
return (if_false);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
double GetLots()
{
return (Lots);
}
int CloseOrders(int type)
{
int cnt = OrdersTotal();
for (int i=cnt-1; i >= 0; i--)
{
if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (OrderSymbol() != Symbol()) continue;
if (OrderMagicNumber() != Magic) continue;
if (OrderType() != type) continue;
if (type == OP_BUY)
{
RefreshRates();
CloseOrder(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID));
continue;
}
if (type == OP_SELL)
{
RefreshRates();
CloseOrder(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK));
continue;
}}
int orders = 0;
cnt = OrdersTotal();
for (i = 0; i < cnt; i++)
{
if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (OrderSymbol() != Symbol()) continue;
if (OrderMagicNumber() != Magic) continue;
if (OrderType() == type) orders++;
}
return (orders);
}
//======================================================================================================================
void TrailPositions()
{
int cnt = OrdersTotal();
for (int i=0; i<cnt; i++)
{
if (!(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))) continue;
if (OrderSymbol() != Symbol()) continue;
if (OrderMagicNumber() != Magic) continue;
//=====ÁËÎÊ==================================TrailingStop===============================================
if (OrderType() == OP_BUY)
{
for(i=1;i<=Bars_n;i++)
{
if (i==1) new_extremum = iLow(NULL,Tmfrm,i);
else
if (new_extremum>iLow(NULL,Tmfrm,i)) new_extremum = iLow(NULL,Tmfrm,i);
}
if ((((new_extremum - Bars_n*Point)>OrderStopLoss()) || (OrderStopLoss()==0)) && ((new_extremum - Indent*Point)>OrderOpenPrice())
&& (new_extremum - Indent*Point<Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
if (!OrderModify(OrderTicket(),OrderOpenPrice(),new_extremum - Indent*Point,OrderTakeProfit(),OrderExpiration()))
return;
}
//=====ÁËÎÊ=================================TrailingStop=================================================
if (OrderType() == OP_SELL)
{
for(i=1;i<=Bars_n;i++)
{
if (i==1) new_extremum = iHigh(NULL,Tmfrm,i);
else
if (new_extremum<iHigh(NULL,Tmfrm,i)) new_extremum = iHigh(NULL,Tmfrm,i);
}
if ((((new_extremum + (Bars_n + MarketInfo(Symbol(),MODE_SPREAD))*Point)<OrderStopLoss()) || (OrderStopLoss()==0)) &&
((new_extremum + (Indent + MarketInfo(Symbol(),MODE_SPREAD))*Point)<OrderOpenPrice()) &&
(new_extremum + (Indent + MarketInfo(Symbol(),MODE_SPREAD))*Point>Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
if (!OrderModify(OrderTicket(),OrderOpenPrice(),new_extremum + (Indent + MarketInfo(Symbol(),MODE_SPREAD))*Point,OrderTakeProfit(),OrderExpiration()))
return;
}}}
//======================================================================================================================
int SleepOk = 2000;
int SleepErr = 6000;
int Buy(string symbol, double lot, double price, double sl, double tp, int magic, string comment="")
{
int dig = MarketInfo(symbol, MODE_DIGITS);
price = NormalizeDouble(price, dig);
sl = NormalizeDouble(sl, dig);
tp = NormalizeDouble(tp, dig);
string _lot = DoubleToStr(lot, 2);
string _price = DoubleToStr(price, dig);
string _sl = DoubleToStr(sl, dig);
string _tp = DoubleToStr(tp, dig);
//======================================================================================================================
int res = OrderSend(symbol, OP_BUY, lot, price, Slippage, sl, tp, comment, magic, 0);
PlaySound(Sound_o);
if (res >= 0)
{
Sleep(SleepOk);
return (res);
}
int code = GetLastError();
Print("Error opening BUY order: ", ErrorDescription(code), " (", code, ")");
Sleep(SleepErr);
return (-1);
}
int Sell(string symbol, double lot, double price, double sl, double tp, int magic, string comment="")
{
int dig = MarketInfo(symbol, MODE_DIGITS);
price = NormalizeDouble(price, dig);
sl = NormalizeDouble(sl, dig);
tp = NormalizeDouble(tp, dig);
string _lot = DoubleToStr(lot, 2);
string _price = DoubleToStr(price, dig);
string _sl = DoubleToStr(sl, dig);
string _tp = DoubleToStr(tp, dig);
//======================================================================================================================
int res = OrderSend(symbol, OP_SELL, lot, price, Slippage, sl, tp, comment, magic, 0);
PlaySound(Sound_o);
if (res >= 0)
{
Sleep(SleepOk);
return (res);
}
int code = GetLastError();
Print("Error opening SELL order: ", ErrorDescription(code), " (", code, ")");
Sleep(SleepErr);
return (-1);
}
bool CloseOrder(int ticket, double lot, double price)
{
if (!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES)) return(false);
int dig = MarketInfo(OrderSymbol(), MODE_DIGITS);
string _lot = DoubleToStr(lot, 2);
string _price = DoubleToStr(price, dig);
Print("CloseOrder ", ticket, ", ", _lot, ", ", _price, ", ", Slippage);
bool res = OrderClose(ticket, lot, price, Slippage);
if (res)
{
Sleep(SleepOk);
return (res);
}
int code = GetLastError();
Print("CloseOrder failed: ", ErrorDescription(code), " (", code, ")");
Sleep(SleepErr);
return (false);
}
//======================================================================================================================
Comments