//+------------------------------------------------------------------+ //| LoteSizeCalc.mqh | //| Copyright 2025, Niquel Mendoza. | //| https://www.mql5.com/es/users/nique_372/news | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, Niquel Mendoza." #property link "https://www.mql5.com/es/users/nique_372/news" #property strict #ifndef MQLARTICLES_ACCOUNT_RM_BASES_LOTSIZECALC_MQH #define MQLARTICLES_ACCOUNT_RM_BASES_LOTSIZECALC_MQH //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ #include "Def.mqh" #include "..\\..\\..\\Utils\\FA\\Events.mqh" //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ namespace TSN { //+------------------------------------------------------------------+ //| Defines | //+------------------------------------------------------------------+ //--- #define MqlArticlesOrderTToOrder(v) ENUM_ORDER_TYPE(v == ORDER_TYPE_CLOSE_BY ? WRONG_VALUE : (v&1)) #define MqlArticlesRmOpIsSell(v) (((v)&1)==1) //--- #define MQLART_ORDERT_START_LIMITS (ORDER_TYPE_BUY_LIMIT) #define MQLART_ORDERT_START_STOPLIMIT (ORDER_TYPE_BUY_STOP_LIMIT) //--- // la idea es que solo pase buy limit y sell setop (resta) // entonces podemos hacer que // 2-3 (unsinegd) = overflow // 3-3 = 0 // 4-3 = 1 // 5-3 = 2 // minimo comun >1 #define MQLART_ORDERT_LIMIT_ENCIMAP(v) (((v)-3u)>1u) //--- //--- Por defecto usaremos el round (para manteer compatiblidad) #ifndef MQLART_LOTSIZE_CALC_ROUND #define MQLART_LOTSIZE_CALC_ROUND(number, step) TSNMQLART_ROUND_LOTSIZE_F(MathRound, number, step) #endif // MQLART_LOTSIZE_CALC_ROUND //--- enum ENUM_MQLART_GLOT_LAST_ERR { MQLART_GLOT_LAST_ERR_NOT, //--- MQLART_GLOT_LAST_ERR_INVALID_MAX_LOT, MQLART_GLOT_LAST_ERR_INVALID_STOPLOSS, MQLART_GLOT_LAST_ERR_INVALID_MAX_RISK_PER_OP, //--- sl MQLART_GLOT_LAST_ERR_INVALID_RISKOP, MQLART_GLOT_LAST_ERR_FAIL_CALC_IDEAL_SL, //--- money MQLART_GLOT_LAST_ERR_INVALID_CHOOSENLOT, }; //#define MQLART_GLOT_ENABLE_LOGS //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ class CGetLote { private: string m_symbol; double m_vol_step; double m_vol_min; double m_vol_max; double m_vol_limit; double m_point_value; int8_t m_digits; double m_ganancia_por_tick_real; ENUM_MQLART_GLOT_LAST_ERR m_last_err; public: CGetLote(const string& _symbol) : m_symbol(_symbol) { Update(); } CGetLote() : m_symbol(_Symbol) { Update(); } ~CGetLote() {} //--- Update void Update(); //--- Symbol void SetSymbol(const string& new_value); inline string GetSymbol() const { return m_symbol; } //--- inline double MinVolume() const { return m_vol_min; } inline double MaxVolume() const { return m_vol_max; } //--- __forceinline ENUM_MQLART_GLOT_LAST_ERR LastErr() const { return m_last_err; } //--- General functions // Calcula el stop loss ideal en puntos, basandose en el riesgo de operacion y en un lote especificado // Calculates the ideal stop loss in points, based on the transaction risk and a specified lot // si retorna=-1 =error long CalculateSLWithLotSize(double risk_per_operation, double entry_price, double lot, ulong deviation, ulong stop_limit); // Transforma dinero a puntos.. // Transform money to points long MoneyToPoints(const ENUM_ORDER_TYPE type, double risk_per_operation, double entry_price, double &chosen_lot, ulong deviation, ulong stop_limit); // Calcula el lote en base al riesgo por operacion y el stop loss en puntos // Calculate the lot based on the risk per operation and the stop loss in points bool GetLoteByRiskPerOperationAndSL(double glot, double max_risk_per_operation, double &new_risk_per_operation, long StopLoss, double& nlot); // Obtiene el lote maximo que se puede ejecutar // Get the maximum batch that can be executed __forceinline double GetMaxLote(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit); // Obtiene el lote maximo que se puede comprar por el riesgo por operacion en USD (no %, osea un riesgo ya calculado) // Gets the maximum lot that can be purchased for the risk per operation in USD (not %, i.e. a risk already calculated) double CalculateLoteSizeWVal(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit, double max_risk); //--- static void FormatErr(CGetLote* ptr, string& str); }; //+---------------------------------------------------------------------+ //| Determine the optimal lot size based on risk and current conditions | //+---------------------------------------------------------------------+ bool CGetLote::GetLoteByRiskPerOperationAndSL(double glot, double max_risk_per_operation, double &new_risk_per_operation, long StopLoss, double& nlot) { //--- new_risk_per_operation = 0.0; nlot = 0.00; //--- if(glot <= 0) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("Lote maximo invalido: %.2f", glot)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_INVALID_MAX_LOT; return false; } if(StopLoss <= 0) // por si acaso { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("Stop Loss distance is less than or equal to zero, now correct the stoploss distance: %d", StopLoss)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_INVALID_STOPLOSS; return false; } if(max_risk_per_operation <= 0) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("El riesgo maximo por operacion %.2f es invalido", max_risk_per_operation)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_INVALID_MAX_RISK_PER_OP; return false; } //--- const long spread = SymbolInfoInteger(m_symbol, SYMBOL_SPREAD); const double rpo = glot * (m_ganancia_por_tick_real * (spread + 1 + StopLoss)); //--- if(rpo > max_risk_per_operation) { double new_lot = (max_risk_per_operation / rpo) * glot; new_lot = MQLART_LOTSIZE_CALC_ROUND(new_lot, m_vol_step); new_risk_per_operation = new_lot * (m_ganancia_por_tick_real * (spread + 1 + StopLoss)); nlot = new_lot; } else { new_risk_per_operation = rpo; nlot = glot; } //--- if(nlot > m_vol_max) nlot = m_vol_max; //--- #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Risk per operation(%.2f) = %.2f * ( %f * ( %i + 1 + %i)))", new_risk_per_operation, nlot, m_ganancia_por_tick_real, spread, StopLoss)); #endif // MQLART_GLOT_ENABLE_LOGS //--- #ifdef MQLART_GLOT_ENABLE_LOGS if(nlot <= 0.00) FastLog(FUNCION_ACTUAL, WARNING_TEXT, StringFormat("The lot %.2f is invalid, the risk %.2f increases or the sl %d decreases", nlot, max_risk_per_operation, StopLoss)); else FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("For the stop loss %i in points and risk per operation: %.2f, the ideal lot is: %.2f", StopLoss, max_risk_per_operation, nlot)); #endif // MQLART_GLOT_ENABLE_LOGS //--- return true; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ long CGetLote::CalculateSLWithLotSize(double risk_per_operation, double entry_price, double lot, ulong deviation, ulong stop_limit) { //--- Check lot if(lot <= 0) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("No se pudo calcular lote valido para el riesgo especificado = %.2f", risk_per_operation)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_INVALID_RISKOP; return -1; } //--- Calculamos el stop loss en base al riesgo por operacion y al lote const long spread = SymbolInfoInteger(m_symbol, SYMBOL_SPREAD); const double result = (risk_per_operation / (lot * m_ganancia_por_tick_real)) - spread - 1; const long ideal_sl = long(MathRound(result)); //--- Check SL if(ideal_sl <= 0) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("Stop loss %i invalid, please increase the risk per trade %.2f", ideal_sl, risk_per_operation)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_FAIL_CALC_IDEAL_SL; return -1; } return ideal_sl; } //+-----------------------------------------------------------------------+ //| Calculate the stop loss distance in points based on risk and lot size | //+-----------------------------------------------------------------------+ long CGetLote::MoneyToPoints(const ENUM_ORDER_TYPE type, double money, double entry_price, double &chosen_lot, ulong deviation, ulong stop_limit) { //--- chosen_lot = CalculateLoteSizeWVal(type, entry_price, deviation, stop_limit, money); if(chosen_lot <= 0) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("No se pudo calcular lote valido para el dinero especificado = %.2f", money)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_INVALID_CHOOSENLOT; return -1; } //--- const long spread = SymbolInfoInteger(m_symbol, SYMBOL_SPREAD); const double result = (money / (chosen_lot * m_ganancia_por_tick_real)) - spread - 1; const long ideal_sl = long(MathRound(result)); //--- if(ideal_sl <= 0) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("Stop loss %i invalid, please increase the money = %.2f", ideal_sl, money)); #endif // MQLART_GLOT_ENABLE_LOGS m_last_err = MQLART_GLOT_LAST_ERR_FAIL_CALC_IDEAL_SL; return -1; } return ideal_sl; } //+--------------------------------------------------------------------+ //| Function to obtain the ideal lot based on your risk per operation | //+--------------------------------------------------------------------+ // risk_per_operation in USD, not % __forceinline double CGetLote::GetMaxLote(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit) { return CalculateLoteSizeWVal(type, entry_price, deviation, stop_limit, DBL_MAX); } //+------------------------------------------------------------------+ // 1. Se asume que: // Type, entry price, deviation, stoplimit son valores validos (en rango no fuera) y entry price es positivo double CGetLote::CalculateLoteSizeWVal(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit, double max_risk) { //--- //double price, ulong deviation, ulong stop_limit, double m_point_value, int8_t m_digits if(type >= MQLART_ORDERT_START_LIMITS && type < ORDER_TYPE_CLOSE_BY) { if(type < MQLART_ORDERT_START_STOPLIMIT) entry_price += (MQLART_ORDERT_LIMIT_ENCIMAP(type)) ? -(m_point_value * deviation) : (m_point_value * deviation); else if(MqlArticlesRmOpIsSell(type)) // Para stop restamos cuando es sell (sell stop limit) entry_price = entry_price - (m_point_value * deviation) + (m_point_value * stop_limit); else entry_price = entry_price + (m_point_value * deviation) - (m_point_value * stop_limit); } //--- //const double entry_price = OrderTypeToPriceCalculator[type](entry_price, deviation, stop_limit, m_point_value, m_digits); const double margin_free = AccountInfoDouble(ACCOUNT_MARGIN_FREE); if(margin_free <= 0.00) return 0.0; // normal no hay nada.. //--- double margin = EMPTY_VALUE; ::ResetLastError(); if(!OrderCalcMargin(MqlArticlesOrderTToOrder(type), m_symbol, 1.0, entry_price, margin)) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("OrderCalcMargin() failed. Error = %d", ::GetLastError())); #endif // MQLART_GLOT_ENABLE_LOGS return 0.0; } //--- if(max_risk >= margin_free) max_risk = margin_free; //--- const double result = MathFloor((max_risk / margin) / m_vol_step) * m_vol_step; //--- if(result >= m_vol_min) { if(result <= m_vol_max) { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Lote calculado = %.2f >> precio = %.*f >> margen(1) = %.2f", result, m_digits, entry_price, margin)); #endif // MQLART_GLOT_ENABLE_LOGS return result; } return (m_vol_limit > 0.00 && result >= m_vol_limit) ? m_vol_limit : m_vol_max; } else { #ifdef MQLART_GLOT_ENABLE_LOGS FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("Calculo invalido, lote muy pequeño = %.4f >> precio = %.*f >> margen(1) = %.2f", result, m_digits, entry_price, margin)); #endif // MQLART_GLOT_ENABLE_LOGS return 0.0; // Invalido } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CGetLote::Update(void) { //--- m_vol_step = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_STEP); m_vol_min = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_MIN); m_vol_max = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_MAX); m_vol_limit = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_LIMIT); m_digits = (int8_t)SymbolInfoInteger(m_symbol, SYMBOL_DIGITS); m_point_value = SymbolInfoDouble(m_symbol, SYMBOL_POINT); //--- const ENUM_SYMBOL_CALC_MODE calc_mode = (ENUM_SYMBOL_CALC_MODE)SymbolInfoInteger(m_symbol, SYMBOL_TRADE_CALC_MODE);; switch(calc_mode) { case SYMBOL_CALC_MODE_FOREX: case SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE: m_ganancia_por_tick_real = SymbolInfoDouble(m_symbol, SYMBOL_TRADE_TICK_VALUE); break; case SYMBOL_CALC_MODE_CFD: case SYMBOL_CALC_MODE_CFDINDEX: case SYMBOL_CALC_MODE_CFDLEVERAGE: m_ganancia_por_tick_real = SymbolInfoDouble(m_symbol, SYMBOL_TRADE_CONTRACT_SIZE) * SymbolInfoDouble(m_symbol, SYMBOL_TRADE_TICK_SIZE); break; default: m_ganancia_por_tick_real = SymbolInfoDouble(m_symbol, SYMBOL_TRADE_CONTRACT_SIZE) * SymbolInfoDouble(m_symbol, SYMBOL_TRADE_TICK_SIZE); break; } } //+------------------------------------------------------------------+ void CGetLote::SetSymbol(const string& new_value) { m_symbol = new_value; Update(); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ static void CGetLote::FormatErr(CGetLote *ptr, string &str) { str.Reserve(128); str += FUNCION_ACTUAL + " -- "; switch(ptr.LastErr()) { case MQLART_GLOT_LAST_ERR_NOT: str += "Not error"; break; case MQLART_GLOT_LAST_ERR_INVALID_MAX_LOT: str += "Invalid maxium lote (must be > 0.0)"; break; case MQLART_GLOT_LAST_ERR_INVALID_STOPLOSS: str += "Invalid stop loss value (must be > 0)"; break; case MQLART_GLOT_LAST_ERR_INVALID_MAX_RISK_PER_OP: str += "Invalid risk per operatrion (value), must be > 0.0"; break; case MQLART_GLOT_LAST_ERR_INVALID_RISKOP: str += "Invalid lot size, must be > 0.0"; break; case MQLART_GLOT_LAST_ERR_FAIL_CALC_IDEAL_SL: str += "Failed calc ideal sl, result is minor or eqaul at zero"; break; case MQLART_GLOT_LAST_ERR_INVALID_CHOOSENLOT: str += "Calculed lot are <= 0, check: risk per op | free margin"; break; default: str += "Uknow error"; break; } } //--- } //+------------------------------------------------------------------+ #endif // MQLARTICLES_ACCOUNT_RM_BASES_LOTSIZECALC_MQH //+------------------------------------------------------------------+