My code does not give order

 

Hello dear trader community,


I have coded sth.It does not give order. I am about to lose my mind. Anyone can help me solve this problem out? I really appreciate that.


Thanks in advance for your help and time.


Best Regards

//+------------------------------------------------------------------+
//|                                           GENERALincludeFile.mqh |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property strict
//+------------------------------------------------------------------+
//| defines                                                          |
//+------------------------------------------------------------------+
// #define MacrosHello   "Hello, world!"
// #define MacrosYear    2010
//+------------------------------------------------------------------+
//| DLL imports                                                      |
//+------------------------------------------------------------------+
// #import "user32.dll"
//   int      SendMessageA(int hWnd,int Msg,int wParam,int lParam);
// #import "my_expert.dll"
//   int      ExpertRecalculate(int wParam,int lParam);
// #import
//+------------------------------------------------------------------+
//| EX5 imports                                                      |
//+------------------------------------------------------------------+
// #import "stdlib.ex5"
//   string ErrorDescription(int error_code);
// #import
//+------------------------------------------------------------------+


// Pip Point Function
      double PipPoint(string Currency)
         {
            double CalcPoint; 
            int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
            if(CalcDigits == 2 || CalcDigits == 3) CalcPoint = 0.01;
            else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;
            return(CalcPoint);
         }
   
// Get Slippage Function /// DEFINE SLIPPAGE VALUE GLOBALLY
      int GetSlippage(string Currency, int SlippagePips)
         {
            double CalcSlippage ;
            int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
            if(CalcDigits == 2 || CalcDigits == 4) CalcSlippage = SlippagePips;
            else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage = SlippagePips * 10;
            return(CalcSlippage);
         }

// IS TRADE ALLOWED ??
      bool IsTradingAllowed() // check if trade is allowed
         {
            if(!IsTradeAllowed())
            {
               Print("Expert Advisor is NOT Allowed to Trade. Check AutoTrading.");
               return false;
            }
            
            if(!IsTradeAllowed(Symbol(), TimeCurrent()))
            {
               Print("Trading NOT Allowed for specific Symbol and Time");
               return false;
            }
            
            return true;
         }
         /*
///// OPTIMAL LOTSIZE
      double OptimalLotSize(double maxRiskPrc, int maxLossInPips)
         {
            
              double accEquity = AccountEquity();
              Print("accEquity: " + accEquity);
              
              double lotSize = MarketInfo(NULL,MODE_LOTSIZE);
              Print("lotSize: " + lotSize);
              
              double tickValue = MarketInfo(NULL,MODE_TICKVALUE);
              
              if(Digits <= 3)
              {
               tickValue = tickValue /100;
              }
              
              Print("tickValue: " + tickValue);
              
              double maxLossDollar = accEquity * maxRiskPrc;
              Print("maxLossDollar: " + maxLossDollar);
              
              double maxLossInQuoteCurr = maxLossDollar / tickValue;
              Print("maxLossInQuoteCurr: " + maxLossInQuoteCurr);
              
              double optimalLotSize = NormalizeDouble(maxLossInQuoteCurr /(maxLossInPips * PipPoint(Symbol()))/lotSize,2);
              
              return optimalLotSize;
             
         }
         //
      double OptimalLotSize(double maxRiskPrc, double entryPrice, double stopLoss)
         {
            int maxLossInPips = MathAbs(entryPrice - stopLoss)/PipPoint(Symbol());
            return OptimalLotSize(maxRiskPrc,maxLossInPips);
         }

*/

//// CHECK OPEN ORDERS BY MAGIC NUMBER
bool CheckIfOpenOrdersByMagicNB(int magicNB)
{
   int openOrders = OrdersTotal();
   
   for(int i = 0; i < openOrders; i++)
   {
      if(OrderSelect(i,SELECT_BY_POS)==true)
      {
         if(OrderMagicNumber() == magicNB) 
         {
            return true;
         }  
      }
   }
   return false;
}

// LOT SIZE CALCULATION
// Lot size calculation
double CalcLotSize(bool argDynamicLotSize, double argEquityPercent,double argStopLoss, double argFixedLotSize)
   {
      double LotSize;
      
         if(argDynamicLotSize == true && argStopLoss > 0)
            {
            double RiskAmount = AccountEquity() * (argEquityPercent / 100);
            double TickValue = MarketInfo(Symbol(),MODE_TICKVALUE);
            if(Point == 0.001 || Point == 0.00001) TickValue *= 10;
            LotSize = (RiskAmount / argStopLoss) / TickValue;
            }
         else LotSize = argFixedLotSize;
         //////////////////////////////////////// VERIFY IT
      if(LotSize < MarketInfo(Symbol(),MODE_MINLOT))
      {
      LotSize = MarketInfo(Symbol(),MODE_MINLOT);
      }
      else if(LotSize > MarketInfo(Symbol(),MODE_MAXLOT))
      {
      LotSize = MarketInfo(Symbol(),MODE_MAXLOT);
      }
      if(MarketInfo(Symbol(),MODE_LOTSTEP) == 0.1)
      {
      LotSize = NormalizeDouble(LotSize,1);
      }
      else LotSize = NormalizeDouble(LotSize,2);
     
      return(LotSize);
   }
   
   
   
////// ORDERS ///////




double CalcBuyStopLoss(string argSymbol, int argStopLoss, double argOpenPrice)
   {
      if(argStopLoss == 0) return(0);
      double BuyStopLoss = argOpenPrice - (argStopLoss * PipPoint(argSymbol));
      return(BuyStopLoss);
   }


double CalcSellStopLoss(string argSymbol, int argStopLoss, double argOpenPrice)
   {
      if(argStopLoss == 0) return(0);
      double SellStopLoss = argOpenPrice + (argStopLoss * PipPoint(argSymbol));
      return(SellStopLoss);
   }


double CalcBuyTakeProfit(string argSymbol, int argTakeProfit, double argOpenPrice)
   {
      if(argTakeProfit == 0) return(0);
      double BuyTakeProfit = argOpenPrice + (argTakeProfit * PipPoint(argSymbol));
      return(BuyTakeProfit);
   }


double CalcSellTakeProfit(string argSymbol, int argTakeProfit, double argOpenPrice)
   {
      if(argTakeProfit == 0) return(0);
      double SellTakeProfit = argOpenPrice - (argTakeProfit * PipPoint(argSymbol));
      return(SellTakeProfit);
   }
   

void BuyTrailingStop(string argSymbol, int argTrailingStop, int argMinProfit, int argMagicNumber)
   {
      for(int Counter = 0; Counter <= OrdersTotal()-1; Counter++)
         {
            OrderSelect(Counter,SELECT_BY_POS);
            // Calculate Max Stop and Min Profit
            double MaxStopLoss = MarketInfo(argSymbol,MODE_BID) - (argTrailingStop * PipPoint(argSymbol));
            MaxStopLoss = NormalizeDouble(MaxStopLoss, MarketInfo(OrderSymbol(),MODE_DIGITS));
            double CurrentStop = NormalizeDouble(OrderStopLoss(),MarketInfo(OrderSymbol(),MODE_DIGITS));
            double PipsProfit = MarketInfo(argSymbol,MODE_BID) - OrderOpenPrice();
            double MinProfit = argMinProfit * PipPoint(argSymbol);
            // Modify Stop
               if(OrderMagicNumber() == argMagicNumber && OrderSymbol() == argSymbol && OrderType() == OP_BUY && CurrentStop < MaxStopLoss&& PipsProfit >= MinProfit)
               {
               bool Trailed = OrderModify(OrderTicket(),OrderOpenPrice(),MaxStopLoss,OrderTakeProfit(),0);
               
               }
         }
   }

void SellTrailingStop(string argSymbol, int argTrailingStop, int argMinProfit, int argMagicNumber)
   {
      for(int Counter = 0; Counter <= OrdersTotal()-1; Counter++)
      {
         OrderSelect(Counter,SELECT_BY_POS);
         // Calculate Max Stop and Min Profit
         double MaxStopLoss = MarketInfo(argSymbol,MODE_ASK) +
         (argTrailingStop * PipPoint(argSymbol));
         MaxStopLoss = NormalizeDouble(MaxStopLoss,MarketInfo(OrderSymbol(),MODE_DIGITS));
         double CurrentStop = NormalizeDouble(OrderStopLoss(),
         MarketInfo(OrderSymbol(),MODE_DIGITS));
         double PipsProfit = OrderOpenPrice() - MarketInfo(argSymbol,MODE_ASK);
         double MinProfit = argMinProfit * PipPoint(argSymbol);
         // Modify Stop
            if(OrderMagicNumber() == argMagicNumber && OrderSymbol() == argSymbol&& OrderType() == OP_SELL && (CurrentStop > MaxStopLoss || CurrentStop == 0)
            && PipsProfit >= MinProfit)
               {
               bool Trailed = OrderModify(OrderTicket(),OrderOpenPrice(),MaxStopLoss, OrderTakeProfit(),0);
               }
      }
   }
   
   
   
