//+------------------------------------------------------------------+
//|                                                      Samuray.mq4 |
//|                                                            Kokas |
//|                                       http://www.forexforums.org |
//|                 Check EA Main thread at:                         |
//|                 http://www.forexforums.org/showthread.php?t=1888 |
//+------------------------------------------------------------------+
#property copyright "Kokas"
#property link      "http://www.forexforums.org"
//---- input parameters
extern string     ExpertName         = "Samuray V.10";
extern double     BalanceForTrade    = 0;
extern bool       AutoTrade          = true;
extern double     RecycleProfit      = 1000;
extern bool       SecureEquitity     = true;
extern int        MaxTrades          = 20;                          // Set to 0 to use Automatic calculation of Maxtrades
extern bool       AutoMaxTrades      = true;
extern int        PreventPos         = 10;                          // Prevent the opening of a new position if there are other near
extern bool       UseLongs           = true;
extern bool       UseShorts          = false;
extern bool       UseSwap            = false;
extern double     InitialStop        = 1000;                        // Initial StopLoss Set for every Order
extern double     BreakEven          = 100;                         // Profit Lock in pips
extern double     BEOffset           = 10;                          // BreakEven profit capture
extern double     TrailStop          = 250;                         // 
extern bool       SecureOrders       = true;                        // If set to true only open orders when in profit MinPip
extern bool       NewAllLocked       = false;                       // Only open a new order if all previous are locked on profit.
extern double     MinPips            = 20;                          // Min Profit Pips to open another order (read above)
extern bool       CloseAll           = false;                       // Set true to close all current Orders
extern int        Magic              = 5665;                        // Magic Number of the EA
extern double     Lots               = 0.01;                        // Lot size when not using MM
extern bool       MoneyManagement    = true;                        // Set to true to use Money Management 
extern double     MaxLotSize         = 1.5;                         // Max Lot size when using Money Management
extern double     Risk               = 15;                          // Risk factor when using MM
extern string     RSI                = "RSI FILTER SETTINGS";       // 
extern bool       UseRSI             = true;
extern int        RSIPeriod          = 7;
extern int        RSITimeFrame       = 0;
extern int        UpperRSI           = 75;
extern int        LowerRSI           = 25;
extern string     EMA                = "EMA FILTER SETTINGS";
extern int        ShortEma           = 19;
extern int        LongEma            = 110;                         // Minimum diference between EMA's that allow opening
extern int        MinEmaDiverg       = 10;
extern bool       CloseOnEmaCross    = false;                        // Close all orders if EMA's reverse
extern string     BOLLINGER          = "BOLLINGER BANDS SETTINGS";
extern bool       UseBollinger       = true;                         // Turn to true to filter your orders with Bollinger Bands
extern double     Bollinger_Period   = 20;                           
extern double     Bollinger_TF       = 60;
extern double     Bollinger_Dev      = 2;
extern string     GLOBALMANAGEMENT   = "Global Settings";            
extern int        TotalStopLoss      = 0;                           // Close all Trades if reached
extern int        GlobalBE           = 1000;                        // Lock all positions when reached
extern int        GlobalBEOffset     = 800;                         // Global BreakEven Offset
//extern int      GlobalTrailStop    = 2000;
extern bool       UseReport          = false;                       // Print Entried on Journal
extern string     ANGLE_FILTER       = "Settings for Angle";        
extern bool       UseAngleFilter     = true;
extern int        AnglePeriod1       = 18;
extern int        AnglePeriod2       = 114;
extern double     MinAngleLong1      = 20;
extern double     MinAngleShort1     = -25;
extern double     MinAngleLong2      = 10;
extern double     MinAngleShort2     = -12;
//---- indicator parameters for MA_Angle_v4
//extern int MAPeriod=34;
string  m = "--Moving Average Types--";
//extern string  m0 = " 0 = SMA";
//extern string  m1 = " 1 = EMA";
//extern string  m2 = " 2 = SMMA";
//extern string  m3 = " 3 = LWMA";
//extern string  m4 = " 4 = LSMA";
int MA_Type = 1; //0=SMA, 1=EMA, 2=SMMA, 3=LWMA, 4=LSMA
string  p = "--Applied Price Types--";
//extern string  p0 = " 0 = close";
//extern string  p1 = " 1 = open";
//extern string  p2 = " 2 = high";
//extern string  p3 = " 3 = low";
//extern string  p4 = " 4 = median(high+low)/2";
//extern string  p5 = " 5 = typical(high+low+close)/3";
//extern string  p6 = " 6 = weighted(high+low+close+close)/4";
int MA_AppliedPrice = 0;//0=close, 1=open, 2=high, 3=low, 4=median(high+low)/2, 5=typical(high+low+close)/3, 6=weighted(high+low+close+close)/4
double AngleTreshold=8;
int PrevMAShift=1;
int CurMAShift=0;
//---- end indicator parameters for MA_Angle_v4
// Global variables for MA_Angle_v4
int MA_Mode;
string strMAType;
// End Global variables for MA_Angle_v4
int   k, digit=0,MaxT2 = 0; 
double AccountSize,totalPips,totalProfits,SEma,LEma,error,shortPips,longPips,sidePips, MaxT;
double pBid, pAsk, pp,valueswap,RSIValue;
bool AccountIsMicro, SignalEMAShort, SignalEMALong;
bool signal1 = true, signal2 =true, signal3 = true , signal4 = true, signal5 = true, signal6 = true, SecureSignal = true, RSISignal = true, bolsignal=true;
bool AllLocked = true, AngleSignal = true;
string comment = "";
int    ticket;
double EMA1,EMA2;
double LWMA1,LWMA2;
bool   Sell=0, Buy=0;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
   if (MarketInfo(Symbol(),MODE_LOTSTEP) == 0.01)
   {
     AccountIsMicro = true;
   }
   else
   {
     AccountIsMicro = false;
   }
   
   initMA_Angle_v4();
  
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
  
  digit  = MarketInfo(Symbol(),MODE_DIGITS);
  
  SEma = iMA(Symbol(),0,ShortEma,0,MODE_EMA,PRICE_CLOSE,0);
  LEma = iMA(Symbol(),0,LongEma,0,MODE_EMA,PRICE_CLOSE,0);
  
  sidePips();
  EMA1  = iMA(0,0,ShortEma,0,MODE_EMA,PRICE_CLOSE,1);
  EMA2  = iMA(0,0,ShortEma,0,MODE_EMA,PRICE_CLOSE,2);
  LWMA1 = iMA(0,0,ShortEma,0,MODE_LWMA,PRICE_CLOSE,1);
  LWMA2 = iMA(0,0,ShortEma,0,MODE_LWMA,PRICE_CLOSE,2); 
  Sell=   LWMA1 < EMA1 && LWMA1 < LWMA2 && EMA1 < EMA2 ; 
  Buy=    LWMA1 > EMA1 && LWMA1 > LWMA2 && EMA1 > EMA2 ;
  if (SecureEquitity)
  {
  
  if (AccountEquity() < AccountBalance()/2)
  //if ((AccountEquity()- AccountBalance()/Risk <0 )  && (ScanOpenTrades()-CheckLocked() > 1))
  {
  
  if (longPips >shortPips && MathAbs(longPips - shortPips) < 10 ) OpenShortClose();
  if (shortPips > longPips && MathAbs(longPips - shortPips) < 10) OpenLongClose();
  if (shortPips < 0 && longPips < 0 ) OpenOrdClose(); 
  signal4 = false;
  }   
  
  }
  
  if (AutoMaxTrades) MaxTrades = MathCeil(AccountFreeMargin()/(Risk * AccountLeverage()));
  
  MaxT2 = MaxTrades + CheckLocked();
  
  AllLocked = false;
  
  if (NewAllLocked) {
     
     if (CheckLocked() == ScanOpenTrades()) AllLocked = true;
  
  }else {
  
     AllLocked = true;
  
  }
  
  signal1 = false;
  signal2 = false;
  signal4 = true;
  if (CloseAll) {
      
      OpenOrdClose();
      signal4 = false; 
      
  }
  
  TotalProfit();
  
  sidePips();
  
  
  if (-TotalStopLoss > totalPips && TotalStopLoss !=0 ) {
  
      OpenOrdClose();
      signal4 = false;
  
  }
  
  if (ScanOpenTrades() < MaxT2) signal1 = true;
  
  signal3 = false;
  
  if (!IsPosition(PreventPos)) signal3 = true;
  
  if (MoneyManagement) Lots = LotSize();
