I wrote a function to calculate position loss, but the code needs improvement

 

I've already written the first part of the code. I think that it's the first ever open-source EA that calculates the StopLoss in Cash!!!!! Later we can add NetLossPerOnePrecentLotPerPoint into the code also, but at first, we should improve its calculation functions therefore it never gives us a wrong answer. It calculates everything perfectly right now when one side of the forex currency pairs is USD like EURUSD. But when USD is not on any sides then it calculates a wrong answer. Does anybody have any ideas to improve it? Here is the code:

#property copyright "Gerald Mann (P. Ghasemi)"
#property link      "https://twitter.com/PeimanGhasemi"
#property version   "1.00"

void OnTick()
{
   if (PositionsTotal() > 0)
   {
      double ContractSize = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_CONTRACT_SIZE);
      // Check Handle
      if(!PositionSelect(_Symbol))
      {
         PrintFormat("PositionSelect(%s) failed. Error %d",_Symbol, GetLastError());
         return;
      }
      ResetLastError();
      long ticket=PositionGetInteger(POSITION_TICKET);
      //Check ticket
      if(ticket==0)
      {
         PrintFormat("Failed to get %s position ticket. Error %d", _Symbol, GetLastError());
         return;
      }
      // Position info
      double EntryPrice = PositionGetDouble(POSITION_PRICE_OPEN);
      double Price = PositionGetDouble(POSITION_PRICE_OPEN);
      double StopLossLevel = PositionGetDouble(POSITION_SL);
      double LotSize = PositionGetDouble(POSITION_VOLUME);
      
      //Calculations
      double Spent = LotSize * ContractSize;
      double Distance = MathAbs(Price - StopLossLevel);
      double PositionSlLossValueInCurrencyBaseValue = -(Spent * Distance);
      
      Print("EntryPrice:", EntryPrice);
      Print("StopLossLevel:", StopLossLevel);
      Print("Spent:", Spent);
      Print("PositionSlLossValueInCurrencyBaseValue:", PositionSlLossValueInCurrencyBaseValue);
   }
}
 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 

It's better to use SYMBOL_TRADE_TICK_VALUE in the formula because different brokers can have different tick values due to variations in liquidity providers

double StopLossValueCalc(double lot, double sl_points) {

   // Get tick value for the current symbol (value per pip in the account currency per 1 lot)
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
  
   double stopLossValue = sl_points * tickValue;

   maxLoss = -(lot * stopLossValue);

   return maxLoss;  
}


example use:

StopLossValueCalc(1.0, 300); // the stop loss in base currency for 300 points of risk