Close Far Position

Author: Copyright © 2019, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
0 Views
0 Downloads
0 Favorites
Close Far Position
ÿþ//+------------------------------------------------------------------+

//|                                           Close Far Position.mq5 |

//|                              Copyright © 2019, Vladimir Karputov |

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

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

#property copyright "Copyright © 2019, Vladimir Karputov"

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

#property version   "1.000"

/*

   barabashkakvn Trading engine 3.043

*/

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>

//---

CPositionInfo  m_position;                   // object of CPositionInfo class

CTrade         m_trade;                      // object of CTrade class

CSymbolInfo    m_symbol;                     // object of CSymbolInfo class

//--- input parameters

input double   InpCloseProfit       = 6.0;         // Close Profit, in money

input ulong    InpDeviation         = 10;          // Deviation, in points (1.00045-1.00055=10 points)

input bool     InpPrintLog          = false;       // Print log

//---

ulong FarTicketBuy=0;

ulong FarTicketSell=0;

ulong CloseTickets[];

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

//| Expert initialization function                                   |

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

int OnInit()

  {

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

     {

      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");

      return(INIT_FAILED);

     }

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(357);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(InpDeviation);

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   int size=ArraySize(CloseTickets);

   if(size>0)

     {

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

        {

         if(!m_position.SelectByTicket(CloseTickets[i]))

            ArrayRemove(CloseTickets,i,1);

         else

           {

            double level;

            if(FreezeStopsLevels(level))

               ClosePosition(CloseTickets[i],level);

           }

        }

     }

   if(FarTicketBuy!=0)

     {

      if(!m_position.SelectByTicket(FarTicketBuy))

         FarTicketBuy=0;

      else

        {

         double level;

         if(FreezeStopsLevels(level))

            ClosePosition(FarTicketBuy,level);

        }

     }

   if(FarTicketSell!=0)

     {

      if(!m_position.SelectByTicket(FarTicketSell))

         FarTicketSell=0;

      else

        {

         double level;

         if(FreezeStopsLevels(level))

            ClosePosition(FarTicketSell,level);

        }

     }

//---

   if(FarTicketBuy==0 && FarTicketSell==0 && size==0)

     {

      double FarProfitBuy=0.0,FarProfitSell=0.0;

      double FarPriceBuy=DBL_MIN,FarPriceSell=DBL_MAX;

      double Profits=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())

              {

               double profit=m_position.Commission()+m_position.Swap()+m_position.Profit();

               if(profit<0.0)

                 {

                  if(m_position.PositionType()==POSITION_TYPE_BUY)

                    {

                     if(m_position.PriceOpen()>FarPriceBuy)

                       {

                        FarTicketBuy=m_position.Ticket();

                        FarProfitBuy=profit;

                        FarPriceBuy=m_position.PriceOpen();

                       }

                    }

                  else

                    {

                     if(m_position.PriceOpen()<FarPriceSell)

                       {

                        FarTicketSell=m_position.Ticket();

                        FarProfitSell=profit;

                        FarPriceSell=m_position.PriceOpen();

                       }

                    }

                 }

               else

                 {

                  int new_size=ArraySize(CloseTickets);

                  ArrayResize(CloseTickets,new_size+1);

                  CloseTickets[new_size]=m_position.Ticket();

                  Profits+=profit;

                 }

              }

      //---

      if(FarProfitBuy<FarProfitSell || FarProfitSell<FarProfitBuy)

        {

         //--- Far Buy

         if(FarProfitBuy<FarProfitSell)

           {

            if(FarProfitBuy+Profits>=InpCloseProfit)

              {

               FarTicketSell=0;

              }

            else

              {

               FarTicketBuy=0;

               FarTicketSell=0;

               ArrayFree(CloseTickets);

              }

           }

         //--- Far Sell

         if(FarProfitSell<FarProfitBuy)

           {

            if(FarProfitSell+Profits>=InpCloseProfit)

              {

               FarTicketBuy=0;

              }

            else

              {

               FarTicketBuy=0;

               FarTicketSell=0;

               ArrayFree(CloseTickets);

              }

           }

        }

      else

        {

         FarTicketBuy=0;

         FarTicketSell=0;

         ArrayFree(CloseTickets);

        }

     }

//---

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//---



  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");

      return(false);

     }

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

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

     {

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");

      return(false);

     }

//---

   return(true);

  }

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

//| Check Freeze and Stops levels                                    |

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

bool FreezeStopsLevels(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.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;

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



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

      return(false);



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



   double spread=m_symbol.Spread()*m_symbol.Point();

   level=(level>spread)?level:spread;

//---

   return(true);

  }

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

//| Print CTrade result                                              |

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

void PrintResultTrade(CTrade &trade,CSymbolInfo &symbol)

  {

   Print(__FILE__," ",__FUNCTION__,", Symbol: ",symbol.Name()+", "+

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

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

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

         "Order ticket: "+IntegerToString(trade.ResultOrder())+", "+

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

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

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

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

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

  }

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

//| Close position                                                   |

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

void ClosePosition(const ulong ticket,const double 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(m_position.SelectByTicket(ticket)) // selects the position by index for further access to its properties

     {

      if(m_position.PositionType()==POSITION_TYPE_BUY)

        {

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

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

         if(take_profit_level && stop_loss_level)

            if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol

               if(InpPrintLog)

                  Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.PositionClose ",m_position.Ticket());

        }

      if(m_position.PositionType()==POSITION_TYPE_SELL)

        {

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

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

         if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol

            if(InpPrintLog)

               Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.PositionClose ",m_position.Ticket());

        }

     }

  }

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

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