//------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"
#property strict
//------------------------------------------------------------------

enum  enPrices
      {
         pr_close,                                                 // Close
         pr_open,                                                  // Open
         pr_high,                                                  // High
         pr_low,                                                   // Low
         pr_median,                                                // Median
         pr_typical,                                               // Typical
         pr_weighted,                                              // Weighted
         pr_average,                                               // Average (high+low+open+close)/4
         pr_medianb,                                               // Average median body (open+close)/2
         pr_tbiased,                                               // Trend biased price
         pr_tbiased2,                                              // Trend biased (extreme) price
         pr_haclose,                                               // Heiken ashi close
         pr_haopen,                                                // Heiken ashi open
         pr_hahigh,                                                // Heiken ashi high
         pr_halow,                                                 // Heiken ashi low
         pr_hamedian,                                              // Heiken ashi median
         pr_hatypical,                                             // Heiken ashi typical
         pr_haweighted,                                            // Heiken ashi weighted
         pr_haaverage,                                             // Heiken ashi average
         pr_hamedianb,                                             // Heiken ashi median body
         pr_hatbiased,                                             // Heiken ashi trend biased price
         pr_hatbiased2,                                            // Heiken ashi trend biased (extreme) price
         pr_habclose,                                              // Heiken ashi (better formula) close
         pr_habopen,                                               // Heiken ashi (better formula) open
         pr_habhigh,                                               // Heiken ashi (better formula) high
         pr_hablow,                                                // Heiken ashi (better formula) low
         pr_habmedian,                                             // Heiken ashi (better formula) median
         pr_habtypical,                                            // Heiken ashi (better formula) typical
         pr_habweighted,                                           // Heiken ashi (better formula) weighted
         pr_habaverage,                                            // Heiken ashi (better formula) average
         pr_habmedianb,                                            // Heiken ashi (better formula) median body
         pr_habtbiased,                                            // Heiken ashi (better formula) trend biased price
         pr_habtbiased2                                            // Heiken ashi (better formula) trend biased (extreme) price
      };

enum enMaTypes
         {
            ma_adxvma,                                           // Adxvma
            ma_ahr,                                              // Ahrens moving average
            ma_alxma,                                            // Alexander moving average - ALXMA
            ma_dema,                                             // Double exponential moving average - DEMA
            ma_dfema,                                            // Double fast exponential moving average - DFEMA
            ma_dsema,                                            // Double smoothed exponential moving average - DSEMA
            ma_dsema2,                                           // Double smoothed EMA (variation)
            ma_dsemaf,                                           // Double smoothed fast exponential moving average - DSFEMA
            ma_dswema,                                           // Double smoothed Wilders exponential moving average - DSWEMA
            ma_dscma,                                            // Deviation scaled MA - DSCMA
            ma_dwma,                                             // Double weighted MA - DWMA
            ma_edic,                                             // Ehlers distance coefficient filter - EDIC
            ma_emas,                                             // Ema derivative - EMAD
            ma_ema,                                              // Exponential moving average - EMA
            ma_epma,                                             // End point moving average - EPMA
            ma_emaf,                                             // Fast exponential moving average - FEMA
            ma_eotf,                                             // Ehlers Optimal tracking filter
            ma_frama,                                            // Fractal adaptive moving average - FRAMA
            ma_gchan,                                            // G Channel average - GCHAN
            ma_hull,                                             // Hull moving average - HMA
            ma_hulle,                                            // Hull moving average EMA based - HMAe
            ma_hullf,                                            // Hull moving average Fast EMA based - HMAf
            ma_hulls,                                            // Hull moving average Slow ma based - HMAs
            ma_ie2,                                              // IE/2
            ma_ilinr,                                            // Integral of linear regression slope
            ma_itl,                                              // Instantaneous trendline
            ma_jur,                                              // Jurik smoothing
            ma_lagg,                                             // Laguerre filter
            ma_lead,                                             // Leader exponential moving average
            ma_linr,                                             // Linear regression value - LSMA
            ma_slwma,                                            // Smoothed linear weighted moving average - SLWMA
            ma_lwma,                                             // Linear weighted moving average - LWMA
            ma_mcg,                                              // McGinley Dynamic
            ma_mcma,                                             // McNicholl ema
            ma_nlma,                                             // Non lag moving average
            ma_nma,                                              // Natural moving average - NMA
            ma_pdfma,                                            // Probability density funcion ma (pdfma)
            ma_pwma,                                             // Parabolic weighted moving average - PWMA
            ma_qrma,                                             // Quadratic regression average
            ma_qwma,                                             // Quadratic weighted average
            ma_rma,                                              // Rolling moving average - RMA
            ma_rmta,                                             // Recursive moving trendline - RMTA
            ma_rwavg,                                            // Range weighted average - RWAVG
            ma_rwema,                                            // Range weighted EMA - RWEMA
            ma_rwemads,                                          // Range weighted EMA double smooth - RWDSEMA
            ma_sma,                                              // Simple moving average - SMA
            ma_sid,                                              // Simple decycler - SDEC
            ma_sine,                                             // Sine weighted moving average
            ma_smma,                                             // Smoothed moving average - SMMA
            ma_smoo,                                             // Smoother
            ma_smoo2,                                            // Smoother JMA like
            ma_ssm,                                              // Super smoother
            ma_b3p,                                              // Three pole Ehlers Butterworth
            ma_s3p,                                              // Three pole Ehlers smoother
            ma_tma,                                              // Triangular moving average - TMA
            ma_tema,                                             // Triple exponential moving average - TEMA
            ma_tsema2,                                           // Triple smoothed EMA (variation)
            ma_twema,                                            // Triple wilders exponential moving average - TWEMA
            ma_b2p,                                              // Two pole Ehlers Butterworth
            ma_s2p,                                              // Two pole Ehlers smoother
            ma_vidya,                                            // Vidya
            ma_vema,                                             // Volume weighted ema - VEMA
            ma_vwma,                                             // Volume weighted moving average - VWMA
            ma_zldema,                                           // Zero lag dema
            ma_zlhulle,                                          // Zero lag Hull ema based - ZLHMAe
            ma_zlhullf,                                          // Zero lag Hull fast ema - ZLHMAf
            ma_zlhulls,                                          // Zero lag Hull slow ma - ZLHMAs
            ma_zlma,                                             // Zero lag moving average
            ma_zltema                                            // Zero lag tema
      };
enum  enColorMode
      {
            cc_Prc,                                               // TRADE on price cross g channel
            cc_Slo                                                // TRADE on slope change
      };
input string              __dis__01       = "";                   //.Display settings
input enColorMode         inpColorMode    = cc_Slo;               // Color change:

input double          MaxLot          = 2;                            // Maximum lots to risk
input double          LotsPer15K      = 1;                            // Lots per $15K in account

extern string         dummy1          = "";                           // . 
extern double         TakeProfit      = 1300;                        // Initial take profit (in pips)
extern double         StopLoss        = 0;                          // 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() / 15000)*LotsPer15K); //calculate the lot size according to how many lots input per 15K in "LotsPer15K"
   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,"! g channel",25,pr_high,pr_low,21,ma_ema,21,ma_ema,"",inpColorMode,8,BarToUse);
   double preTrend =  iCustom(_Symbol,_Period,"! g channel",25,pr_high,pr_low,21,ma_ema,21,ma_ema,"",inpColorMode,8,BarToUse+1);
   doWhat = _doNothing;
   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);
}
//------------------------------------------------------------------
//
//------------------------------------------------------------------