Long Waiting

Download script
Author: Etrid
Profit factor:
0.00

This automated trading script is designed to manage "long" (buying) positions on a daily basis with a specific focus on profit realization and risk management. Below is a breakdown of how the logic operates in plain language:

Core Trading Strategy

The primary goal of this script is to ensure that you have an active long position open for each trading day. It follows a simple "open, monitor, and refresh" cycle:

  • Daily Entry: If the script detects that there is no current position open for the day, it will automatically open one.
  • Profit Taking and Re-entry: If you already have a position open and it becomes profitable (reaching a user-defined minimum profit level), the script will "fix" your profit by closing that position and immediately opening a new one. This allows you to bank gains while remaining active in the market.

Smart Volume Management

The script includes several layers of protection to ensure your trade sizes are appropriate for your account:

  • Dynamic Calculation: It calculates your trade volume based on your current account balance and a "Coefficient" set by you. For example, if you want a specific ratio of margin to capital, the script adjusts the size automatically.
  • Liquidity Safety Check: The script checks the specific requirements of the asset you are trading (liquidity rate). If the calculated volume is too high for that specific market's rules, it automatically scales the trade down to prevent errors.
  • Hard Caps: You can set a "Maximum Volume" limit. Even if your account balance allows for a massive trade, the script will respect this ceiling to keep your risk controlled.

Timing and Execution Controls

The behavior of the script can be customized based on when you want your positions to refresh:

  • Flexible Closing Windows: You can choose between two different "versions" for end-of-day logic. Depending on your selection, the script will look for specific hours (such as 18:00 or 23:00) to evaluate your positions.
  • Daily Tracking: The script keeps track of its actions using a date stamp. This ensures it knows when it has already performed its task for the current day so it doesn't create unnecessary duplicate trades.

Summary for the User

This tool is built for traders who prefer a consistent "Long" bias in their portfolio. It automates the tedious work of monitoring profit targets—closing out winning trades and resetting them to keep the momentum going—while simultaneously handling the math behind safe lot sizing and market-specific restrictions.

Orders Execution
It Closes Orders by itself It automatically opens orders when conditions are reached
11 Views
0 Downloads
0 Favorites
Long Waiting
ÿþ//+------------------------------------------------------------------+

//|                                                 Long Waiting.mq5 |

//|                                                            Etrid |

//|                              https://www.mql5.com/ru/users/etrid |

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

#property copyright "Etrid"

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

#property version   "1.00"

//---

#property description "Expert every day opening long position for CurrentPeriod active if haven't opened position"

#property description "In the end day if we have profit then we will fix position and open new. If we haven't profit the we nothing do"

#property description "InpCoefficient - if set on 100 and deposit is 1000, Volume will be 1000/100 = 10 * 0.01 = 0.1"

//--- input parameters

input long   InpOrderMagic                = 0000072;  // Order magic

input int    InpCoefficient               = 100;      // Volume coeficient

input double InpMaximumVolume             = 0.01;     // Maximum volume

input double InpMinimumProfit             = 0.5;      // Minimum profit for fixation

input bool   InpClosePositionVersionTwo   = false;    // if true then position will be fixed 23:00 else if false then in 18:00

//--- other parameters

double Balance          = AccountInfoDouble(ACCOUNT_BALANCE);  // Account balance

double MicroVolumes     = MathFloor(Balance/InpCoefficient);   // Number of microlots

double Volume           = 0.01*MicroVolumes;                   // Total volume

string LastUpDate       = "00:00";                             // Last time script action (actions with positions)

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

//|  Main action                                                     |

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

void OnTick()

  {

//---

   Balance = AccountInfoDouble(ACCOUNT_BALANCE);

   if(Balance < InpCoefficient)

     {

      Balance = InpCoefficient;

     }

   MicroVolumes = MathFloor(Balance/InpCoefficient);



   if(SymbolInfoDouble(_Symbol,SYMBOL_TRADE_LIQUIDITY_RATE) * Volume > Balance)

     {

      MicroVolumes = MathFloor(Balance/(SymbolInfoDouble(_Symbol,SYMBOL_TRADE_LIQUIDITY_RATE) * Volume));

     }



   Volume = 0.01*MicroVolumes;



   if(Volume > InpMaximumVolume)

     {

      Volume = InpMaximumVolume;

     }



//---

   bool CurrentPeriod = false; // started new bar for CurrentPeriod period



   datetime Date = TimeLocal();

   MqlDateTime MDT;

   TimeToStruct(Date,MDT);

//---

   if(Period() == PERIOD_D1)

     {

      int CurrentHour = 18; // Current hour for working



      if(InpClosePositionVersionTwo)

        {

         CurrentHour = 23;

        }



      if(MDT.hour == CurrentHour)

        {

         CurrentPeriod = true;

        }



      if(LastUpDate == IntegerToString(MDT.mon)+":"+IntegerToString(MDT.day))

        {

         CurrentPeriod = false;

        }



      if(CurrentPeriod && _Symbol != "XAUUSD")

        {

         if(PositionSelect(_Symbol))

           {

            //--- close and reopen position if we have profit

            if(PositionGetDouble(POSITION_PROFIT) > InpMinimumProfit)

              {

               OrderClose(InpOrderMagic, PositionGetDouble(POSITION_VOLUME), PositionGetInteger(POSITION_TICKET));

               OrderOpen(InpOrderMagic, Volume, "long");

               LastUpDate = IntegerToString(MDT.mon)+":"+IntegerToString(MDT.day);

              }

           }

         else //--- open position if we haven't positions

           {

            OrderOpen(InpOrderMagic, Volume, "long");

            LastUpDate = IntegerToString(MDT.mon)+":"+IntegerToString(MDT.day);

           }

        }

     }

   else

     {

      Print("Error: Undefinded CurrentPeriod timeframe");

     }

//---

  }



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

//| Open order                                                       |

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

void OrderOpen(long const magic_number, double OpenVolume, string OrderType)

  {

//---

   MqlTradeRequest request= {0};

   MqlTradeResult  result= {0};



   double price = 0;



//---

   if(OrderType == "long") // long tp

     {

      price        = SymbolInfoDouble(_Symbol,SYMBOL_ASK);

      request.type = ORDER_TYPE_BUY;

     }

   else

      if(OrderType == "short") // short tp

        {

         price        = SymbolInfoDouble(_Symbol,SYMBOL_BID);

         request.type = ORDER_TYPE_SELL;

        }

//---

   Print("volume ",OpenVolume);

   request.action  =  TRADE_ACTION_DEAL;    // set market order

   request.magic   =  magic_number;

   request.symbol  =  _Symbol;

   request.volume  =  OpenVolume;

   request.sl      =  0;

   request.tp      =  0;

   request.price   =  price;                // open price (market)

//---

   if(OrderSend(request,result))

     {

      Print(__FUNCTION__,":",result.comment);

      if(result.retcode==10016)

         Print(result.bid,result.ask,result.price);

     }

   else

     {

      PrintFormat("Error for opening %s  With code %d",_Symbol,result.retcode);

     }

  }



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

//|   Close order                                                    |

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

void OrderClose(long const magic_number, double Volumes, ulong  position_ticket)

  {

//---

   MqlTradeRequest request;

   MqlTradeResult  result;



   ZeroMemory(request);

   ZeroMemory(result);



//---



   request.action     =  TRADE_ACTION_DEAL;            // actyion type

   request.position   =  position_ticket;              // position ticket

   request.symbol     =  _Symbol;                      // symbol

   request.volume     =  Volumes;                      // volume

   request.deviation  =  5;                            // deviation

   request.magic      =  magic_number;                 // MagicNumber position



//---

   if(PositionGetInteger(POSITION_TYPE)  ==  ORDER_TYPE_BUY)

     {

      request.price  =  SymbolInfoDouble(_Symbol,SYMBOL_BID);

      request.type   =  ORDER_TYPE_SELL;

     }

   else

     {

      request.price  =  SymbolInfoDouble(_Symbol,SYMBOL_ASK);

      request.type   =  ORDER_TYPE_BUY;

     }

//---

   if(OrderSend(request,result))

     {

      PrintFormat("Close #%I64d %s",position_ticket,_Symbol);

     }

   else

     {

      PrintFormat("Error for closing #%I64d %s  With code %d",position_ticket,_Symbol,result.retcode);

     }

  }

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

Comments