Signal Multicurrency

Author: Copyright © 2021, Aleksandr Klapatyuk
Price Data Components
Miscellaneous
It plays sound alerts
0 Views
0 Downloads
0 Favorites
Signal Multicurrency
ÿþ//+------------------------------------------------------------------+

//|                                          Many currency pairs.mq5 |

//|                   Copyright 2009-2017, MetaQuotes Software Corp. |

//|                                              http://www.mql5.com |

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

#property copyright   "Copyright © 2021, Aleksandr Klapatyuk"

#property link        "https://www.mql5.com/ru/users/sanalex"

#property version     "1.00"

#property description "Copyright © 2021, Vladimir Karputov"

#property description "http://wmua.ru/slesar/"

#property description "Copyright © 2021, SEM "

#property description "https://www.mql5.com/ru/users/seliveru"

//---

#define MACD_MAGIC  0

//---

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>

#include <Trade\PositionInfo.mqh>

#include <Trade\AccountInfo.mqh>

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

//| ENUM_LOT_RISK                                                    |

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

enum LotMax

  {

   Lots=0,  // Lots

   Risk=1,  // Risk

  };

//---

sinput group "----------------- Balans Parameters ----------------------------------------------"

input double   InpTargetProfit    = 1000000;             // Balance + Profit(add to balance)

input double   InpTargetLoss      = 0;                   // Balance - Loss(subtract from the balance)

sinput group "----------------- CLOSE: ALL: ----------------------------------------------------"

input double   InpTProfitAll      = 40000;               // ALL Take Profit --> (In currency the amount)

input double   InpSLossAll        = 1000000;             // ALL Stop Loss --> (In currency the amount)

sinput group "----------------- ALL:>SELL:ALL:>BUY ---------------------------------------------"

input double   InpTProfitSB       = 40000;               // Take Profit ALL>SELL:ALL>BUY --> (In currency the amount)

input double   InpSLossSB         = 1000000;             // Stop Loss ALL>SELL:ALL>BUY --> (In currency the amount)

sinput group "----------------- TP:SL: Position ------------------------------------------------"

input double   InpTakeProfit      = 40000;               // Take Profit Position (In currency the amount)

input double   InpStopLoss        = 1000000;             // Stop Loss Position (In currency the amount)

sinput group "----------------- Time: 1 :Start Stop --------------------------------------------"

input datetime InpHoursFrom1      = D'1970.01.02';       // 1 Time: Start

input datetime InpHoursTo1        = D'1970.01.01';       // Time: Stop

input datetime InpHoursFrom2      = D'1970.01.01';       // 2 Time: Start

sinput group "----------------- Time: 2 :Start Stop --------------------------------------------"

input datetime InpHoursFrom       = D'1970.01.01 00:01'; // Start (Only time)

input datetime InpHoursTo         = D'1970.01.01 23:59'; // Stop (Only time)

input bool     InpCloseAll        = false;               // CloseAll (Time: Start)

sinput group "----------------- Risk in percentage ---------------------------------------------"

input LotMax   InpLotRisk         = Risk;                // Lots - Risk

input double   InpMaximumRisk     = 0.1;                 // Maximum Risk in percentage

sinput group "----------------- NAME: Indicators -----------------------------------------------"

input bool     InpIndicator_Start = false;               // Start Indicators

input string   InpFastEMA         = "Key_Reversal";      // Name Indicators

sinput group "----------------- Revers: Parameters ---------------------------------------------"

input bool     InpClosPos         = true;                // Close Position

input bool     InpRevers          = true;                // Revers

//---

string symb_name[]= {"EURCHF","USDCHF","EURAUD","EURGBP","CADJPY","GBPNZD","NZDUSD","GBPAUD","GBPCAD"};

double m_macd_current[]= {0,1,2,3,4,5,6,7,8};

double m_signal_current[]= {0,1,2,3,4,5,6,7,8};

int    m_handle_macd[]= {0,1,2,3,4,5,6,7,8};

