//+------------------------------------------------------------------+
//|                                                    MGH EA_v3.1.mq4
//+------------------------------------------------------------------+

#property description "MGH System (Martingale Grid & Hedging) by Kfx"
#property description "http://www.forexfactory.com/showthread.php?t=497448"
#property description "EA autor: GoldenEA; some changes: SwingMan"
#property description "minor modifications proposed by Paracelsus #post 707"

/*--------------------------------------------------------------------
07.11.2014  -  v2.4  -  error corrections
08.11.2014  -  v3.1  -  lot calculation with the new algorithm
--------------------------------------------------------------------*/

#include <WinUser32.mqh>
//#include <stdlib.mqh>
#include <OrderSendReliable_v2.1.mqh>
//
enum ENUM_ENTRY_METHOD
  {
   Close_And_EMA_200,
   SMA_Slope
  };
//--- input parameters
//===================================================================
//input double   LotsMultiplier =2.5;
extern   int   BaseOrder_Grid=10;
extern double  BaseLot        = 0.10;
//extern double  maxLot         =10;
input double TakeProfit_GridFactor=2.0;
input double Basket_TakeProfit=0;
input int Maximum_Baskets=8;
input ENUM_TIMEFRAMES timeFrameDirection=PERIOD_H1;
int     MaxLevel       =2;
extern int     MagicNo        = 2900;
//
input string ___EntryDirection="-------------------------------------------";
input ENUM_ENTRY_METHOD Entry_Method=SMA_Slope;
//
//....................................................................
double OrderGap;
int  InsideOrder_Grid=5;
//bool Enable_InsideOrders=false;
//double  ClsPercnt=0.1;

bool Show_Comment=true;
bool Show_CheckReport=false;
bool Entry_OnlyNewBars=true;
//===================================================================
//
string         TextDisplay;

static double  pt;
string         TradeComment="mghA";
string CR="\n";

int            numBuy,numSell,prevnumBuy,prevnumSell,numPenBuy,numPenSell;

double         maxBuyLots,maxSellLots,totalProfit,AllProfit,prevEquity=0,currEquity=0;

static double  lowestBuyPrice,highestSellPrice,lowestSellPrice,highestBuyPrice;
datetime       lastBuyTime,lastSellTime;
double lastBuyPrice,lastSellPrice,lastLotsValue;
double         totalSellProfit,totalBuyProfit;
int            lastestOrderCloseType;
int lastBatchType,lastBatchCount,maxBatchCount;
double         AveragePrice,TotalVolume;

double firstBuyTP,firstSellTP;
int nBatchCount;

bool newBar;
datetime oldTime;
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void init()
  {
   pt=Point;
   if(Digits==3 || Digits==5) pt=10*pt;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void deinit()
  {
//Comment("");
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void start()
  {
   CountOrders();
   if(numBuy==0 && numSell==0)
     {
      prevEquity=AccountEquity();
      OrderGap=1.0*BaseOrder_Grid;
     }
   if(numBuy!=0 || numSell!=0) currEquity=AccountEquity();

   prevnumSell=numSell;
   prevnumBuy=numBuy;
   double tp=0;

//-- check new bar
   datetime thisTime=Time[0];
   if(thisTime!=oldTime)
     {
      newBar=true;
      oldTime=thisTime;
     }
   else
      newBar=false;

   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol() && OrderTakeProfit()==0)
        {
         if(OrderType()==OP_SELL && numSell<=MaxLevel)
           {
            if(numSell==1)
              {
               tp=lowestSellPrice -OrderGap*TakeProfit_GridFactor *pt;
               firstSellTP=tp;
              }
            if(numSell>1)
               //tp=lowestSellPrice-2*pt;
               tp=firstSellTP;
            SetTakeProfit(OP_SELL,tp);
           }

         if(OrderType()==OP_BUY && numBuy<=MaxLevel)
           {
            if(numBuy==1)
              {
               tp=highestBuyPrice+OrderGap*TakeProfit_GridFactor *pt;
               firstBuyTP=tp;
              }
            if(numBuy>1)
               //tp=highestBuyPrice+2*pt;
               tp=firstBuyTP;
            SetTakeProfit(OP_BUY,tp);
           }
        }
     }

   double OpenProfit=totalBuyProfit+totalSellProfit;

   TextDisplay="\n\n                                Open Buy: "+numBuy+" Open Sell: "+numSell+
               "\n                                Open Sell Profit: "+DoubleToString(totalSellProfit,2)+
               "  Open Buy Profit: "+DoubleToString(totalBuyProfit,2)+
               "\n                                Open Profit: "+DoubleToString(OpenProfit,2)+
               "\n                                BatchCount= "+nBatchCount+"   (maxBatchCount= "+maxBatchCount+")";

   if(Show_CheckReport==true)
      TextDisplay=CheckReport()+TextDisplay;

   if(Show_Comment==true)
      Comment(TextDisplay);

//-- close all orders
//  if((numBuy == MaxLevel && numSell == MaxLevel) && (currEquity-prevEquity)/prevEquity>= ClsPercnt) CloseOpenPairPositions();
   if(numBuy+numSell>1 && OpenProfit>=Basket_TakeProfit && nBatchCount>1)
      CloseOpenPairPositions();

   ManageOrders();
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ManageOrders()
  {
   CountOrders();
   double Lots=0;

   int iDirection=Get_TrendDirection();
   if(iDirection!=OP_BUY && iDirection!=OP_SELL)
      return;

   double dNumBuy=1.0*numBuy;
   double dNumSell=1.0*numSell;
   double dMaxLevel=1.0*MaxLevel;

//===================================================================
//-- BUY orders
//===================================================================
   if(numSell==0)
     {
      //-- Batch 1; first BUY order
      if(numBuy==0 && iDirection==OP_BUY)
        {
         if(Entry_OnlyNewBars==true && newBar==false)
            return;
         nBatchCount=1;
         if(nBatchCount>maxBatchCount) maxBatchCount=nBatchCount;
         lastBatchType=OP_BUY;
         lastBatchCount=nBatchCount;
         Lots=Get_LotsNumber(nBatchCount,1);
         RefreshRates();
         lastLotsValue=Lots;
         PlaceSingleOrder(Symbol(),OP_BUY,Lots,Ask);
         Print("  ### BUY;  BatchCount= ",nBatchCount,"   Lots= ",DoubleToStr(Lots,2),"  Time= ",TimeToString(TimeCurrent()),
               "   Ask= ",DoubleToString(Bid,Digits),"   maxBatchCount= ",maxBatchCount);
        }

      //-- Batch 1; second BUY order
      if(numBuy>0 && numBuy<MaxLevel && Ask<=(lowestBuyPrice-OrderGap*pt))
        {
         Lots=Get_LotsNumber(nBatchCount,2);
         RefreshRates();
         PlaceSingleOrder(Symbol(),OP_BUY,Lots,Ask);
        }
     }
//-------------------------------------------------------------------     
//-- BUY orders;  full BUY and SELL Batches
   else  if(MathMod(dNumBuy,dMaxLevel)==0 && MathMod(dNumSell,dMaxLevel)==0 && dNumBuy>0)
     {
      if(nBatchCount==Maximum_Baskets)
         CloseOpenPairPositions();
      //-- Batch N; Buy order above SELL Batch      
      if(Ask>=(highestSellPrice+OrderGap*pt) && lastBatchType==OP_SELL)
        {
         nBatchCount++;
         if(nBatchCount>maxBatchCount) maxBatchCount=nBatchCount;
         lastBatchType=OP_BUY;
         lastBatchCount=nBatchCount;
         Lots=Get_LotsNumber(nBatchCount,1);
         RefreshRates();
         lastLotsValue=Lots;
         PlaceSingleOrder(Symbol(),OP_BUY,Lots,Ask);
         Print("  ### BUY;  BatchCount= ",nBatchCount,"   Lots= ",DoubleToStr(Lots,2),"  Time= ",TimeToString(TimeCurrent()),
               "   Ask= ",DoubleToString(Bid,Digits),"   maxBatchCount= ",maxBatchCount);
        }
     }
//-------------------------------------------------------------------
   else if(numSell>0 && MathMod(dNumSell,dMaxLevel)==0)
     {
      if(MathMod(dNumBuy,dMaxLevel)==0 && Ask>(highestSellPrice+OrderGap*pt))
        {
         DeleteTakeProfit(OP_SELL);
         nBatchCount++;
         if(nBatchCount>maxBatchCount) maxBatchCount=nBatchCount;
         lastBatchType=OP_BUY;
         lastBatchCount=nBatchCount;
         Lots=Get_LotsNumber(nBatchCount,1);
         RefreshRates();
         lastLotsValue=Lots;
         PlaceSingleOrder(Symbol(),OP_BUY,Lots,Ask);
         Print("  ### BUY;  BatchCount= ",nBatchCount,"   Lots= ",DoubleToStr(Lots,2),"  Time= ",TimeToString(TimeCurrent()),
               "   Ask= ",DoubleToString(Bid,Digits),"   maxBatchCount= ",maxBatchCount);
        }
      else
      //-- Batch N; second BUY order
      if(MathMod(dNumBuy,dMaxLevel)>0 && Ask<=(lastBuyPrice-OrderGap*pt))
        {
         Lots=Get_LotsNumber(nBatchCount,2);
         RefreshRates();
         PlaceSingleOrder(Symbol(),OP_BUY,Lots,Ask);
        }
     }
   CountOrders();

//===================================================================
//-- SELL orders
//===================================================================
   if(numBuy==0)
     {
      //-- Batch 1; first SELL order
      if(numSell==0 && iDirection==OP_SELL)
        {
         if(newBar==false)
            return;
         nBatchCount=1;
         if(nBatchCount>maxBatchCount) maxBatchCount=nBatchCount;
         lastBatchType=OP_SELL;
         lastBatchCount=nBatchCount;
         Lots=Get_LotsNumber(nBatchCount,1);
         RefreshRates();
         lastLotsValue=Lots;
         PlaceSingleOrder(Symbol(),OP_SELL,Lots,Bid);
         Print("  ### SELL;  BatchCount= ",nBatchCount,"   Lots= ",DoubleToStr(Lots,2),"  Time= ",TimeToString(TimeCurrent()),
               "   Bid= ",DoubleToString(Bid,Digits),"   maxBatchCount= ",maxBatchCount);
        }

      //-- Batch 1; second SELL order
      if(numSell>0 && numSell<MaxLevel && Bid>=(highestSellPrice+OrderGap*pt))
        {
         Lots=Get_LotsNumber(nBatchCount,2);
         RefreshRates();
         PlaceSingleOrder(Symbol(),OP_SELL,Lots,Bid);
        }
     }
//-------------------------------------------------------------------     
//-- SELL orders;  full BUY and SELL Batches
   else  if(MathMod(dNumBuy,dMaxLevel)==0 && MathMod(dNumSell,dMaxLevel)==0 && dNumSell>0)
     {
      if(nBatchCount==Maximum_Baskets)
         CloseOpenPairPositions();
      //-- Batch N; Sell order belove BUY Batch
      if(Bid<=(lowestBuyPrice-OrderGap*pt) && lastBatchType==OP_BUY)
        {
         RefreshRates();
         nBatchCount++;
         if(nBatchCount>maxBatchCount) maxBatchCount=nBatchCount;
         lastBatchType=OP_SELL;
         lastBatchCount=nBatchCount;
         Lots=Get_LotsNumber(nBatchCount,1);
         PlaceSingleOrder(Symbol(),OP_SELL,Lots,Bid);
         Print("  ### SELL;  BatchCount= ",nBatchCount,"   Lots= ",DoubleToStr(Lots,2),"  Time= ",TimeToString(TimeCurrent()),
               "   Bid= ",DoubleToString(Bid,Digits),"   maxBatchCount= ",maxBatchCount);
        }
     }
//-------------------------------------------------------------------
   else if(numBuy>0 && MathMod(dNumBuy,dMaxLevel)==0)
     {
      //-- Batch N; first SELL order
      if(MathMod(dNumSell,dMaxLevel)==0 && Bid<(lowestBuyPrice-OrderGap*pt))
        {
         DeleteTakeProfit(OP_BUY);
         nBatchCount++;
         if(nBatchCount>maxBatchCount) maxBatchCount=nBatchCount;
         lastBatchType=OP_SELL;
         lastBatchCount=nBatchCount;
         Lots=Get_LotsNumber(nBatchCount,1);
         RefreshRates();
         PlaceSingleOrder(Symbol(),OP_SELL,Lots,Bid);
         Print("  ### SELL;  BatchCount= ",nBatchCount,"   Lots= ",DoubleToStr(Lots,2),"  Time= ",TimeToString(TimeCurrent()),
               "   Bid= ",DoubleToString(Bid,Digits),"   maxBatchCount= ",maxBatchCount);
        }
      else
      //-- Batch N; second SELL order
      if(MathMod(dNumSell,dMaxLevel)>0 && Bid>=(lastSellPrice+OrderGap*pt))
        {
         Lots=Get_LotsNumber(nBatchCount,2);
         RefreshRates();
         PlaceSingleOrder(Symbol(),OP_SELL,Lots,Bid);
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double Get_LotsNumber(int BatchCount,int tradeNumber)
  {
   double dLots;
   double lotsFactor=BaseLot/0.10;

//-- first order --------------------------------
   if(tradeNumber==1)
     {
      if(BatchCount==1) dLots=0.10; else
      if(BatchCount==2) dLots=0.28; else
      if(BatchCount==3) dLots=0.48; else
      if(BatchCount==4) dLots=1.08; else
      if(BatchCount==5) dLots=2.43; else
      if(BatchCount==6) dLots=5.47; else
      if(BatchCount==7) dLots=12.30; else
      if(BatchCount==8) dLots=27.68;
     }
   else
//-- second order -------------------------------
   if(tradeNumber==2)
     {
      if(BatchCount==1) dLots=0.05; else
      if(BatchCount==2) dLots=0.06; else
      if(BatchCount==3) dLots=0.14; else
      if(BatchCount==4) dLots=0.32; else
      if(BatchCount==5) dLots=0.73; else
      if(BatchCount==6) dLots=1.64; else
      if(BatchCount==7) dLots=3.69; else
      if(BatchCount==8) dLots=8.30;
     }

   dLots=dLots*lotsFactor;
   dLots=NormalizeDouble(dLots,2);
   return(dLots);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string CheckReport()
  {
   static string   ProfitReport="";
   static int   TimeToReport = 0;
   static int   TradeCounter = 0;
#define Daily    0
#define Weekly   1
#define Monthly  2
#define All      3

   if(TradeCounter!=HistoryTotal())
     {
      TradeCounter = HistoryTotal();
      TimeToReport = 0;
     }

   if(TimeLocal()>TimeToReport)
     {
      TimeToReport=TimeLocal()+300;
      double   Profit[10],Lots[10],Count[10];
      ArrayInitialize(Profit,0);
      ArrayInitialize(Lots,0.000001);
      ArrayInitialize(Count,0.000001);

      int Today     = TimeCurrent() - (TimeCurrent() % 86400);
      int ThisWeek  = Today - TimeDayOfWeek(Today)*86400;
      int ThisMonth = TimeMonth(TimeCurrent());
      for(int i=0; i<HistoryTotal(); i++)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) && OrderSymbol()==Symbol() && OrderCloseTime()>0)
           {
            Count[All]+=1;
            Profit[All]+=OrderProfit()+OrderSwap();
            Lots[All]+=OrderLots();
            if(OrderCloseTime()>=Today)
              {
               Count[Daily]+=1;
               Profit[Daily]+=OrderProfit()+OrderSwap();
               Lots[Daily]+=OrderLots();
              }
            if(OrderCloseTime()>=ThisWeek)
              {
               Count[Weekly]+=1;
               Profit[Weekly]+=OrderProfit()+OrderSwap();
               Lots[Weekly]+=OrderLots();
              }
            if(TimeMonth(OrderCloseTime())==ThisMonth)
              {
               Count[Monthly]+=1;
               Profit[Monthly]+=OrderProfit()+OrderSwap();
               Lots[Monthly]+=OrderLots();
              }
           }
        }
      double OpenProfit=totalBuyProfit+totalSellProfit;

      ProfitReport="\n\n                                 PROFIT REPORT ( "+AccountCurrency()+" )"+
                   "\n                                Today: "+DoubleToStr(Profit[Daily],2)+
                   "\n                                This Week: "+DoubleToStr(Profit[Weekly],2)+
                   "\n                                This Month: "+DoubleToStr(Profit[Monthly],2)+
                   "\n                                All Profits: "+DoubleToStr(Profit[All],2)+
                   "\n                                All Trades: "+DoubleToStr(Count[All],0)+"  (Average "+DoubleToStr(Profit[All]/Count[All],2)+" per trade)"+
                   "\n                                All Lots: "+DoubleToStr(Lots[All],2)+"  (Average "+DoubleToStr(Profit[All]/Lots[All],2)+" per lot)";
     }
   return (ProfitReport);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int Get_TrendDirection()
  {
   int iDirection;

//-- entry PARACELSUS -----------------------------------------------
   if(Entry_Method==Close_And_EMA_200)
     {
      double dClose1=iClose(Symbol(),timeFrameDirection,1);
      double dEMA1=iMA(Symbol(),timeFrameDirection,200,0,MODE_EMA,PRICE_CLOSE,1);
      if(dClose1>=dEMA1)
         iDirection=OP_BUY;
      else
      if(dClose1<dEMA1)
         iDirection=OP_SELL;
     }
   else
   if(Entry_Method==SMA_Slope)
     {
      //-- entry SnowBall -------------------------------------------------  
      int ma_period= 8;
      int ma_method= MODE_SMA;
      int applied_price=PRICE_TYPICAL;
      int signalBar=1;

      double avg10 = iMA(Symbol(),timeFrameDirection,ma_period,0,ma_method,applied_price,signalBar);
      double avg11 = iMA(Symbol(),timeFrameDirection,ma_period,1,ma_method,applied_price,signalBar);
      double diff10= 10000*(avg10-avg11)/avg10;

      double avg20 = iMA(Symbol(),timeFrameDirection,ma_period,0,ma_method,applied_price,signalBar+1);
      double avg21 = iMA(Symbol(),timeFrameDirection,ma_period,1,ma_method,applied_price,signalBar+1);
      double diff20= 10000*(avg20-avg21)/avg20;

      double avg30 = iMA(Symbol(),timeFrameDirection,ma_period,0,ma_method,applied_price,signalBar+2);
      double avg31 = iMA(Symbol(),timeFrameDirection,ma_period,1,ma_method,applied_price,signalBar+2);
      double diff30= 10000*(avg30-avg31)/avg30;

      double avg40 = iMA(Symbol(),timeFrameDirection,ma_period,0,ma_method,applied_price,signalBar+3);
      double avg41 = iMA(Symbol(),timeFrameDirection,ma_period,1,ma_method,applied_price,signalBar+3);
      double diff40= 10000*(avg40-avg41)/avg40;

      double trigger1= (diff10+diff20+diff30)/3.0;
      double trigger2= (diff20+diff30+diff40)/3.0;

      //-- trend direction; condition for two bars
      iDirection=-100;
      if( (diff10>0 && diff10>trigger1) || (diff20>0 && diff20>trigger2)) iDirection= OP_BUY; else
      if( (diff10<0 && diff10<trigger1) || (diff20<0 && diff30<trigger2)) iDirection= OP_SELL;
     }
   return(iDirection);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void PlaceSingleOrder(string sym,int type,double lotsize,double price)
  {
   int ticket;
//int result;
   color cColor;
   if(type==OP_BUY) cColor=clrDodgerBlue; else
   if(type==OP_SELL) cColor=clrRed;

   lotsize=NormalizeDouble(lotsize,2);

   ticket=OrderSendReliable(sym,type,lotsize,price,0,0,0,TradeComment,MagicNo,0,cColor);

   if(ticket>0 && type==OP_SELL)
     {
      while(prevnumSell==numSell)
        {
         CountOrders();
        }
      prevnumSell=numSell;
     }

   if(ticket>0 && type==OP_BUY)
     {
      while(prevnumBuy==numBuy)
        {
         CountOrders();
        }
      prevnumBuy=numBuy;
     }

   if(ticket<0)
     {
      // error handling: to be implemented
      int e=GetLastError();
      Print("Error: "+DoubleToStr(e,0));
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CountOrders()
  {
   numBuy=0; numSell=0; maxBuyLots=0; maxSellLots=0; totalSellProfit=0; totalBuyProfit=0;
   double buyProfit1=0; double buyProfit2=0; double sellProfit1=0; double sellProfit2=0;
   lowestBuyPrice=9999; lowestSellPrice=9999;
   highestBuyPrice=0;   highestSellPrice=0;
   bool bRes;
   lastBuyTime=0;
   lastSellTime=0;

   for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)
     {
      bRes=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol())
        {
         //-- BUY order -------------------------
         if(OrderType()==OP_BUY)
           {
            numBuy++;
            buyProfit1+=OrderProfit()+OrderSwap()+OrderCommission();
            if(OrderOpenPrice()<lowestBuyPrice)
              {
               lowestBuyPrice=OrderOpenPrice();
               if(OrderOpenTime()>lastBuyTime)
                 {
                  lastBuyTime=OrderOpenTime();
                  lastBuyPrice=OrderOpenPrice();
                 }
              }
            if(OrderOpenPrice()>highestBuyPrice)
              { highestBuyPrice=OrderOpenPrice();}

            if(OrderLots()>maxBuyLots) maxBuyLots=OrderLots();
           }
         //-- SELL order ------------------------
         else if(OrderType()==OP_SELL)
           {
            numSell++;
            sellProfit1+=OrderProfit()+OrderSwap()+OrderCommission();
            if(OrderOpenPrice()>highestSellPrice)
              {
               highestSellPrice=OrderOpenPrice();
               if(OrderOpenTime()>lastSellTime)
                 {
                  lastSellTime=OrderOpenTime();
                  lastSellPrice=OrderOpenPrice();
                 }
              }
            if(OrderOpenPrice()<lowestSellPrice)
              { lowestSellPrice=OrderOpenPrice();}

            if(OrderLots()>maxSellLots) maxSellLots=OrderLots();
           }

         totalBuyProfit=buyProfit1;
         totalSellProfit=sellProfit1;
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void  DeleteTakeProfit(int type)
  {
//-- delete take profit for Batch 2
   if(nBatchCount>1)
      return;

   for(int i=0; i<OrdersTotal(); i++)
     {
      //        if ( OrderSelect(i, SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()  && OrderMagicNumber()==Magic && OrderType()==type ) ModifySelectedOrder(type, TP);
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol() && OrderType()==type)
         ModifySelectedOrder(type,0);
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void  SetTakeProfit(int type,double tp)
  {
//-- set take profit only for Batch 1
   if(nBatchCount>1)
      return;

   for(int i=0; i<OrdersTotal(); i++)
     {
      //        if ( OrderSelect(i, SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol()  && OrderMagicNumber()==Magic && OrderType()==type ) ModifySelectedOrder(type, TP);
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symbol() && OrderType()==type)
         ModifySelectedOrder(type,tp);
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseOpenPairPositions()
  {
   bool bRes;
   for(int i=10; i>=0; i--)
     {
      for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)
        {
         bRes=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if(OrderMagicNumber()==MagicNo)
           {
            if(OrderType()==OP_BUY && OrderSymbol()==Symbol())
               OrderCloseReliable(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),5);
            else
            if(OrderType()==OP_SELL && OrderSymbol()==Symbol())
               OrderCloseReliable(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ModifySelectedOrder(int type,double tp)
  {
   bool ok=OrderModifyReliable(OrderTicket(),OrderOpenPrice(),0,tp,0);
   if(!ok)
     {
      int err=GetLastError();
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double Punto(string symbol)
  {
   if(StringFind(symbol,"JPY")>=0)
     {
      return(0.01);
     }
   else
     {
      return(0.0001);
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double SPREAD()
  {
   double this=(Ask-Bid)/Punto(Symbol());
   return(this);
  }
//+------------------------------------------------------------------+
