Okay, here's a breakdown of what this MetaTrader script does, explained in a way that avoids technical jargon and is geared towards someone who isn't a programmer:
Overall Goal:
This script is designed to automatically place buy or sell orders on a specific currency pair in the MetaTrader platform, aiming to profit from price fluctuations. It uses a combination of indicators and rules to determine when to enter and potentially exit trades.
Here's how it works, step-by-step:
-
Setup and Preferences:
- The script starts by reading a set of instructions defined through input parameters, think of these as dials that you tune to adjust how the script behaves. These instructions include:
mn
: A magic number to identify orders placed by the script.tp
: Take Profit distance (in points) ? how much profit the script aims for before automatically closing a trade.sl
: Stop Loss distance (in points) ? how much the script is willing to lose before automatically closing a trade.TrailingStop
: Activates the trailing stop functionality to further secure profits.lots
: The default trade size (volume) to use for each order.Risk
: A percentage of the account balance to risk on each trade (used to dynamically calculate the trade size).multilot
: Increment lot size on losses.closeby
: A parameter that enables trade closure using the psv() function.sh2
,sh3
,sh4
,sh5
: Parameters to tune the fractal indicator.per_rsi
: period for RSI indicator calculation.sars1
,sars2
: Parameters for the Parabolic SAR indicator.
- The script starts by reading a set of instructions defined through input parameters, think of these as dials that you tune to adjust how the script behaves. These instructions include:
-
Checking for Existing Trades:
- Before placing any new trades, the script checks if it already has open trades for the same currency pair that were placed by this script (identified by the magic number). This prevents the script from opening multiple conflicting trades.
-
Managing Existing Trades:
- If the script finds an existing trade, it does two main things:
- Trailing Stop: If the trade is profitable, the script adjusts the stop loss order automatically so the stop loss moves with the price, securing profits.
- Close Trade (optional): If parameter
closeby
is active, it checks the psv() function, if the existing trade is a buy and the psv() is negative it closes the trade, if the existing trade is a sell and the psv() is positive it closes the trade.
- If the script finds an existing trade, it does two main things:
-
Deciding When to Trade (The
psv()
function):-
This is the core of the script's trading logic. The script uses a combination of three technical indicators to decide whether to buy or sell:
- Fractals: Detects potential turning points in the price by identifying patterns. The
Crof()
function determines if a fractal indicates an upward or downward direction. - Relative Strength Index (RSI): Measures the momentum of price changes. The script uses RSI on a larger timeframe (1440 minutes, or one day).
- Parabolic SAR (SAR): Identifies potential trend reversals. The script uses two different SAR settings (
sars1
andsars2
) and compares their values.
- Fractals: Detects potential turning points in the price by identifying patterns. The
-
The
psv()
function combines these indicators with specific rules:- Buy Signal: If the fractal indicator on two different timeframes points upward, the RSI is below 50, and SAR1 is greater than or equal to SAR2, the function returns 1, indicating a buy signal.
- Sell Signal: If the fractal indicator on two different timeframes points downward, the RSI is above 50, and SAR1 is less than or equal to SAR2, the function returns -1, indicating a sell signal.
- No Signal: If none of these conditions are met, the function returns 0, meaning the script should not place a trade.
-
-
Placing a Trade:
- If the
psv()
function returns a buy or sell signal, the script places a new order:- It uses the
LotSize()
function to determine the appropriate trade size, based on the account balance and the risk setting. The function increases lot size depending on previous losses by checking the history and multiplying the size by the "multilot" parameter. - It sets a stop-loss order to limit potential losses and a take-profit order to automatically close the trade when a certain profit level is reached.
- It uses the
- If the
-
Error Handling:
- If there's an error when placing an order, the script pauses and tries again later, avoiding immediate retries that could exacerbate the problem.
In essence: The script automates trading based on a specific strategy. It monitors price movements, uses technical indicators to identify potential trading opportunities, and places buy or sell orders according to its pre-defined rules.
//+---------------------------------------------------------------------------------+
//| ComFracti.mq4 |
//| |
//| If You make too much money with this EA - some gift or donations accepted [:-) |
//+---------------------------------------------------------------------------------+
#property copyright " mich99@o2.pl "
#property link " "
//---- input parameters
extern int mn = 818;
extern double tp = 2000; // ( for 5 digits brokers )
extern double sl = 1000;
extern double TrailingStop=300;
extern double lots = 0.1;
extern double Risk= 0.005;
extern double multilot=0;
extern bool closeby = false;
static int prevtime = 0;
extern int sh2 = 3;
extern int sh3 = 3;
extern int sh4 = 3;
extern int sh5 = 3;
extern int per_rsi=3; // rsi1440 period
extern double sars1=0.02; // if sar1 = sar2,that sar filter is with out mining.
extern double sars2=0.03;
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
if (Time[0] == prevtime) return(0);
prevtime = Time[0];
if (! IsTradeAllowed()) {
again();
return(0);
}
//----
int total = OrdersTotal();
for (int i = 0; i < total; i++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == Symbol() && OrderMagicNumber() == mn) {
if(OrderType()<=OP_SELL && TrailingStop>0)
{
TrailingPositions();
}
if(OrderType() == OP_BUY && psv() < 0 && closeby )
{
OrderClose(OrderTicket(),LotSize(),MarketInfo(Symbol(),MODE_BID),30,GreenYellow);
}
if(OrderType() == OP_SELL && psv() > 0 && closeby)
{
OrderClose(OrderTicket(),LotSize(),MarketInfo(Symbol(),MODE_BID),30,GreenYellow);
}
return(0);
}
}
int ticket = -1;
RefreshRates();
if (psv() > 0) {
ticket = OrderSend(Symbol(), OP_BUY, LotSize(), Ask, 30, Bid - sl * Point, Bid + tp * Point, WindowExpertName(), mn, 0, Blue);
if (ticket < 0) {
again();
}
} if (psv() < 0) {
ticket = OrderSend(Symbol(), OP_SELL, LotSize(), Bid, 30, Ask + sl * Point, Ask - tp * Point, WindowExpertName(), mn, 0, Red);
if (ticket < 0) {
again();
}
}
//-- Exit --
return(0);
}
double Crof(int t , int s)
{
double frup = iFractals(NULL, t, MODE_UPPER, s);
double frdw = iFractals(NULL, t, MODE_LOWER, s);
if ( (frup==0 ) && frdw!=0 ) return (1);
if ( (frdw==0 ) && frup!=0 ) return (-1);
return (0); //elsewhere
}
double psv() {
double s1 = iSAR(NULL, 0, sars1, 0.2, 0);
double s2 = iSAR(NULL, 0, sars2, 0.2, 0);
double m6=iRSI(NULL, 1440, per_rsi, PRICE_OPEN, 0);
if ( Crof(0 , sh2)>0 && Crof(60 , sh3)>0 && m6<50 && s1>=s2 ) return(1);
if ( Crof(0 , sh4)<0 && Crof(60 , sh5)<0 && m6>50 && s1<=s2 ) return(-1);
return(0);
}
//+--------------------------- getLots ----------------------------------+
double LotSize()
{
double DecreaseFactor=multilot;
double lot=lots;
int orders=HistoryTotal(); // history orders total
int losses=0; // number of losses orders without a break
//---- select lot size
lot=MathCeil(AccountFreeMargin() * Risk / 1000)/10;
//---- calcuulate number of losses orders without a break
if(DecreaseFactor>0)
{
for(int i=orders-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
//----
if(OrderProfit()>0) break;
if(OrderProfit()<0) losses++;
}
if(losses>0) lot=NormalizeDouble(lot-(-1)*lot*DecreaseFactor,1);
}
//---- return lot size
if(lot<0.1) lot=0.1;
return(lot);
}
void TrailingPositions() {
double pp;
int TrailingStep = 1;
bool ProfitTrailing = true;
pp = Point;
if (OrderType()==OP_BUY)
{
if (!ProfitTrailing || (Bid-OrderOpenPrice())>TrailingStop*pp*2)
{
if (OrderStopLoss()<Bid-(TrailingStop+TrailingStep-1)*pp)
{
ModifyStopLoss(Bid-TrailingStop*pp);
return;
}
}
}
if (OrderType()==OP_SELL)
{
if (!ProfitTrailing || OrderOpenPrice()-Ask>TrailingStop*pp*2)
{
if (OrderStopLoss()>Ask+(TrailingStop+TrailingStep-1)*pp || OrderStopLoss()==0)
{
ModifyStopLoss(Ask+TrailingStop*pp);
return;
}
}
}
}
//--------------------------------------------------------------------------------------//
void ModifyStopLoss(double ldStopLoss) {
bool fm;
fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,Yellow);
}
//-------------------------
void again() {
prevtime = Time[1];
Sleep(10000);
}
Comments