// *************************************************************************************
//  EMA FILTER SECTION
// *************************************************************************************
SignalEMALong = false;
SignalEMAShort = false;
if ((SEma > LEma) && (SEma != LEma)) SignalEMALong = true;
if ((LEma > SEma) && (SEma != LEma)) SignalEMAShort = true;
  if (MinEmaDiverg >0)
      {
      
      if  (MathAbs((SEma-LEma) * 100) > MinEmaDiverg) signal2 = true;
      
      }
  if (MinEmaDiverg == 0) signal2 = true;
  
  if (CloseOnEmaCross) {
  
    if (MathAbs(SEma - LEma)*100 < 1 ) {
      OpenOrdClose();
      signal4 = false;
    
    }
  }
// *************************************************************************************
// *************************************************************************************
  if (SignalEMALong)  //5
  {
     sidePips = longPips;
  
  } else {
  
     sidePips = shortPips;
  
  }
// *************************************************************************************
//  RSI FILTER SECTION
// *************************************************************************************
if (UseRSI)
{
  RSIValue = iRSI(Symbol(),RSITimeFrame,RSIPeriod,0,0);
  RSISignal = false;
  if (UseLongs && RSIValue < UpperRSI) RSISignal = true;
  
  if (UseShorts && RSIValue > LowerRSI) RSISignal = true;
  
  if (UseShorts && UseLongs && (RSIValue < UpperRSI && RSIValue > LowerRSI)) RSISignal = true;
  
} else {
  RSISignal = true;
}
// *************************************************************************************
// *************************************************************************************
// *************************************************************************************
//  Bollinger  FILTER SECTION
// *************************************************************************************
 bolsignal = true;
  
  if (UseBollinger){
     
    double BandsLower = iBands(Symbol(),Bollinger_TF,Bollinger_Period,Bollinger_Dev,0,0,2,0);          // Lower  Bollinger
    double BandsUpper = iBands(Symbol(),Bollinger_TF,Bollinger_Period,Bollinger_Dev,0,0,1,0);          // Upper  Bollinger
    double Bands = (BandsLower + BandsUpper) / 2; 
  
    if (UseLongs) {
      if (MarketInfo(Symbol(),MODE_BID) > Bands) {
          bolsignal = true;
      }else{
          bolsignal = false;
      }
      }
      
    if (UseShorts) {
      if (MarketInfo(Symbol(),MODE_ASK) < Bands) {
          bolsignal = true;
      }else{
          bolsignal = false;
      }
      }      
    if (UseLongs && UseShorts) bolsignal = true;  
  
  }
