Moving Average Cross Fibonacci TakeProfit

MA_Cross_Fibo_TP


SHORT SIGNAL:

When 5EMA crosses 20SMA down:
Draw 2 points as below:
POINT A; Candle close price that confirmed the downside crossover
POINT B: highest price of the current wave prior to the crossover,
Profit Target: @ 161.8 fibo level
Stop Loss: maximum 38.2 (minimum @ 78.6) based on your risk appetite.

LONG SIGNAL:

When 5EMA crosses 20SMA up:
Draw 2 points as below:
POINT A; Candle close price that confirmed the upside crossover
POINT B: lowest price of the current wave prior to the crossover,
Profit Target: @ 161.8 fibo level
Stop Loss: maximum 38.2 (minimum @ 78.6) based on your risk appetite.

Exit mechanism for losing trades, if stoploss yet to hit: if 5EMA cross 8SMA in direction opposite of your open trade.


Code :
//+------------------------------------------------------------------+
//|                                             MA_Cross_Fibo_TP.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                                  http://meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright     "Copyright 2018, MetaEditor."
#property link          "http://meta-editor.blogspot.com"
#property description   "http://meta-editor.blogspot.com"
#property version       "1.00"
#include <stderror.mqh>
#include <stdlib.mqh>

//#property indicator_chart_window
extern string Trade_Time ="+++Trade Time Parameters+++";
extern int StartHour  =0;  // London open 7GMT;close 15GMT
extern int EndHour  =16;   // NY open=12GMT;close 20GMT
extern bool FridayTrade  =true;  // Trade on Fridays
extern bool MondayTrade  =true;  // Trade on Mondays

extern string MA_Params  ="+++MA Parameters+++";
extern string MA_Mode_Types ="0=SMA; 1=EMA; 2=SMMA; 3=LWMA;";
extern int Fast_MA  =5;
extern int Fast_Mode  =1;
//extern int MidMA  =8;
extern int Slow_MA  =20;
extern int Slow_Mode  =0;
extern int Mid_MA  =8;
extern int Mid_Mode  =0;
extern string Trade_Params ="+++Trade Parameters+++";
extern double Lots  =0.1;
extern int Min_TP  =10;  // Minimum take profit
extern int Max_SL  =50;  // Max Stop loss
extern int MagicNum  =12345;
extern int MaxOpnPos  =10;
extern color Long_Entry_Clr =Blue;
extern color Shrt_Entry_Clr =Red;

extern bool Close_at_fastXmid   =true;

double myPoint=1, slippage=3, mySlip, myMin_TP, myMax_SL;
int sft=0;
double MA5_now, MA8_now, MA20_now, MA5_prv, MA8_prv, MA20_prv, MA5_aft, MA8_aft, MA20_aft;
double POINT_A, POINT_B, P_2000, P_1618, P_1250, P_0786, P_0618, P_0500, P_0382;
string TRADE;
int bars_snc_dn_strtd=0,bars_snc_up_strtd=0;
datetime barTime=0;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
   if(Digits==3||Digits==5) myPoint=10;
   mySlip=(slippage*myPoint);
   myMin_TP=((Min_TP*myPoint)*Point);
   myMax_SL=((Max_SL*myPoint)*Point);
   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() { return(0); }


//+------------------------------------------------------------------+
//| Check Trading Time function                                      |
//+------------------------------------------------------------------+
// TradeTime
bool TradeTime()
{
   bool TradeDay, TradeHour;

   // Check Monday Friday Trading
   if(DayOfWeek()==1 && MondayTrade==false) TradeDay=false; else
   if(DayOfWeek()==5 && FridayTrade==false) TradeDay=false;
   else TradeDay=true;  

   // Check Market Hour
   if( TimeHour(TimeCurrent()) >= StartHour && TimeHour(TimeCurrent()) < EndHour ) TradeHour=true; else TradeHour=false;
   // Trade condition
   if( TradeDay==true && TradeHour==true ) return(true); else return(false);
}  // End: TradeTime


//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
if(!IsTradeAllowed()) { Print("Allow Live Trading First."); return(0); }
if(IsTradeContextBusy()) { Print("Trade context is busy. Try again"); return(0); }

   int OpenPosCnt=0, BUYPosCnt=0, SELLPosCnt=0;
   for(int cnt=0; cnt<OrdersTotal(); cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNum )
      {
         if(OrderType()==OP_BUY) BUYPosCnt=BUYPosCnt+1;
         if(OrderType()==OP_SELL) SELLPosCnt=SELLPosCnt+1;
      }
   }
   OpenPosCnt=BUYPosCnt+SELLPosCnt;


if(NewBar())
{
   MA5_now = iMA(NULL, 0, Fast_MA, 0, Fast_Mode, PRICE_CLOSE, sft+1);
   MA5_prv = iMA(NULL, 0, Fast_MA, 0, Fast_Mode, PRICE_CLOSE, sft+2);
   MA5_aft = iMA(NULL, 0, Fast_MA, 0, Fast_Mode, PRICE_CLOSE, sft);

   MA8_now = iMA(NULL, 0, Mid_MA, 0, Mid_Mode, PRICE_CLOSE, sft+1);
   MA8_prv = iMA(NULL, 0, Mid_MA, 0, Mid_Mode, PRICE_CLOSE, sft+2);
   MA8_aft = iMA(NULL, 0, Mid_MA, 0, Mid_Mode, PRICE_CLOSE, sft);

   MA20_now = iMA(NULL, 0, Slow_MA, 0, Slow_Mode, PRICE_CLOSE, sft+1);
   MA20_prv = iMA(NULL, 0, Slow_MA, 0, Slow_Mode, PRICE_CLOSE, sft+2);
   MA20_aft = iMA(NULL, 0, Slow_MA, 0, Slow_Mode, PRICE_CLOSE, sft);
  
   POINT_AB();
   if( TradeTime()==true && OpenPosCnt<MaxOpnPos && TRADE != "NA" ) { Open_Pos(); }
   if( OpenPosCnt>0 && Close_at_fastXmid==true ) { Close_fastXmid(); }

}


   return(0);
} // END: start


//+------------------------------------------------------------------+
//| Check Open possibilities function                                |
//+------------------------------------------------------------------+
// POINT_AB
void POINT_AB()
{
   string POINT_A_BAR_OPN, POINT_B_BAR_OPN;

   // 5EMA cross above 20SMA UP
   if((MA5_now > MA20_now) && (MA5_prv < MA20_prv) && (MA5_aft > MA20_aft))
   {
      TRADE="BUY";
      int low_bar_shft=iLowest(NULL,0,MODE_LOW,bars_snc_dn_strtd,sft+1);
      POINT_A=Close[sft+1]; // close of the bar which confirm MA cross
      POINT_B=Low[low_bar_shft];
      Print("BUY Trade. POINT_A: ",POINT_A," POINT_B: ", POINT_B);
Set_fibo();
      // Draw POINT_A, POINT_B and connecting line
      POINT_A_BAR_OPN=StringConcatenate( TimeHour(Time[sft+1]),":",TimeMinute(Time[sft+1]) );
      POINT_B_BAR_OPN=StringConcatenate( TimeHour(Time[low_bar_shft]),":",TimeMinute(Time[low_bar_shft]) );
      DrawObjects("MACFIBO-A "+POINT_A_BAR_OPN, sft+2, POINT_A, sft, POINT_A, Long_Entry_Clr, 3 );
      DrawObjects("MACFIBO-B "+POINT_B_BAR_OPN, low_bar_shft+1, POINT_B, low_bar_shft-1, POINT_B, Long_Entry_Clr, 3 );
      DrawObjects("MACFIBO-Line "+POINT_A_BAR_OPN+"-"+POINT_B_BAR_OPN, low_bar_shft, POINT_B, sft+1, POINT_A, Long_Entry_Clr, 3 );
   }
   // 5EMA cross below 20SMA DN
   else if ((MA5_now < MA20_now) && (MA5_prv > MA20_prv) && (MA5_aft < MA20_aft))
   {
      TRADE="SELL";
      Print("MA Cross DN : bars_snc_up_strtd ", bars_snc_up_strtd);
      int High_bar_shft=iHighest(NULL,0,MODE_HIGH,bars_snc_up_strtd,sft+1);
      POINT_A=Close[sft+1]; // close of the bar which confirm MA cross
      POINT_B=High[High_bar_shft];
      Print("SELL Trade. POINT_A: ",POINT_A," POINT_B: ", POINT_B);
Set_fibo();
      // Draw POINT_A, POINT_B anc connecting line
      POINT_A_BAR_OPN=StringConcatenate( TimeHour(Time[sft+1]),":",TimeMinute(Time[sft+1]) );
      POINT_B_BAR_OPN=StringConcatenate( TimeHour(Time[High_bar_shft]),":",TimeMinute(Time[High_bar_shft]) );
      DrawObjects("MACFIBO-A "+POINT_A_BAR_OPN, sft+2, POINT_A, sft, POINT_A, Shrt_Entry_Clr, 3 );
      DrawObjects("MACFIBO-B "+POINT_B_BAR_OPN, High_bar_shft+1, POINT_B, High_bar_shft-1, POINT_B, Shrt_Entry_Clr, 3 );
      DrawObjects("MACFIBO-Line "+POINT_A_BAR_OPN+"-"+POINT_B_BAR_OPN, High_bar_shft, POINT_B, sft+1, POINT_A, Shrt_Entry_Clr, 3 );
   }
   else { TRADE="NA"; }

   if( MA5_now < MA20_now ) // Trend is DN
   { bars_snc_up_strtd=0; bars_snc_dn_strtd++; }
   else if( MA5_now > MA20_now ) // Trend is UP
   { bars_snc_up_strtd++; bars_snc_dn_strtd=0; }

}  // End: POINT_AB


//+------------------------------------------------------------------+
//| Set fibo levels function                                         |
//+------------------------------------------------------------------+
// Set_fibo
void Set_fibo()
{
//POINT_A is 0 level. POINT_B is 100 level.
double diff;

   if(TRADE=="BUY")
   {
      diff=(POINT_A-POINT_B);
      P_2000=POINT_B+diff*2; P_1618=POINT_B+diff*1.618; P_1250=POINT_B+diff*1.250;
      P_0786=POINT_B+diff*0.786; P_0618=POINT_B+diff*0.618; P_0500=POINT_B+diff*0.50;
      P_0382=POINT_B+diff*0.382;
   }

   if(TRADE=="SELL")
   {
      diff=(POINT_B-POINT_A);
      P_2000=POINT_B-diff*2; P_1618=POINT_B-diff*1.618; P_1250=POINT_B-diff*1.250;
      P_0786=POINT_B-diff*0.786; P_0618=POINT_B-diff*0.618; P_0500=POINT_B-diff*0.50;
      P_0382=POINT_B-diff*0.382;
   }
   Print("Fibo 200%=",P_2000," : 1.618%=",P_1618," : 0.786%=",
      P_0786," : 0.618%=",P_0618," : 0.500%=",P_0500," : 0.382%=",P_0382);


}  // End: Set_fibo


//+------------------------------------------------------------------+
//| Get TP function                                          |
//+------------------------------------------------------------------+
double get_TP()
{
double Day_high[], Day_low[], TP_NEW;
int prv_day_shft;
int cur_day_shft = iBarShift(NULL, PERIOD_D1, iTime(NULL, 0, 0));
double prv_day_high=iHigh( NULL, PERIOD_D1, cur_day_shft+1) ;
double prv_day_low=iLow( NULL, PERIOD_D1, cur_day_shft+1) ;


if(TRADE=="BUY")
{
   if(prv_day_high>P_1618) { TP_NEW=P_1618; } else
   if(prv_day_high>P_1250) { TP_NEW=P_1250; }
   else if(prv_day_high>POINT_A) { TP_NEW=prv_day_high; }
   else { TP_NEW=P_1618; }
   TP_NEW=MathMax( (Ask+myMin_TP), TP_NEW);
   Print("New Take Profit: ",TP_NEW);
}
else if(TRADE=="SELL")
{
   if(prv_day_low<P_1618) { TP_NEW=P_1618; } else
   if(prv_day_low<P_1250) { TP_NEW=P_1250; }
   else if(prv_day_low<POINT_A) { TP_NEW=prv_day_low; }
   else { TP_NEW=P_1618; }
   TP_NEW=MathMin( (Bid-myMin_TP), TP_NEW);
   Print("New Take Profit: ",TP_NEW);
}

return(TP_NEW);
} // END: get_TP()


//+------------------------------------------------------------------+
//| Get SL function                                          |
//+------------------------------------------------------------------+
double get_SL()
{
double SL_NEW;
if(TRADE=="BUY")
{
   SL_NEW=MathMax( (Bid-myMax_SL), P_0382);
   Print("New Stop Loss: ",SL_NEW);
}
else if(TRADE=="SELL")
{
   SL_NEW=MathMin( (Ask+myMax_SL), P_0382);
   Print("New Stop Loss: ",SL_NEW);
}

return(SL_NEW);
} // END: get_SL()

//+------------------------------------------------------------------+
//| Open positions function                                          |
//+------------------------------------------------------------------+
// Open_Pos
void Open_Pos()
{
   double SL=0, TP=0, price;
   int cmd;
   string cmt;
   color clr;

   if(AccountFreeMargin()<(1000*Lots))
   {  Print("We have no money. Free Margin = ", AccountFreeMargin());
      return(0);  
   }
   // Open long position
   if( TRADE=="BUY" )
   {
      RefreshRates();
      cmd=OP_BUY; price=Ask;
      SL=get_SL(); TP=get_TP();
      cmt=(DoubleToStr(POINT_A,5)+","+DoubleToStr(POINT_B,5) ); // "BUY"
      clr=Green;
      Print("Placing BUY at: ",price," SL: ", SL ," TP: ",TP );
   }
   // Open short position
   else if( TRADE=="SELL" )
   {
      RefreshRates();
      cmd=OP_SELL; price=Bid;
      SL=get_SL(); TP=get_TP();
      cmt=(DoubleToStr(POINT_A,5)+","+DoubleToStr(POINT_B,5) ); // "SELL"
      clr=Red;
      Print("Placing SELL at: ",price," SL: ", SL ," TP: ",TP );
   }
   Print("Comment is: ",cmt);
   int ticket=OrderSend(Symbol(),cmd,Get_lot(),price,mySlip,SL,TP,cmt,MagicNum,0,clr);
   if(ticket<0) { Print("OrderSend Error #",GetLastError()," Desc: ",ErrorDescription(GetLastError()) ); }
  
}  // End: Open_Pos


