ma-slow6_ma1-fast

Price Data Components
Series array that contains close prices for each bar
Orders Execution
Checks for the total of open 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
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
ma-slow6_ma1-fast
//+------------------------------------------------------------------+
//|                                               Moving Average.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#define MAGICMA  20050610

extern double Lots               = 0.05;
extern double MaximumRisk        = 0.05;
extern double DecreaseFactor     = 3;
extern double MovingPeriod       = 14;
extern double MovingShift        = 2;
extern double MovingPeriod1       = 4;
extern double MovingShift1        = 2;
extern double Tral_Stop           =500;
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   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);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- 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
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma;
   int    res;
//---- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//---- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//---- sell conditions
   if(Open[1]>ma && Close[1]<ma)
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
   if(Open[1]<ma && Close[1]>ma)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }

 }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma1;
//---- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//---- get Moving Average 
   ma1=iMA(NULL,0,MovingPeriod1,MovingShift1,MODE_SMA,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)
        {
         if(Open[1]>ma1 && Close[1]<ma1) OrderClose(OrderTicket(),OrderLots(),Bid,3,White);  ///Open[1]>ma && Close[1]<ma
         break;
        }
      if(OrderType()==OP_SELL)
        {
         RefreshRates();
         if(Open[1]<ma1 && Close[1]>ma1)OrderClose(OrderTicket(),OrderLots(),Ask,3,White);  //Open[1]<ma && Close[1]>ma
         break;
        }
        
     }

  } 
 
  void CheckForOrderModify()
  {
   string Symb=Symbol();                        // Ôèíàíñ. èíñòðóìåíò
//--------------------------------------------------------------- 2 --
   for(int i=1; i<=OrdersTotal(); i++)          // Öèêë ïåðåáîðà îðäåð
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé
        {                                       // Àíàëèç îðäåðîâ:
         int Tip=OrderType();                   // Òèï îðäåðà
         if(OrderSymbol()!=Symb||Tip>1)continue;// Íå íàø îðäåð
         double SL=OrderStopLoss();             // SL âûáðàííîãî îðä.
         //------------------------------------------------------ 3 --
         while(true)                            // Öèêë ìîäèôèêàöèè
           {
            double TS=Tral_Stop;                // Èñõîäíîå çíà÷åíèå
            int Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL);//Ìèíèì. äèñò
            if (TS < Min_Dist)                  // Åñëè ìåíüøå äîïóñò.
               TS=Min_Dist;                     // Íîâîå çíà÷åíèå TS
            //--------------------------------------------------- 4 --
            bool Modify=false;                  // Íå íàçíà÷åí ê ìîäèôè
            switch(Tip)                         // Ïî òèïó îðäåðà
              {
               case 0 :                         // Îðäåð Buy
                  if (NormalizeDouble(SL,Digits)< // Åñëè íèæå æåëàåì.
                     NormalizeDouble(Bid-TS*Point,Digits))
                    {
                     SL=Bid-TS*Point;           // òî ìîäèôèöèðóåì åãî
                     string Text="Buy ";        // Òåêñò äëÿ Buy 
                     Modify=true;               // Íàçíà÷åí ê ìîäèôè.
                    }
                  break;                        // Âûõîä èç switch
               case 1 :                         // Îðäåð Sell
                  if (NormalizeDouble(SL,Digits)> // Åñëè âûøå æåëàåì.
                     NormalizeDouble(Ask+TS*Point,Digits)
                     || NormalizeDouble(SL,Digits)==0)//èëè ðàâíî íóëþ
                    {
                     SL=Ask+TS*Point;           // òî ìîäèôèöèðóåì åãî
                     Text="Sell ";              // Òåêñò äëÿ Sell 
                     Modify=true;               // Íàçíà÷åí ê ìîäèôè.
                    }
              }                                 // Êîíåö switch
            if (Modify==false)                  // Åñëè åãî íå ìîäèôè
               break;                           // Âûõîä èç while
            //--------------------------------------------------- 5 --
            double TP    =OrderTakeProfit();    // TP âûáðàííîãî îðä.
            double Price =OrderOpenPrice();     // Öåíà âûáðàíí. îðä.
            int    Ticket=OrderTicket();        // Íîìåð âûáðàíí. îðä.
 
            Alert ("Ìîäèôèêàöèÿ ",Text,Ticket,". Æä¸ì îòâåò..");
            bool Ans=OrderModify(Ticket,Price,SL,TP,0);//Ìîäèôè åãî!
            //--------------------------------------------------- 6 --
            if (Ans==true)                      // Ïîëó÷èëîñü :)
              {
               Alert ("Îðäåð ",Text,Ticket," ìîäèôèöèðîâàí:)");
               break;                           // Èç öèêëà ìîäèôè.
              }
            //--------------------------------------------------- 7 --
            int Error=GetLastError();           // Íå ïîëó÷èëîñü :(
            switch(Error)                       // Ïðåîäîëèìûå îøèáêè
              {
               case 130:Alert("Íåïðàâèëüíûå ñòîïû. Ïðîáóåì åù¸ ðàç.");
                  RefreshRates();               // Îáíîâèì äàííûå
                  continue;                     // Íà ñëåä. èòåðàöèþ
               case 136:Alert("Íåò öåí. Æä¸ì íîâûé òèê..");
                  while(RefreshRates()==false)  // Äî íîâîãî òèêà
                     Sleep(1);                  // Çàäåðæêà â öèêëå
                  continue;                     // Íà ñëåä. èòåðàöèþ
               case 146:Alert("Ïîäñèñòåìà òîðãîâ çàíÿòà.Ïðîáóåì åù¸");
                  Sleep(500);                   // Ïðîñòîå ðåøåíèå
                  RefreshRates();               // Îáíîâèì äàííûå
                  continue;                     // Íà ñëåä. èòåðàöèþ
                  // Êðèòè÷åñêèå îøèáêè
               case 2 : Alert("Îáùàÿ îøèáêà.");
                  break;                        // Âûõîä èç switch
               case 5 : Alert("Ñòàðàÿ âåðñèÿ êëèåíòñêîãî òåðìèíàëà.");
                  break;                        // Âûõîä èç switch
               case 64: Alert("Ñ÷åò çàáëîêèðîâàí.");
                  break;                        // Âûõîä èç switch
               case 133:Alert("Òîðãîâëÿ çàïðåùåíà");
                  break;                        // Âûõîä èç switch
               default: Alert("Âîçíèêëà îøèáêà ",Error);//Äð. îøèáêè
              }
            break;                              // Èç öèêëà ìîäèôè.
           }                                    // Êîíåö öèêëà ìîäèôè.
         //------------------------------------------------------ 8 --
        }                                       // Êîíåö àíàëèçà îðä.
     }                                          // Êîíåö ïåðåáîðà îðä.
//--------------------------------------------------------------- 9 --
   return;                                      // Âûõîä èç start()
  }

//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) 
   CheckForOpen();
   CheckForClose();
   CheckForOrderModify();
//----
  }
//+------------------------------------------------------------------+

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 ---