Download MetaTrader 5
To add comments, please log in or register
No time to learn MQL5? Order your application from a developer!
mar
1143
mar 2015.01.11 17:47 

Hi,

I thought that MathRand()  returns an Integer value within the range of 0 to 32767 based on MathSrand().

Can somebody please tell me why this script always prints the same number?

void OnStart()
  {
   MathSrand(Bars);
   int test = MathRand();
   Comment(test); 
  }

 How can I modify it that I receive different numbers? 

Keith Watford
Moderator
8028
Keith Watford 2015.01.11 19:58  
mar:

Hi,

I thought that MathRand()  returns an Integer value within the range of 0 to32767 based on MathSrand().

Can somebody please tell me why this script always prints the same number?

 How can I modify it that I receive different numbers? 

Read the documentation

It is because you are seeding with the same value (Bars) every time.

The documentation recommends using

MathSrand(GetTickCount())
whroeder1
13656
whroeder1 2015.01.11 21:24  
You need to call Srand only once, (in OnInit,) to set the random sequence. You do not want to call it for testing, so you get the same sequence for each test.
mar
1143
mar 2015.01.11 22:25  

Here is why I need it. I made a small script which plots a horizontal trendline I like to use for my weekend analysis. I use it by a hotkey and then I just move the line where I want to place it. Much faster and easier for me instead of drawing it by the mouse. So far, so good. Plotting the lines when the markets are open works fine because a part of the objects' name is TimeCurrent(). But when I plot them on the weekend when markets are closed there is a problem because TimeCurrent() doesn't change of course. Therefore I wanted a random number to be calculated that I can use my script also at the weekends.

Here is the script:

void OnStart()
  {
//---
   double YMid    = (WindowPriceMax() + WindowPriceMin())/2;
   int XMid       = WindowBarsPerChart()/4;
   datetime begin = iTime(NULL, 0, XMid);
   MathSrand(Bars);
   int rndNo = MathRand();
   ObjectCreate("Level "+(string)TimeCurrent()+"_"+(string)rndNo, OBJ_TREND, 0, begin, YMid, Time[0]+PeriodSeconds(), YMid);
   ObjectSet("Level "+(string)TimeCurrent()+"_"+(string)rndNo, OBJPROP_RAY_RIGHT, false);
   ObjectSet("Level "+(string)TimeCurrent()+"_"+(string)rndNo, OBJPROP_COLOR, clrWhite);
   ObjectSet("Level "+(string)TimeCurrent()+"_"+(string)rndNo, OBJPROP_SELECTED, true);
  }

 Can anyone tell me how I can fix that? I have no idea how to give the lines different names when nothing (time, price) is running.

/
To add comments, please log in or register