// *************************************************************************************
// *************************************************************************************
// *************************************************************************************
// Angle Signal 
// *************************************************************************************
AngleSignal = false;
if (UseAngleFilter){
   if ((MAAngle(AnglePeriod1) > MinAngleLong1) && (MAAngle(AnglePeriod2) > MinAngleLong2)&& UseLongs && !UseShorts) AngleSignal = true;
   
   if ((MAAngle(AnglePeriod1) < MinAngleShort1) && (MAAngle(AnglePeriod1) < MinAngleShort2) && UseShorts && !UseLongs) AngleSignal = true; 
   if (UseLongs && UseShorts && (MAAngle(AnglePeriod1) < MinAngleShort1) || (MAAngle(AnglePeriod1) > MinAngleLong1) &&(MAAngle(AnglePeriod2) < MinAngleShort2) || (MAAngle(AnglePeriod2) > MinAngleLong2)) AngleSignal = true;
} else {
   AngleSignal = true;
   
}
// *************************************************************************************
  if (SecureOrders){
  
     if (sidePips > MinPips || sidePips == 0){
     
        SecureSignal = true;
               
     } else {
     
        SecureSignal = false;
    
     }  
  
  } else {
  
  SecureSignal = true;
  
  }
  
  
  if (sidePips > RecycleProfit) {
  
      if (SignalEMALong)
        {
        OpenLongClose();
        } else {
        OpenShortClose();
        }
     
      signal4 = false;
  
  }
 
