MACD signal

Author: tom112
Price Data Components
Indicators Used
Indicator of the average true rangeMACD Histogram
0 Views
0 Downloads
0 Favorites
MACD signal
ÿþ//+------------------------------------------------------------------+

//|                         MACD signal(barabashkakvn's edition).mq5 |

//|                                                           tom112 |

//|                                            tom112@mail.wplus.net |

//+------------------------------------------------------------------+

#property copyright "tom112"

#property link "tom112@mail.wplus.net"

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Trade\AccountInfo.mqh>

#include <Trade\DealInfo.mqh>

#include <Trade\OrderInfo.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

CAccountInfo   m_account;                    // account info wrapper

CDealInfo      m_deal;                       // deals object

COrderInfo     m_order;                      // pending orders object

//---- input parameters

input ushort   InpTakeProfit=10;             // TakeProfit

input double   Lots=0.01;

input ushort   InpTrailingStop=25;

input int      Pfast = 9;

input int      Pslow = 15;

input int      Psignal=8;

input double   LEVEL=0.004;

//---

double         Points=0.0;

ulong          m_magic=16384;                // magic number

//---

double         ExtTakeProfit=0.0;

double         ExtTrailingStop=0.0;

int            handle_iATR;                  // variable for storing the handle of the iATR indicator 

int            handle_iMACD;                 // variable for storing the handle of the iMACD indicator 

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//SetMarginMode();

//if(!IsHedging())

//  {

//   Print("Hedging only!");

//   return(INIT_FAILED);

//  }

//---

   m_symbol.Name(Symbol());                  // sets symbol name

   if(!RefreshRates())

     {

      Print("Error RefreshRates. Bid=",DoubleToString(m_symbol.Bid(),Digits()),

            ", Ask=",DoubleToString(m_symbol.Ask(),Digits()));

      return(INIT_FAILED);

     }

   m_symbol.Refresh();

   m_trade.SetExpertMagicNumber(m_magic);    // sets magic number

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)

      digits_adjust=10;



   ExtTakeProfit     = InpTakeProfit   * digits_adjust;

   ExtTrailingStop   = InpTrailingStop * digits_adjust;

   Points            = m_symbol.Point();



// ?5@28G=K5 ?@>25@:8 40==KE

// 206=> C4>AB>25@8BLAO GB> M:A?5@B @01>B05B =0 =>@<0;L=>< 3@0D8:5 8

// ?>;L7>20B5;L ?@028;L=> 2KAB028; 2=5H=85 ?5@5<5==K5 (Lots, StopLoss,

// ExtTakeProfit, ExtTrailingStop)

// 2 =0H5< A;CG05 ?@>25@O5< B>;L:> ExtTakeProfit

   if(Bars(Symbol(),Period())<205)

     {

      Print("bars less than 205 (period of iATR)");

      return(INIT_FAILED); // =0 3@0D8:5 <5=55 205 10@>2

     }

   if(ExtTakeProfit<10)

     {

      Print("TakeProfit less than 10");

      return(INIT_FAILED); // ?@>25@O5< ExtTakeProfit

     }



//--- create handle of the indicator iATR

   handle_iATR=iATR(Symbol(),Period(),200);

//--- if the handle is not created 

   if(handle_iATR==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iATR indicator for the symbol %s/%s, error code %d",

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }



//--- create handle of the indicator iMACD

   handle_iMACD=iMACD(Symbol(),Period(),Pfast,Pslow,Psignal,PRICE_CLOSE);