//+------------------------------------------------------------------+
//| Find fastXmid MA function                                        |
//+------------------------------------------------------------------+
// Close_fastXmid
void Close_fastXmid()
{
   bool cmd_out; double price;
   string To_close;
   // 5EMA cross above 8SMA UP. Close all short positions
   if((MA5_now > MA8_now) && (MA5_prv < MA8_prv) && (MA5_aft > MA8_aft))
   { To_close="SELL"; Print("5EMA cross 8SMA up. Time to close short positions."); }
   // 5EMA cross below 8SMA DN. Close all long positions
   else if ((MA5_now < MA8_now) && (MA5_prv > MA8_prv) && (MA5_aft < MA8_aft))
   { To_close="BUY"; Print("5EMA cross 8SMA down. Time to close long positions."); }
   else { To_close="NA"; }

   for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderMagicNumber() == MagicNum && OrderSymbol()==Symbol())
      {
         if(To_close=="BUY" && OrderType()==OP_BUY && OrderProfit()<0 )
         {
            price=NormalizeDouble( MarketInfo(OrderSymbol(),MODE_BID), MarketInfo(OrderSymbol(),MODE_DIGITS));
            cmd_out=OrderClose(OrderTicket(),OrderLots(),price,mySlip,CLR_NONE);
            Print("Closing ",OrderSymbol()," BUY at ",price);
            if(!cmd_out) { Print("OrderClose BUY error #",GetLastError()," Desc: ",ErrorDescription(GetLastError()) ); }
         }
         if(To_close=="SELL" && OrderType()==OP_SELL && OrderProfit()<0 )
         {
            price=NormalizeDouble( MarketInfo(OrderSymbol(),MODE_ASK), MarketInfo(OrderSymbol(),MODE_DIGITS));
            cmd_out=OrderClose(OrderTicket(),OrderLots(),price,mySlip, CLR_NONE);
            Print("Closing ",OrderSymbol()," SELL at ",price);
            if(!cmd_out) { Print("OrderClose SELL error #",GetLastError()," Desc: ",ErrorDescription(GetLastError()) ); }
         }
      }
   }
   return(0);
}  // END: Close_fastXmid


//+------------------------------------------------------------------+
//| Check NewBar function                                            |
//+------------------------------------------------------------------+
// NewBar
bool NewBar()
{
   if( barTime < Time[0] )
   {  // we have a new bar opened
      barTime = Time[0];
      return(true);
   }
   return (false);
} // END: NewBar


void DrawObjects(string ObjName, int shft_bgn, double Price_Bgn, int shft_end, double Price_End, color clr, int wdth)
{
   ObjectDelete(ObjName);
   ObjectCreate(ObjName, OBJ_TREND, 0, Time[shft_bgn], Price_Bgn, Time[shft_end], Price_End );
   ObjectSet(ObjName, OBJPROP_WIDTH, wdth);
   ObjectSet(ObjName,OBJPROP_RAY,false);
   ObjectSet(ObjName,OBJPROP_STYLE,STYLE_SOLID);
   ObjectSet(ObjName,OBJPROP_COLOR,clr);
}


//+------------------------------------------------------------------+
//| Get Lot function                                            |
//+------------------------------------------------------------------+
double Get_lot()
{
   return(Lots);
} //Get_lot()


//+------------------------------------------------------------------+

Download : MA_Cross_Fibo_TP.mq4
 

Auto TakeProfit and StopLoss

 Auto_TP_SL


This EA will help you set Stop Loss and Take Profit on your open position (manual order).

EA can set SL/TP to all pairs, and you just need attach the EA on one pair only.

In the input settings, you can set single pair or all pairs. If AllPairs = True, it means EA will manage all pairs. Just attach on one chart, EA will work with all pairs.


Code :
//+------------------------------------------------------------------+
//|                                                   Auto_TP_SL.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                                  http://meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright     "Copyright 2018, MetaEditor."
#property link          "http://meta-editor.blogspot.com"
#property description   "http://meta-editor.blogspot.com"
#property version       "1.00"

input bool   AllPairs   = True;
input double TakeProfit = 400; //40-->4 digits; 400-->5 digits
input double StopLoss   = 150; //15-->4 digits; 150-->5 digits
input double DurasiTime = 60;
//---
int ticket;
double poen;
string pair="";
double iTakeProfit,iStopLoss;
double slbuy;
double tpbuy;
double slsell;
double tpsell;
double stoplevel;
double digi;
double poin;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   for(int cnt=0; cnt<OrdersTotal(); cnt++)
     {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderTicket()>0 && OrderMagicNumber()==0 && OrderTakeProfit()==0 && TimeCurrent()-OrderOpenTime()<=DurasiTime)
           {
            if(AllPairs) pair=OrderSymbol(); else pair=Symbol();
            //---
            stoplevel=MarketInfo(pair,MODE_STOPLEVEL);
            digi=MarketInfo(pair,MODE_DIGITS);
            poin=MarketInfo(pair,MODE_POINT);

            iStopLoss=StopLoss;
            iTakeProfit=TakeProfit;
            if(StopLoss<stoplevel) iStopLoss=stoplevel;
            if(TakeProfit<stoplevel) iTakeProfit=stoplevel;
            //---
            slbuy=NormalizeDouble(OrderOpenPrice()-iStopLoss*poin,digi);
            tpbuy=NormalizeDouble(OrderOpenPrice()+iTakeProfit*poin,digi);
            slsell=NormalizeDouble(OrderOpenPrice()+iStopLoss*poin,digi);
            tpsell=NormalizeDouble(OrderOpenPrice()-iTakeProfit*poin,digi);
            //---
            if(OrderSymbol()==pair && (OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP))
              {
               ticket=OrderModify(OrderTicket(),OrderOpenPrice(),slbuy,tpbuy,0,Blue);
              }
            if(OrderSymbol()==pair && (OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP))
              {
               ticket=OrderModify(OrderTicket(),OrderOpenPrice(),slsell,tpsell,0,Red);
              }
           }
        }
     }