//+------------------------------------------------------------------+
if (UseReport){
if (!signal1)      Print("Max trades Reached");               // signal1 - Control the number of open orders
if (!signal2)      Print("Divergence on EMAs");               // signal2 - Check the Divergence on EMA's 
if (!signal3)      Print("Another Position on Proximity");    // signal3 - Bollinger Bands Filter
if (!signal4)      Print("Recycling Orders");                 // signal4 - Control Recycle Profits
if (!SignalEMAShort && !SignalEMALong)      Print("Ask EMA to enter trades!");         // signal5 - Check EMA's before place trades
if (!bolsignal)    Print("Bollinger dos not permit");         // bolsignal - Check Bollinger Bands for entry
if (!AutoTrade)    Print("Autotrade disabled on properties");
if (!SecureSignal) Print("Not safe to enter yet");
if (!AllLocked)    Print("Not all orders are locked yet");
if (!AngleSignal)  Print("Angle not suficient");
}
  
   if (signal1 && signal2 && signal3 && signal4 && AutoTrade && SecureSignal && RSISignal && bolsignal && AllLocked  && AngleSignal){
    
  
   if (SignalEMALong && UseLongs && Buy) {
  
   error = 1;
   while (error != 0) {
   if (InitialStop > 0){
     OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),3,Ask-InitialStop*Point,0,ExpertName,Magic,0,Blue);
     error = GetLastError();
   } else {
     OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),3,0,0,ExpertName,Magic,0,Blue);
     error = GetLastError();
   }
   if (error !=0 ) Print("Error:  ",error); 
   
   }
   }  
  
   if (SignalEMAShort && UseShorts && Sell){
   
   error = 1;
   while (error != 0) {
   if (InitialStop > 0){
   OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),3,Bid+InitialStop*Point,0,ExpertName,Magic,0,Red);
   } else {
   OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),3,0,0,ExpertName,Magic,0,Red);
   }
   error = GetLastError();
   if (error !=0 ) Print(error); }
     
   }
   
   
   }
   
   
   ChartComment();
   
    if (TrailStop > 0) 
    {
      TrailIt(TrailStop);
    }
   
    if (BreakEven > 0)
    {
      DoBE(BreakEven);
    }
    
    if (GlobalBE > 0 && ScanOpenTrades()!=0 )
    {
      GlobalDoBE(MathCeil(GlobalBE / ScanOpenTrades()));
    }
/*    
    if (GlobalTrailStop > 0 && ScanOpenTrades()!=0)
    {
    
      GlobalTrail(MathCeil(GlobalTrailStop / ScanOpenTrades()));
    
    }
*/
  return(0);
  }
//+------------------------------------------------------------------+
 void TrailIt( int byPips )                   // based on trailing stop code from MT site... thanks MT!
  {
  if (byPips >=5)
  {
  for (int i = 0; i < OrdersTotal(); i++) {
     OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
     if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic)) ) 
        {
            if (OrderType() == OP_BUY) {
               if (Bid - OrderOpenPrice() > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
                  if (OrderStopLoss() < Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
                  }
               }
            } else if (OrderType() == OP_SELL) {
               if (OrderOpenPrice() - Ask > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
                  if ((OrderStopLoss() > Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT)) || 
                        (OrderStopLoss() == 0)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(),
                        Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
                  }
               }
            }
        }
	  }
	  }
  } // proc TrailIt()
  
