package jforex.converted;
import java.awt.Color;
import com.dukascopy.api.*;
import com.dukascopy.connector.engine.*;
public class MaBreak_Contest extends MQL4ConnectorStrategy {

protected void initProperties() {
if (properties == null) {
properties = new Properties();
}
properties.setProperty("link","http:");
properties.setProperty("copyright","Copyright 2012, MetaQuotes Software Corp.");
properties.setProperty("connector_timezone","GMT");
}

@Configurable("") public String Expert_Settings = toString("   Expert Settings");
@Configurable("") public int    MagicNumber     = toInt(1234);
@Configurable("") public int    NumberOfTries   = toInt(10)  ;
@Configurable("") public int    Slippage        = toInt(50)  ;

@Configurable("") public String Lot_Size = toString("   Lot Size Settings");
@Configurable("") public double Lots     = toDouble(0.1);

@Configurable("") public String  Auto_Management = toString("   Auto Management Settings");
@Configurable("") public double  RiskLevel       = toDouble(0.1) ;
@Configurable("") public boolean AutoLots        = toBool(true)  ;
@Configurable("") public double  MaxLots         = toDouble(1000);

@Configurable("") public String  Trailing_Stop   = toString("   Trailing Stop Settings");
@Configurable("") public boolean UseTrailingStop = toBool(true);
@Configurable("") public int     TrailingStopType= toInt(1);/*1:will start trailing if profit in pips is greater / same with TrailingStop.
                                                              2:will start trailing as soon as trade in profit.*/
@Configurable("") public int     TrailingStop    = toInt(100);

@Configurable("") public String  Trade_Limits  = toString("    Trade Limits Settings");
@Configurable("") public double  StopLoss      = toDouble(300);
@Configurable("") public boolean Auto_StopLoss = toBool(true) ;
@Configurable("") public int     SafeStop      = toInt(500)   ;
@Configurable("") public double  TakeProfit    = toDouble(0)  ;

@Configurable("") public String  Trading_Hours = toString("   Time Filter Settings");
@Configurable("") public boolean TimeFilter    = toBool(true) ;
@Configurable("") public int     StartHour     = toInt(8)    ;
@Configurable("") public int     EndHour       = toInt(15)    ;
@Configurable("") public boolean ExcludeMonday = toBool(false);
@Configurable("") public boolean ExcludeFriday = toBool(true) ;
@Configurable("") public boolean Exclude_Month = toBool(false);
@Configurable("") public int     ExcludeMonth1 = toInt(12)    ;
@Configurable("") public int     ExcludeMonth2 = toInt(1)     ;

@Configurable("") public String Moving_Average = toString("   Moving Average Settings");
@Configurable("") public int    MaPeriod       = toInt(25)      ;
@Configurable("") public int    MaType         = toInt(1)       ;
@Configurable("") public int    CandlesNum     = toInt(5)       ;
@Configurable("") public double Factor         = toDouble(1.618);

/*Global Variables*/
String  CheckTrade   = "";
double  AutoStopLoss = 0.0  ;
long    checkentry   = 0    ;
boolean Valid        = false;
int     start        = 0    ;
int     end          = 0    ;

public int init() throws JFException 
{
 start=toInt(StartHour);
 end=toInt(EndHour);
 if(true)return toInt((0));return 0;
}

public int start() throws JFException 
{
   if (equal(Instrument(), "EUR/USD")&&equal(Period(), 30))
   { 
    String equity1    = "" ;
    double equity     = 0.0;
    int    stoploss   = 0  ;
    int    takeprofit = 0  ;
    int    ticket     = 0  ;
    int    total      = 0  ;
    int    cnt        = toInt(0);
   
    if (greaterThan(subTotalTrade(), 0))
    {
     if (toBool(UseTrailingStop)&&greaterThan(TrailingStop, 0))
     {
      total=toInt(OrdersTotal());
      for(   cnt=toInt(0);lessThan(cnt, total);cnt++)
      {
       OrderSelect(toInt(cnt),toInt(SELECT_BY_POS),toInt(MODE_TRADES));
       if (lessThanOrEqualTo(OrderType(), OP_SELL)&&equal(OrderSymbol(), Instrument())&&equal(OrderMagicNumber(), MagicNumber))
       {
        subTrailingStop  (toInt( OrderType())); 
       }
      }
     }
     if(true)return toInt((0));
    }
   
/*Lot Size Proportional To Equity*/   
    equity1=toString((AccountEquity()/100));
    equity=toDouble(StrToDouble(toString(equity1)));
    if (toBool(AutoLots))
    {
     Lots=toDouble(equity*RiskLevel);
     if (greaterThan(Lots, MaxLots))
     {
      Lots=toDouble(MaxLots);
     }
    }
/*Set Time Filter*/   
    if ((ExcludeFriday&&equal(DayOfWeek(), 5))||(ExcludeMonday&&(equal(DayOfWeek(), 0)||equal(DayOfWeek(), 1))))
    {
     if(true)return toInt((0));
    }
    if (toBool(Exclude_Month)&&(equal(Month(), ExcludeMonth1)||equal(Month(), ExcludeMonth2)))
    {
     if(true)return toInt((0));
    }
    if (toBool(TimeFilter))
    {
     StartHour=toInt(start);
     EndHour=toInt(end);
    }
    else 
    {
     StartHour=toInt(0);
     EndHour=toInt(23);
    }
   
/*Open BUY/SELL Trade*/   
    if (greaterThanOrEqualTo(Hour(), StartHour)&&lessThan(Hour(), EndHour))
    {
     if (equal(GetDirection(), "up")&&notEqual(checkentry, iTime(toInstrument(null),toPeriod(0),toInt(0))))
     {
      if (toBool(Auto_StopLoss))
      {
       stoploss=toInt(AutoStopLoss);
      }
      else 
      {
       stoploss=toInt(StopLoss);
      }
      ticket=toInt(subOpenOrder(toInt(OP_BUY),toInt(stoploss),toInt(TakeProfit)));
      if (greaterThan(ticket, 0))
      {
       checkentry=toInt(iTime(toInstrument(null),toPeriod(0),toInt(0)));
      }
     }
     if (equal(GetDirection(), "down")&&notEqual(checkentry, iTime(toInstrument(null),toPeriod(0),toInt(0))))
     {
      if (toBool(Auto_StopLoss))
      {
       stoploss=toInt(AutoStopLoss);
      }
      else 
      {
       stoploss=toInt(StopLoss);
      }
      ticket=toInt(subOpenOrder(toInt(OP_SELL),toInt(stoploss),toInt(TakeProfit)));
      if (greaterThan(ticket, 0))
      {
       checkentry=toInt(iTime(toInstrument(null),toPeriod(0),toInt(0)));
      }
     }
    }
   }
    if(true)return toInt((0));return 0;
   
}
  
/* ---- Start Of Functions Section ---- */

/*Get The Number Of Opened Trades*/
public int subTotalTrade() throws JFException 
{
   int cnt  = 0       ;
   int total= toInt(0);

   for(cnt=toInt(0);lessThan(cnt, OrdersTotal());cnt++)
   {
    OrderSelect(toInt(cnt),toInt(SELECT_BY_POS),toInt(MODE_TRADES));
    if (lessThanOrEqualTo(OrderType(), OP_SELL)&&equal(OrderSymbol(), Instrument())&&equal(OrderMagicNumber(), MagicNumber))
    {
     total++;
    }
   }
   if(true)return toInt((total));return 0;
}

// Open Buy/Sell Trade Function
public int subOpenOrder(int type, int stoploss, int takeprofit) throws JFException {
   int    ticket      = toInt(0)   ;
   int    err         = toInt(0)   ;
   int    c           = toInt(0)   ;
   double aStopLoss   = toDouble(0);
   double aTakeProfit = toDouble(0);
   double bStopLoss   = toDouble(0);
   double bTakeProfit = toDouble(0);
   
   if (notEqual(stoploss, 0))
   {
    aStopLoss = toDouble(NormalizeDouble(toDouble(Ask-stoploss*Point),toInt(4)));
    bStopLoss = toDouble(NormalizeDouble(toDouble(Bid+stoploss*Point),toInt(4)));
   }
   if (notEqual(takeprofit, 0))
   {
    aTakeProfit = toDouble(NormalizeDouble(toDouble(Ask+takeprofit*Point),toInt(4)));
    bTakeProfit = toDouble(NormalizeDouble(toDouble(Bid-takeprofit*Point),toInt(4)));
   }
   if (equal(type, OP_BUY))
   {
    c = toInt(0);
    for(c=toInt(0);lessThan(c, NumberOfTries);c++)
    {
     ticket=toInt(OrderSend(toInstrument(Instrument()),toInt(OP_BUY),toDouble(Lots),toDouble(Ask),
                            toInt(Slippage),toDouble(aStopLoss),toDouble(aTakeProfit),toString("BUY"),
                            toInt(MagicNumber),toInt(0),toColor(Green)));
     err=toInt(GetLastError());
     if (equal(err, 0))
     {
      if (greaterThan(ticket, 0))
      { 
       break;
      }
     }
     else 
     if (equal(err, 0)||equal(err, 4)||equal(err, 136)||equal(err, 137)||equal(err, 138)||equal(err, 146))
     {
      Sleep(toInt(5000));
      if(true)continue;
     }
     else 
     if (greaterThan(ticket, 0))
     {
      break;
     }
    }
   }
   
   if (equal(type, OP_SELL))
   {
    c = toInt(0);
    for(  c=toInt(0);lessThan(c, NumberOfTries);c++)
    {
     ticket=toInt(OrderSend(toInstrument(Instrument()),toInt(OP_SELL),toDouble(Lots),toDouble(Bid),toInt(Slippage),
                            toDouble(bStopLoss),toDouble(bTakeProfit),toString("SELL"),
                            toInt(MagicNumber),toInt(0),toColor(Red)));
     err=toInt(GetLastError());
     if (equal(err, 0))
     { 
      if (greaterThan(ticket, 0))
      {
       break;
      }
     }
     else 
     if (equal(err, 0)||equal(err, 4)||equal(err, 136)||equal(err, 137)||equal(err, 138)||equal(err, 146))
     {
      Sleep(toInt(5000));
      if(true)continue;
     }
     else 
     if (greaterThan(ticket, 0))
     {
      break;
     }
    }
   }
   if(true)return toInt((ticket));return 0;
}

/*Trailing Stop Function*/
public void subTrailingStop(int Type) throws JFException
{
   if (equal(Type, OP_BUY))
   {
    switch (toInt(TrailingStopType))
    {
     case 1: 
     if (greaterThan(Bid-OrderOpenPrice(), Point*TrailingStop)&&lessThan(OrderStopLoss(), Bid-Point*TrailingStop))
     {
      OrderModify(toInt(OrderTicket()),toDouble(OrderOpenPrice()),toDouble(Bid-Point*TrailingStop),
                  toDouble(OrderTakeProfit()),toInt(0),toColor(Green));
      if(true)return ;
     }
     break;
     case 2: 
     if (greaterThan(Bid, OrderOpenPrice())&&lessThan(OrderStopLoss(), Bid-Point*TrailingStop))
     {
      OrderModify(toInt(OrderTicket()),toDouble(OrderOpenPrice()),toDouble(Bid-Point*TrailingStop),
                  toDouble(OrderTakeProfit()),toInt(0),toColor(Green));
      if(true)return ;
     }
     break;
     default :
     if (greaterThan(Bid-OrderOpenPrice(), Point*TrailingStop)&&lessThan(OrderStopLoss(), Bid-Point*TrailingStop))
     {
     OrderModify(toInt(OrderTicket()),toDouble(OrderOpenPrice()),toDouble(Bid-Point*TrailingStop),toDouble(OrderTakeProfit()),toInt(0),toColor(Green));
     if(true)return ;
     }
    }
   }
   
   if (equal(Type, OP_SELL))
   {
    switch (toInt(TrailingStopType))
    {
     case 1: 
     if (greaterThan(OrderOpenPrice()-Ask, Point*TrailingStop))
     {
      if (greaterThan(OrderStopLoss(), Ask+Point*TrailingStop)||equal(OrderStopLoss(), 0))
      {
       OrderModify(toInt(OrderTicket()),toDouble(OrderOpenPrice()),toDouble(Ask+Point*TrailingStop),
                   toDouble(OrderTakeProfit()),toInt(0),toColor(Red));
       if(true)return ;
      }
     }
     break;
     case 2: 
     if (greaterThan(OrderOpenPrice(), Ask))
     {
      if (greaterThan(OrderStopLoss(), Ask+Point*TrailingStop)||equal(OrderStopLoss(), 0))
      {
       OrderModify(toInt(OrderTicket()),toDouble(OrderOpenPrice()),toDouble(Ask+Point*TrailingStop),
                   toDouble(OrderTakeProfit()),toInt(0),toColor(Red));
       if(true)return ;
      }
     }
     break;
     default :
     if (greaterThan(OrderOpenPrice()-Ask, Point*TrailingStop))
     {
      if (greaterThan(OrderStopLoss(), Ask+Point*TrailingStop)||equal(OrderStopLoss(), 0))
      {
       OrderModify(toInt(OrderTicket()),toDouble(OrderOpenPrice()),toDouble(Ask+Point*TrailingStop),
                  toDouble(OrderTakeProfit()),toInt(0),toColor(Red));
       if(true)return ;
      }
     }
    }
   }
   return ;
}

/*Get The Trade Direction (Up/Down)*/
public String GetDirection() throws JFException
{
   String direcs  = "";
   String direcb  = "";
   double drmahi  = 0.0;
   double drmalow = 0.0;
   double op      = 0.0;
   double cl      = 0.0;
   double hi      = 0.0;
   double lw      = 0.0;
   double lowtail = 0.0;
   double hitail  = 0.0;
   double body    = 0.0;
   double highest = 0.0;
   double lowest  = 0.0;
   
   drmahi  = toDouble(iMA(toInstrument(null),toPeriod(0),toInt(MaPeriod),toInt(0),toInt(MaType),toInt(PRICE_HIGH),toInt(1)));
   drmalow = toDouble(iMA(toInstrument(null),toPeriod(0),toInt(MaPeriod),toInt(0),toInt(MaType),toInt(PRICE_LOW),toInt(1)));

   highest = toDouble(High(toInt(iHighest(toInstrument(null),toPeriod(0),toInt(MODE_HIGH),toInt(CandlesNum),toInt(2)))));
   lowest  = toDouble(Low(toInt(iLowest(toInstrument(null),toPeriod(0),toInt(MODE_LOW),toInt(CandlesNum),toInt(2))))); 

/*Check the Candle Validity by Comparing Body to Shadows magnitudes*/   
   op = toDouble(Open(toInt(1)));
   cl = toDouble(Close(toInt(1)));
   hi = toDouble(High(toInt(1)));
   lw = toDouble(Low(toInt(1)));
  
   body = toDouble(MathAbs(toDouble(op-cl)));
   if (greaterThan(cl, op))
   {
    lowtail = toDouble(op-lw);
    hitail  = toDouble(hi-cl);
   }
   else 
   if (lessThan(cl, op))
   {
    lowtail = toDouble(cl-lw);
    hitail  = toDouble(hi-op);
   }
   else 
   {
    Valid = toBool(false);
   }
   if ((greaterThan(cl, op)&&greaterThan(body, (hitail*Factor)))||(lessThan(cl, op)&&greaterThan(body, (lowtail*Factor))))
   {
    Valid = toBool(true);
   }
   else 
   {
    Valid = toBool(false);
   }
   if (toBool(Valid)&&(lessThan(op, drmahi)&&greaterThan(cl, drmahi))&&(greaterThan(cl, highest)&&greaterThan(cl, op)))
   {
    direcb       = toString("up");
    AutoStopLoss = toDouble(cl-lw);
    AutoStopLoss = toDouble(AutoStopLoss/Point);
    if (greaterThan(AutoStopLoss, SafeStop))
    {
     AutoStopLoss = toDouble(SafeStop);
    }
   }
   else 
   {
    direcb=toString("none");
   }
   if (toBool(Valid)&&(greaterThan(op, drmalow)&&lessThan(cl, drmalow))&&(lessThan(cl, lowest)&&lessThan(cl, op)))
   {
    direcs       = toString("down");
    AutoStopLoss = toDouble(hi-cl);
    AutoStopLoss = toDouble(AutoStopLoss/Point);
    if (greaterThan(AutoStopLoss, SafeStop))
    {
     AutoStopLoss = toDouble(SafeStop);
    }
   }
   else 
   {
    direcs = toString("none");
   }
   if (equal(direcb, "up"))
   {
    CheckTrade = toString(direcb);
   }
   else 
   if (equal(direcs, "down"))
   {
    CheckTrade = toString(direcs);
   }
   else
   {
    CheckTrade = toString("none");
   }
   if(true)return toString((CheckTrade));return "";
}

public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException{}
};