//----
   return(0);
  }
//+------------------------------------------------------------------+

Download : Auto_TP_SL.mq4
 

Close Orders With further filtering

Close_Orders_Filter


The attached script allows you to close more orders at once.

You can choose the following filters:

  •     Only instrument in the chart where the script is run or all instruments.
  •     Only orders in profit.
  •     Only orders in loss.
  •     Only order matching a magic number.
  •     Only order marching a comment.

The script will scan all the open orders and close the ones matching the criteria.

Code :
//+------------------------------------------------------------------+
//|                                          Close_Orders_Filter.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                              http://www.meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright     "Copyright 2018, MetaEditor."
#property link          "http://www.meta-editor.blogspot.com"
#property description   "http://www.meta-editor.blogspot.com"
#property version       "1.00"
#property strict
#property description   "This script allows you to close all or only the selected positions"
#property description   ""
#property description   ""
#property description   "DISCLAIMER: This script comes with no guarantee at all, you can use it at your own risk"
#property description   "We recommend to test it first on a Demo Account"
#property show_inputs

//Configure the external variables
extern bool OnlyCurrentSymbol    = false;    //Close only instrument in the chart
extern bool OnlyInProfit         = false;    //Close only orders in profit
extern bool OnlyInLoss           = false;    //Close only orders in loss
extern bool OnlyMagicNumber      = false;    //Close only orders matching the magic number
extern int MagicNumber           = 0;        //Matching magic number
extern bool OnlyWithComment      = false;    //Close only orders with the following comment
extern string MatchingComment    = "";       //Matching comment
extern double Slippage           = 2;        //Slippage
extern int Delay                 = 0;        //Delay to wait between closing orders (in milliseconds)

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   //Counter for orders closed
   int TotalClosed=0;
   
   //Normalization of the digits
   if(Digits==3 || Digits==5){
      Slippage=Slippage*10;
   }
   
   //Scan the open orders backwards
   for(int i=OrdersTotal()-1; i>=0; i--){
   
      //Select the order, if not selected print the error and continue with the next index
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) {
         Print("ERROR - Unable to select the order - ",GetLastError());
         continue;
      } 
      
      //Check if the order can be closed matching the criteria, if criteria not matched skip to the next
      if(OnlyCurrentSymbol && OrderSymbol()!=Symbol()) continue;
      if(OnlyInProfit && OrderProfit()<=0) continue;
      if(OnlyInLoss && OrderProfit()>=0) continue;
      if(OnlyMagicNumber && OrderMagicNumber()!=MagicNumber) continue;
      if(OnlyWithComment && StringCompare(OrderComment(),MatchingComment)!=0) continue;
      
      //Prepare the close price
      double ClosePrice=0;
      RefreshRates();
      if(OrderType()==OP_BUY) ClosePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),Digits);
      if(OrderType()==OP_SELL) ClosePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),Digits);
         
      //Try to close the order
      if(OrderClose(OrderTicket(),OrderLots(),ClosePrice,Slippage,CLR_NONE)){
         TotalClosed++;
      }
      else{
         Print("Order failed to close with error - ",GetLastError());
      }      
      
      //Wait a delay
      Sleep(Delay);
   
   }
   
   //Print the total of orders closed
   Print("Total orders closed = ",TotalClosed);
   
  }
//+------------------------------------------------------------------+

Download : Close_Orders_Filter.mq4
 

Modify All TakeProfit and StopLoss Filter orders by Magic Number and Comment

OrderModify_All_TP_n_SL_by_Magic_n_Comment


This script scans for open orders and sets a Stop Loss and Take Profit to all of the filtered orders.

You can filter orders by:

  •     Magic Number
  •     Comment
You will have to specify the Stop Loss and Take Profit in pips.


Code :
//+------------------------------------------------------------------+
//|                   OrderModify_All_TP_n_SL_by_Magic_n_Comment.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                              http://www.meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright     "Copyright 2018, MetaEditor."
#property link          "http://www.meta-editor.blogspot.com"
#property description   "http://www.meta-editor.blogspot.com"
#property version       "1.00"
#property strict
#property show_inputs

//Configure the external variables
extern int TakeProfit            = 40;        //Take Profit in pips
extern int StopLoss              = 20;        //Stop Loss in pips
extern bool OnlyMagicNumber      = false;     //Modify only orders matching the magic number
extern int MagicNumber           = 0;         //Matching magic number
extern bool OnlyWithComment      = false;     //Modify only orders with the following comment
extern string MatchingComment    = "";        //Matching comment
extern double Slippage           = 2;         //Slippage
extern int Delay                 = 0;         //Delay to wait between modifying orders (in milliseconds)

//Function to normalize the digits
double CalculateNormalizedDigits()
{
   if(Digits<=3){
      return(0.01);
   }
   else if(Digits>=4){
      return(0.0001);
   }
   else return(0);
}

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   //Counter for orders modified
   int TotalModified=0;
   
   //Normalization of the digits
   if(Digits==3 || Digits==5){
      Slippage=Slippage*10;
   }
   double nDigits=CalculateNormalizedDigits();
   
   //Scan the open orders backwards
   for(int i=OrdersTotal()-1; i>=0; i--){
   
      //Select the order, if not selected print the error and continue with the next index
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) {
         Print("ERROR - Unable to select the order - ",GetLastError());
         continue;
      } 
      
      //Check if the order can be modified matching the criteria, if criteria not matched skip to the next
      if(OrderSymbol()!=Symbol()) continue;
      if(OnlyMagicNumber && OrderMagicNumber()!=MagicNumber) continue;
      if(OnlyWithComment && StringCompare(OrderComment(),MatchingComment)!=0) continue;
      
      //Prepare the prices
      double TakeProfitPrice=0;
      double StopLossPrice=0;
      double OpenPrice=OrderOpenPrice();
      RefreshRates();
      if(OrderType()==OP_BUY){
         TakeProfitPrice=NormalizeDouble(OpenPrice+TakeProfit*nDigits,Digits);
         StopLossPrice=NormalizeDouble(OpenPrice-StopLoss*nDigits,Digits);
      } 
      if(OrderType()==OP_SELL){
         TakeProfitPrice=NormalizeDouble(OpenPrice-TakeProfit*nDigits,Digits);
         StopLossPrice=NormalizeDouble(OpenPrice+StopLoss*nDigits,Digits);      
      }
         
      //Try to modify the order
      if(OrderModify(OrderTicket(),OpenPrice,StopLossPrice,TakeProfitPrice,0,clrNONE)){
         TotalModified++;
      }
      else{
         Print("Order failed to update with error - ",GetLastError());
      }      
      
      //Wait a delay
      Sleep(Delay);
   
   }
   
   //Print the total of orders modified
   Print("Total orders modified = ",TotalModified);
   
  }
//+------------------------------------------------------------------+

Download : OrderModify_All_TP_n_SL_by_Magic_n_Comment.mq4
 

Virtual TakeProfit and StopLoss

Virtual_TakeProfit_StopLoss


The adviser exposes the stop-loss and take-profit, invisible to the broker. But keep in mind that the adviser must be constantly at work. Those. You can not turn off the computer or close the terminal.

In the tester, the Expert Advisor opens the positions for himself and accompanies them with stops.



Code :
//+------------------------------------------------------------------+
//|                                  Virtual_TakeProfit_StopLoss.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                              http://www.meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaEditor."
#property link      "http://www.meta-editor.blogspot.com"
#property version   "1.00"
#property strict

//--------------------------------------------------------------------
input int     Stoploss      = 100;
input int     Takeprofit    = 50;
input int     slippage      = 30;
//--------------------------------------------------------------------
void OnTick()
{      
   double OOP;
   for (int i=0; i<OrdersTotal(); i++)
   {    
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      { 
         if (OrderSymbol()==Symbol())
         { 
            int tip = OrderType(); 
            OOP = NormalizeDouble(OrderOpenPrice(),Digits);
            if (tip==OP_BUY)             
            {  
               if (Stoploss!=0   && Bid<=OOP - Stoploss   * Point) {if (OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),slippage,clrNONE)) continue;}
               if (Takeprofit!=0 && Bid>=OOP + Takeprofit * Point) {if (OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),slippage,clrNONE)) continue;}
            }                                         
            if (tip==OP_SELL)        
            {  
               if (Stoploss!=0   && Ask>=OOP + Stoploss   * Point) {if (OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),slippage,clrNONE)) continue;}
               if (Takeprofit!=0 && Ask<=OOP - Takeprofit * Point) {if (OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),slippage,clrNONE)) continue;}
            } 
         }
      }
   } 
   //---
   int err;
   if (IsTesting() && OrdersTotal()==0)
   {
      double Lot=0.1;
      err=OrderSend(Symbol(),OP_BUY,Lot,NormalizeDouble(Ask,Digits),slippage,0,0,"тест",0);
      err=OrderSend(Symbol(),OP_SELL,Lot,NormalizeDouble(Bid,Digits),slippage,0,0,"тест",0);
      return;
   }
}
//+------------------------------------------------------------------+

Download : Virtual_TakeProfit_StopLoss.mq4
 

Open Fibonacci Order

Open_Fibo_Order


This is simple script which opens positions according to a Fibonacci Retracement object. Open_Fibo_Order script has just one input variable ? number of lots. The script searches for the latest Fibonacci Retracement object. Order open level is set to 1 pip over 100 fibonacci level for buy order and 1 pip under 100 fibonacci level for sell order. SL level is fixed on 0 fibonacci level. Then the script gets the first fibonacci level over 100 and sets in this place TP, so it is possible to change TP range by modification of the Fibonacci Retracement object. Open_Fibo_Order calculates proper levels taking into consideration a difference between ask and bid price (spread). Just before placing order the script checks whether SL, TP and order open levels are not too close. If any error occurs, the script displays message.


Code :
//+------------------------------------------------------------------+
//|                                              Open_Fibo_Order.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                                  http://meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright     "Copyright 2018, MetaEditor."
#property link          "http://meta-editor.blogspot.com"
#property version       "1.00"
#property description   "http://meta-editor.blogspot.com"
#property show_inputs

#include <stderror.mqh>
#include <stdlib.mqh>
#include <WinUser32.mqh>

extern double Lots = 0.1;
int MAGIC = 0;

int start() {

    int cnt;
    datetime dt;
    string fibo = "";
    
    for (cnt = ObjectsTotal() - 1; cnt >= 0; cnt--) {
        string name = ObjectName(cnt);
        if (ObjectType(name) == OBJ_FIBO) {
            if (ObjectGet(name, OBJPROP_TIME1) > dt) {
                fibo = name;
                dt = ObjectGet(name, OBJPROP_TIME1);
            }
        }
    }    

    if (fibo == "") {
        MessageBox("Fibonacci Retracement object not found!\n\nCreate one and run this script again.", "Warning", MB_OK | MB_ICONWARNING);
        return (-1);
    }
   
    double open = ObjectGet(fibo, OBJPROP_PRICE1);
    double sl = ObjectGet(fibo, OBJPROP_PRICE2);

    double tpFract = 0;
    int fiboLevels = ObjectGet(fibo, OBJPROP_FIBOLEVELS);
    for (cnt = 0; cnt < fiboLevels; cnt++) {
        tpFract = ObjectGet(fibo, OBJPROP_FIRSTLEVEL + cnt);
        if (tpFract > 1.0) {
            break;
        }
    }

    if (tpFract <= 1.0) {
        MessageBox("Fibonacci Retracement object has no level above 1.0!\n\nSet default levels in Fibonacci Retracement object and run this script again.", "Warning", MB_OK | MB_ICONWARNING);
        return (-1);    
    }
        
    if (Lots < MarketInfo(Symbol(), MODE_MINLOT)) {
        MessageBox("Choosen position size is lower than minimum permitted amount of a lot (" + DoubleToStr(MarketInfo(Symbol(), MODE_MINLOT), 2) + ")!", "Warning", MB_OK | MB_ICONWARNING);
        return (-1);    
    }        
        
    double tp = open + (tpFract - 1.0) * (open - sl);    
    int ticket, error;
    
    if (open > sl) { // buystop order
        open += getSpread(OP_BUYSTOP, 1);
        sl += getSpread(OP_SELLSTOP, 0);
        tp += getSpread(OP_SELLSTOP, 0);
        if (!checkStops(open, sl, tp)) {
            MessageBox("Fibonacci Retracement object is too small so that price levels are too close!", "Warning", MB_OK | MB_ICONWARNING);
            return (-1);
        }
        ticket = OrderSendNormalize(Symbol(), OP_BUYSTOP, Lots, open, 0, sl, tp, NULL, MAGIC);
        if (ticket < 0) {
            error = GetLastError();
            Print("OrderSend failed with error #", error);
            MessageBox("An error occurred: " + ErrorDescription(error) + ".", "Error", MB_OK | MB_ICONERROR);            
            return (0);
        }
    } else if (open < sl) { // sellstop order
        open += getSpread(OP_SELLSTOP, 1);
        sl += getSpread(OP_BUYSTOP, 0);
        tp += getSpread(OP_BUYSTOP, 0);            
        if (!checkStops(open, sl, tp)) {
            MessageBox("Fibonacci Retracement object is too small so that price levels are too close!", "Warning", MB_OK | MB_ICONWARNING);
            return (-1);
        }
        ticket = OrderSendNormalize(Symbol(), OP_SELLSTOP, Lots, open, 0, sl, tp, NULL, MAGIC);
        if (ticket < 0) {
            error = GetLastError();
            Print("OrderSend failed with error #", error);
            MessageBox("An error occurred: " + ErrorDescription(error) + ".", "Error", MB_OK | MB_ICONERROR);            
            return (0);
        }
    }

    return (0);
}

int OrderSendNormalize(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment = "", int magic = 0, datetime expiration = 0, color arrow_color = CLR_NONE) {
    return (OrderSend(symbol, cmd, volume, NormalizeDouble(price, Digits), slippage, NormalizeDouble(stoploss, Digits), NormalizeDouble(takeprofit, Digits), comment, magic, expiration, arrow_color));
}

bool checkStops(double open, double sl, double tp) {
    double minStop = MarketInfo(Symbol(), MODE_STOPLEVEL) * MarketInfo(Symbol(), MODE_POINT);    
    if (sl != 0) {
        if (MathAbs(open - sl) < minStop) {
            return (false);
        }
    }
    if (tp != 0) {
        if (MathAbs(open - tp) < minStop) {
            return (false);
        }
    }
    return (true);
}

double getSpread(int type, int marginPoints = 0) {
    if (type == OP_SELL || type == OP_SELLSTOP || type == OP_SELLLIMIT) {
        return (NormalizeDouble(- marginPoints * Point, Digits));
    } else if (type == OP_BUY || type == OP_BUYSTOP || type == OP_BUYLIMIT) {
        return (NormalizeDouble(Ask - Bid + marginPoints * Point, Digits));
    }
}

Download : Open_Fibo_Order.mq4
 

Orders Info

Orders_Info


The indicator shows information on orders. You can see the magic order, its profit and how long the order is already in the market.

Also, the indicator shows what profit or loss we will receive when the order is closed by stop-loss or take-profit.

The information is summarized and displayed at the top of the window separately by TP and SL.


