Fibo Grider

Author: Copyright © 2018, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
Orders Execution
Checks for the total of open orders
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Fibo Grider
ÿþ//+------------------------------------------------------------------+

//|                                                  Fibo Grider.mq5 |

//|                              Copyright © 2018, Vladimir Karputov |

//|                                           http://wmua.ru/slesar/ |

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

#property copyright "Copyright © 2018, Vladimir Karputov"

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

#property version   "1.000"

//---

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Trade\AccountInfo.mqh>

#include <Trade\DealInfo.mqh>

#include <Trade\OrderInfo.mqh>

#include <Expert\Money\MoneyFixedMargin.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade_0;                    // trading object

CTrade         m_trade_1;                    // trading object

CTrade         m_trade_2;                    // trading object

CSymbolInfo    m_symbol_0;                   // symbol info object

CSymbolInfo    m_symbol_1;                   // symbol info object

CSymbolInfo    m_symbol_2;                   // symbol info object

CAccountInfo   m_account;                    // account info wrapper

CDealInfo      m_deal;                       // deals object

COrderInfo     m_order;                      // pending orders object

//--- input parameters

/*

input ushort   InpStopLoss       = 30;       // Stop Loss, in pips (1.00045-1.00055=1 pips)

input ushort   InpTakeProfit     = 90;       // Take Profit, in pips (1.00045-1.00055=1 pips)

input ushort   InpTrailingStop   = 30;       // Trailing Stop (min distance from price to Stop Loss, in pips

input ushort   InpTrailingStep   = 5;        // Trailing Step, in pips (1.00045-1.00055=1 pips)*/

input uchar    InpCountLotsMin_0 = 6;        // Symbol 0: amount minimum lots

input uchar    InpStartTime_0    = 13;       // Symbol 0: start time

input double   InpMinProfit_0    = 90;       // Symbol 0: minimum profit

input double   InpMaxLoss_0      = -90;      // Symbol 0: maximum loss

input string   InpSymbol_1       = "USDJPY"; // Symbol 1 (Non-existent symbol -> parameter is disabled)

input uchar    InpCountLotsMin_1 = 6;        // Symbol 1: amount minimum lots

input uchar    InpStartTime_1    = 10;       // Symbol 1: start time

input double   InpMinProfit_1    = 90;       // Symbol 1: minimum profit

input double   InpMaxLoss_1      = -90;      // Symbol 1: maximum loss

input string   InpSymbol_2       = "USDCAD"; // Symbol 2 (Non-existent symbol -> parameter is disabled)

input uchar    InpCountLotsMin_2 = 6;        // Symbol 2: amount minimum lots

input uchar    InpStartTime_2    = 8;        // Symbol 2: start time

input double   InpMinProfit_2    = 90;       // Symbol 2: minimum profit

input double   InpMaxLoss_2      = -90;      // Symbol 2: maximum loss

input bool     InpPrintLog       = false;    // Print log

input ulong    m_magic=227997032;            // magic number

//---

ulong  m_slippage=10;                        // slippage

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

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

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

bool   m_use_1                = false;

bool   m_use_2                = false;

datetime m_last_time_0=D'1970.01.01 00:00';

datetime m_last_time_1=D'1970.01.01 00:00';

datetime m_last_time_2=D'1970.01.01 00:00';

bool   m_need_open_buy_limit_0= false;

bool   m_need_open_buy_limit_1= false;

bool   m_need_open_buy_limit_2= false;

bool   m_need_delete_all_0    = false;

bool   m_need_delete_all_1    = false;

bool   m_need_delete_all_2    = false;

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

/*  if(InpTrailingStop!=0 && InpTrailingStep==0)

     {

      string err_text=(TerminalInfoString(TERMINAL_LANGUAGE)=="Russian")?

                      ""@59;8=3 =52>7<>65=: ?0@0<5B@ \"Trailing Step\" @025= =C;N!":

                      "Trailing is not possible: parameter \"Trailing Step\" is zero!";

      //--- when testing, we will only output to the log about incorrect input parameters

      if(MQLInfoInteger(MQL_TESTER))

        {

         Print(__FUNCTION__,", ERROR: ",err_text);

         return(INIT_FAILED);

        }

      else // if the Expert Advisor is run on the chart, tell the user about the error

        {

         Alert(__FUNCTION__,", ERROR: ",err_text);

         return(INIT_PARAMETERS_INCORRECT);

        }

     }*/

