Moving_Average

Price Data Components
Series array that contains open prices of each barSeries array that contains close prices for each bar
Orders Execution
Checks for the total of open ordersChecks for the total of closed ordersIt automatically opens orders when conditions are reachedIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
Indicators Used
Moving average indicator
0 Views
0 Downloads
0 Favorites
Moving_Average
//+------------------------------------------------------------------+
//|                                           Moving_Average_v01.mq4 |
//+------------------------------------------------------------------+
#define MAGICMA  20140101
 
extern double Lots               = 0.01;
extern double MaximumRisk        = 0.0025;
extern double DecreaseFactor     = 10;
extern int    MovingPeriod       = 89;
extern int    MovingPeriod2      = 34;
extern int    MovingShift        = 0;
extern int    MovingShift2       = 0;
extern int    StopLoss           = 100;
extern double WR                 = 6;
                                          // òðåéëèíã-ñòîï (0 - îòêë)
extern int    Trail_Stop         = 300;
                                          // øàã òðåéëèíã-ñòîïà
extern int    Step_TS            = 300;
                                          // ïåðèîä òîðãîâëè
extern int    Period_Torg        = 60;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders()
{
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
      {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
      }
   }
//---- return orders volume
   if(buys>0) return(buys);
   return(-sells);
}
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=OrdersHistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,01);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   double min_l=MarketInfo(Symbol(),MODE_MINLOT);
   double max_l=MarketInfo(Symbol(),MODE_MAXLOT);
   //.............................................
   if(lot<min_l) lot=min_l;
   if(lot>max_l) lot=max_l;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
{
   double ma;
   double lma;
   int    res;
//---- go trading only for first tiks of new bar
   ma =iMA(NULL,Period_Torg,MovingPeriod, MovingShift, MODE_SMMA,PRICE_CLOSE,0);
   lma=iMA(NULL,Period_Torg,MovingPeriod2,MovingShift2,MODE_SMMA,PRICE_CLOSE,0);
 
//---- sell conditions
   if(ma>lma && iOpen(Symbol(),Period_Torg,1)>ma && iClose(Symbol(),Period_Torg,1)<ma)
   {
      RefreshRates();
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      if (res<0)Comment(GetLastError());
      return;
   }
 
//---- buy conditions
   if(lma>ma && iOpen(Symbol(),Period_Torg,1)<ma && iClose(Symbol(),Period_Torg,1)>ma)  
   {
      RefreshRates();
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      if (res<0)Comment(GetLastError());
      return;
}
//----
}
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
{
   double ma;
   double lma;
//---- get Moving Average 
   ma =iMA(NULL,0,MovingPeriod, MovingShift,MODE_SMMA,PRICE_CLOSE,0);
   lma=iMA(NULL,0,MovingPeriod2,MovingShift,MODE_SMMA,PRICE_CLOSE,0);
//----
   for(int i=0;i<OrdersTotal();i++)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //---- check order type 
      if(OrderType()==OP_BUY)
      {
         RefreshRates();
         if(iClose(Symbol(),Period_Torg,1)<lma && iOpen(Symbol(),Period_Torg,1)>lma && lma>ma) OrderClose(OrderTicket(),OrderLots(),Bid,3,White);
         break;            
      }
      if(OrderType()==OP_SELL)
      {
         RefreshRates();
         if(iClose(Symbol(),Period_Torg,1)>lma && iOpen(Symbol(),Period_Torg,1)<lma && ma>lma) OrderClose(OrderTicket(),OrderLots(),Ask,3,White);
         break;         
      }
   }
//----
}
//+------------------------------------------------------------------+
void Check_TP_SL()
{
   double ma =iMA(NULL,0,MovingPeriod, MovingShift,MODE_SMMA,PRICE_CLOSE,0);
   
   double SL;
   double TP;
   for(int i=0;i<OrdersTotal();i++)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //---- check order type 
      if(OrderType()==OP_BUY)
      {
         RefreshRates();
         SL=0;
         if (StopLoss>0)SL=ND(ma-StopLoss*Point);
         TP=0;
         if (WR>0)TP=ND(Ask+WR*(OrderOpenPrice()-SL));
         if((WR>0 && OrderTakeProfit()==0) || (StopLoss>0 && OrderTakeProfit()==0))
            OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,Green);
         break;            
      }
      if(OrderType()==OP_SELL)
      {
         RefreshRates();
         SL=0;
         if (StopLoss>0)SL=ND(ma+StopLoss*Point);
         TP=0;
         if (WR>0)TP=ND(Ask-WR*(SL-OrderOpenPrice()));
         if((WR>0 && OrderTakeProfit()==0) || (StopLoss>0 && OrderTakeProfit()==0))
            OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,Green);
         break;            
      }
   }
//----
}
//+------------------------------------------------------------------+
void Check_Trail_Stop()
{     // òðåéëèíã-ñòîï
   if (Step_TS<1)Step_TS=1;
   double sl;
   
   RefreshRates();
   double tek_bid=Bid;
   double tek_ask=Ask;

   for(int i=0; i<OrdersTotal(); i++)
   {
      if (!OrderSelect(i,SELECT_BY_POS)==true)continue;
      if (OrderSymbol()!=Symbol())continue;
      if (OrderMagicNumber()!=MAGICMA)continue;
      
      if (OrderType() == OP_BUY)
         if (ND(tek_bid) >= ND(OrderOpenPrice()+Trail_Stop*Point))
         {
            if (ND(OrderStopLoss())==0 || ND(OrderStopLoss()) < ND(OrderOpenPrice()))
               OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0);
            else
            {
               sl=OrderStopLoss()+Step_TS*Point;
               if (ND(sl) <= ND(tek_bid-(Trail_Stop+Step_TS)*Point) && ND(sl)>ND(OrderStopLoss()))
                  OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0);
            }
         }

      if (OrderType() == OP_SELL)
         if (ND(tek_ask) <= ND(OrderOpenPrice()-Trail_Stop*Point))
         {
            if (ND(OrderStopLoss())==0 || ND(OrderStopLoss()) > ND(OrderOpenPrice()))
               OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0);
            else
            {
               sl=OrderStopLoss()-Step_TS*Point;
               if (ND(sl) >= ND(tek_ask+(Trail_Stop+Step_TS)*Point) && ND(sl)<ND(OrderStopLoss()))
                  OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0);
            }
         }
   }
}
//-----------------------------------------------
double ND(double n)
{
   return(NormalizeDouble(n,Digits));
}
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
{
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
   if(CalculateCurrentOrders()==0) 
      CheckForOpen();
   else
   {
      CheckForClose();
      if (StopLoss>0 || WR>0)Check_TP_SL();
      if (Trail_Stop>0)Check_Trail_Stop();
   }
//----
}
//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---