Auto Lot Size EA Help

 

Hi, I have an expert advisor that I wanted to see how it performs under auto lot size management. I wanna know if someone could help code into the expert advisor to calculate lot size based off of:

((( my account balance * .05) / 30 ) / 10) 

[.05 being my risk percentage, 30 being my SL, and dividing by 10 to get the lot size]

I know that after computation there would be many digits.for example, (((100 * .05) / 30 ) / 10)= .0166666667, so it would have to be rounded to .02 lots because lot sizes don't exceed 2 decimal places. Any help would be much appreciated!

//+------------------------------------------------------------------+
//                        DO NOT DELETE THIS HEADER
//             DELETING THIS HEADER IS COPYRIGHT INFRIGMENT 
//
//                   Copyright ©2011, ForexEAdvisor.com
//                 ForexEAdvisor Strategy Builder version 0.2
//                        http://www.ForexEAdvisor.com 
//
// THIS EA CODE HAS BEEN GENERATED USING FOREXEADVISOR STRATEGY BUILDER 0.2 
// on: 4/1/2018 2:21:31 AM
// Disclaimer: This EA is provided to you "AS-IS", and ForexEAdvisor disclaims any warranty
// or liability obligations to you of any kind. 
// UNDER NO CIRCUMSTANCES WILL FOREXEADVISOR BE LIABLE TO YOU, OR ANY OTHER PERSON OR ENTITY,
// FOR ANY LOSS OF USE, REVENUE OR PROFIT, LOST OR DAMAGED DATA, OR OTHER COMMERCIAL OR
// ECONOMIC LOSS OR FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, STATUTORY, PUNITIVE,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES WHATSOEVER RELATED TO YOUR USE OF THIS EA OR 
// FOREXEADVISOR STRATEGY BUILDER     
// Because software is inherently complex and may not be completely free of errors, you are 
// advised to verify this EA. Before using this EA, please read the ForexEAdvisor Strategy Builder
// license for a complete understanding of ForexEAdvisor' disclaimers.  
// USE THIS EA AT YOUR OWN RISK. 
//  
// Before adding this expert advisor to a chart, make sure there are NO
// open positions.
//                      DO NOT DELETE THIS HEADER
//             DELETING THIS HEADER IS COPYRIGHT INFRIGMENT 
//+------------------------------------------------------------------+
extern int MagicNumber=10001;
extern double Lots;
extern double StopLoss=30;
extern double TakeProfit=0;
extern int TrailingStop=5;
extern int Slippage=3;
datetime PreviousBarTime;
//+------------------------------------------------------------------+
//    expert start function
//+------------------------------------------------------------------+
int start()
{
  double MyPoint=Point;
  if(Digits==3 || Digits==5) MyPoint=Point*10;
  
  double TheStopLoss=0;
  double TheTakeProfit=0;
  if( TotalOrdersCount()==0||1||2||3||4||5||6||7) 
  {
     int result=0;
     if(Close[1]>Close[2]&&NewBar()) // Here is your open buy rule
     {
        result=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"EA Generator www.ForexEAdvisor.com",MagicNumber,0,Blue);
        if(result>0)
        {
         TheStopLoss=0;
         TheTakeProfit=0;
         if(TakeProfit>0) TheTakeProfit=Ask+TakeProfit*MyPoint;
         if(StopLoss>0) TheStopLoss=Ask-StopLoss*MyPoint;
         OrderSelect(result,SELECT_BY_TICKET);
         OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green);
        }
        return(0);
     }
     if(Close[1]<Close[2]&&NewBar()) // Here is your open Sell rule
     {
        result=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"EA Generator www.ForexEAdvisor.com",MagicNumber,0,Red);
        if(result>0)
        {
         TheStopLoss=0;
         TheTakeProfit=0;
         if(TakeProfit>0) TheTakeProfit=Bid-TakeProfit*MyPoint;
         if(StopLoss>0) TheStopLoss=Bid+StopLoss*MyPoint;
         OrderSelect(result,SELECT_BY_TICKET);
         OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green);
        }
        return(0);
     }
  }
  
  for(int cnt=0;cnt<OrdersTotal();cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   
         OrderSymbol()==Symbol() &&
         OrderMagicNumber()==MagicNumber 
         )  
        {
         if(OrderType()==OP_BUY)  
           {
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>MyPoint*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-MyPoint*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MyPoint,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
           }
         else 
           {
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(MyPoint*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+MyPoint*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+MyPoint*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
           }
        }
     }
   return(0);
}

int TotalOrdersCount()
{
  int result=0;
  for(int i=0;i<OrdersTotal();i++)
  {
     OrderSelect(i,SELECT_BY_POS ,MODE_TRADES);
     if (OrderMagicNumber()==MagicNumber) result++;

   }
  return (result);
}
bool NewBar()
{
if(PreviousBarTime<Time[0])
{
PreviousBarTime = Time[0];
return(true);
}

return(false); // in case if - else statement is not executed
}
 
tyrenw461:

calculate lot size based off of: ((( my account balance * .05) / 30 ) / 10) 

would have to be rounded to .02 lots because lot sizes don't exceed 2 decimal places.

Any help would be much appreciated!

  1. Risk depends on your initial stop loss, lot size, and the value of the pair. It is not a function of account balance.
    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. Account Balance * 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.
    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=0.1 Lots maximum.

  2. № 1.4

  3. Help you with what? You haven't stated a problem. Show us your attempt (using CODE button) and state the nature of your problem.
              No free help
              urgent help.

  4. // THIS EA CODE HAS BEEN GENERATED USING FOREXEADVISOR STRATEGY BUILDER 0.2 
    EA builder, EATree, fxDreema, FxPro, Online Forex Expert Advisor Generator, Quant, Visual Trader Studio, MQL5 Wizard, etc. are all the same. You will get something quick, but then you will spend a much longer time trying to get it right, than if you learned the language up front, and then just wrote it.
    • Since you haven't learned MQL4/5, therefor there is no common language for us to communicate.
      If we tell you what you need, you can't code it.
      If we give you the code, you don't know how to integrate it into yours.
      We are willing to HELP you when you post your attempt (using SRC) and the nature of your problem, but we are not going to debug your hundreds of lines of code. You are essentially going to be on your own.

    • EA builder makes bad code counting up while closing multiple orders.
      EA builder makes bad code Bars is unreliable (max bars on chart) volume is unreliable (miss ticks) Always use time. New candle - MQL4 forum
      EA builder makes bad code, not adjusting for 4/5 digit brokers, TP/SL and slippage.
      EA builder makes bad code, not adjusting for ECN brokers. (pre-Build 500)
      EA builder makes bad code, not checking return codes.
      EATree uses objects on chart to save values - not persistent storage (files or GV+Flush.) No recovery (crash/power failure.)
    Learn to code it or or pay (Freelance) someone to code it.

  5. if( TotalOrdersCount()==0||1||2||3||4||5||6||7) 
    That does do what you think it does. True = non-zero and false = zero so you get
    if( 3 < 2 < 1 )
    if( false < 1 )
    if(     0 < 1 )
    if(     true  )
    if( 3 > 2 > 1 )
    iftrue > 1 )
    if(     1 > 1 )
    if(     false )
    
    In your case you get TotalOrdersCount() == 0.

  6. result=OrderSend(...);
            if(result>0)
    Check your return codes for errors, report them and you would know why. Don't just silence the compiler, it is trying to help you.
              What are Function return values ? How do I use them ? - MQL4 and MetaTrader 4 - MQL4 programming forum
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    Only those functions that return a value (e.g. iClose, MarketInfo, etc.) must you call ResetLastError before in order to check after.

  7.          OrderSelect(result,SELECT_BY_TICKET);
             OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(TheStopLoss,Digits),NormalizeDouble(TheTakeProfit,Digits),0,Green);
    
    No need to open and then modify (pre-Build 500)
  8. Do NOT use NormalizeDouble, EVER. For ANY Reason. It's a kludge, don't use it. It's use is usually wrong

  9. for(int cnt=0;cnt<OrdersTotal();cnt++)
    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 (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 and MetaTrader 4 - MQL4 programming forum
      For FIFO (US brokers,) and you (potentially) process multiple orders per symbol, you must count up and on a successful operation, reprocess all positions (set index to -1 before continuing.)
    2. and check OrderSelect in case earlier positions were deleted.
                What are Function return values ? How do I use them ? - MQL4 and MetaTrader 4 - 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 the Predefined Variables (Bid/Ask) or OrderClosePrice() instead, on the next order/server call.

Reason: