V1N1 New Order

Author: Copyright © 2015, Vinicius Oliveira - V1N1
Orders Execution
It automatically opens orders when conditions are reached
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
V1N1 New Order
ÿþ//+-----------------------------------------------------------------------------------------------------------------+

//|                                                                                              V1N1 New Order.mq4 |

//|                                                                      Copyright © 2015, Vinicius Oliveira - V1N1 |

//|                                                                       https://www.mql5.com/en/users/vinicius-fx |

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



//=== Properties

#property copyright   "Copyright © 2015, Vinicius Oliveira - V1N1"

#property description "This tool is designed to open positions in MetaTrader 4 terminals with absolute"

#property description "control of the risk / reward ratio, automatically calculating the lot size according"

#property description "to Risk and Stop Loss defined in the input parameters, with agility and precision,"

#property description "assisting in the risk management strategy of user manual trades."

#property link        "https://www.mql5.com/en/users/vinicius-fx"

#property version     "2.00"

#property strict

#property script_show_inputs



//=== Enumerations

enum ENUM_OP_TYPE

  {

   OpNo        = -1,             // Select...

   OpBuy       = OP_BUY,         // Buy

   OpSell      = OP_SELL,        // Sell

   OpBuyLimit  = OP_BUYLIMIT,    // Buy Limit

   OpSellLimit = OP_SELLLIMIT,   // Sell Limit

   OpBuyStop   = OP_BUYSTOP,     // Buy Stop

   OpSellStop  = OP_SELLSTOP     // Sell Stop

  };

enum ENUM_ENTRY_LEVEL_BY

  {

   EntryLevelPrice,    // Price

   EntryLevelPoints,   // Points

   EntryLevelNo        // None

  };

enum ENUM_RISK_BY

  {

   RiskPercentage,     // Percentage

   RiskAmount          // Amount

  };

enum ENUM_SL_BY

  {

   SL_Price,           // Price

   SL_Points           // Points

  };

enum ENUM_TP_BY

  {

   TP_Percentage,      // Percentage

   TP_Amount,          // Amount

   TP_Price,           // Price

   TP_Points           // Points

  };



//=== Global input variables

input ENUM_OP_TYPE        iOpType       = OpNo;             // Order Operation Type

input ENUM_ENTRY_LEVEL_BY iPendLevelBy  = EntryLevelNo;     // Set Pending Order Level By

input double              iPendLevel    = 0.0;              // Pending Order Level

input ENUM_RISK_BY        iRiskBy       = RiskPercentage;   // Set Order Risk By

input double              iRisk         = 0.0;              // Order Risk

input ENUM_SL_BY          iStopLossBy   = SL_Price;         // Set Stop Loss By

input double              iStopLoss     = 0.0;              // Stop Loss

input ENUM_TP_BY          iTakeProfitBy = TP_Percentage;    // Set Take Profit By

input double              iTakeProfit   = 0.0;              // Take Profit

input string              iOrdComment   = "";               // Order Comment

input int                 iMagicNumber  = 0;                // Order Magic Number

input int                 iSlippage     = 20;               // Maximum Price Slippage - Points



//=== Global internal variables

string ErrMsg;

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

//| Script program start function                                                                                   |

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

void OnStart()

  {

   //--- Local variables

   double SL, TP, Price, TickValue, VolumeStep, RISK, Lot, Profit;

   int    nDigits = 2;



   //--- Checks the input parameters

   if(iOpType == OpNo)

     {Alert("Please select Order Operation Type."); return;}

   if((iOpType == OpBuy || iOpType == OpSell) && (iPendLevelBy != EntryLevelNo || iPendLevel != 0))

     {

      ErrMsg = "Please do not enter Set Pending Order Level By or\n"

               "Pending Order Level at the opening of an immediate\n"

               "execution order.";

      Alert(ErrMsg);

      return;

     }

   if(iOpType != OpBuy && iOpType != OpSell && (iPendLevelBy == EntryLevelNo || iPendLevel <= 0))

     {

      ErrMsg = "Please enter Set Pending Order Level By and\n"

               "Pending Order Level at the opening of an pending order.";

      Alert(ErrMsg);

      return;

     }

   if(iRisk <= 0)

     {Alert("Please enter the Order Risk."); return;}

   if(iStopLoss <= 0)

     {Alert("Please enter the Stop Loss."); return;}



   //--- Minimal allowed volume for trade operations

   double MinVolume = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MIN);



   //--- Maximal allowed volume of trade operations

   double MaxVolume = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MAX);



   //--- Initializes stop loss and take profit

   SL = NormalizeDouble(iStopLoss, Digits);

   TP = NormalizeDouble(iTakeProfit, Digits);



   //--- Checks order buy

   if(iOpType == OpBuy || iOpType == OpBuyLimit || iOpType == OpBuyStop)

     {

      //--- Price

      Price = Ask;

      if(iOpType == OpBuyLimit)

        {

         if(iPendLevelBy == EntryLevelPoints) {Price = NormalizeDouble(Ask - iPendLevel * Point, Digits);}

         else {Price = iPendLevel;}

        }

      else if(iOpType == OpBuyStop)

        {

         if(iPendLevelBy == EntryLevelPoints) {Price = NormalizeDouble(Ask + iPendLevel * Point, Digits);}

         else {Price = iPendLevel;}

        }

      //--- Stop Loss

      if(iStopLossBy == SL_Points) {SL = NormalizeDouble(Price - iStopLoss * Point, Digits);}

      //--- Get minimal step of volume changing

      VolumeStep = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);

      if(VolumeStep == 0.1) {nDigits = 1;}

      else

      if(VolumeStep == 1.0) {nDigits = 0;}

      //--- Risk

      RISK = iRisk;

      if(iRiskBy == RiskPercentage) {RISK = (AccountBalance() + AccountCredit()) * (iRisk / 100);}

      //--- Volume

      TickValue = ((Price - SL) / Point) * MarketInfo(Symbol(), MODE_TICKVALUE);

      if(TickValue == 0.0) {Lot = 0.0;}

      else {Lot = NormalizeDouble(RISK / TickValue, nDigits);}



      if(Lot < MinVolume) {Lot = MinVolume;}

      else

      if(Lot > MaxVolume) {Lot = MaxVolume;}



      if(!CheckVolume(Lot)) {Alert(ErrMsg); return;}

      //--- Take Profit

      if(iTakeProfit > 0 && iTakeProfitBy != TP_Price)

        {

         if(iTakeProfitBy == TP_Points)

           {

            TP = NormalizeDouble(Price + iTakeProfit * Point, Digits);

           }

         else

           {

            Profit = iTakeProfit;

            if(iTakeProfitBy == TP_Percentage) {Profit = (AccountBalance() + AccountCredit()) * (iTakeProfit / 100);}

            TP = NormalizeDouble(Price + (Profit / (MarketInfo(Symbol(), MODE_TICKVALUE) * Lot)) * Point, Digits);

           }

        }

     }

   //--- Checks order sell

   else

     {

      //--- Price

      Price = Bid;

      if(iOpType == OpSellLimit)

        {

         if(iPendLevelBy == EntryLevelPoints) {Price = NormalizeDouble(Bid + iPendLevel * Point, Digits);}

         else {Price = iPendLevel;}

        }

      else if(iOpType == OpSellStop)

        {

         if(iPendLevelBy == EntryLevelPoints) {Price = NormalizeDouble(Bid - iPendLevel * Point, Digits);}

         else {Price = iPendLevel;}

        }

      //--- Stop Loss

      if(iStopLossBy == SL_Points) {SL = NormalizeDouble(Price + iStopLoss * Point, Digits);}

      //--- Get minimal step of volume changing

      VolumeStep = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);

      if(VolumeStep == 0.1) {nDigits = 1;}

      else

      if(VolumeStep == 1.0) {nDigits = 0;}

      //--- Risk

      RISK = iRisk;

      if(iRiskBy == RiskPercentage) {RISK = (AccountBalance() + AccountCredit()) * (iRisk / 100);}

      //--- Volume

      TickValue = ((SL - Price) / Point) * MarketInfo(Symbol(), MODE_TICKVALUE);

      if(TickValue == 0.0) {Lot = 0.0;}

      else {Lot = NormalizeDouble(RISK / TickValue, nDigits);}



      if(Lot < MinVolume) {Lot = MinVolume;}

      else

      if(Lot > MaxVolume) {Lot = MaxVolume;}



      if(!CheckVolume(Lot)) {Alert(ErrMsg); return;}

      //--- Take Profit

      if(iTakeProfit > 0 && iTakeProfitBy != TP_Price)

        {

         if(iTakeProfitBy == TP_Points)

           {

            TP = NormalizeDouble(Price - iTakeProfit * Point, Digits);

           }

         else

           {

            Profit = iTakeProfit;

            if(iTakeProfitBy == TP_Percentage) {Profit = (AccountBalance() + AccountCredit()) * (iTakeProfit / 100);}

            TP = NormalizeDouble(Price - (Profit / (MarketInfo(Symbol(), MODE_TICKVALUE) * Lot)) * Point, Digits);

           }

        }

     }



   //--- Opens order

   if(OrderSend(Symbol(), iOpType, Lot, Price, iSlippage, SL, TP, iOrdComment, iMagicNumber, 0, clrNONE) == -1)

     {Alert(Symbol(), AcronymsTF(Period()), " Error ", GetLastError());}

     {Print(Symbol(), AcronymsTF(Period()), " Error ", GetLastError());}

  }

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

//| Check volume function                                                                                           |

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

bool CheckVolume(double Lot)

  {

   //--- Minimal allowed volume for trade operations

   double MinVolume = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MIN);

   if(Lot < MinVolume)

     {

      ErrMsg = StringConcatenate("Volume less than the minimum allowed. The minimum volume is ", MinVolume, ".");

      return(false);

     }



   //--- Maximal allowed volume of trade operations

   double MaxVolume = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MAX);

   if(Lot > MaxVolume)

     {

      ErrMsg = StringConcatenate("Volume greater than the maximum allowed. The maximum volume is ", MaxVolume, ".");

      return(false);

     }



   //--- Get minimal step of volume changing

   double VolumeStep = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);



   int Ratio = (int)MathRound(Lot / VolumeStep);

   if(MathAbs(Ratio * VolumeStep - Lot) > 0.0000001)

     {

      ErrMsg = StringConcatenate("The volume is not multiple of the minimum gradation ", VolumeStep,

                                 ". Volume closest to the valid ", Ratio * VolumeStep, ".");

      return(false);

     }



   //--- Correct volume value

   return(true);

  }

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

//| Acronyms timeframes function                                                                                       |

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

string AcronymsTF(int CodeTF)

  {

   //--- Local variable

   string ResTF;



   switch(CodeTF)

     {

      case PERIOD_M1:    ResTF = " M1";    break;

      case PERIOD_M2:    ResTF = " M2";    break;

      case PERIOD_M3:    ResTF = " M3";    break;

      case PERIOD_M4:    ResTF = " M4";    break;

      case PERIOD_M5:    ResTF = " M5";    break;

      case PERIOD_M6:    ResTF = " M6";    break;

      case PERIOD_M10:   ResTF = " M10";   break;

      case PERIOD_M12:   ResTF = " M12";   break;

      case PERIOD_M15:   ResTF = " M15";   break;

      case PERIOD_M20:   ResTF = " M20";   break;

      case PERIOD_M30:   ResTF = " M30";   break;

      case PERIOD_H1:    ResTF = " H1";    break;

      case PERIOD_H2:    ResTF = " H2";    break;

      case PERIOD_H3:    ResTF = " H3";    break;

      case PERIOD_H4:    ResTF = " H4";    break;

      case PERIOD_H6:    ResTF = " H6";    break;

      case PERIOD_H8:    ResTF = " H8";    break;

      case PERIOD_H12:   ResTF = " H12";   break;

      case PERIOD_D1:    ResTF = " D1";    break;

      case PERIOD_W1:    ResTF = " W1";    break;

      case PERIOD_MN1:   ResTF = " MN1";   break;

      default:           ResTF = " NI";    break;

     }

   return(ResTF);

  }

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

//| Script End                                                                                                      |

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

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