exp_Amstell

Download script
Author: Copyright © 2018, Vladimir Karputov

This script is an automated trading tool designed for the MetaTrader 5 platform. It manages trades by monitoring price movements and executing orders based on specific distance thresholds and profit targets. Below is a breakdown of its logic in plain language:

Core Trading Logic

The script operates by constantly monitoring the current market price and comparing it to the prices of recent successful transactions. Its behavior can be summarized into three main actions:

  • Entry Signals (Buy/Sell):

    • Buy Orders: The script will trigger a "Buy" action if it detects that the current market price has dropped significantly compared to the last recorded "Buy" deal (specifically, if the difference meets or exceeds your predefined "Step").
    • Sell Orders: Conversely, it will trigger a "Sell" action if the current market price rises significantly compared to the last recorded "Sell" deal.
    • Initial State: If there are no previous trades on the account for the specific symbol, the script defaults to opening a Buy position to begin the cycle.
  • Virtual Take Profit:

    • Unlike a standard "hard" take profit that sits on the broker's server, this script uses a Virtual Take Profit.
    • It constantly calculates the profit of your open positions. Once the profit reaches your specified target (measured in pips), the script sends an instruction to close the trade immediately.
  • Dynamic Order Management:

    • The script keeps track of how many "Buy" and "Sell" positions are currently open.
    • It uses this information to reset its memory; for example, if all Buy positions are closed and a Sell position is active, it clears the historical price data for the Buy side to ensure the next signal is calculated correctly.

Safety and Automation Features

To ensure the script runs smoothly and stays within the rules of your broker, it includes several automated "checks":

  • Volume Validation: Before opening a trade, the script automatically verifies that your requested "Lot" size is valid. It ensures your volume isn't too small (under the broker's minimum), too large (over the maximum), or an unsupported increment (e.g., trying to trade 0.15 when the broker only allows steps of 0.10).
  • Price Refreshing: The script constantly requests updated "Live" quotes from the market. If it cannot receive a clear price (if the price returns as zero), it will pause its logic to prevent making trades based on old or incorrect data.
  • Precision Adjustment: The script is designed to be smart about different broker types. It automatically detects if your broker uses 3-digit or 5-digit pricing and adjusts its internal math accordingly so that your "Pips" and "Steps" remain accurate regardless of the platform's decimal setup.
  • Unique Identification: Every trade opened by this script is tagged with a unique "Magic Number." This allows the script to manage only its own trades, ensuring it doesn't accidentally interfere with other manual trades or different automated systems you might have running on the same account.
Price Data Components
9 Views
0 Downloads
0 Favorites
exp_Amstell
ÿþ//+------------------------------------------------------------------+

//|                                                  exp_Amstell.mq5 |

//|                              Copyright © 2018, Vladimir Karputov |

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

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

#property copyright "Copyright © 2018, Vladimir Karputov"

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

#property version   "1.001"

//---

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

//--- input parameters

input double   InpLots           = 0.1;      // Lots

input ushort   InpTakeProfit     = 50;       // Virtual Take Profit (in pips)

input ushort   InpStep           = 15;       // Step (in pips)

input ulong    m_magic           = 101175802;// magic number

//---

ulong          m_slippage=10;                // slippage



double         ExtTakeProfit=0.0;

double         ExtStep=0.0;



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



double         price_last_deal_buy=0.0;

double         price_last_deal_sell=0.0;

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

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

      return(INIT_FAILED);

   RefreshRates();



   string err_text="";

   if(!CheckVolumeValue(InpLots,err_text))

     {

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

      return(INIT_PARAMETERS_INCORRECT);

     }

//---

   m_trade.SetExpertMagicNumber(m_magic);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

//---

   m_trade.SetDeviationInPoints(m_slippage);

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



   ExtTakeProfit  = InpTakeProfit* m_adjusted_point;

   ExtStep        = InpStep      * m_adjusted_point;

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   if(price_last_deal_buy==0.0 && price_last_deal_sell==0.0)

     {

      m_trade.Buy(InpLots);

      return;

     }

//---

   if(!RefreshRates())

      return;

//--- signal buy

   if(price_last_deal_buy==0.0 || (price_last_deal_buy!=0.0 && price_last_deal_buy-m_symbol.Ask()>=ExtStep))

     {

      m_trade.Buy(InpLots);

      return;

     }

//--- signal sell

   if(price_last_deal_sell==0.0 || (price_last_deal_sell!=0.0 && m_symbol.Bid()-price_last_deal_sell>=ExtStep))

     {

      m_trade.Sell(InpLots);

      return;

     }