//---

   if(!m_symbol_0.Name(Symbol())) // sets symbol name

      return(INIT_FAILED);

   RefreshRates(m_symbol_0);



   if(!m_symbol_1.Name(InpSymbol_1)) // sets symbol name

      m_use_1=false;

   else

     {

      m_use_1=true;

      RefreshRates(m_symbol_1);

     }



   if(!m_symbol_2.Name(InpSymbol_2)) // sets symbol name

      m_use_2=false;

   else

     {

      m_use_2=true;

      RefreshRates(m_symbol_2);

     }

//---

   m_trade_0.SetExpertMagicNumber(m_magic);

   m_trade_0.SetMarginMode();

   m_trade_0.SetTypeFillingBySymbol(m_symbol_0.Name());

   m_trade_0.SetDeviationInPoints(m_slippage);



   if(m_use_1)

     {

      m_trade_1.SetExpertMagicNumber(m_magic+1);

      m_trade_1.SetMarginMode();

      m_trade_1.SetTypeFillingBySymbol(m_symbol_1.Name());

      m_trade_1.SetDeviationInPoints(m_slippage);

     }



   if(m_use_2)

     {

      m_trade_2.SetExpertMagicNumber(m_magic+2);

      m_trade_2.SetMarginMode();

      m_trade_2.SetTypeFillingBySymbol(m_symbol_2.Name());

      m_trade_2.SetDeviationInPoints(m_slippage);

     }

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

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

      digits_adjust=10;

   m_adjusted_point_0=m_symbol_0.Point()*digits_adjust;



   if(m_use_1)

     {

      digits_adjust=1;

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

         digits_adjust=10;

      m_adjusted_point_1=m_symbol_1.Point()*digits_adjust;

     }



   if(m_use_2)

     {

      digits_adjust=1;

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

         digits_adjust=10;

      m_adjusted_point_2=m_symbol_2.Point()*digits_adjust;

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   if(m_need_delete_all_0)

     {

      if(IsPendingOrdersExists(m_symbol_0,m_magic))

        {

         double level;

         if(FreezeStopsLevels(m_symbol_0,level))

            DeleteAllPendingOrders(m_trade_0,m_symbol_0,m_magic,level);

         return;

        }

      else

         m_need_delete_all_0=false;

     }



   if(m_need_delete_all_1)

     {

      if(IsPendingOrdersExists(m_symbol_1,m_magic+1))

        {

         double level;

         if(FreezeStopsLevels(m_symbol_1,level))

            DeleteAllPendingOrders(m_trade_1,m_symbol_1,m_magic+1,level);

         return;

        }

      else

         m_need_delete_all_1=false;

     }



   if(m_need_delete_all_2)

     {

      if(IsPendingOrdersExists(m_symbol_2,m_magic+2))

        {

         double level;

         if(FreezeStopsLevels(m_symbol_2,level))

            DeleteAllPendingOrders(m_trade_2,m_symbol_2,m_magic+2,level);

         return;

        }

      else

         m_need_delete_all_2=false;

     }

//---

   if(m_need_open_buy_limit_0)

     {

      int count_buy_limits=0;

      CalculateAllPendingOrders(m_symbol_0,m_magic,count_buy_limits);

      if(count_buy_limits==0)

        {

         double level;

         if(FreezeStopsLevels(m_symbol_0,level))

            PlaceOrders(m_trade_0,m_symbol_0,m_magic,ORDER_TYPE_BUY_LIMIT,level);

         return;

        }

      else

         m_need_open_buy_limit_0=false;

     }



   if(m_need_open_buy_limit_1)

     {

      int count_buy_limits=0;

      CalculateAllPendingOrders(m_symbol_1,m_magic+1,count_buy_limits);

      if(count_buy_limits==0)

        {

         double level;

         if(FreezeStopsLevels(m_symbol_1,level))

            PlaceOrders(m_trade_1,m_symbol_1,m_magic+1,ORDER_TYPE_BUY_LIMIT,level);

         return;

        }

      else

         m_need_open_buy_limit_1=false;

     }



   if(m_need_open_buy_limit_2)

     {

      int count_buy_limits=0;

      CalculateAllPendingOrders(m_symbol_2,m_magic+2,count_buy_limits);

      if(count_buy_limits==0)

        {

         double level;

         if(FreezeStopsLevels(m_symbol_2,level))

            PlaceOrders(m_trade_2,m_symbol_2,m_magic+2,ORDER_TYPE_BUY_LIMIT,level);

         return;

        }

      else

         m_need_open_buy_limit_2=false;

     }

//--- we work only at the time of the birth of new bar

   static datetime PrevBars=0;

   datetime time_0=iTime(m_symbol_0.Name(),PERIOD_M1,0);

   if(time_0==PrevBars)

      return;

   PrevBars=time_0;

   if(!RefreshRates(m_symbol_0))

     {

      PrevBars=0;

      return;

     }



   MqlDateTime STime;

   TimeToStruct(time_0,STime);



   double profit=0.0;

   if(CalculateAllPositions(m_symbol_0,m_magic,profit)>0)

     {

      if(profit>=InpMinProfit_0 || profit<=InpMaxLoss_0)

         CloseAllPositions(m_trade_0,m_symbol_0,m_magic);

     }

   if(STime.hour==InpStartTime_0 && !IsPendingOrdersExists(m_symbol_0,m_magic))

     {

      m_need_open_buy_limit_0=true;

     }



   if(m_use_1)

     {

      profit=0.0;

      if(CalculateAllPositions(m_symbol_1,m_magic+1,profit)>0)

        {

         if(profit>=InpMinProfit_1 || profit<=InpMaxLoss_1)

            CloseAllPositions(m_trade_1,m_symbol_1,m_magic+1);

        }

      if(STime.hour==InpStartTime_1 && !IsPendingOrdersExists(m_symbol_1,m_magic+1))

        {

         m_need_open_buy_limit_1=true;

        }

     }



   if(m_use_2)

     {

      profit=0.0;

      if(CalculateAllPositions(m_symbol_2,m_magic+2,profit)>0)

        {

         if(profit>=InpMinProfit_2 || profit<=InpMaxLoss_2)

            CloseAllPositions(m_trade_2,m_symbol_2,m_magic+2);

        }

      if(STime.hour==InpStartTime_2 && !IsPendingOrdersExists(m_symbol_2,m_magic+2))

        {

         m_need_open_buy_limit_2=true;

        }

     }

//---



  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {



//---

  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates(CSymbolInfo &m_symbol)

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      Print("RefreshRates error");

      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                                    |

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

bool FreezeStopsLevels(CSymbolInfo &m_symbol,double &level)

  {

//--- check Freeze and Stops levels

/*

   Type of order/position  |  Activation price  |  Check

   ------------------------|--------------------|--------------------------------------------

   Buy Limit order         |  Ask               |  Ask-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

   Buy Stop order          |  Ask	            |  OpenPrice-Ask  >= SYMBOL_TRADE_FREEZE_LEVEL

   Sell Limit order        |  Bid	            |  OpenPrice-Bid  >= SYMBOL_TRADE_FREEZE_LEVEL

   Sell Stop order	      |  Bid	            |  Bid-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

   Buy position            |  Bid	            |  TakeProfit-Bid >= SYMBOL_TRADE_FREEZE_LEVEL 

                           |                    |  Bid-StopLoss   >= SYMBOL_TRADE_FREEZE_LEVEL

   Sell position           |  Ask	            |  Ask-TakeProfit >= SYMBOL_TRADE_FREEZE_LEVEL

                           |                    |  StopLoss-Ask   >= SYMBOL_TRADE_FREEZE_LEVEL

                           

   Buying is done at the Ask price                 |  Selling is done at the Bid price

   ------------------------------------------------|----------------------------------

   TakeProfit        >= Bid                        |  TakeProfit        <= Ask

   StopLoss          <= Bid	                     |  StopLoss          >= Ask

   TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL

   Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL

*/

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

      return(false);

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

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

   if(freeze_level==0.0)

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

   freeze_level*=1.1;

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

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

   if(stop_level==0.0)

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

   stop_level*=1.1;



   if(freeze_level<=0.0 || stop_level<=0.0)

      return(false);



   level=(freeze_level>stop_level)?freeze_level:stop_level;

//---

   return(true);

  }

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

//| Place Orders                                                     |

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

void PlaceOrders(CTrade &m_trade,CSymbolInfo &m_symbol,const long magic,const ENUM_ORDER_TYPE order_type,const double level)

  {

   MqlRates rates_d1[];

   ArraySetAsSeries(rates_d1,true);

   if(CopyRates(m_symbol.Name(),PERIOD_D1,0,1,rates_d1)!=1)

      return;

//--- check Freeze and Stops levels

/*

   Type of order/position  |  Activation price  |  Check

   ------------------------|--------------------|--------------------------------------------

   Buy Limit order         |  Ask               |  Ask-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

   Buy Stop order          |  Ask	            |  OpenPrice-Ask  >= SYMBOL_TRADE_FREEZE_LEVEL

   Sell Limit order        |  Bid	            |  OpenPrice-Bid  >= SYMBOL_TRADE_FREEZE_LEVEL

   Sell Stop order	      |  Bid	            |  Bid-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

   Buy position            |  Bid	            |  TakeProfit-Bid >= SYMBOL_TRADE_FREEZE_LEVEL 

                           |                    |  Bid-StopLoss   >= SYMBOL_TRADE_FREEZE_LEVEL

   Sell position           |  Ask	            |  Ask-TakeProfit >= SYMBOL_TRADE_FREEZE_LEVEL

                           |                    |  StopLoss-Ask   >= SYMBOL_TRADE_FREEZE_LEVEL

                           

   Buying is done at the Ask price                 |  Selling is done at the Bid price

   ------------------------------------------------|----------------------------------

   TakeProfit        >= Bid                        |  TakeProfit        <= Ask

   StopLoss          <= Bid	                     |  StopLoss          >= Ask

   TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL

   Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL

*/

//--- buy limit

   if(order_type==ORDER_TYPE_BUY_LIMIT)

     {

      double array[6]={1.0,1.236,1.382,1.5,1.618,2.0};

      double start=rates_d1[0].high;

      double ext=rates_d1[0].high-rates_d1[0].low;

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

        {

         double price=start-(ext*(array[i]-1.0));

         if(m_symbol.Ask()-price>=level)

           {

            double lot=LotCheck(m_symbol,InpCountLotsMin_0*m_symbol.LotsMin()+(InpCountLotsMin_0*m_symbol.LotsMin()*(array[i]-1.0)));

            PendingOrder(m_trade,m_symbol,lot,magic,order_type,price,0.0,0.0/*,sl,tp*/);

           }

        }

/*

      if(price-m_symbol.Ask()<level) // check price

         price=m_symbol.Ask()+level;



      double sl=(InpStopLoss==0)?0.0:price-ExtStopLoss;

      if(sl!=0.0 && ExtStopLoss<level)// check sl

         sl=price-level;



      double tp=(InpTakeProfit==0)?0.0:price+ExtTakeProfit;

      if(tp!=0.0 && ExtTakeProfit<level) // check price

         tp=price+level;



      PendingOrder(CSymbolInfo &m_symbol,const long magic,order_type,price,sl,tp);*/

     }

  }

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

//| Pending order                                                    |

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

bool PendingOrder(CTrade &m_trade,CSymbolInfo &m_symbol,const double lot,const long magic,ENUM_ORDER_TYPE order_type,double price,double sl,double tp)

  {

   sl=m_symbol.NormalizePrice(sl);

   tp=m_symbol.NormalizePrice(tp);

//--- check volume before OrderSend to avoid "not enough money" error (CTrade)

   ENUM_ORDER_TYPE check_order_type=-1;

   switch(order_type)

     {

      case  ORDER_TYPE_BUY:

         check_order_type=ORDER_TYPE_BUY;

         break;

      case ORDER_TYPE_SELL:

         check_order_type=ORDER_TYPE_SELL;

         break;

      case ORDER_TYPE_BUY_LIMIT:

         check_order_type=ORDER_TYPE_BUY;

         break;

      case ORDER_TYPE_SELL_LIMIT:

         check_order_type=ORDER_TYPE_SELL;

         break;

      case ORDER_TYPE_BUY_STOP:

         check_order_type=ORDER_TYPE_BUY;

         break;

      case ORDER_TYPE_SELL_STOP:

         check_order_type=ORDER_TYPE_SELL;

         break;

      default:

         return(false);

         break;

     }

//---

   double long_lot=lot;

   double short_lot=lot;

//--- check volume before OrderSend to avoid "not enough money" error (CTrade)

   double check_price=0;

   double check_lot=0;

   if(check_order_type==ORDER_TYPE_BUY)

     {

      check_price=m_symbol.Ask();

      check_lot=long_lot;

     }

   else

     {

      check_price=m_symbol.Bid();

      check_lot=short_lot;

     }

//---

   if(m_symbol.LotsLimit()>0.0)

     {

      double volume_buys        = 0.0;   double volume_sells       = 0.0;

      double volume_buy_limits  = 0.0;   double volume_sell_limits = 0.0;

      double volume_buy_stops   = 0.0;   double volume_sell_stops  = 0.0;

      CalculateAllVolumes(m_symbol,

                          volume_buys,volume_sells,

                          volume_buy_limits,volume_sell_limits,

                          volume_buy_stops,volume_sell_stops);

      if(volume_buys+volume_sells+

         volume_buy_limits+volume_sell_limits+

         volume_buy_stops+volume_sell_stops+check_lot>m_symbol.LotsLimit())

        {

         if(InpPrintLog)

            Print("#0 ,",EnumToString(order_type),", ",

                  "Volume Buy's (",DoubleToString(volume_buys,2),")",

                  "Volume Sell's (",DoubleToString(volume_sells,2),")",

                  "Volume Buy limit's (",DoubleToString(volume_buy_limits,2),")",

                  "Volume Sell limit's (",DoubleToString(volume_sell_limits,2),")",

                  "Volume Buy stops's (",DoubleToString(volume_buy_stops,2),")",

                  "Volume Sell stops's (",DoubleToString(volume_sell_stops,2),")",

                  "Check lot (",DoubleToString(check_lot,2),")",

                  " > Lots Limit (",DoubleToString(m_symbol.LotsLimit(),2),")");

         return(false);

        }

     }

//---

   double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),check_order_type,check_lot,check_price);

   if(free_margin_check>0.0)

     {

      if(m_trade.OrderOpen(m_symbol.Name(),order_type,check_lot,0.0,

         m_symbol.NormalizePrice(price),m_symbol.NormalizePrice(sl),m_symbol.NormalizePrice(tp),ORDER_TIME_DAY))

        {

         if(m_trade.ResultOrder()==0)

           {

            if(InpPrintLog)

               Print("#1 ",EnumToString(order_type)," -> false. Result Retcode: ",m_trade.ResultRetcode(),

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

            if(InpPrintLog)

               PrintResultTrade(m_trade,m_symbol);

            return(false);

           }

         else

           {

            if(InpPrintLog)

               Print("#2 ",EnumToString(order_type)," -> true. Result Retcode: ",m_trade.ResultRetcode(),

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

            if(InpPrintLog)

               PrintResultTrade(m_trade,m_symbol);

            return(true);

           }

        }

      else

        {

         if(InpPrintLog)

            Print("#3 ",EnumToString(order_type)," -> false. Result Retcode: ",m_trade.ResultRetcode(),

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

         if(InpPrintLog)

            PrintResultTrade(m_trade,m_symbol);

         return(false);

        }

     }

   else

     {

      if(InpPrintLog)

         Print(__FUNCTION__,", ERROR: method CAccountInfo::FreeMarginCheck returned the value ",DoubleToString(free_margin_check,2));

      return(false);

     }

//---

   return(false);

  }

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

//| Print CTrade result                                              |

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

void PrintResultTrade(CTrade &trade,CSymbolInfo &symbol)

  {

   Print("File: ",__FILE__,", symbol: ",symbol.Name());

   Print("Code of request result: "+IntegerToString(trade.ResultRetcode()));

   Print("code of request result as a string: "+trade.ResultRetcodeDescription());

   Print("Deal ticket: "+IntegerToString(trade.ResultDeal()));

   Print("Order ticket: "+IntegerToString(trade.ResultOrder()));

   Print("Volume of deal or order: "+DoubleToString(trade.ResultVolume(),2));

   Print("Price, confirmed by broker: "+DoubleToString(trade.ResultPrice(),symbol.Digits()));

   Print("Current bid price: "+DoubleToString(symbol.Bid(),symbol.Digits())+" (the requote): "+DoubleToString(trade.ResultBid(),symbol.Digits()));

   Print("Current ask price: "+DoubleToString(symbol.Ask(),symbol.Digits())+" (the requote): "+DoubleToString(trade.ResultAsk(),symbol.Digits()));

   Print("Broker comment: "+trade.ResultComment());

   int d=0;

  }

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

//| Close positions                                                  |

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

void ClosePositions(CTrade &m_trade,CSymbolInfo &m_symbol,const long magic,const ENUM_POSITION_TYPE pos_type)

  {

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

      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==magic)

            if(m_position.PositionType()==pos_type) // gets the position type

               m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol

  }

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

//| Calculate all pending orders                                     |

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

void CalculateAllPendingOrders(CSymbolInfo &m_symbol,const long magic,int &count_buy_limits)

  {

   count_buy_limits=0;



   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders

      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties

         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==magic)

           {

            if(m_order.OrderType()==ORDER_TYPE_BUY_LIMIT)

               count_buy_limits++;

           }

  }

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

//| Is pendinf orders exists                                         |

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

bool IsPendingOrdersExists(CSymbolInfo &m_symbol,const long magic)

  {

   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders

      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties

         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==magic)

            return(true);

//---

   return(false);

  }

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

//| Delete all pending orders                                        |

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

void DeleteAllPendingOrders(CTrade &m_trade,CSymbolInfo &m_symbol,const long magic,const double level)

  {

   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders

      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties

         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==magic)

           {

            if(m_order.OrderType()==ORDER_TYPE_BUY_LIMIT)

              {

               if(m_symbol.Ask()-m_order.PriceOpen()>=level)

                  m_trade.OrderDelete(m_order.Ticket());

               continue;

              }

            if(m_order.OrderType()==ORDER_TYPE_BUY_STOP)

              {

               if(m_order.PriceOpen()-m_symbol.Ask()>=level)

                  m_trade.OrderDelete(m_order.Ticket());

               continue;

              }

            if(m_order.OrderType()==ORDER_TYPE_SELL_LIMIT)

              {

               if(m_order.PriceOpen()-m_symbol.Bid()>=level)

                  m_trade.OrderDelete(m_order.Ticket());

               continue;

              }

            if(m_order.OrderType()==ORDER_TYPE_SELL_STOP)

              {

               if(m_symbol.Bid()-m_order.PriceOpen()>=level)

                  m_trade.OrderDelete(m_order.Ticket());

               continue;

              }

           }

  }

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

//| Calculate all positions                                          |

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

int CalculateAllPositions(CSymbolInfo &m_symbol,const long magic,double &profit_all)

  {

   int total=0;



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

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==magic)

           {

            profit_all+=m_position.Commission()+m_position.Swap()+m_position.Profit();

            total++;

           }

//---

   return(total);

  }

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

//| Close all positions                                              |

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

void CloseAllPositions(CTrade &m_trade,CSymbolInfo &m_symbol,const long magic)

  {

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

      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==magic)

            m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol

  }

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

//| Calculate all volumes                                            |

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

void CalculateAllVolumes(CSymbolInfo &m_symbol,

                         double &volumne_buys,double &volumne_sells,

                         double &volumne_buy_limits,double &volumne_sell_limits,

                         double &volumne_buy_stops,double &volumne_sell_stops)

  {

   volumne_buys         = 0.0;   volumne_sells        = 0.0;

   volumne_buy_limits   = 0.0;   volumne_sell_limits  = 0.0;

   volumne_buy_stops    = 0.0;   volumne_sell_stops   = 0.0;



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

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name())

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

               volumne_buys+=m_position.Volume();

            else if(m_position.PositionType()==POSITION_TYPE_SELL)

               volumne_sells+=m_position.Volume();

           }



   for(int i=OrdersTotal()-1;i>=0;i--) // returns the number of current orders

      if(m_order.SelectByIndex(i)) // selects the pending order by index for further access to its properties

         if(m_order.Symbol()==m_symbol.Name())

           {

            if(m_order.OrderType()==ORDER_TYPE_BUY_LIMIT)

               volumne_buy_limits+=m_order.VolumeInitial();

            else if(m_order.OrderType()==ORDER_TYPE_SELL_LIMIT)

               volumne_sell_limits+=m_order.VolumeInitial();

            else if(m_order.OrderType()==ORDER_TYPE_BUY_STOP)

               volumne_buy_stops+=m_order.VolumeInitial();

            else if(m_order.OrderType()==ORDER_TYPE_SELL_STOP)

               volumne_sell_stops+=m_order.VolumeInitial();

           }

  }

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

//| Lot Check                                                        |

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

double LotCheck(CSymbolInfo &m_symbol,double lots)

  {

//--- calculate maximum volume

   double volume=NormalizeDouble(lots,2);

   double stepvol=m_symbol.LotsStep();

   if(stepvol>0.0)

      volume=stepvol*MathFloor(volume/stepvol);

//---

   double minvol=m_symbol.LotsMin();

   if(volume<minvol)

      volume=0.0;

//---

   double maxvol=m_symbol.LotsMax();

   if(volume>maxvol)

      volume=maxvol;

   return(volume);

  }

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

Comments