//// CLOSE SELL ORDER

void closeSELLorder ( int argTicketSELL,int ArgGetSlippage ) 

{
   // order Select
   OrderSelect(argTicketSELL,SELECT_BY_TICKET);
   if (OrderCloseTime() == 0 && argTicketSELL>0)
   {
      double CloseLots = OrderLots();
      while(IsTradeContextBusy()) Sleep(10);
      RefreshRates();
      double closePrice = Ask;
      bool closed = OrderClose( argTicketSELL, CloseLots, closePrice,ArgGetSlippage,clrRed);
   }
}

//// CLOSE BUY ORDER
void closeBUYorder ( int argTicketSELL,int ArgGetSlippage ) 

{
   // order Select
   OrderSelect(argTicketSELL,SELECT_BY_TICKET);
   if (OrderCloseTime() == 0 && argTicketSELL>0)
   {
      double CloseLots = OrderLots();
      while(IsTradeContextBusy()) Sleep(10);
      RefreshRates();
      double closePrice = Bid;
      bool closed = OrderClose( argTicketSELL, CloseLots, closePrice,ArgGetSlippage,clrRed);
   }
}

//DELETE SELL ORDER 

void deleteSELL (int argSellTicket )
{
   if(OrderCloseTime() == 0 && argSellTicket > 0 && OrderType() == OP_SELLSTOP)
      {
      bool Deleted = OrderDelete(argSellTicket,Red);
      if(Deleted == true) argSellTicket = 0;
      // Error handling
      if(Deleted == false)
      {
      Print(GetLastError());
      }
      }
}

//DELETE BUY ORDER 

void deleteBUY (int argBuyTicket )
{
   if(OrderCloseTime() == 0 && argBuyTicket > 0 && OrderType() == OP_SELLSTOP)
      {
      bool Deleted = OrderDelete(argBuyTicket,Red);
      if(Deleted == true) argBuyTicket = 0;
      // Error handling
      if(Deleted == false)
      {
      Print(GetLastError());
      }
      }
}

//+------------------------------------------------------------------+
//|                                                      DraftEA.mq4 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#include <GENERALincludeFile.mqh>
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

//EXTERN VARS
extern bool DynamicLotSize = true ;
extern double FixedLotSize = 0.1;
extern double EquityPercent = 2;


extern double TakeProfit = 100;
extern double StopLoss = 40;

extern int Slippage = 5;

extern double TrailingStop = 50;
extern int MinimumProfit = 50;

//GLOBAL VARS
int MagicNumber = 0000;
int TicketBUY;
int TicketSELL;


int OnInit()
  {
//---
   PipPoint(Symbol());
   GetSlippage(Symbol(), Slippage);
   
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
   /////// INDICATOR LINES  ////////////
   double UpperBB = iBands(Symbol(),PERIOD_H1,30,1,0,PRICE_CLOSE,MODE_UPPER,0);
   double UpperBBpre = iBands(Symbol(),PERIOD_H1,30,1,0,PRICE_CLOSE,MODE_UPPER,1);

   double MA = iMA(Symbol(), PERIOD_H1, 10, -1,MODE_EMA,PRICE_CLOSE,-1);
   double MApre = iMA(Symbol(), PERIOD_H1, 10, -1,MODE_EMA,PRICE_CLOSE,-1);
   
  
   if (!CheckIfOpenOrdersByMagicNB (MagicNumber) )
   {
   
      if ( TicketBUY < 0 &&  MApre < UpperBBpre && MA > UpperBB)
         {

             closeSELLorder(TicketSELL,Slippage);
             while(IsTradeContextBusy()) Sleep (10);
             RefreshRates();
             TicketBUY = OrderSend(Symbol(),OP_BUY,CalcLotSize(DynamicLotSize,EquityPercent,StopLoss,FixedLotSize),Ask,GetSlippage(Symbol(),Slippage),0,0,NULL,MagicNumber,0,clrPink);
               if(  TicketBUY < 0)
               {
               int a = GetLastError();
               Alert( a );
               } 
         }
   
  }
   
   
   
   
   
   
   
   
  }
 
emsahii: I have coded sth.It does not give order. … Anyone can help me solve this problem out?
  1. No idea what a "sth" is.

  2. Why did you post your MT4 question in the Root / MT5 General section instead of the MQL4 section, (bottom of the Root page?)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
    Next time post in the correct place. The moderators will likely move this thread there soon.

  3. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

  4.            double TickValue = MarketInfo(Symbol(),MODE_TICKVALUE);
                if(Point == 0.001 || Point == 0.00001) TickValue *= 10;
    PIP, Point, or Tick are all different in general.
              What is a TICK? - MQL4 programming forum
    Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    Risk depends on your initial stop loss, lot size, and the value of the pair. It does not depend on margin and leverage. No SL means you have infinite risk.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.
    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/pip but it takes account of the exchange rates of the pair vs. your account currency.)
    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum 2017.10.10
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum 2018.02.11
                Lot value calculation off by a factor of 100 - MQL5 programming forum 2019.07.19
    4. You must normalize lots properly and check against min and max.
    5. You must also check FreeMargin to avoid stop out

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  5. double BuyStopLoss = argOpenPrice - (argStopLoss * PipPoint(argSymbol));
    You buy at the Ask and sell at the Bid. So for buy orders you pay the spread on open. For sell orders you pay the spread on close.
    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid reaches it. Not the Ask. Your SL is shorter by the spread and your TP would be longer. Don't you want the same/specified amount for either direction?
    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25
    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

  6.       for(int Counter = 0; Counter <= OrdersTotal()-1; Counter++){
                OrderSelect(Counter,SELECT_BY_POS);
    In the presence of multiple orders (one EA multiple charts, multiple EAs, manual trading,) while you are waiting for the current operation (closing, deleting, modifying) to complete, any number of other operations on other orders could have concurrently happened and changed the position indexing:
    1. For non-FIFO (non-US brokers), (or the EA only opens one order per symbol,) you can simply count down, in a position loop, and you won't miss orders. Get in the habit of always counting down.
                Loops and Closing or Deleting Orders - MQL4 programming forum
      For In First Out (FIFO rules-US brokers,) and you (potentially) process multiple orders per symbol, you must find the earliest order, close it, and on a successful operation, reprocess all positions.
                CloseOrders by FIFO Rules - Strategy Tester - MQL4 programming forum - Page 2 #16
                MetaTrader 5 platform beta build 2155: MQL5 scope, global Strategy Tester and built-in Virtual Hosting updates - Best Expert Advisors - General - MQL5 programming forum #1 № 11 ACCOUNT_FIFO_CLOSE

    2. and check OrderSelect in case earlier positions were deleted.
                What are Function return values ? How do I use them ? - MQL4 programming forum
                Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    3. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use, on the next order / server call, the Predefined Variables (Bid/Ask) or (be direction independent and use) OrderClosePrice().

  7. Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
              Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum
              PositionClose is not working - MQL5 programming forum
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles

 
emsahii:

Hello dear trader community

I have coded sth.It does not give order. I am about to lose my mind. Anyone can help me solve this problem out? I really appreciate that.

Write in English!

sth.It is not a word

 
emsahii:

Hello dear trader community,


I have coded sth.It does not give order. I am about to lose my mind. Anyone can help me solve this problem out? I really appreciate that.


Thanks in advance for your help and time.


Best Regards


Hello,

what is this?

-1 mean count in the future.

Shift = 0. Current bar.

Shift = 1. One bar back.


To get correct variable current and previous iMA, need second iMA have 1 or more Shift greater value.

In your code current and previous iMA have same shift value (-1 wrong). 

double MA    = iMA(Symbol(), PERIOD_H1, 10, -1,MODE_EMA,PRICE_CLOSE,-1);
double MApre = iMA(Symbol(), PERIOD_H1, 10, -1,MODE_EMA,PRICE_CLOSE,-1);



Reason: