Lot size calculation: multiple orders

 

Hi,

For an EA, I need a function with loop to find lot size.

There may be a random number of open lots.

When a lot is open, there is always a Take Profit as target. But if the Take Profit is not reach and there is a opposed open signal, we open this new order by calculting the new lot size of this order (with Take profit as target for the new order opened).

For example, what would be the mql4 code (function) to find the lot size of this third trade (BUY at 1.18393) to close all orders in profit?

Lot size

Thank you for your answer.

 

8tango:

When a lot is open, there is always a Take Profit as target.

But if the Take Profit is not reach and there is a opposed open signal, we open this new order by calculting the new lot size of this order (with Take profit as target for the new order op @8tango ened).

For example, what would be the mql4 code (function) to find the lot size of this third trade (BUY at 1.18393) to close all orders in profit?

  1. Why did you post your MT4 question in the MT5 EA 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.

  2. When an order is open, There is a Take Profit only if you set it. There must be a Stop Loss or you can't compute your risk and lot size.

    Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk. Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    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.

  3. The existing order is irrevalent in computing the new order's risk.

  4. Show us your attempt at closing (using the CODE button) and state the nature of your problem. You already know how to open.
              No free help 2017.04.21

    Or pay someone. Top of every page is the link Freelance.
              Hiring to write script - General - MQL5 programming forum 2018.05.12

    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
    2. For In First Out (FIFO rules — US brokers,) and you (potentially) process multiple orders per symbol, you must find the earliest order (count up,) 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

    3. 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
    4. 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 instead, be direction independent and just use OrderClosePrice().
 
William Roeder:
  1. Why did you post your MT4 question in the MT5 EA 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.

  2. When an order is open, There is a Take Profit only if you set it. There must be a Stop Loss or you can't compute your risk and lot size.
  3. The existing order is irrevalent in computing the new order's risk.

  4. Show us your attempt at closing (using the CODE button) and state the nature of your problem. You already know how to open.
              No free help 2017.04.21

    Or pay someone. Top of every page is the link Freelance.
              Hiring to write script - General - MQL5 programming forum 2018.05.12

Thank you for your answer.

I began to build this function below to calculte the lot size (it is not finished).

// Take Profit
double TakeProfit = 1.18559;

OrderSizeLot(TakeProfit);

// Function: Calculate Lot Size
double OrderSizeLot(double TakeProfitTarget)
{
double GrandTotal, TotalBuy, TotalSell;
for(int pos=0;pos<OrdersTotal();pos++)
  {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)){
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
        {
         if(OrderType()==OP_BUY)
           {
           if(Ask<=TakeProfitTarget){TotalBuy = (((TakeProfitTarget-OrderOpenPrice()) * OrderLots()) * 100) + OrderSwap() + OrderCommission();}
           else{TotalBuy = (((OrderOpenPrice()-TakeProfitTarget) * OrderLots()) * 100) + OrderSwap() + OrderCommission();}
           }
         if(OrderType()==OP_SELL)
           {
           if(Bid>=TakeProfitTarget){TotalSell = (((OrderOpenPrice()-TakeProfitTarget) * OrderLots()) * 100) + OrderSwap() + OrderCommission();}
           else{TotalSell = (((TakeProfitTarget-OrderOpenPrice()) * OrderLots()) * 100) + OrderSwap() + OrderCommission();}
           }        
        GrandTotal = TotalBuy + TotalSell;
        // Calculate Lot Size
        // ?????
     }
    }      
  }  
  return(0);
}

I would like a function with a loop which calculate (for example the trades into my picture above):

1) The profit or lost for my 0.01 BUY if I close the trade at 1.18559.

2)  The profit or lost for my 0.08 SELL if I close the trade at 1.18559.

3) The total profit or lost of my 0.01 BUY and my 0.08 SELL if I close the 2 trades at 1.18559.

4) The lot size for a new BUY trade open at 1.18393 with a take profit at 1.18559.

 
8tango:

In future please post in the correct section.

I will move your topic to the MQL4 and Metatrader 4 section.

 

8tango:

1) The profit or lost for my 0.01 BUY if I close the trade at 1.18559.

2)  The profit or lost for my 0.08 SELL if I close the trade at 1.18559.

3) The total profit or lost of my 0.01 BUY and my 0.08 SELL if I close the 2 trades at 1.18559.

4) The lot size for a new BUY trade open at 1.18393 with a take profit at 1.18559.

  1. OrderLots()) * 100) + …
    Don't hard code constants. That is correct only if the quote currency is your account currency. Do the algebra. #1.2.2
  2. Do the algebra. #1.2.2
  3. Do the algebra. #1.2.2
  4. What part of "Risk depends on your initial stop loss, lot size, and the value of the symbol." is unclear to you? Do the algebra. #1.2.2 The TakeProfit is irrevalent.
Reason: