it does something else as expected

 

Hi,

im newbie in MQL5 and i wrote this simple code me to test whats going on...


#include<Trade\Trade.mqh>
CTrade trade;

void OnTick()
  {
   Comment("Williams %R ");
   
   double WPArray[];
   ArraySetAsSeries(WPArray,true);
   int WPDef = iWPR(_Symbol,_Period,14);
   CopyBuffer(WPDef,0,0,3,WPArray);
   
   double WPVal = NormalizeDouble(WPArray[0],2);
   
   double Bid=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   double Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   
   double TakeProfit = 10;
   double StopLoss = 5;    // RRR = 1:2
   
   double TakeProfitLevel = Bid + TakeProfit*Point();
   double StopLossLevel = Bid - StopLoss*Point();
   
   if(WPVal<-80)
   {
      Comment("preprodano - oversold");
      trade.Buy(0.1,_Symbol,Bid,StopLossLevel,TakeProfitLevel);
      
   } 
   
   if(WPVal>-20)
   {
      Comment("prekoupeno - overbought");
      trade.Sell(0.1,_Symbol,Bid,StopLossLevel,TakeProfitLevel);
   } 
   
  }

Well, i would expect if it is the value of Williams %R up to -20 it will be opened a sell position and if it is below -80 it will be opened the buy position however it doesnt happend...Actually sometimes yes sometimes no, but definitely not by every crossing of these values...whats wrong? My code is probably too simple and it miss something....

Im trying understand how to open position by given parameters..


Thanks for help

 
first - change your lower "Comment" statements instead of "Print" statement. 
I don´t read your thoughts, but at first glance it seems that if you compare logical negative values using the less- or greater than  operators, you may have to turn the other way around. If You are a beginner I would avoid this and use the MathAbs() function that passes the absolute value without the minus and now it is easier for you to make logics.  If you do not need extra tight scalper you can try element WPArray[1] instead of [0] .
double WPVal = MathAbs(NormalizeDouble(WPArray[0],2));
The main thing is that you use the Print() function to debug your code. it would also be good if you added your variable WPVal in the comment to see its value on an ongoing basis. for that change your first comment "Comment(WPVal)" 
 

I see four major problems here:

1. You do not check if there is an already opened trade. So when the condition is met it enters several times.

2. You are using too small stop loss(5 points) probably that causes trouble. 

3. You are entering Buy trade with Bid price. You should enter with Ask price.

4. TP and SL are to be calculated separately depending on the direction of the trade.