//--- if the handle is not created 

   if(handle_iMACD==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iMACD indicator for the symbol %s/%s, error code %d",

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//---



  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

   double MacdCurrent=0,MacdPrevious=0,SignalCurrent=0;

   double SignalPrevious=0,MaCurrent=0,MaPrevious=0;

   double Range,rr,Delta,Delta1;//val3;



   Range=iATRGet(1);

   rr=Range*LEVEL;

   Delta=iMACDGet(MAIN_LINE,0)-iMACDGet(SIGNAL_LINE,0);

   Delta1=iMACDGet(MAIN_LINE,1)-iMACDGet(SIGNAL_LINE,1);

// B5?5@L =04> >?@545;8BLAO - 2 :0:>< A>AB>O=88 B>@3>2K9 B5@<8=0;?

// ?@>25@8<, 5ABL ;8 @0=55 >B:@KBK5 ?>78F88 8;8 >@45@K?

   if(TotalPositions()<1)

     {

      // =5B =8 >4=>3> >B:@KB>3> >@45@0

      // =0 2AO:89 A;CG09 ?@>25@8<, 5A;8 C =0A A2>1>4=K5 45=L38 =0 AG5BC?

      // 7=0G5=85 1000 27OB> 4;O ?@8<5@0, >1KG=> <>6=> >B:@KBL 1 ;>B

      if(m_account.FreeMargin()<(1000*Lots))

        {

         Print("We have no money");

         return; // 45=53 =5B - 2KE>48<

        }

      // ?@>25@8<, =5 A;8H:>< ;8 G0AB> ?KB05<AO >B:@KBLAO?

      // 5A;8 ?>A;54=89 @07 B>@3>20;8 <5=55 G5< 5 <8=CB(5*60=300 A5:)

      // =0704, B> 2KE>48<

      // If((CurTime-LastTradeTime)<300) return(0);

      // ?@>25@O5< =0 2>7<>6=>ABL 2AB0BL 2 4;8==CN ?>78F8N (BUY)

      if(Delta>rr && Delta1<rr)

        {

         if(!RefreshRates())

            return;



         if(m_trade.Buy(Lots,Symbol(),m_symbol.Ask(),0,

            m_symbol.NormalizePrice(m_symbol.Ask()+ExtTakeProfit*Points),"macd signal")) // 8A?>;=O5<

            Print("Positions opened : ",m_trade.ResultPrice());

         else

            Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),

                  ", description of result: ",m_trade.ResultRetcodeDescription(),

                  ", ticket of deal: ",m_trade.ResultDeal());

         //--- 2KE>48<, B0: :0: 2A5 @02=> ?>A;5 A>25@H5=8O B>@3>2>9 >?5@0F88

         //--- =0ABC?8; 10-B8 A5:C=4=K9 B09<0CB =0 A>25@H5=85 B>@3>2KE >?5@0F89

         return;

        }

      // ?@>25@O5< =0 2>7<>6=>ABL 2AB0BL 2 :>@>B:CN ?>78F8N (SELL)

      if(Delta<-rr && Delta1>-rr)

        {

         if(!RefreshRates())

            return;



         if(m_trade.Sell(Lots,Symbol(),m_symbol.Bid(),0,

            m_symbol.NormalizePrice(m_symbol.Bid()-ExtTakeProfit*Points),"macd sample")) // 8A?>;=O5<

            Print("Order opened : ",m_trade.ResultPrice());

         else

            Print("Sell -> false. Result Retcode: ",m_trade.ResultRetcode(),

                  ", description of result: ",m_trade.ResultRetcodeDescription(),

                  ", ticket of deal: ",m_trade.ResultDeal());

         return; // 2KE>48<

        }

      //--- 745AL <K 7025@H8;8 ?@>25@:C =0 2>7<>6=>ABL >B:@KB8O =>2KE ?>78F89.

      //--- =>2K5 ?>78F88 >B:@KBK =5 1K;8 8 ?@>AB> 2KE>48< ?> Exit, B0: :0:

      //--- 2A5 @02=> 0=0;878@>20BL =5G53>

      return;

     }

//--- ?5@5E>48< : 206=>9 G0AB8 M:A?5@B0 - :>=B@>;N >B:@KBKE ?>78F89

//--- '206=> ?@028;L=> 2>9B8 2 @K=>:, => 2K9B8 - 5I5 206=55...'

   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions

      if(m_position.SelectByIndex(i)) // 2K18@05< ?>78F8N ?> 8=45:AC

         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic) // 5A;8 A8<2>; 8 <038: A>2?040NB

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY) // >B:@KB0 4;8==0O ?>78F8O

              {

               //--- ?@>25@8<, <>65B C65 ?>@0 70:@K20BLAO?

               if(Delta<0)

                 {

                  //--- 70:@K205< ?>78F8N

                  m_trade.PositionClose(m_position.Ticket());

                  return; // 2KE>48<

                 }

               //--- ?@>25@8< - <>65B <>6=>/=C6=> C65 B@59;8=3 AB>? AB028BL?

               if(ExtTrailingStop>0) // ?>;L7>20B5;L 2KAB028; 2 =0AB@>9:0E B@59;8=3AB>?

                 { // 7=0G8B <K 845< 53> ?@>25@OBL

                  if(!RefreshRates())

                     return;



                  if(m_symbol.Bid()-m_position.PriceOpen()>Points*ExtTrailingStop)

                    {

                     if(m_position.StopLoss()<m_symbol.Bid()-Points*ExtTrailingStop)

                       {

                        m_trade.PositionModify(m_position.Ticket(),

                                               m_symbol.Bid()-Points*ExtTrailingStop,

                                               m_position.TakeProfit());

                        return;

                       }

                    }

                 }

              }

            else // 8=0G5 MB> :>@>B:0O ?>78F8O

              {

               //--- ?@>25@8<, <>65B C65 ?>@0 70:@K20BLAO?

               if(Delta>0)

                 {

                  //--- 70:@K205< ?>78F8N

                  m_trade.PositionClose(m_position.Ticket());

                  return; // 2KE>48<

                 }

               //--- ?@>25@8< - <>65B <>6=>/=C6=> C65 B@59;8=3 AB>? AB028BL?

               if(ExtTrailingStop>0) // ?>;L7>20B5;L 2KAB028; 2 =0AB@>9:0E B@59;8=3AB>?

                 { // 7=0G8B <K 845< 53> ?@>25@OBL

                  if(!RefreshRates())

                     return;



                  if((m_position.PriceOpen()-m_symbol.Ask())>(Points*ExtTrailingStop))

                    {

                     if(m_position.StopLoss()==0.0 || m_position.StopLoss()>

                        (m_symbol.Ask()+Points*ExtTrailingStop))

                       {

                        m_trade.PositionModify(m_position.Ticket(),

                                               m_symbol.Ask()+Points*ExtTrailingStop,

                                               m_position.TakeProfit());

                        return;

                       }

                    }

                 }

              }

           }

   return;

  }

//+------------------------------------------------------------------+

//| Refreshes the symbol quotes data                                 |

//+------------------------------------------------------------------+

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

      return(false);

//--- protection against the return value of "zero"

   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)

      return(false);

//---

   return(true);

  }

//+------------------------------------------------------------------+

//| Get value of buffers for the iATR                                |

//+------------------------------------------------------------------+

double iATRGet(const int index)

  {

   double ATR[];

   ArraySetAsSeries(ATR,true);

//--- reset error code 

   ResetLastError();

//--- fill a part of the iATR array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iATR,0,0,index+1,ATR)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iATR indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(ATR[index]);

  }

//+------------------------------------------------------------------+

//| Get value of buffers for the iMACD                               |

//|  the buffer numbers are the following:                           |

//|   0 - MAIN_LINE, 1 - SIGNAL_LINE                                 |

//+------------------------------------------------------------------+

double iMACDGet(const int buffer,const int index)

  {

   double MACD[];

   ArraySetAsSeries(MACD,true);

//--- reset error code 

   ResetLastError();

//--- fill a part of the iMACDBuffer array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iMACD,buffer,0,index+1,MACD)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iMACD indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(MACD[index]);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int TotalPositions()

  {

   int total=0;

   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions

      if(m_position.SelectByIndex(i))

         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)

            total++;

   return(total);

  }

//+------------------------------------------------------------------+

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