• Home
  • Forums
  • Trades
  • News
  • Calendar
  • Market
  • Brokers
  • Login
  • Join
  • User/Email: Password:
  • 1:31pm
Menu
  • Forums
  • Trades
  • News
  • Calendar
  • Market
  • Brokers
  • Login
  • Join
  • 1:31pm
Sister Sites
  • Metals Mine
  • Energy EXCH
  • Crypto Craft

Options

Bookmark Thread

First Page First Unread Last Page Last Post

Print Thread

Similar Threads

MT4 EA used 100% of CPU Power? 1 reply

MetaTrader is running slow: Taking 100% of CPU 6 replies

EA is using 100% CPU in MetaTrader 4 10 replies

Help ! this Indicator causes CPU spikes 2 replies

Using Bid in While Loop? 11 replies

  • Platform Tech
  • /
  • Reply to Thread
  • Subscribe
Tags: while loop in EA causes 100% CPU
Cancel

while loop in EA causes 100% CPU

  • Post #1
  • Quote
  • First Post: Dec 29, 2010 6:03pm Dec 29, 2010 6:03pm
  •  ido370
  • | Joined Mar 2010 | Status: Member | 464 Posts
i created an EA but it contains a while loop, but when i run it, my CPU load goes to 100%, even backtesting won't start. Can someone show what i am doing wrong in my code to prevent this, and so that i can backtest normally?

Inserted Code
//Wait for first VALID signal and enter trade - WHILE loop
   while (ready==0)
   {
      //Create waiting label
      ObjectCreate("wait", OBJ_LABEL, 0, 0, 0);// Creating obj. 
      ObjectSet("wait", OBJPROP_CORNER, 1); // Reference corner 
      ObjectSet("wait", OBJPROP_XDISTANCE, 5);// X coordinate 
      ObjectSet("wait", OBJPROP_YDISTANCE, 15);// Y coordinate
      ObjectSetText("wait", "Waiting for signal..",15,"Arial Bold",White);
      
      Trendlord=iMA(NULL,0,50,0,MODE_EMA,PRICE_CLOSE,1);
      BarClose=iClose(NULL,0,1);
      BarOpen=iOpen(NULL,0,1);
   
      if (BarOpen > Trendlord&& BarClose < Trendlord) 
      {
      OrderSend(Symbol(),OP_SELL,Lotsize,Bid,50,NULL,NULL,NULL,MagicNumber,0,Red);
      ObjectDelete("wait");
      ready = 1;
      }
   
      if (BarOpen < Trendlord&& BarClose > Trendlord) 
      {
      OrderSend(Symbol(),OP_BUY,Lotsize,Ask,50,NULL,NULL,NULL,MagicNumber,0,Blue);
      ObjectDelete("wait");
      ready = 1;
      }
    }

when ready =1 it should continue with the rest of my code. i just placed this in it, so it wont start trading when attaching the EA, but waits for first signal/cross first.
  • Post #2
  • Quote
  • Dec 29, 2010 8:28pm Dec 29, 2010 8:28pm
  •  CodeMeister
  • Joined Sep 2009 | Status: Making Code While Making Pips | 1,672 Posts
You only need to check the condition once per bar - at the opening of the new bar because you are checking for a crossover of the previous bar. So you don't need a While loop. A simple If condition will be sufficient and won't even register on your CPU meter.

How do you know that the bar is a new one? Use this logic in the Start() function, be sure to declare barStart as a static datetime variable.

if (barStart < Time[0]) //start of new bar
{
barStart = Time[0];
//crossover checking goes here

}
 
 
  • Post #3
  • Quote
  • Dec 30, 2010 2:42am Dec 30, 2010 2:42am
  •  ido370
  • | Joined Mar 2010 | Status: Member | 464 Posts
thanks! i changed to if.. instead of while.
so my variables should be like this right?
Inserted Code
//Variables
extern double Lotsize = 0.1;
int MagicNumber;
double Trendlord;
double BarClose;
double BarOpen;
int existbuy;
int existsell;
int ready;
double Profit;
[b]static datetime barStart;[/b]
 
 
  • Post #4
  • Quote
  • Dec 30, 2010 2:58am Dec 30, 2010 2:58am
  •  CodeMeister
  • Joined Sep 2009 | Status: Making Code While Making Pips | 1,672 Posts
Looks OK to Me
 
 
  • Post #5
  • Quote
  • Dec 30, 2010 11:49am Dec 30, 2010 11:49am
  •  Xaphod
  • Joined Mar 2010 | Status: Member | 1,380 Posts
The sleep() function is used in looping EA's to suspend execution of the EA for a set amount of time. It will prevent the loop from using 100% of the processor time.
http://docs.mql4.com/common/Sleep
 
 
  • Post #6
  • Quote
  • Dec 31, 2010 2:07pm Dec 31, 2010 2:07pm
  •  ido370
  • | Joined Mar 2010 | Status: Member | 464 Posts
current EA code:
Inserted Code
//+------------------------------------------------------------------+
//|                                              Trendlord EA v2.mq4 |
//|                                      Copyright © 2010, Ido Kasse |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, Ido Kasse"
#property link      ""

//Variables
extern double Lotsize = 0.1;
double BarClose;
double BarOpen;
double Profit;
double Trendlord;
string ha;
int existbuy;
double existsell;
double ready;
double MagicNumber;
static datetime barStart;
double Heiken_op;
double Heiken_cl;

//Check Heiken Ashi
void Heiken()
{
Heiken_op = iCustom(NULL,0,"Heiken Ashi",Red,White,Red,White,2,1);
Heiken_cl = iCustom(NULL,0,"Heiken Ashi",Red,White,Red,White,3,1);
if (Heiken_op < Heiken_cl) ha ="Buy"; //Up
if (Heiken_op > Heiken_cl) ha ="Sell"; //Down
}

//Close Buy
void CloseBuy()
{
int total = OrdersTotal();
for (int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_BUY&& OrderMagicNumber()==MagicNumber)
OrderClose(OrderTicket(),OrderLots(),Bid,NULL, Yellow);
}
existbuy = 0;
}

//Close Sell
void CloseSell()
{
int total = OrdersTotal();
for (int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_SELL&& OrderMagicNumber()==MagicNumber) 
OrderClose(OrderTicket(),OrderLots(),Ask,NULL, Yellow);
}
existsell = 0;
}

//Check Buy
void CheckBuy()
{
int total = OrdersTotal();
for (int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_BUY&& OrderMagicNumber()==MagicNumber) existbuy = 1;
}
//if (Heiken_cl > Heiken_op) CloseBuy();
}

//Check Sell
void CheckSell()
{
int total = OrdersTotal();
for (int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_SELL&& OrderMagicNumber()==MagicNumber) existsell = 1;
}
//if (Heiken_op < Heiken_cl) CloseSell();
}

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   //Randomize MagicNumber
   MathSrand(TimeLocal());
   MagicNumber = MathRand();
   Print("Trendlord EA - MagicNumber: ", MagicNumber);
   //Set ready signal for first entry
   ready = 0;
   //Create label
   ObjectCreate("label", OBJ_LABEL, 0, 0, 0);// Creating obj. 
   ObjectSet("label", OBJPROP_CORNER, 1); // Reference corner 
   ObjectSet("label", OBJPROP_XDISTANCE, 5);// X coordinate 
   ObjectSet("label", OBJPROP_YDISTANCE, 15);// Y coordinate
   ObjectSetText("label", "Waiting for signal..",15,"Arial Bold",White);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   //Close all existing orders by MagicNumber
   CloseSell();
   CloseBuy();
   ObjectDelete("label");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----

   if (barStart < Time[0]) //start of new bar 
   {
   barStart = Time[0];
  
   CheckBuy();
   CheckSell();
   Heiken();
   
   Trendlord=iMA(NULL,0,50,0,MODE_EMA,PRICE_CLOSE,1);
   BarClose=iClose(NULL,0,1);
   BarOpen=iOpen(NULL,0,1);

   if (BarOpen > Trendlord&& BarClose < Trendlord&& (ready==0)) 
   {
   ready=1;
   }
   
   if (BarOpen < Trendlord&& BarClose > Trendlord&& (ready==0)) 
   {
   ready=1;
   }   
   
   if (BarClose < Trendlord&& existsell==0&& ready==1&& (ha=="Sell")) 
   {
   CloseBuy();
   OrderSend(Symbol(),OP_SELL,Lotsize,Bid,50,NULL,NULL,NULL,MagicNumber,0,Red);
   }
   
   if (BarClose > Trendlord&& existbuy==0&& ready==1&& (ha=="Buy")) 
   {
   CloseSell();
   OrderSend(Symbol(),OP_BUY,Lotsize,Ask,50,NULL,NULL,NULL,MagicNumber,0,Blue);
   } 
   } 
   Profit = OrderProfit();
   ObjectSetText("label", "P/L: " + (DoubleToStr(Profit,2)),15,"Arial Bold",White);
   

//----
   return(0);
  }
//+------------------------------------------------------------------+

so now it checks once a day, and waits for first signal (ready=1), but i want my profit (in label) shown realtime, not once a day. how can i fix it? it did work before...
 
 
  • Post #7
  • Quote
  • Edited 5:38pm Dec 31, 2010 2:32pm | Edited 5:38pm
  •  newyear498
  • Joined Nov 2010 | Status: Pips... or GTFO! | 1,023 Posts
Quoting ido370
Disliked
current EA code:
[code]//+------------------------------------------------------------------+
//|...
Ignored

The code looks correct.. I think your misunderstanding OrderProfit()

OrderProfit() is only going to show unrealized profits for your open trades.. once your trade closes it will go back to 0 on next open trades.. and start over..

maybe your looking to calculate your AccountBalance() every day or week? and then display the difference between that price and the current balance?

not sure how you want it displayed.. but OrderProfit() is updating every tick your unrealized gains per order the way you have it set up..

best wishes
 
 
  • Post #8
  • Quote
  • Dec 31, 2010 2:58pm Dec 31, 2010 2:58pm
  •  hanover
  • Joined Sep 2006 | Status: ... | 8,092 Posts
Quoting newyear498
Disliked
I think your misunderstanding OrderProfit()

OrderProfit() is only going to show unrealized profits for your open trades..
Ignored
OrderProfit() returns unrealized P/L on open trades and realized P/L on closed trades.
 
 
  • Post #9
  • Quote
  • Dec 31, 2010 5:34pm Dec 31, 2010 5:34pm
  •  newyear498
  • Joined Nov 2010 | Status: Pips... or GTFO! | 1,023 Posts
Quoting hanover
Disliked
OrderProfit() returns unrealized P/L on open trades and realized P/L on closed trades.
Ignored
Sorry, I only looked at the code real quick.. but the way Ido has it set up its only returning unrealized gains..

this is because it will only return profit for the selected trade.. and since your EA appears to always have an open trade your always seeing unrealized profits from last selected trade (which is open)

Ido.. your code.. you are showing unrealized gains from your currently open orders, this is because that what you have selected with SelectOrder()

Thus if you want to see your profits adding up from all your trades since the start time of the EA.. you could start adding them up from your last closed trades etc..

Hope this helps..
 
 
  • Post #10
  • Quote
  • Dec 31, 2010 8:48pm Dec 31, 2010 8:48pm
  •  ido370
  • | Joined Mar 2010 | Status: Member | 464 Posts
yes i do mean orderprofit(), since its always in a trade
i just want to see the current profit/loss of the trade in realtime. but somehow when i changed the EA to check with barstart only, and not every tick, the P/L value in the label is also only updating when a bar closes.
but i want to see the P/L change the whole time. is it possible? for as far as i know it should do that since i placed:
Inserted Code
Profit = OrderProfit();
   ObjectSetText("label", "P/L: " + (DoubleToStr(Profit,2)),15,"Arial Bold",White);
after the whole
Inserted Code
if (barStart < Time[0]) //start of new bar 
   {
   barStart = Time[0];

rest of the code goes here

}
part?
 
 
  • Post #11
  • Quote
  • Dec 31, 2010 11:08pm Dec 31, 2010 11:08pm
  •  newyear498
  • Joined Nov 2010 | Status: Pips... or GTFO! | 1,023 Posts
Quoting ido370
Disliked
yes i do mean orderprofit(), since its always in a trade
i just want to see the current profit/loss of the trade in realtime. but somehow when i changed the EA to check with barstart only, and not every tick, the P/L value in the label is also only updating when a bar closes.
but i want to see the P/L change the whole time. is it possible? for as far as i know it should do that since i placed:
[code]Profit = OrderProfit();...
Ignored
Honestly.. I don't know why it waits a bar until updating.. just notice that myself.. AccountProfit() updates every tick if you plug that in.. would this give results your looking for?

try

Profit = AccountProfit();
 
 
  • Post #12
  • Quote
  • Dec 31, 2010 11:37pm Dec 31, 2010 11:37pm
  •  nubcake
  • Joined Oct 2009 | Status: &gt;Apocalypto&lt; for Deputy PM | 2,918 Posts
grain of salt. i don't care enough to run this code on my machine to debug it... and i may be mis-reading what is posted here...

but my cursory look at the quoted code suggests to me that you are missing an orderselect before trying to access orderprofit. the reason it might be updating on the next tick and not the current one is because an order has been selected with those closebuy or closesell or whatever other code is in there that i haven't really taken notice of.

summary : i think you are selecting old orders, or maybe even wrong orders, and are missing an orderselect right before the orderprofit you want to show.
 
 
  • Post #13
  • Quote
  • Jan 1, 2011 8:05am Jan 1, 2011 8:05am
  •  ido370
  • | Joined Mar 2010 | Status: Member | 464 Posts
Quoting nubcake
Disliked
grain of salt....
Ignored
your right , i placed the Profit=OrderProfit(); just after the checking for existing orders, and now it works again thanks for the input
 
 
  • Post #14
  • Quote
  • Jan 1, 2011 8:47am Jan 1, 2011 8:47am
  •  nubcake
  • Joined Oct 2009 | Status: &gt;Apocalypto&lt; for Deputy PM | 2,918 Posts
Quoting ido370
Disliked
your right , i placed the Profit=OrderProfit(); just after the checking for existing orders, and now it works again thanks for the input
Ignored
no prob brother. fresh eyes can help.

edit : further to that, since i appear to have been correct... don't forget to do another for loop and add-up all of the openprofit values for all open orders, else again you will just end-up with bogus info with it only showing 1 of possibly multiple open orders.
 
 
  • Post #15
  • Quote
  • Jan 2, 2011 7:38am Jan 2, 2011 7:38am
  •  ido370
  • | Joined Mar 2010 | Status: Member | 464 Posts
no loop needed, there is always just 1 order active
 
 
  • Post #16
  • Quote
  • Last Post: Feb 14, 2011 6:21am Feb 14, 2011 6:21am
  •  damo76
  • | Joined Jan 2011 | Status: Junior Member | 2 Posts
Anyone able to write me a simple EA based on the appearance of certain arrow alerts I have here. I would like to backtest something I've been tinkering with..

Any help much appreciated
 
 
  • Platform Tech
  • /
  • while loop in EA causes 100% CPU
  • Reply to Thread
0 traders viewing now
Top of Page
  • Facebook
  • Twitter
About FF
  • Mission
  • Products
  • User Guide
  • Media Kit
  • Blog
  • Contact
FF Products
  • Forums
  • Trades
  • Calendar
  • News
  • Market
  • Brokers
  • Trade Explorer
FF Website
  • Homepage
  • Search
  • Members
  • Report a Bug
Follow FF
  • Facebook
  • Twitter

FF Sister Sites:

  • Metals Mine
  • Energy EXCH
  • Crypto Craft

Forex Factory® is a brand of Fair Economy, Inc.

Terms of Service / ©2023