//--- virtual take profit

   bool close=false;

   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()==m_magic)

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

               if(m_position.PriceCurrent()-m_position.PriceOpen()>=ExtTakeProfit)

                 {

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

                  close=true;

                 }



            if(m_position.PositionType()==POSITION_TYPE_SELL)

               if(m_position.PriceOpen()-m_position.PriceCurrent()>=ExtTakeProfit)

                 {

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

                  close=true;

                 }

           }

   if(close)

      return;

//---

   int count_buys=0,count_sells=0;

   CalculatePositions(count_buys,count_sells);

   if(count_buys==0.0 && count_sells!=0.0)

      price_last_deal_buy=0.0;

   else if(count_buys!=0.0 && count_sells==0.0)

                       price_last_deal_sell=0.0;

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

   double res=0.0;

   int losses=0.0;

//--- get transaction type as enumeration value 

   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;

//--- if transaction is result of addition of the transaction in history

   if(type==TRADE_TRANSACTION_DEAL_ADD)

     {

      long     deal_ticket       =0;

      long     deal_order        =0;

      long     deal_time         =0;

      long     deal_time_msc     =0;

      long     deal_type         =-1;

      long     deal_entry        =-1;

      long     deal_magic        =0;

      long     deal_reason       =-1;

      long     deal_position_id  =0;

      double   deal_volume       =0.0;

      double   deal_price        =0.0;

      double   deal_commission   =0.0;

      double   deal_swap         =0.0;

      double   deal_profit       =0.0;

      string   deal_symbol       ="";

      string   deal_comment      ="";

      string   deal_external_id  ="";

      if(HistoryDealSelect(trans.deal))

        {

         deal_ticket       =HistoryDealGetInteger(trans.deal,DEAL_TICKET);

         deal_order        =HistoryDealGetInteger(trans.deal,DEAL_ORDER);

         deal_time         =HistoryDealGetInteger(trans.deal,DEAL_TIME);

         deal_time_msc     =HistoryDealGetInteger(trans.deal,DEAL_TIME_MSC);

         deal_type         =HistoryDealGetInteger(trans.deal,DEAL_TYPE);

         deal_entry        =HistoryDealGetInteger(trans.deal,DEAL_ENTRY);

         deal_magic        =HistoryDealGetInteger(trans.deal,DEAL_MAGIC);

         deal_reason       =HistoryDealGetInteger(trans.deal,DEAL_REASON);

         deal_position_id  =HistoryDealGetInteger(trans.deal,DEAL_POSITION_ID);



         deal_volume       =HistoryDealGetDouble(trans.deal,DEAL_VOLUME);

         deal_price        =HistoryDealGetDouble(trans.deal,DEAL_PRICE);

         deal_commission   =HistoryDealGetDouble(trans.deal,DEAL_COMMISSION);

         deal_swap         =HistoryDealGetDouble(trans.deal,DEAL_SWAP);

         deal_profit       =HistoryDealGetDouble(trans.deal,DEAL_PROFIT);



         deal_symbol       =HistoryDealGetString(trans.deal,DEAL_SYMBOL);

         deal_comment      =HistoryDealGetString(trans.deal,DEAL_COMMENT);

         deal_external_id  =HistoryDealGetString(trans.deal,DEAL_EXTERNAL_ID);

        }

      else

         return;

      if(deal_reason!=-1)

         int d=0;

      if(deal_symbol==Symbol() && deal_magic==m_magic)

         if(deal_entry==DEAL_ENTRY_IN)

           {

            if(deal_type==DEAL_TYPE_BUY)

               price_last_deal_buy=deal_price;

            if(deal_type==DEAL_TYPE_SELL)

               price_last_deal_sell=deal_price;

           }

     }

  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates(void)

  {

//--- 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 the correctness of the position volume                     |

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

bool CheckVolumeValue(double volume,string &error_description)

  {

//--- minimal allowed volume for trade operations

   double min_volume=m_symbol.LotsMin();

   if(volume<min_volume)

     {

      error_description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume);

      return(false);

     }

//--- maximal allowed volume of trade operations

   double max_volume=m_symbol.LotsMax();

   if(volume>max_volume)

     {

      error_description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume);

      return(false);

     }

//--- get minimal step of volume changing

   double volume_step=m_symbol.LotsStep();

   int ratio=(int)MathRound(volume/volume_step);

   if(MathAbs(ratio*volume_step-volume)>0.0000001)

     {

      error_description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f",

                                     volume_step,ratio*volume_step);

      return(false);

     }

   error_description="Correct volume value";

   return(true);

  }

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

//| Calculate positions Buy and Sell                                 |

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

void CalculatePositions(int &count_buys,int &count_sells)

  {

   count_buys=0;

   count_sells=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()==m_magic)

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

               count_buys++;



            if(m_position.PositionType()==POSITION_TYPE_SELL)

               count_sells++;

           }

//---

   return;

  }

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

Comments