string m_name[]= {"Buy","Sell","=","CloseBuy","CloseSell","= =","CLOSE_ALL"};

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

//| MACD Sample expert class                                         |

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

class CSampleExpert

  {

protected:

   double            m_adjusted_point;             // point value adjusted for 3 or 5 points

   CTrade            m_trade;                      // trading object

   CSymbolInfo       m_symbol;                     // symbol info object

   CPositionInfo     m_position;                   // trade position object

   CAccountInfo      m_account;                    // account info wrapper

   //--- indicator buffers

   double            m_buff_MACD_main[];           // MACD indicator main buffer

   double            m_buff_MACD_signal[];         // MACD indicator signal buffer

   int               pairs;

   datetime          timeopen;

   datetime          HoursTo2;



public:

                     CSampleExpert(void);

                    ~CSampleExpert(void);

   bool              Init(void);

   void              Deinit(void);

   bool              Processing(void);

   bool              Processing1(string symbol,int handle_macd,double macd_current,double signal_current);

   bool              iGetArray(const int handle,const int buffer,const int start_pos,

                               const int count,double &arr_buffer[]);

   bool              TimeStartStop(datetime HoursFrom,datetime HoursTo);

   bool              TimeClose(datetime HoursTo);



protected:

   bool              InitIndicators(void);

   bool              LongOpenedBuy(string symbol);

   bool              ShortOpenedSell(string symbol);

   bool              ButtonOnTick(string symbol);

   void              ButtonCreate(string name,int Xdist,int Ydist,int Xsize,int Ysize,int FONTSIZE=12);

   bool              RefreshRates(string symbol);

   void              FreezeStopsLevels(string symbol,double &freeze,double &stops);

   void              ClosePositions(string symbol,const ENUM_POSITION_TYPE pos_type);

   bool              CheckForCloseBuys(string symbol);

   bool              CheckForCloseSells(string symbol);

   void              ClosePosition(string symbol,const ENUM_POSITION_TYPE pos_type);

   void              CloseAll(void);

   void              CloseAllProfit(void);

   void              CloseAllLoss(void);

   void              ClosePosition(const string symbol);

   bool              InitTrade(const string symbol);

   bool              IsFillingTypeAllowed(string symbol,int fill_type);

   void              LongChartSymbol(void);

   void              ShortChartSymbol(void);

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

   //| Calculate optimal lot size                                       |

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

   double            TradeSizeOptimized(string symbol)

     {

      double price=0.0;

      double margin=0.0;

      //--- select lot size

      if(!SymbolInfoDouble(symbol,SYMBOL_ASK,price))

         return(0.0);

      if(!OrderCalcMargin(ORDER_TYPE_BUY,symbol,1.0,price,margin))

         return(0.0);

      if(margin<=0.0)

         return(0.0);

      double lot=InpMaximumRisk;

      double lotmargin=NormalizeDouble(AccountInfoDouble(ACCOUNT_MARGIN_FREE)*InpMaximumRisk/margin,2);

      switch(InpLotRisk)

        {

         case Lots:

            lot=InpMaximumRisk;

            break;

         case Risk:

            lot=lotmargin;

            break;

        }

      //--- normalize and check limits

      double stepvol=SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP);

      lot=stepvol*NormalizeDouble(lot/stepvol,0);

      double minvol=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MIN);

      if(lot<minvol)

         lot=minvol;

      double maxvol=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX);

      if(lot>maxvol)

         lot=maxvol;

      //--- return trading volume

      return(lot);

     }

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

  };

//--- global expert

CSampleExpert ExtExpert;

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

//| Constructor                                                      |

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

CSampleExpert::CSampleExpert(void) : m_adjusted_point(0),

   pairs(9),

   timeopen(0),

   HoursTo2(0)

  {

   ArraySetAsSeries(m_buff_MACD_main,true);

   ArraySetAsSeries(m_buff_MACD_signal,true);

  }

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

//| Destructor                                                       |

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

CSampleExpert::~CSampleExpert(void)

  {

  }

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

//| Initialization and checking for input parameters                 |

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

bool CSampleExpert::Init(void)

  {

//--- initialize common information

   for(int i=0; i<pairs; i++)

      m_symbol.Name(symb_name[i]);           // symbol

   m_trade.SetExpertMagicNumber(MACD_MAGIC); // magic

   m_trade.SetMarginMode();

   for(int i=0; i<pairs; i++)

      m_trade.SetTypeFillingBySymbol(symb_name[i]);

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

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

      digits_adjust=10;

   m_adjusted_point=m_symbol.Point()*digits_adjust;

//--- set default deviation for trading in adjusted points

   m_trade.SetDeviationInPoints(3*digits_adjust);

//---

   int u=15;

   for(int y=0; y<ArraySize(m_name); y++)

     {

      ButtonCreate(m_name[y],5,u,170,15,8);

      u=u+17;

     }

//---

   if(InpIndicator_Start)

      if(!InitIndicators())

         return(false);

//--- succeed

   return(true);

  }

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

//| Initialization of the indicators                                 |

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

bool CSampleExpert::InitIndicators(void)

  {

//--- create MACD indicator

   for(int i=0; i<pairs; i++)

      m_handle_macd[i]=iCustom(symb_name[i],0,InpFastEMA);

   for(int i=0; i<pairs; i++)

      if(m_handle_macd[i]==INVALID_HANDLE)

        {

         printf("Error creating MACD indicator, symb_name= %s : i= %d",symb_name[i],i);

         return(false);

        }

//--- succeed

   return(true);

  }

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

//| Check for long position opening                                  |

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

bool CSampleExpert::LongOpenedBuy(string symbol)

  {

   bool res=false;

   double price=0.0;

//--- check for long position (BUY) possibility

   price=SymbolInfoDouble(symbol,SYMBOL_ASK);

//--- check for free money

   if(m_account.FreeMarginCheck(symbol,ORDER_TYPE_BUY,TradeSizeOptimized(symbol),price)<0.0)

      printf("We have no money. Free Margin = %f",m_account.FreeMargin());

   else

     {

      //--- open position

      if(m_trade.PositionOpen(symbol,ORDER_TYPE_BUY,TradeSizeOptimized(symbol),price,0.0,0.0))

         printf("Position by %s to be opened",symbol);

      else

        {

         printf("Error opening BUY position by %s : '%s'",symbol,m_trade.ResultComment());

         printf("Open parameters : price=%f",price);

        }

      PlaySound("ok.wav");

      //--- in any case we must exit from expert

      res=true;

     }

//--- result

   return(res);

  }

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

//| Check for short position opening                                 |

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

bool CSampleExpert::ShortOpenedSell(string symbol)

  {

   bool res=false;

   double price=0.0;

//--- check for short position (SELL) possibility

   price=SymbolInfoDouble(symbol,SYMBOL_BID);

//--- check for free money

   if(m_account.FreeMarginCheck(symbol,ORDER_TYPE_SELL,TradeSizeOptimized(symbol),price)<0.0)

      printf("We have no money. Free Margin = %f",m_account.FreeMargin());

   else

     {

      //--- open position

      if(m_trade.PositionOpen(symbol,ORDER_TYPE_SELL,TradeSizeOptimized(symbol),price,0.0,0.0))

         printf("Position by %s to be opened",symbol);

      else

        {

         printf("Error opening SELL position by %s : '%s'",symbol,m_trade.ResultComment());

         printf("Open parameters : price=%f",price);

        }

      PlaySound("ok.wav");

      //--- in any case we must exit from expert

      res=true;

     }

//--- result

   return(res);

  }

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

//| Get value of buffers                                             |

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

bool CSampleExpert::iGetArray(const int handle,const int buffer,const int start_pos,

                              const int count,double &arr_buffer[])

  {

   bool result=true;

   if(!ArrayIsDynamic(arr_buffer))

     {

      return(false);

     }

   ArrayFree(arr_buffer);

//--- reset error code

   ResetLastError();

//--- fill a part of the iBands array with values from the indicator buffer

   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);

   if(copied!=count)

     {

      return(false);

     }

   return(result);

  }

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

//| main function returns true if any position processed             |

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

bool CSampleExpert::Processing(void)

  {

//--- stores the current bar opening time

   static datetime timebar=0;

   datetime times[]= {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

//--- refresh rates

   for(int i=0; i<pairs; i++)

      if(!RefreshRates(symb_name[i]))

         return(false);

//---

   for(int i=0; i<pairs; i++)

      ButtonOnTick(symb_name[i]);

//--- get the current bar opening time

   for(int i=0; i<pairs; i++)

      times[i]=iTime(symb_name[i],0,0);

   for(int i=0; i<pairs; i++)

      if(times[i]==timebar)

         return(false);

   for(int i=0; i<pairs; i++)

      timebar=times[i];

//---

   MqlDateTime currTime;

   TimeLocal(currTime);

   datetime hour0 = TimeLocal(currTime);

   if((InpHoursFrom1<InpHoursTo1 && hour0>=InpHoursFrom1 && hour0<InpHoursTo1)  ||

      (InpHoursFrom1>InpHoursTo1 && (hour0<InpHoursTo1 || hour0>=InpHoursFrom1))||

      (InpHoursFrom2<HoursTo2 && hour0>=InpHoursFrom2 && hour0<HoursTo2)  ||

      (InpHoursFrom2>HoursTo2 && (hour0<HoursTo2 || hour0>=InpHoursFrom2)))

     {

      if(InpCloseAll && TimeClose(InpHoursTo))

        {

         CloseAll();

        }

      if(TimeStartStop(InpHoursFrom,InpHoursTo))

        {

         if(InpIndicator_Start)

            for(int i=0; i<pairs; i++)

               Processing1(symb_name[i],m_handle_macd[i],m_macd_current[i],m_signal_current[i]);

        }

     }

//--- exit without position processing

   return(false);

  }

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

//| main function returns true if any position processed             |

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

bool CSampleExpert::Processing1(string symbol,int handle_macd,double macd_current,double signal_current)

  {

   if(iTime(symbol,0,0)==timeopen)

      return(true);

//--- refresh indicators

   if(!iGetArray(handle_macd,0,1,2,m_buff_MACD_main) ||

      !iGetArray(handle_macd,1,1,2,m_buff_MACD_signal))

     {

      return(false);

     }

//--- data are put into internal variables

   macd_current      =m_buff_MACD_main[0];

   signal_current    =m_buff_MACD_signal[0];

//--- check for long position (BUY) possibility

   if(macd_current<signal_current)

     {

      if(!InpRevers)

        {

         if(InpClosPos)

            ClosePosition(symbol,POSITION_TYPE_SELL);

         //--- check for long position (BUY) possibility

         if(LongOpenedBuy(symbol))

            return(true);

        }

      if(InpRevers)

        {

         if(InpClosPos)

            ClosePosition(symbol,POSITION_TYPE_BUY);

         //--- check for short position (SELL) possibility

         if(ShortOpenedSell(symbol))

            return(true);

        }

     }

//--- check for short position (SELL) possibility

   if(macd_current>signal_current)

     {

      if(!InpRevers)

        {

         if(InpClosPos)

            ClosePosition(symbol,POSITION_TYPE_BUY);

         //--- check for short position (SELL) possibility

         if(ShortOpenedSell(symbol))

            return(true);

        }

      if(InpRevers)

        {

         if(InpClosPos)

            ClosePosition(symbol,POSITION_TYPE_SELL);

         //--- check for long position (BUY) possibility

         if(LongOpenedBuy(symbol))

            return(true);

        }

     }

//--- exit without position processing

   return(false);

  }

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

//| Expert tick function                                             |

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

bool CSampleExpert::TimeStartStop(datetime HoursFrom,datetime HoursTo)

  {

//---

   MqlDateTime currTime;

   TimeToStruct(TimeLocal(),currTime);

   long hour0=currTime.hour*60*60+currTime.min*60+currTime.sec;

   if((HoursFrom<HoursTo && hour0>=HoursFrom && hour0<HoursTo) ||

      (HoursFrom>HoursTo && (hour0<HoursTo || hour0>=HoursFrom)))

      return(true);

   return(false);

  }

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

//| Expert tick function                                             |

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

bool CSampleExpert::TimeClose(datetime HoursTo)

  {

//---

   MqlDateTime currTime;

   TimeToStruct(TimeLocal(),currTime);

   long hour0=currTime.hour*60*60+currTime.min*60+currTime.sec;

   if(hour0<HoursTo)

      return(false);

   if(hour0>HoursTo+1*30)

      return(false);

   return(true);

  }

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

//| Script program start function                                    |

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

void CSampleExpert::LongChartSymbol(void)

  {

   long currChart,prevChart=ChartFirst();

   int i=0,limit=100;

   Print("ChartFirst = ",ChartSymbol(prevChart)," ID = ",prevChart);

   while(i<limit)

     {

      currChart=ChartNext(prevChart);

      if(LongOpenedBuy(ChartSymbol(prevChart)))

         if(currChart<0)

            break;

      Print(i,ChartSymbol(currChart)," ID =",currChart);

      prevChart=currChart;

      i++;

     }

  }

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

//| Script program start function                                    |

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

void CSampleExpert::ShortChartSymbol(void)

  {

   long currChart,prevChart=ChartFirst();

   int i=0,limit=100;

   Print("ChartFirst = ",ChartSymbol(prevChart)," ID = ",prevChart);

   while(i<limit)

     {

      currChart=ChartNext(prevChart);

      if(ShortOpenedSell(ChartSymbol(prevChart)))

         if(currChart<0)

            break;

      Print(i,ChartSymbol(currChart)," ID =",currChart);

      prevChart=currChart;

      i++;

     }

  }

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

//| Expert initialization function                                   |

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

int OnInit(void)

  {

//--- create all necessary objects

   if(!ExtExpert.Init())

      return(INIT_FAILED);

//--- secceed

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

   for(int y=0; y<ArraySize(m_name); y++)

     {

      ObjectDelete(0,Symbol()+m_name[y]);

     }

//---

  }

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

//| Expert new tick handling function                                |

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

void OnTick(void)

  {

   ExtExpert.Processing();

  }

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

//| Check for close position conditions                              |

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

bool CSampleExpert::CheckForCloseBuys(string symbol)

  {

   bool res=false;

//--- should it be closed?

   ClosePositions(symbol,POSITION_TYPE_BUY);

//--- processed and cannot be modified

   res=true;

//--- result

   return(res);

  }

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

//| Check for close position conditions                              |

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

bool CSampleExpert::CheckForCloseSells(string symbol)

  {

   bool res=false;

//--- should it be closed?

   ClosePositions(symbol,POSITION_TYPE_SELL);

//--- processed and cannot be modified

   res=true;

//--- result

   return(res);

  }

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

//| Refreshes the symbol quotes data                                 |

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

bool CSampleExpert::RefreshRates(string symbol)

  {

//--- 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);

  }

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

//| Check Freeze and Stops levels                                    |

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

void CSampleExpert::FreezeStopsLevels(string symbol,double &freeze,double &stops)

  {

//--- check Freeze and Stops levels

   double coeff=(double)1;

   if(!RefreshRates(symbol) || !m_symbol.Refresh())

      return;

//--- FreezeLevel -> for pending order and modification

   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();

   if(freeze_level==0.0)

      if(1>0)

         freeze_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;

//--- StopsLevel -> for TakeProfit and StopLoss

   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();

   if(stop_level==0.0)

      if(1>0)

         stop_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;

//---

   freeze=freeze_level;

   stops=stop_level;

   return;

  }

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

//| Close positions                                                  |

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

void CSampleExpert::ClosePositions(string symbol,const ENUM_POSITION_TYPE pos_type)

  {

   double freeze=0.0,stops=0.0;

   FreezeStopsLevels(symbol,freeze,stops);

   int total=PositionsTotal();

   for(int i=total-1; i>=0; i--)

      if(m_position.SelectByIndex(i))

         if(m_position.Magic()==MACD_MAGIC)

            if(m_position.PositionType()==pos_type)

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                 {

                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=freeze) || m_position.TakeProfit()==0.0);

                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=freeze) || m_position.StopLoss()==0.0);

                  if(take_profit_level && stop_loss_level)

                     if(!m_trade.PositionClose(m_position.Ticket()))

                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());

                 }

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                 {

                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=freeze) || m_position.TakeProfit()==0.0);

                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=freeze) || m_position.StopLoss()==0.0);

                  if(take_profit_level && stop_loss_level)

                     if(!m_trade.PositionClose(m_position.Ticket()))

                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());

                 }

               PlaySound("ok.wav");

              }

  }

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

//| Close positions                                                  |

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

void CSampleExpert::ClosePosition(string symbol,const ENUM_POSITION_TYPE pos_type)

  {

   double freeze=0.0,stops=0.0;

   FreezeStopsLevels(symbol,freeze,stops);

   int total=PositionsTotal();

   for(int i=total-1; i>=0; i--)

      if(m_position.SelectByIndex(i))

         if(m_position.Symbol()==symbol && m_position.Magic()==MACD_MAGIC)

            if(m_position.PositionType()==pos_type)

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                 {

                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=freeze) || m_position.TakeProfit()==0.0);

                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=freeze) || m_position.StopLoss()==0.0);

                  if(take_profit_level && stop_loss_level)

                     if(!m_trade.PositionClose(m_position.Ticket()))

                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());

                 }

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                 {

                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=freeze) || m_position.TakeProfit()==0.0);

                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=freeze) || m_position.StopLoss()==0.0);

                  if(take_profit_level && stop_loss_level)

                     if(!m_trade.PositionClose(m_position.Ticket()))

                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());

                 }

               PlaySound("ok.wav");

              }

  }

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

//| start function                                                   |

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

void CSampleExpert::CloseAll(void)

  {

   int total=PositionsTotal();

   for(int i=total-1; i>=0; i--)

      if(m_position.SelectByIndex(i))

        {

         ClosePosition(m_position.Symbol());

        }

  }

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

//| start function                                                   |

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

void CSampleExpert::CloseAllProfit(void)

  {

   int total=PositionsTotal();

   for(int i=total-1; i>=0; i--)

      if(m_position.SelectByIndex(i))

        {

         if(m_position.Commission()+m_position.Swap()+m_position.Profit()>=InpTakeProfit)

            ClosePosition(m_position.Symbol());

        }

  }

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

//| start function                                                   |

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

void CSampleExpert::CloseAllLoss(void)

  {

   int total=PositionsTotal();

   for(int i=total-1; i>=0; i--)

      if(m_position.SelectByIndex(i))

        {

         if(m_position.Commission()+m_position.Swap()+m_position.Profit()<=-InpStopLoss)

            ClosePosition(m_position.Symbol());

        }

  }

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

//| Close selected position                                          |

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

void CSampleExpert::ClosePosition(const string symbol)

  {

   if(InitTrade(symbol))

      m_trade.PositionClose(m_position.Ticket());

   PlaySound("ok.wav");

  }

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

//| Init trade object                                                |

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

bool CSampleExpert::InitTrade(const string symbol)

  {

   if(!m_symbol.Name(symbol))

      return(false);

//---

   if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_FOK))

      m_trade.SetTypeFilling(ORDER_FILLING_FOK);

   else

      if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_IOC))

         m_trade.SetTypeFilling(ORDER_FILLING_IOC);

      else

         m_trade.SetTypeFilling(ORDER_FILLING_RETURN);

//---

   return(true);

//---

  }

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

//| Checks if the specified filling mode is allowed                  |

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

bool CSampleExpert::IsFillingTypeAllowed(string symbol,int fill_type)

  {

//--- Obtain the value of the property that describes allowed filling modes

   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);

//--- Return true, if mode fill_type is allowed

   return((filling & fill_type)==fill_type);

  }

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

//|                                                                  |

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

void CSampleExpert::ButtonCreate(string name,int Xdist,int Ydist,int Xsize,int Ysize,int FONTSIZE=12)

  {

   if(ObjectFind(0,Symbol()+name)<0)

      ObjectCreate(0,Symbol()+name,OBJ_BUTTON,0,100,100);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_COLOR,clrWhite);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_BGCOLOR,clrDimGray);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_XDISTANCE,Xdist);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_YDISTANCE,Ydist);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_XSIZE,Xsize);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_YSIZE,Ysize);

   ObjectSetString(0,Symbol()+name,OBJPROP_FONT,"Sans Serif");

   ObjectSetString(0,Symbol()+name,OBJPROP_TEXT,name);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_FONTSIZE,FONTSIZE);

   ObjectSetInteger(0,Symbol()+name,OBJPROP_SELECTABLE,false);

  }

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

//| ButtonOnTick                                                     |

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

bool CSampleExpert::ButtonOnTick(string symbol)

  {

   bool res=false;

//---

   CloseAllLoss();

   CloseAllProfit();

//---

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

   double PROFIT_CLOSE=0.00;

   double PROFIT_EQUITY=0.00;

   double PROFIT_BUY_Lot=0.00;

   double PROFIT_SELL_Lot=0.00;

//---

   int total=PositionsTotal();

   for(int i=total-1; i>=0; i--)

      if(m_position.SelectByIndex(i))

         if(symbol==symbol)

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

               PROFIT_BUY_Lot=PROFIT_BUY_Lot+PositionGetDouble(POSITION_VOLUME);

              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)

              {

               PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

               PROFIT_SELL_Lot=PROFIT_SELL_Lot+PositionGetDouble(POSITION_VOLUME);

              }

            PROFIT_CLOSE=AccountInfoDouble(ACCOUNT_PROFIT);

           }

   PROFIT_EQUITY=AccountInfoDouble(ACCOUNT_EQUITY);

//---

   if(PROFIT_EQUITY<=InpTargetLoss || PROFIT_EQUITY>=InpTargetProfit)

     {

      if(!CheckForCloseBuys(symbol))

         return(true);

      if(!CheckForCloseSells(symbol))

         return(true);

      CloseAll();

      ExpertRemove();

      PlaySound("expert.wav");

     }

//---

   if(PROFIT_CLOSE<=-InpSLossAll || PROFIT_CLOSE>=InpTProfitAll)

     {

      if(!CheckForCloseBuys(symbol))

         return(true);

      if(!CheckForCloseSells(symbol))

         return(true);

      CloseAll();

      PlaySound("request.wav");

     }

//---

   if(PROFIT_BUY<=-InpSLossSB || PROFIT_BUY>=InpTProfitSB)

     {

      if(!CheckForCloseBuys(symbol))

         return(true);

      PlaySound("request.wav");

     }

//---

   if(PROFIT_SELL<=-InpSLossSB || PROFIT_SELL>=InpTProfitSB)

     {

      if(!CheckForCloseSells(symbol))

         return(true);

      PlaySound("request.wav");

     }

//---

   if(ObjectGetInteger(0,Symbol()+"Buy",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,Symbol()+"Buy",OBJPROP_STATE,0);

      //--- check for long position (BUY) possibility

      if(!InpIndicator_Start)

         LongChartSymbol();

      else

         if(!LongOpenedBuy(symbol))

            return(true);

     }

   if(ObjectGetInteger(0,Symbol()+"CloseBuy",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,Symbol()+"CloseBuy",OBJPROP_STATE,0);

      if(!CheckForCloseBuys(symbol))

         return(true);

     }

   if(ObjectGetInteger(0,Symbol()+"Sell",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,Symbol()+"Sell",OBJPROP_STATE,0);

      //--- check for short position (SELL) possibility

      if(!InpIndicator_Start)

         ShortChartSymbol();

      else

         if(!ShortOpenedSell(symbol))

            return(true);

     }

   if(ObjectGetInteger(0,Symbol()+"CloseSell",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,Symbol()+"CloseSell",OBJPROP_STATE,0);

      if(!CheckForCloseSells(symbol))

         return(true);

     }

   if(ObjectGetInteger(0,Symbol()+"CLOSE_ALL",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,Symbol()+"CLOSE_ALL",OBJPROP_STATE,0);

      if(!CheckForCloseBuys(symbol))

         return(true);

      if(!CheckForCloseSells(symbol))

         return(true);

      CloseAll();

     }

//---

   ObjectSetString(0,Symbol()+"Buy",OBJPROP_TEXT,"BUY = Lot ("+DoubleToString(PROFIT_BUY_Lot,2)+")");

   if(PROFIT_BUY_Lot>0)

     {

      ObjectSetInteger(0,Symbol()+"Buy",OBJPROP_BGCOLOR,clrDarkSlateGray);

     }

   else

      if(PROFIT_BUY_Lot==0)

        {

         ObjectSetInteger(0,Symbol()+"Buy",OBJPROP_BGCOLOR,clrDimGray);

        }

//---

   ObjectSetString(0,Symbol()+"CloseBuy",OBJPROP_TEXT,"Close_Buy =("+DoubleToString(PROFIT_BUY,2)+")");

   if(PROFIT_BUY>0)

     {

      ObjectSetInteger(0,Symbol()+"CloseBuy",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_BUY==0)

        {

         ObjectSetInteger(0,Symbol()+"CloseBuy",OBJPROP_BGCOLOR,clrDimGray);

        }

      else

        {

         ObjectSetInteger(0,Symbol()+"CloseBuy",OBJPROP_BGCOLOR,clrCrimson);

        }

//---

   ObjectSetString(0,Symbol()+"Sell",OBJPROP_TEXT,"SELL = Lot ("+DoubleToString(PROFIT_SELL_Lot,2)+")");

   if(PROFIT_SELL_Lot>0)

     {

      ObjectSetInteger(0,Symbol()+"Sell",OBJPROP_BGCOLOR,clrDarkSlateGray);

     }

   else

      if(PROFIT_SELL_Lot==0)

        {

         ObjectSetInteger(0,Symbol()+"Sell",OBJPROP_BGCOLOR,clrDimGray);

        }

//---

   ObjectSetString(0,Symbol()+"CloseSell",OBJPROP_TEXT,"Close_Sell =("+DoubleToString(PROFIT_SELL,2)+")");

   if(PROFIT_SELL>0)

     {

      ObjectSetInteger(0,Symbol()+"CloseSell",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_SELL==0)

        {

         ObjectSetInteger(0,Symbol()+"CloseSell",OBJPROP_BGCOLOR,clrDimGray);

        }

      else

        {

         ObjectSetInteger(0,Symbol()+"CloseSell",OBJPROP_BGCOLOR,clrCrimson);

        }

//---

   ObjectSetString(0,Symbol()+"CLOSE_ALL",OBJPROP_TEXT,"CLOSE_ALL =("+DoubleToString(PROFIT_CLOSE,2)+")"

                   +" :all="+DoubleToString(PositionsTotal(),0));

   if(PROFIT_CLOSE>0)

     {

      ObjectSetInteger(0,Symbol()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_CLOSE==0)

        {

         ObjectSetInteger(0,Symbol()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrDimGray);

        }

      else

        {

         ObjectSetInteger(0,Symbol()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrCrimson);

        }

//---

   return(res);

  }

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

Comments