Okay, here's a breakdown of what this MetaTrader script does, explained in a way that someone without programming knowledge can understand:
Overall Purpose:
This script is designed to automatically trade on the Forex market (the global currency exchange) based on a trading strategy called "Divergence." It aims to identify potential buying or selling opportunities based on the relationship between two moving averages, and then automatically open and manage trades. It also has some built-in risk management features to limit losses and secure profits.
Key Components and How They Work:
-
User Settings: At the start, the script has a section where you can customize how it behaves. These settings include:
Lots
: The size of the trades it will make (e.g., how much of a currency to buy or sell).Fast_Period
andSlow_Period
: These values determine how two moving averages are calculated. Moving averages smooth out price fluctuations to show trends. The script uses two different moving averages, a "fast" one and a "slow" one.DVBuySell
andDVStayOut
: These are trigger levels. When the difference (or "divergence") between the two moving averages reaches these levels, it signals the script to consider a buy or sell trade.ProfitMade
andLossLimit
: These set the target profit and maximum loss, in pips, for each trade. A pip is a standard unit of measurement in Forex trading.TrailStop
: This activates a "trailing stop," which automatically adjusts the stop-loss order as the trade moves in a profitable direction, helping to lock in gains.PLBreakEven
: If the trade reaches this level of profit (in pips), it will automatically move the stop-loss to the entry price (breakeven).BasketProfit
andBasketLoss
: These settings allow the script to close all open trades if the total profit or loss across all trades reaches a certain level. This is a way to manage overall portfolio risk.
-
Initialization (init): When the script starts, it performs a few setup tasks:
- It clears any old visual elements (objects) that were drawn on the chart from previous runs of the script.
- It sets up a text label on the chart to display the current "divergence" value (the difference between the moving averages).
-
Deinitialization (deinit): When the script is stopped or removed from the chart, it:
- It clears any old visual elements (objects) that were drawn on the chart.
- It prints some statistics about the script's performance (maximum number of orders, maximum and minimum equity) to the "Experts" tab.
-
Main Logic (start): This is where the core trading decisions happen. This section runs repeatedly, with every "tick" (price change) or new bar on the chart. It does the following:
-
Detecting New Bars: It checks if a new bar (a period of time on the chart) has started. If it has, it resets a trade permission flag and increments bar counters.
-
Checking Existing Orders: It counts how many trades the script currently has open for the currency pair it's running on.
- It tracks the max orders on a variable so the user can evaluate.
-
Calculating the Divergence:
- It calculates the values of the "fast" and "slow" moving averages using historical price data. The user defined the periods for these values.
- Calculates the difference between the fast and slow MA.
-
Determining Buy/Sell Signals: It checks if the "divergence" between the two moving averages has reached the pre-defined trigger levels (
DVBuySell
andDVStayOut
). If it has, it sets flags (BUYme
orSELLme
) to indicate whether a buy or sell trade should be considered. -
Placing Trades:
- If
BUYme
is true AND a new trade is allowed on the current bar AND the script thinks it's a good time to buy, it will send a "buy" order to the trading platform. It also defines the stop-loss and take-profit levels for the trade, based on the user's settings. - If
SELLme
is true AND a new trade is allowed AND the script thinks it's a good time to sell, it will send a "sell" order to the trading platform, with similar stop-loss and take-profit settings.
- If
-
Risk Management:
- Basket Close: It monitors the total profit or loss across ALL open trades. If the total profit reaches
BasketProfit
or the total loss reachesBasketLoss
, it will close ALL open trades. - Individual Trade Management: For each open trade, it checks:
- Break-Even: If the trade reaches
PLBreakEven
pips of profit, it moves the stop-loss to breakeven (the entry price). - Trailing Stop: If the trade reaches
TrailStop
pips of profit, it activates the trailing stop, which will automatically adjust the stop-loss as the price moves in a favorable direction. - Profit Target/Loss Limit: It checks if the trade has reached its target profit (
ProfitMade
) or hit its maximum loss (LossLimit
). If either of these occurs, it closes the trade.
- Break-Even: If the trade reaches
- Basket Close: It monitors the total profit or loss across ALL open trades. If the total profit reaches
-
-
Closing All Trades (CloseEverything): This function is called when the
BasketProfit
orBasketLoss
levels are reached. It goes through all open trades and closes them.
In simpler terms:
The script is like a robot trader that:
- Watches the price chart and calculates two different moving averages.
- Compares the moving averages to look for potential buying or selling opportunities based on "divergence."
- Places trades automatically when the conditions are right, according to your settings.
- Manages the trades by setting stop-loss and take-profit levels, using a trailing stop, and closing trades when they reach their profit target or loss limit.
- It can close all trades at once if your total profit or loss across all trades reaches a certain point.
The goal is to automate a trading strategy based on divergence and manage risk according to the user's preferences.
/*-----------------------------+
| |
| Shared by www.Aptrafx.com |
| |
+------------------------------*/
/*
+--------+
|Divergence Trader
+--------+
*/
// variables declared here are GLOBAL in scope
#property copyright "Ron Thompson"
#property link "http://www.lightpatch.com/forex"
// user input
extern double Lots=0.10; // how many lots to trade at a time
extern int Fast_Period=7;
extern int Slow_Period=88;
extern double DVBuySell=0.0011;
extern double DVStayOut=0.0073;
extern double ProfitMade=20; // how much money do you expect to make
extern double LossLimit=115; // how much loss can you tolorate
extern double TrailStop=9999; // trailing stop (999=no trailing stop)
extern int PLBreakEven=9999; // set break even when this many pips are made (999=off)
extern int BasketProfit= 10; // if equity reaches this level, close trades
extern int BasketLoss=9999; // if equity reaches this negative level, close trades
// externals that don't need to be external
int Slippage=2; // how many pips of slippage can you tolorate
bool FileData=false; // write to file exery tick?
// naming and numbering
int MagicNumber = 200601182020; // allows multiple experts to trade on same account
string TradeComment = "Divergence_07_";
// Bar handling
datetime bartime=0; // used to determine when a bar has moved
int bartick=0; // number of times bars have moved
int objtick=0; // used to draw objects on the chart
int tickcount=0;
// Trade control
bool TradeAllowed=true; // used to manage trades
// Min/Max tracking
double maxOrders;
double maxEquity;
double minEquity;
//+-------------+
//| Custom init |
//|-------------+
// Called ONCE when EA is added to chart or recompiled
int init()
{
int i;
string o;
//remove the old objects
for(i=0; i<Bars; i++)
{
o=DoubleToStr(i,0);
ObjectDelete("myx"+o);
ObjectDelete("myz"+o);
}
objtick=0;
ObjectDelete("Cmmt");
ObjectCreate( "Cmmt", OBJ_TEXT, 0, Time[20], High[20]+(5*Point) );
ObjectSetText("Cmmt","Divergence=X.XXXX",10,"Arial",White);
Print("Init happened ",CurTime());
Comment(" ");
}
//+----------------+
//| Custom DE-init |
//+----------------+
// Called ONCE when EA is removed from chart
int deinit()
{
int i;
string o;
//remove the old objects
for(i=0; i<Bars; i++)
{
o=DoubleToStr(i,0);
ObjectDelete("myx"+o);
ObjectDelete("myz"+o);
}
objtick=0;
Print("MAX number of orders ",maxOrders);
Print("MAX equity ",maxEquity);
Print("MIN equity ",minEquity);
Print("DE-Init happened ",CurTime());
Comment(" ");
}
//+-----------+
//| Main |
//+-----------+
// Called EACH TICK and each Bar[]
int start()
{
double p=Point;
double spread=Ask-Bid;
double spread2=(Ask-Bid)+2*Point; // for setting unattended stoploss and takeprofit
int cnt=0;
int gle=0;
int OrdersPerSymbol=0;
int iFileHandle;
// stoploss and takeprofit and close control
double SL=0;
double TP=0;
double CurrentProfit=0;
double CurrentBasket=0;
// direction control
bool BUYme=false;
bool SELLme=false;
// Trade stuff
double diverge;
double maF1, maS1;
// bar counting
if(bartime!=Time[0])
{
bartime=Time[0];
bartick++;
objtick++;
TradeAllowed=true;
}
OrdersPerSymbol=0;
for(cnt=OrdersTotal();cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
OrdersPerSymbol++;
}
}
if(OrdersPerSymbol>maxOrders) maxOrders=OrdersPerSymbol;
//+-----------------------------+
//| Insert your indicator here |
//| And set either BUYme or |
//| SELLme true to place orders |
//+-----------------------------+
int Fast_Price = PRICE_OPEN;
int Fast_Mode = MODE_EMA;
maF1=iMA(Symbol(),0,Fast_Period,0,Fast_Mode,Fast_Price,0);
int Slow_Price = PRICE_OPEN;
int Slow_Mode = MODE_SMMA;
maS1=iMA(Symbol(),0,Slow_Period,0,Slow_Mode,Slow_Price,0);
diverge=(maF1-maS1);
ObjectDelete("Cmmt");
ObjectCreate("Cmmt", OBJ_TEXT, 0, Time[20], High[20]+(10*p));
ObjectSetText("Cmmt","Divergence="+DoubleToStr(diverge,4),10,"Arial",White);
if( diverge>= DVBuySell && diverge<= DVStayOut ) BUYme=true;
if( diverge<=(DVBuySell*(-1)) && diverge>=(DVStayOut*(-1)) ) SELLme=true;
if(FileData)
{
tickcount++;
iFileHandle = FileOpen("eaDivergence07", FILE_CSV|FILE_READ|FILE_WRITE, ",");
FileSeek(iFileHandle, 0, SEEK_END);
FileWrite(iFileHandle, bartick, " ", tickcount, " ", diverge);
FileFlush(iFileHandle);
FileClose(iFileHandle);
}
//+------------+
//| End Insert |
//+------------+
//ENTRY LONG (buy, Ask)
if(TradeAllowed && BUYme)
{
//Ask(buy, long)
if(LossLimit ==0) SL=0; else SL=Ask-( (LossLimit +7)*Point );
if(ProfitMade==0) TP=0; else TP=Ask+( (ProfitMade+7)*Point );
OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,SL,TP,TradeComment,MagicNumber,White);
gle=GetLastError();
if(gle==0)
{
Print("BUY Ask=",Ask," bartick=",bartick);
ObjectCreate("myx"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], High[0]+(5*p));
ObjectSetText("myx"+DoubleToStr(objtick,0),"B",15,"Arial",Red);
bartick=0;
TradeAllowed=false;
}
else
{
Print("-----ERROR----- BUY Ask=",Ask," error=",gle," bartick=",bartick);
}
}
//ENTRY SHORT (sell, Bid)
if(TradeAllowed && SELLme)
{
//Bid (sell, short)
if(LossLimit ==0) SL=0; else SL=Bid+((LossLimit+7)*Point );
if(ProfitMade==0) TP=0; else TP=Bid-((ProfitMade+7)*Point );
OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,SL,TP,TradeComment,MagicNumber,Red);
gle=GetLastError();
if(gle==0)
{
Print("SELL Bid=",Bid," bartick=",bartick);
ObjectCreate("myx"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], High[0]+(5*p));
ObjectSetText("myx"+DoubleToStr(objtick,0),"S",15,"Arial",Red);
bartick=0;
TradeAllowed=false;
}
else
{
Print("-----ERROR----- SELL Bid=",Bid," error=",gle," bartick=",bartick);
}
}
//Basket profit or loss
CurrentBasket=AccountEquity()-AccountBalance();
if(CurrentBasket>maxEquity) maxEquity=CurrentBasket;
if(CurrentBasket<minEquity) minEquity=CurrentBasket;
// actual basket closure
if( CurrentBasket>=BasketProfit || CurrentBasket<=(BasketLoss*(-1)) )
{
CloseEverything();
}
// CLOSE order if profit target made
for(cnt=OrdersTotal();cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
{
if(OrderType()==OP_BUY)
{
CurrentProfit=Bid-OrderOpenPrice() ;
// modify for break even
if (CurrentProfit >= PLBreakEven*p && OrderOpenPrice()>OrderStopLoss())
{
SL=OrderOpenPrice()+(spread*2);
TP=OrderTakeProfit();
OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, White);
gle=GetLastError();
if(gle==0)
{
Print("MODIFY BREAKEVEN BUY Bid=",Bid," bartick=",bartick);
ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
ObjectSetText("myz"+DoubleToStr(objtick,0),"BE",15,"Arial",White);
}
else
{
Print("-----ERROR----- MODIFY BREAKEVEN BUY Bid=",Bid," error=",gle," bartick=",bartick);
}
}
// modify for trailing stop
if(CurrentProfit >= TrailStop*p )
{
SL=Bid-(TrailStop*p);
TP=OrderTakeProfit();
OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, White);
gle=GetLastError();
if(gle==0)
{
Print ("MODIFY TRAILSTOP BUY StopLoss=",SL," bartick=",bartick,"OrderTicket=",OrderTicket()," CurrProfit=",CurrentProfit);
ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
ObjectSetText("myz"+DoubleToStr(objtick,0),"TS",15,"Arial",White);
}
else
{
Print("-----ERROR----- MODIFY TRAILSTOP BUY Bid=",Bid," error=",gle," bartick=",bartick);
}
}
// did we make our desired BUY profit
// or did we hit the BUY LossLimit
if((ProfitMade>0 && CurrentProfit>=(ProfitMade*p)) || (LossLimit>0 && CurrentProfit<=((LossLimit*(-1))*p)) )
{
OrderClose(OrderTicket(),Lots,Bid,Slippage,White);
gle=GetLastError();
if(gle==0)
{
Print("CLOSE BUY Bid=",Bid," bartick=",bartick);
ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
ObjectSetText("myz"+DoubleToStr(objtick,0),"C",15,"Arial",White);
}
else
{
Print("-----ERROR----- CLOSE BUY Bid=",Bid," error=",gle," bartick=",bartick);
}
}
} // if BUY
if(OrderType()==OP_SELL)
{
CurrentProfit=OrderOpenPrice()-Ask;
// modify for break even
if (CurrentProfit >= PLBreakEven*p && OrderOpenPrice()<OrderStopLoss())
{
SL=OrderOpenPrice()-(spread*2);
TP=OrderTakeProfit();
OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, Red);
gle=GetLastError();
if(gle==0)
{
Print("MODIFY BREAKEVEN SELL Ask=",Ask," bartick=",bartick);
ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
ObjectSetText("myz"+DoubleToStr(objtick,0),"BE",15,"Arial",Red);
}
else
{
Print("-----ERROR----- MODIFY BREAKEVEN SELL Ask=",Ask," error=",gle," bartick=",bartick);
}
}
// modify for trailing stop
if(CurrentProfit >= TrailStop*p)
{
SL=Ask+(TrailStop*p);
TP=OrderTakeProfit();
OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, Red);
gle=GetLastError();
if(gle==0)
{
Print ("MODIFY TRAILSTOP SELL StopLoss=",SL," bartick=",bartick,"OrderTicket=",OrderTicket()," CurrProfit=",CurrentProfit);
ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
ObjectSetText("myz"+DoubleToStr(objtick,0),"TS",15,"Arial",Red);
}
else
{
Print("-----ERROR----- MODIFY TRAILSTOP SELL Ask=",Ask," error=",gle," bartick=",bartick);
}
}
// did we make our desired SELL profit?
if( (ProfitMade>0 && CurrentProfit>=(ProfitMade*p)) || (LossLimit>0 && CurrentProfit<=((LossLimit*(-1))*p)) )
{
OrderClose(OrderTicket(),Lots,Ask,Slippage,Red);
gle=GetLastError();
if(gle==0)
{
Print("CLOSE SELL Ask=",Ask," bartick=",bartick);
ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
ObjectSetText("myz"+DoubleToStr(objtick,0),"C",15,"Arial",Red);
}
else
{
Print("-----ERROR----- CLOSE SELL Ask=",Ask," error=",gle," bartick=",bartick);
}
}
} //if SELL
} // if(OrderSymbol)
} // for
} // start()
//+-----------------+
//| CloseEverything |
//+-----------------+
// Closes all OPEN and PENDING orders
int CloseEverything()
{
double myAsk;
double myBid;
int myTkt;
double myLot;
int myTyp;
int i;
bool result = false;
for(i=OrdersTotal();i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
myAsk=MarketInfo(OrderSymbol(),MODE_ASK);
myBid=MarketInfo(OrderSymbol(),MODE_BID);
myTkt=OrderTicket();
myLot=OrderLots();
myTyp=OrderType();
switch( myTyp )
{
//Close opened long positions
case OP_BUY :result = OrderClose(myTkt, myLot, myBid, Slippage, Red);
break;
//Close opened short positions
case OP_SELL :result = OrderClose(myTkt, myLot, myAsk, Slippage, Red);
break;
//Close pending orders
case OP_BUYLIMIT :
case OP_BUYSTOP :
case OP_SELLLIMIT:
case OP_SELLSTOP :result = OrderDelete( OrderTicket() );
}
if(result == false)
{
Alert("Order " , myTkt , " failed to close. Error:" , GetLastError() );
Print("Order " , myTkt , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
Sleep(1000);
} //for
} // closeeverything
Comments