void DoBE(int byPips)
  {
    for (int i = 0; i < OrdersTotal(); i++) {
     OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
     if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic) ) )  
        {
            if (OrderType() == OP_BUY && (OrderStopLoss() < (OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if ((Bid - OrderOpenPrice() > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) && (OrderOpenPrice()-OrderStopLoss() > 0)) if (OrderStopLoss() != (OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset, OrderTakeProfit(), Red);
            if (OrderType() == OP_SELL && (OrderStopLoss() > (OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if ((OrderOpenPrice() - Ask > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) && (OrderOpenPrice()-OrderStopLoss() > 0)) if (OrderStopLoss() != (OrderOpenPrice() -  MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() -  MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset, OrderTakeProfit(), Red);
        }
    }
  }
void GlobalDoBE(int byPips)
  {
         
     for (int i = 0; i < OrdersTotal(); i++) {
     OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
     if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic) ) )  
        {
            if (OrderType() == OP_BUY && (OrderStopLoss() < (OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if (OrderStopLoss() != (OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT)*byPips, OrderTakeProfit(), Blue);
            if (OrderType() == OP_SELL && (OrderStopLoss() > (OrderOpenPrice() +  MarketInfo(OrderSymbol(), MODE_POINT)*BEOffset))) if (OrderStopLoss() != (OrderOpenPrice() -  MarketInfo(OrderSymbol(), MODE_POINT))) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() -  MarketInfo(OrderSymbol(), MODE_POINT)*byPips, OrderTakeProfit(), Blue);
        }
    }
  }
  
 /* void GlobalTrail( int byPips )
  {
  if (byPips >=5)
  {
  for (int i = 0; i < OrdersTotal(); i++) {
     OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
     if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == Magic)) ) 
        {
            if (OrderType() == OP_BUY) {
               if (Bid - OrderOpenPrice() > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
                  if (OrderStopLoss() < Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
                  }
               }
            } else if (OrderType() == OP_SELL) {
               if (OrderOpenPrice() - Ask > byPips * MarketInfo(OrderSymbol(), MODE_POINT)) {
                  if ((OrderStopLoss() > Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT)) || 
                        (OrderStopLoss() == 0)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(),
                        Ask + byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
                  }
               }
            }
        }
	  }
	  }
  } // proc TrailIt()
 */
bool IsPosition(double inRange)
{
  int totalorders = OrdersTotal();
  for(int i = 0;i < totalorders;i++)
  {
    OrderSelect(i, SELECT_BY_POS);
    if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic)) 
    {  
      int type = OrderType();
      
      if ((MathAbs(OrderOpenPrice() - MarketInfo(Symbol(),MODE_ASK))*90) < (inRange))
      {        
        if (type == OP_BUY || type == OP_SELL)
        { 
          return(true); 
        }
      }
     }
   } 
   return(false);
 }
 
 
 void OpenLongClose()
{
    int total=OrdersTotal();
    
    for (int cnt=0;cnt<total;cnt++)
    { 
    OrderSelect(total-cnt-1, SELECT_BY_POS);
    int mode=OrderType();
    bool res = false; 
    bool condition = false;
    if (OrderMagicNumber()==Magic ) condition = true;
      if (condition &&  mode==OP_BUY )
      { 
       
         res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,Yellow);
               
            if( !res )
            {
            Print(" BUY: OrderClose failed with error #",GetLastError());
            Print(" Ticket=",OrderTicket());
            Sleep(3000);
            }
         
         
      }                  
   }
}
 
 void OpenShortClose()
{
    int total=OrdersTotal();
    
    for (int cnt=0;cnt<total;cnt++)
    { 
    OrderSelect(total-cnt-1, SELECT_BY_POS);
    int mode=OrderType();
    bool res = false; 
    bool condition = false;
    if (OrderMagicNumber()==Magic ) condition = true;
      if (condition && mode==OP_SELL )
      { 
       
         res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3,White);
                 
            if( !res )
            {
            Print(" SELL: OrderClose failed with error #",GetLastError());
            Print(" Ticket=",OrderTicket());
            Sleep(3000);
            } 
        
          
      }                  
   }
}
 
 void TotalProfit()
{
   int total=OrdersTotal();
   totalPips = 0;
   totalProfits = 0;
   for (int cnt=0;cnt<total;cnt++)
   { 
   OrderSelect(cnt, SELECT_BY_POS);
      
   int mode=OrderType();
   bool condition = false;
   if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
   else if ( Magic==0 ) condition = true;   
      if (condition)
      {      
         switch (mode)
         {
         case OP_BUY:
            totalPips += MathRound((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT));
            //totalPips += MathRound((Bid-OrderOpenPrice())/Point);
            totalProfits += OrderProfit();
            break;
            
         case OP_SELL:
            totalPips += MathRound((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK))/MarketInfo(OrderSymbol(),MODE_POINT));
            //totalPips += MathRound((OrderOpenPrice()-Ask)/Point);
            totalProfits += OrderProfit();
            break;
         }
      }            
	
	if (UseSwap) {
	
	SwapProfit();
	totalProfits = totalProfits + valueswap;
	}
	
	}
}
void ChartComment()
{
   string sComment   = "";
   string sp         = "****************************\n";
   string NL         = "\n";
   sComment = sp;
   sComment = sComment + "**        SAMURAY\n" + sp;
   sComment = sComment + "Open Positions      = " + ScanOpenTrades() + " / " + MaxTrades + NL;
   sComment = sComment + "Locked Positions    = " + CheckLocked() + NL;
   sComment = sComment + "Current Profit(Pip) = " + DoubleToStr(totalPips,0) + NL;
  
   if(UseSwap) sComment = sComment + "SWAP Value (Pip)   = " + DoubleToStr(valueswap,2) + NL;
  
   sComment = NL + sComment + "Net Value (Pip)      = " + DoubleToStr(totalPips+valueswap,0) + NL;
   
   sComment = NL + sComment + "Angle 1 = " + DoubleToStr(MAAngle(AnglePeriod1),4) + NL;
   
   sComment = NL + sComment + "Angle 2 = " + DoubleToStr(MAAngle(AnglePeriod2),4) + NL;
   
   sComment = NL + sComment + "Account Leverage: " + DoubleToStr(AccountLeverage(),0) + NL;
   
   sComment = sComment + NL + sp;
   
   Comment(sComment);
}	    
  
  
int ScanOpenTrades()
{   
   int total = OrdersTotal();
   int numords = 0;
    
   for(int cnt=0; cnt<=total-1; cnt++) 
   {        
   OrderSelect(cnt, SELECT_BY_POS);
      if(OrderType()<=OP_SELL)
      {
      if(Magic > 0) if(OrderMagicNumber() == Magic) numords++;
      if(Magic == 0) numords++;
      }
   }   
   return(numords);
}  
// Closing of Open Orders      
void OpenOrdClose()
{
    int total=OrdersTotal();
    
    for (int cnt=0;cnt<total;cnt++)
    { 
    OrderSelect(total-cnt-1, SELECT_BY_POS);
    int mode=OrderType();
    bool res = false; 
    bool condition = false;
    if (OrderMagicNumber()==Magic ) condition = true;
      if (condition && ( mode==OP_BUY || mode==OP_SELL ))
      { 
       
// - BUY Orders         
         if(mode==OP_BUY)
         {  
         res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,Yellow);
               
            if( !res )
            {
            Print(" BUY: OrderClose failed with error #",GetLastError());
            Print(" Ticket=",OrderTicket());
            Sleep(3000);
            }
         }
         else     
// - SELL Orders          
         if( mode == OP_SELL)
         {
         res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3,White);
                 
            if( !res )
            {
            Print(" SELL: OrderClose failed with error #",GetLastError());
            Print(" Ticket=",OrderTicket());
            Sleep(3000);
            } 
         }  
      }                  
   }
}
void sidePips()
{
   int total=OrdersTotal();
   
   shortPips = 0;
   longPips = 0;
   
   for (int cnt=0;cnt<total;cnt++)
   { 
   OrderSelect(cnt, SELECT_BY_POS);
      
   int mode=OrderType();
   bool condition = false;
   if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
   else if ( Magic==0 ) condition = true;   
      if (condition)
      {      
         switch (mode)
         {
         case OP_BUY:
            longPips += MathRound((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT));
                       
            break;
            
         case OP_SELL:
            shortPips += MathRound((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK))/MarketInfo(OrderSymbol(),MODE_POINT));
                       
            break;
         }
      }            
	
	}
}
// MoneyManagement
double LotSize()
{
     double Account = 0;
  
     if (BalanceForTrade > AccountFreeMargin()) 
  
     { 
    
     Account = AccountFreeMargin();
    
     } else {
    
     Account = BalanceForTrade;
  
     if (BalanceForTrade == 0) Account = AccountFreeMargin();
  
     }
  
 
     double lotMM = MathCeil(Account *  Risk / 1000) / 1000;
     
     if(AccountIsMicro)  {
     
     if(lotMM < 0.01) lotMM = 0.01;
     if(lotMM >= MaxLotSize) lotMM = MaxLotSize;
     
     AccountSize=2;
     
     } else {
     
     if(lotMM < 0.1) lotMM = 0.1;
     if(lotMM >= MaxLotSize) lotMM = MaxLotSize;
     
     AccountSize=1;
     
     }
     
     lotMM = NormalizeDouble(lotMM,AccountSize);
     
	  return (lotMM);
}
void SwapProfit()
{
   int total=OrdersTotal();
   valueswap = 0;
   for (int cnt=0;cnt<total;cnt++)
   { 
   OrderSelect(cnt, SELECT_BY_POS);   
   int mode=OrderType();
   bool condition = false;
   if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
   else if ( Magic==0 ) condition = true;   
      if (condition && OrderSwap()!=0)
      {     
      valueswap = valueswap + OrderSwap()/PipCost(OrderSymbol());         // ERROOOOOOOOOOOOOOOOOOOOOOOOOOO
      }            
	}
}
/* bool CheckAllProfit()
{
   bool sig = true;
   
   int total=OrdersTotal();
   for (int cnt=0;cnt<total;cnt++)
   { 
   OrderSelect(cnt, SELECT_BY_POS);   
   int mode=OrderType();
   bool condition = false;
   if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
   else if ( Magic==0 ) condition = true;   
      if (condition)
      {  
      if (MarketInfo(OrderSymbol(),MODE_BID) < OrderOpenPrice()) 
      {
        sig = false;
        Print(MarketInfo(OrderSymbol(),MODE_BID),"  <  ", OrderOpenPrice()," NOT ALL ORDERS IN PROFIT !!! ");
      }
      }            
	}
if (ScanOpenTrades() == 0) sig = true;
return(sig);
}
*/
bool CheckLocked()
{
   int sig = 0;
   
   int total=OrdersTotal();
   for (int cnt=0;cnt<total;cnt++)
   { 
   OrderSelect(cnt, SELECT_BY_POS);   
   int mode=OrderType();
   bool condition = false;
   if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
   
   if (condition &&  mode==OP_BUY) if (OrderStopLoss() > OrderOpenPrice()) sig = sig + 1;
   if (condition &&  mode==OP_SELL) if (OrderStopLoss() < OrderOpenPrice()) sig = sig + 1;
             
	}
return(sig);
}
//+--------- --------- --------- --------- --------- --------- ----+
//+ Calculate cost in USD of 1pip of given symbol
//+--------- --------- --------- --------- --------- --------- ----+
double PipCost (string TradeSymbol) {
double Base, Cost;
string TS_13, TS_46, TS_4L;
TS_13 = StringSubstr (TradeSymbol, 0, 3);
TS_46 = StringSubstr (TradeSymbol, 3, 3);
TS_4L = StringSubstr (TradeSymbol, 3, StringLen(TradeSymbol)-3);
Base = MarketInfo (TradeSymbol, MODE_LOTSIZE) * MarketInfo (TradeSymbol,MODE_POINT);
if ( TS_46 == "USD" )
Cost = Base;
else if ( TS_13 == "USD" )
Cost = Base / MarketInfo (TradeSymbol, MODE_BID);
else if ( PairExists ("USD"+TS_4L) )
Cost = Base / MarketInfo ("USD"+TS_4L, MODE_BID);
else
Cost = Base * MarketInfo (TS_46+"USD" , MODE_BID);
return(Cost) ;
}
//+--------- --------- --------- --------- --------- --------- ----+
//+ Returns true if given symbol exists
//+--------- --------- --------- --------- --------- --------- ----+
bool PairExists (string TradeSymbol) {
return ( MarketInfo (TradeSymbol, MODE_LOTSIZE) > 0 );
}
void initMA_Angle_v4()
{
   switch (MA_Type)
   {
      case 1: strMAType="EMA"; MA_Mode=MODE_EMA; break;
      case 2: strMAType="SMMA"; MA_Mode=MODE_SMMA; break;
      case 3: strMAType="LWMA"; MA_Mode=MODE_LWMA; break;
      case 4: strMAType="LSMA"; break;
      default: strMAType="SMA"; MA_Mode=MODE_SMA; break;
   }
}
//+------------------------------------------------------------------+
//| LSMA with PriceMode                                              |
//| PrMode  0=close, 1=open, 2=high, 3=low, 4=median(high+low)/2,    |
//| 5=typical(high+low+close)/3, 6=weighted(high+low+close+close)/4  |
//+------------------------------------------------------------------+
double LSMA(int Rperiod, int prMode, int shift)
{
   int i, mshift;
   double sum, pr;
   int length;
   double lengthvar;
   double tmp;
   double wt;
   length = Rperiod;
 
   sum = 0;
   for(i = length; i >= 1  ; i--)
   {
     lengthvar = length + 1;
     lengthvar /= 3;
     tmp = 0;
     mshift = length-i+shift;
     switch (prMode)
     {
     case 0: pr = Close[mshift];break;
     case 1: pr = Open[mshift];break;
     case 2: pr = High[mshift];break;
     case 3: pr = Low[mshift];break;
     case 4: pr = (High[mshift] + Low[mshift])/2;break;
     case 5: pr = (High[mshift] + Low[mshift] + Close[mshift])/3;break;
     case 6: pr = (High[mshift] + Low[mshift] + 2 * Close[mshift])/4;break;
     }
     tmp = ( i - lengthvar)*pr;
     sum+=tmp;
    }
    wt = MathFloor(sum*6/(length*(length+1))/Point)*Point;
    
    return(wt);
}
//+------------------------------------------------------------------+
//| The angle for MA                                                |
//+------------------------------------------------------------------+
double MAAngle(int RPeriod)
{
   double fCurMA, fPrevMA;
   double fAngle, mFactor, dFactor;
   int nLimit, i, R;
   int nCountedBars;
   double angle;
   int ShiftDif;
   string Sym;
 
   if(CurMAShift >= PrevMAShift)
   {
      Print("Error: CurMAShift >= PrevMAShift");
      PrevMAShift = 6;
      CurMAShift = 0;      
   }  
         
   dFactor = 3.14159/180.0;
   mFactor = 1000.0;
   Sym = StringSubstr(Symbol(),3,3);
   if (Sym == "JPY") mFactor = 10.0;
   ShiftDif = PrevMAShift-CurMAShift;
   if (MA_Type == 4)
   {
     fCurMA=LSMA(RPeriod,MA_AppliedPrice, i+CurMAShift);
     fPrevMA=LSMA(RPeriod,MA_AppliedPrice, i+PrevMAShift);
   }
   else
   {
     fCurMA=iMA(NULL,0,RPeriod,0,MA_Mode,MA_AppliedPrice,i+CurMAShift);
     fPrevMA=iMA(NULL,0,RPeriod,0,MA_Mode,MA_AppliedPrice,i+PrevMAShift);
   }
   fAngle = (fCurMA - fPrevMA)/ShiftDif;
   fAngle = mFactor * MathArctan(fAngle)/dFactor;
   return(fAngle);
  }
             
            
Comments