Code :
//+------------------------------------------------------------------+
//|                                                  Orders_Info.mq4 |
//|                                      Copyright 2018, MetaEditor. |
//|                             https://www.meta-editor.blogspot.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaEditor."
#property link      "https://www.meta-editor.blogspot.com"
#property description "https://www.meta-editor.blogspot.com"
#property version   "1.00"
#property strict
#property indicator_chart_window
double TICKVALUE;
string AC;
extern bool showm = false;       //Show MagicNumber
extern bool showp = true;        //Show Profit
extern bool showt = false;       //Show Time
extern bool showsl = true;       //Show StopLoss
extern bool showtp = true;       //Show TakeProfit
extern color plus = clrGreen;    //Color Plus
extern color minus = clrMaroon;     //Color Minus
//+------------------------------------------------------------------+
int OnInit()
  {
   TICKVALUE=MarketInfo(Symbol(),MODE_TICKVALUE);
   AC=AccountCurrency();
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   double sumsl=0;
   double sumtp=0;
   ObjectsDeleteAll(0,"sl");
   ObjectsDeleteAll(0,"tp");
   ObjectsDeleteAll(0,"or");
   for(int j=0; j<OrdersTotal(); j++)
     {
      if(OrderSelect(j,SELECT_BY_POS))
        {
         int pips=0,OT=OrderType();
         double OOP=OrderOpenPrice();
         double OTP=OrderTakeProfit();
         double OSL=OrderStopLoss();
         double OL=OrderLots();
         string name=StringConcatenate("or",OrderTicket());
         ObjectDelete(0,name);
         string txt=NULL;
         if(showm) txt=StringConcatenate("Magic ",OrderMagicNumber()," ");
         if(showp) txt=StringConcatenate(txt,"Profit ",DoubleToStr(OrderProfit(),2)," ",AC," ");
         if(showt) txt=StringConcatenate(txt,"Time ",MathFloor((TimeCurrent()-OrderOpenTime())/60)," Minute ");
         TextCreate(0,name,0,Time[0]+Period()*300,OOP,txt,"Arial",8,Color(OrderProfit()<0,minus,plus));
         if(OTP!=0)
           {
            name=StringConcatenate("tp",name);
            ObjectDelete(0,name);
            if(OT==OP_BUY)  pips=(int)((OTP-OOP)/Point);
            if(OT==OP_SELL) pips=(int)((OOP-OTP)/Point);
            if(showtp) TextCreate(0,name,0,Time[WindowFirstVisibleBar()/2],OTP,StringConcatenate(DoubleToStr(TICKVALUE*pips*OL,2)," ",AC,"  ",pips),"Arial",8,Color(pips<0,minus,plus));
            sumtp+=TICKVALUE*pips*OL;
           }
         if(OSL!=0)
           {
            name=StringConcatenate("sl",name);
            ObjectDelete(0,name);
            if(OT==OP_BUY)  pips=(int)((OSL-OOP)/Point);
            if(OT==OP_SELL) pips=(int)((OOP-OSL)/Point);
            if(showsl) TextCreate(0,name,0,Time[WindowFirstVisibleBar()/2],OSL,StringConcatenate(DoubleToStr(TICKVALUE*pips*OL,2)," ",AC,"  ",pips),"Arial",8,Color(pips<0,minus,plus));
            sumsl+=TICKVALUE*pips*OL;
           }
        }
     }
   DrawLABEL("sl",0,300,0,Color(sumsl<0,minus,plus),StringConcatenate("Total SL ",DoubleToStr(sumsl,2)," ",AC));
   DrawLABEL("tp",0,300,15,Color(sumtp<0,minus,plus),StringConcatenate("Total TP ",DoubleToStr(sumtp,2)," ",AC));
   return(rates_total);
  }
//-------------------------------------------------------------------
void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0,"sl");
   ObjectsDeleteAll(0,"tp");
   ObjectsDeleteAll(0,"or");
  }
//+------------------------------------------------------------------+
void DrawLABEL(string name,int CORNER,int X,int Y,color clr,string Name)
  {
   if(ObjectFind(name)==-1)
     {
      ObjectCreate(name,OBJ_LABEL,0,0,0);
      ObjectSet(name,OBJPROP_CORNER,CORNER);
      ObjectSet(name,OBJPROP_XDISTANCE,X);
      ObjectSet(name,OBJPROP_YDISTANCE,Y);
     }
   ObjectSetText(name,Name,10,"Arial",clr);
  }
//+------------------------------------------------------------------+
bool TextCreate(const long              chart_ID=0,
                const string            name="Text",
                const int               sub_window=0,
                datetime                time=0,
                double                  price=0,
                const string            text="Text",
                const string            font="Arial",
                const int               font_size=8,
                const color             clr=clrRed,
                const double            angle=0.0,
                const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_LOWER,
                const bool              back=false,
                const bool              selection=false,
                const bool              hidden=true,
                const long              z_order=0)
  {
   ResetLastError();
   if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price))
     {
      Print(__FUNCTION__,
            ": Do not remove the object! = ",GetLastError());
      return(false);
     }
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
   return(true);
  }
//+------------------------------------------------------------------+
color Color(bool P,color a,color b)
  {
   if(P) return(a);
   else return(b);
  }
//------------------------------------------------------------------

Download : Orders_Info.mq4