//------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"
#property strict
//------------------------------------------------------------------

input double                AdxVmaPeriod        = 10;              // Adxvma period
input ENUM_APPLIED_PRICE    AdxVmaPrice         = PRICE_MEDIAN;    // Price to use
input double                BandsPeriod         = 30;              // Bands period
input double                BandsMultiplier1    = 2;               // First bands multiplier
input double                BandsMultiplier2    = 3;               // Second bands multiplier
input bool                  TrendMode           = false;           // Trend mode?
sinput string               __can__00           = "";              //.Candle settings
input bool                  inpCandleShow       = true;            // Show candles?
input bool                  inpAutoChart        = true;            // Auto chart foreground             
input bool                  inpAutoWidth        = true;            // Automatic width?
input int                   inpWidthWick        = 1;               // Wick width
input int                   inpWidthBody        = 4;               // Body width (if not automatic width)
input color                 inpCandleUP         = clrRoyalBlue;    // Bullish candles color
input color                 inpCandleDN         = clrRed;          // Bearish candles color

input double                MaxLot              = 0.3;             // Maximum lots to risk
input double                LotsPer20K          = 2;               // Lots per $20K in account

extern string               dummy1              = "";              // . 
extern double               TakeProfit          = 450;             // Initial take profit (in pips)
extern double               StopLoss            = 2500;            // Initial stop loss (in pips)
extern string               dummy2              = "";              // Settings for indicators

extern string               dummy3              = "";              // 
extern int                  MagicNumber         = 123456;          // Magic number to use for the EA
extern bool                 EcnBroker           = true;            // Is your broker ECN/STP type of broker?
extern bool                 MulOnSame           = false;           // Allow multiple opened and closed orders on a same bar?


extern string               dummy4                = "";            // General settings
extern bool                 DisplayInfo           = true;          // Dislay info
extern int                  Slippage              = 50;            // Slipage to use when opening new orders
extern int                  BarToUse              = 1;             // Bar to test (0, for still opened, 1 for first closed, and so on)
input int                   Maximum_Spread_Points = 50;            // Maximum   Spread to use when opening new orders
input uint                  StartHour             =  0;            // Start hour
input uint                  StartMinute           =  0;            // Start minute
input uint                  StartSecond           =  0;            // Start second
input uint                  EndHour               = 24;            // Ending hour
input uint                  EndMinute             =  0;            // Ending minute
input uint                  EndSecond             =  0;            // Ending second
bool dummyResult;
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()   { return(0); }
int deinit() { return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
 double MM_Size() //Calculate position sizing
  {
   double lots = ((AccountEquity() / 20000)*LotsPer20K); //calculate the lot size according to how many lots input per 20K in "LotsPer20K"
   if(lots > MaxLot) lots = MaxLot;  //if greater than max set it to the maxlot size
   return(lots);
  }

//
//
//
//
#define TRADE_RETRY_COUNT 4
#define TRADE_RETRY_WAIT  100
#define _doNothing 0
#define _doBuy     1
#define _doSell    2

int start()
{
   
   int doWhat = _doNothing;
   double curTrend = iCustom(_Symbol,_Period,"! adxvma channel (candles)",AdxVmaPeriod,AdxVmaPrice,BandsPeriod,BandsMultiplier1,BandsMultiplier2,TrendMode,"",inpCandleShow,inpAutoChart,inpAutoWidth,inpWidthWick,inpWidthBody,inpCandleUP,inpCandleDN,13,BarToUse);
   double preTrend = iCustom(_Symbol,_Period,"! adxvma channel (candles)",AdxVmaPeriod,AdxVmaPrice,BandsPeriod,BandsMultiplier1,BandsMultiplier2,TrendMode,"",inpCandleShow,inpAutoChart,inpAutoWidth,inpWidthWick,inpWidthBody,inpCandleUP,inpCandleDN,13,BarToUse+1);
   if (curTrend!=preTrend)
      if (curTrend==1)
            doWhat = _doBuy;
      else  doWhat = _doSell;
      if (doWhat==_doNothing) return(0);
   //
   //
   //
   //
   
   int    openedBuys    = 0;
   int    openedSells   = 0;
   double currentProfit = 0;
  
   
   
   
   
   for (int i = OrdersTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if (OrderSymbol()      != Symbol())            continue;
      if (OrderMagicNumber() != MagicNumber)         continue;

      //
      //
      //
      //
      //
      
      if (DisplayInfo) currentProfit += OrderProfit()+OrderCommission()+OrderSwap();
         
         //
         //
         //
         //
         //
         
         if (OrderType()==OP_BUY)
            if (doWhat==_doSell)
                  { RefreshRates(); if (!OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,CLR_NONE)) openedBuys++; }
            else  openedBuys++;
         if (OrderType()==OP_SELL)
            if (doWhat==_doBuy)
                  { RefreshRates(); if (!OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,CLR_NONE)) openedSells++; }
            else  openedSells++;            
   }
   if (DisplayInfo) Comment("Current profit : "+DoubleToStr(currentProfit,2)+" "+AccountCurrency()); if (doWhat==_doNothing) return(0);

   //
   //
   //
   //
   //

   if (doWhat==_doBuy && openedBuys==0)
      {
         RefreshRates();
         double stopLossBuy   = 0; if (StopLoss>0)   stopLossBuy   = Ask-StopLoss*Point*MathPow(10,Digits%2);
         double takeProfitBuy = 0; if (TakeProfit>0) takeProfitBuy = Ask+TakeProfit*Point*MathPow(10,Digits%2);
         if (EcnBroker)
         {
            int ticketb = OrderSend(Symbol(),OP_BUY, MM_Size(),Ask,Slippage,0,0,"",MagicNumber,0,CLR_NONE);
            if (ticketb>-1)
              dummyResult = OrderModify(ticketb,OrderOpenPrice(),stopLossBuy,takeProfitBuy,0,CLR_NONE);
         }
         else dummyResult = OrderSend(Symbol(),OP_BUY, MM_Size(),Ask,Slippage,stopLossBuy,takeProfitBuy,"",MagicNumber,0,CLR_NONE);
      }
   if (doWhat==_doSell && openedSells==0)
      {
         RefreshRates();
         double stopLossSell   = 0; if (StopLoss>0)   stopLossSell   = Bid+StopLoss*Point*MathPow(10,Digits%2);
         double takeProfitSell = 0; if (TakeProfit>0) takeProfitSell = Bid-TakeProfit*Point*MathPow(10,Digits%2);
         if (EcnBroker)
         {
            int tickets = OrderSend(Symbol(),OP_SELL, MM_Size(),Bid,Slippage,0,0,"",MagicNumber,0,CLR_NONE);
            if (tickets>-1)
              dummyResult = OrderModify(tickets,OrderOpenPrice(),stopLossSell,takeProfitSell,0,CLR_NONE);
         }
         else dummyResult = OrderSend(Symbol(),OP_SELL, MM_Size(),Bid,Slippage,stopLossSell,takeProfitSell,"",MagicNumber,0,CLR_NONE);
      }
   return(0);
}
//------------------------------------------------------------------
//
//------------------------------------------------------------------
bool IsWithinMaxSpread()
{
    bool WithinMaxSpread = true;

    for (int attempt = 0; attempt < TRADE_RETRY_COUNT; attempt++)
    {
        RefreshRates();
        WithinMaxSpread = true;

        if (Maximum_Spread_Points > 0)
        {
            double spread = NormalizeDouble(((Ask - Bid) /_Point ), 0);
            //Need NormalizeDouble here because of rounding errors in MT4 that otherwise occur (confirmed in several backtests).

            if (spread > Maximum_Spread_Points)
            {
                Print("The current spread of ", DoubleToString(spread, 0), " points, is higher than the maximum allowed of ", DoubleToString(Maximum_Spread_Points, 0), " points. Try ", IntegerToString(attempt + 1), " of ", IntegerToString(TRADE_RETRY_COUNT), ".");
                WithinMaxSpread = false;
            }
        }
        Sleep(TRADE_RETRY_WAIT);
    }
    
    return(WithinMaxSpread);
}
//------------------------------------------------------------------
//
//------------------------------------------------------------------