MQLArticles/Account/RM/RiskManagement/Core/Core.mqh
912 行
37 KiB
MQL5
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
//| RiskManagement.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_RISKMANAGEMENT_CORE_CORE_MQH
#define MQLARTICLES_ACCOUNT_RM_RISKMANAGEMENT_CORE_CORE_MQH
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
Nique_372
2026-11-07 21:17:58 -05:00
// manager para los hooks
Nique_372
2026-10-27 18:16:53 -05:00
#include "..\\Hooks\\Man.mqh"
Nique_372
2026-11-07 21:17:58 -05:00
// defincion de extra mod
Nique_372
2026-10-27 18:16:53 -05:00
#include "..\\LPMods\\Def.mqh"
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
namespace TSN
{
//+------------------------------------------------------------------+
//| Clase Base CRiskManagement |
//+------------------------------------------------------------------+
Nique_372
2026-10-27 22:04:41 -05:00
class CRiskManagemet : public CAccountGestor
Nique_372
2026-10-27 18:16:53 -05:00
{
protected:
//---
Nique_372
2026-10-27 22:04:41 -05:00
CTrade m_trade; // Instancia de ctrade
CGetLote m_get_lote; // Obtencino de lote
int m_type; // Tipo de risk
bool m_is_init; // flag indicating if it is init
ulong m_magic_number; // Numero magico
//--- Profits\Times
double m_daily_profit, m_weekly_profit, m_monthly_profit, m_gross_profit; // Profits de la cuenta
datetime m_last_day_time, m_last_weekly_time, m_last_monthly_time, m_init_trade_time; // Times init
//--- Posiciones
int m_positions[RISK_MANAGEMENT_BASES_MAX_POS_OPEN]; // Open positions
int m_positions_size; // Tamaño de posiciones
//--- Relacionados a la obtencino de lote\sl
double m_nmlpo; //last expected loss
Nique_372
2026-10-27 18:16:53 -05:00
ENUM_GET_LOT m_type_get_lot;
long m_StopLoss; //m_StopLoss
Nique_372
2026-10-27 22:04:41 -05:00
//--- Balances
double m_chosen_balance;
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-28 22:50:57 -05:00
//--- Manager (solo shared)
Nique_372
2026-10-28 18:01:47 -05:00
CLossProfitManager* m_loss_profits_manager;
CLossProfit* m_lp_gmlpo;
Nique_372
2026-10-27 18:16:53 -05:00
//--- Modifiers
CRiskManagemeHookManager m_hooks;
Nique_372
2026-10-28 13:32:56 -05:00
bool m_cached_mod[LOSSPROFIT_MANAGER_MAX_ITEMS]; // tabla: [typeLP -> is_modified?]
Nique_372
2026-10-28 18:01:47 -05:00
//---
// nota respescto a previas versiones ya no elimino manualmete dado que no hace falta
// lpmanager el usuario me da un puntero yo solo lo uso
// getlote\ctrade\hooks ahora son instancia, se eliminan solos
Nique_372
2026-10-27 22:04:41 -05:00
//---
public:
double m_pos_current_profit; // Profit curr
protected:
//--- functions extra
bool TryRemoveFromArrayOfPos(const int global_pos_index);
Nique_372
2026-10-27 18:16:53 -05:00
//--- Update profits function
Nique_372
2026-10-28 22:50:57 -05:00
void UpdateProfit(const double profit);
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-28 13:32:56 -05:00
//--- Get F
CLossProfitBaseLP* CreateLossProfit(const uint type) const;
// virtual
virtual FuncionLossProfitSuperate GetSuperateFunc(const uint type) const;
virtual FTSNMQLArtRmPctgVal GetCalcFunc(const uint type, ENUM_APPLIED_PERCENTAGES _applied, ENUM_RISK_CALCULATION_MODE _mode) const;
Nique_372
2026-10-27 18:16:53 -05:00
public:
//--- Constructor and Destructor
Nique_372
2026-10-28 13:32:56 -05:00
CRiskManagemet(const ulong _magic, const int type);
Nique_372
2026-10-27 18:16:53 -05:00
~CRiskManagemet();
//--- Superated funcionts
Nique_372
2026-10-28 18:01:47 -05:00
void SetLossProfitManager(CLossProfitManager& lp_manager) { m_loss_profits_manager = &lp_manager; }
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-28 17:19:08 -05:00
//--- Mods
Nique_372
2026-10-27 18:16:53 -05:00
bool AddModificator(CExtraModifications* modificator); // Modificator pointer
__forceinline bool AddModificator(CExtraModifications &modificator) { return AddModificator(&modificator); }
Nique_372
2026-10-28 17:19:08 -05:00
__forceinline bool IsModAlredyUsed(const int type) const { return m_cached_mod[type]; }
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-28 17:19:08 -05:00
//--- General Hook
Nique_372
2026-10-27 18:16:53 -05:00
bool AddRmHook(IRiskManagementHook* hook);
__forceinline bool AddRmHook(IRiskManagementHook& hook) { return AddRmHook(&hook); }
Nique_372
2026-10-28 17:19:08 -05:00
//--- LP
Nique_372
2026-10-27 18:16:53 -05:00
bool AddLP(CLossProfit* new_loss);
Nique_372
2026-10-28 17:19:08 -05:00
// default version
Nique_372
2026-10-28 10:48:27 -05:00
bool AddLP(double _calc_value, ENUM_APPLIED_PERCENTAGES _applied, ENUM_RISK_CALCULATION_MODE _mode, ENUM_TYPE_LOSS_PROFIT type, bool strict,
Nique_372
2026-10-27 18:16:53 -05:00
bool is_dynamic = false, string percentages_to_activate = NULL, string risks_to_be_applied = NULL); // Loss
Nique_372
2026-10-28 17:19:08 -05:00
//- finish
Nique_372
2026-10-27 22:04:41 -05:00
void EndAddProfitLoss();
Nique_372
2026-10-27 18:16:53 -05:00
//--- Functions inherited from CAccountGestor
// Basic events
void OnNewDay(const datetime curr_time) override;
void OnNewWeek(const datetime curr_time) override;
void OnNewMonth(const datetime curr_time) override;
// Account status
Nique_372
2026-10-29 08:05:14 -05:00
void OnNewProfit(const datetime curr_time) override;
Nique_372
2026-10-27 18:16:53 -05:00
void OnClosePosition(const ROnClosePosition &pos, const int global_pos_index) override;
void OnOpenPosition(const ROnOpenPosition &pos) override;
void OnWithdrawalDeposit(const double value) override;
void OnInitNewPos(const ROnOpenPosition &position) override;
//--- Get the lot using GMPLO and type_get_lot
double GetLote(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit);
//--- Obtain the SL by risk per operation
Nique_372
2026-10-27 22:04:41 -05:00
__forceinline long GetSL(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit, double& choosen_lot);
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
//--- Calculos (lote y sl) - (relacionados-getter\setter)
// calulador principal de lote
CGetLote* LotCalc() { return &m_get_lote; }
Nique_372
2026-10-28 13:32:56 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
// tipo de obtencion
Nique_372
2026-10-27 18:16:53 -05:00
void TypeGetLot(ENUM_GET_LOT new_get_mode) { m_type_get_lot = new_get_mode; }
inline ENUM_GET_LOT TypeGetLot() const { return m_type_get_lot; }
Nique_372
2026-10-28 13:32:56 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
// estimacion perdida (last)
__forceinline double Nlmpo() const { return m_nmlpo; }
Nique_372
2026-10-28 13:32:56 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
// stop loss
Nique_372
2026-10-28 18:01:47 -05:00
inline void SetStopLoss(const string& sym, double dist_open_sl) { m_StopLoss = (long)ConvertPriceToPoints(sym, dist_open_sl); }
inline void SetStopLoss(long _sl_point_) { m_StopLoss = _sl_point_; }
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
//--- General
inline ulong MagicNumber() const { return m_magic_number; }
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
//--- Function to set general class parameters
Nique_372
2026-10-28 16:35:48 -05:00
virtual bool SetGeneralParameters(const MqlParam &params[]) = 0;
Nique_372
2026-10-27 22:04:41 -05:00
//--- Proftis
inline double GrossProfit() const { return m_gross_profit; }
inline double WeeklyProfit() const { return m_weekly_profit; }
inline double DailyProfit() const { return m_daily_profit; }
inline double MontlyProfit() const { return m_monthly_profit; }
//--- Functions to work with open positions
__forceinline int GetPositions(uint flags) const; // Get total open positions filtered by flags
__forceinline int GetPositionsTotal() const { return m_positions_size; }
__forceinline void CloseAllPositions(uint flags = FLAG_CLOSE_ALL_LOSS | FLAG_CLOSE_ALL_PROFIT | FLAG_POSITION_TYPE_BUY | FLAG_POSITION_TYPE_SELL);
void CloseAllOrders(uint flags);
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
//--- Calcular el profit actual
__forceinline void CalcProfit() { m_pos_current_profit = g_account_open_positions.GetProfitMask(m_positions, m_positions_size); }
Nique_372
2026-10-28 13:32:56 -05:00
//--- Tipo
__forceinline int Type() const { return m_type; }
//--- Ptr
virtual void* GetPtrLossProfits() { return &this; }
//--- Punteros a funcion
//-- is superated
Nique_372
2026-11-01 21:32:38 -05:00
#ifdef MQLARTICLES_RM_MULTI_EA_MODE
Nique_372
2026-10-28 13:32:56 -05:00
// usando profit especifico
Nique_372
2026-11-01 21:32:38 -05:00
static __forceinline bool FNormIsSupertedLoss(const double value, const double saved_value, void *ptr) { return (-((CRiskManagemet*)ptr).m_pos_current_profit) > value; }
static __forceinline bool FNormIsSupertedProfit(const double value, const double saved_value, void *ptr) { return ((CRiskManagemet*)ptr).m_pos_current_profit > value; }
#else // MQLARTICLES_RM_MULTI_EA_MODE
Nique_372
2026-10-28 13:32:56 -05:00
// ussando profit general
Nique_372
2026-10-29 16:46:31 -05:00
static __forceinline bool FNormIsSupertedLoss(const double value, const double saved_value, void *ptr) { return (-account_status_curr_profit) > value; }
static __forceinline bool FNormIsSupertedProfit(const double value, const double saved_value, void *ptr) { return account_status_curr_profit > value; }
Nique_372
2026-11-01 21:32:38 -05:00
#endif // MQLARTICLES_RM_MULTI_EA_MODE
Nique_372
2026-10-28 13:32:56 -05:00
Nique_372
2026-11-02 21:51:46 -05:00
//---
// WARNING:
// Money=TalCaul
// Percentage el usuario por AddLP pasa el porcentaje completo TAL CUAL
// Pero si quiere modificar "in caliente" tendra que pasar EL PORCENTAGGE NORMALIZADO /100.0 para no olvidarse use las macros
// TSNMQLART_RISKM_NORM_PERCERNTAGE_A y TSNMQLART_RISKM_NORM_PERCERNTAGE .. (A=prefijo para "assing")
Nique_372
2026-10-28 13:32:56 -05:00
//-- calculos
static __forceinline double FCalcVMoney(double calc_value, void* ptr) { return calc_value; }
// pctg
Nique_372
2026-11-02 21:51:46 -05:00
static __forceinline double FCalcPctg_Balance(double calc_value, void* ptr) { return ((calc_value) * AccountInfoDouble(ACCOUNT_BALANCE)); }
static __forceinline double FCalcPctg_Equity(double calc_value, void* ptr) { return ((calc_value) * AccountInfoDouble(ACCOUNT_EQUITY)); }
static __forceinline double FCalcPctg_GNeta(double calc_value, void* ptr) { return ((calc_value) * (account_status.account_gross_profit)); }
static __forceinline double FCalcPctg_FreeMag(double calc_value, void* ptr) { return ((calc_value) * AccountInfoDouble(ACCOUNT_MARGIN_FREE)); }
Nique_372
2026-10-28 22:50:57 -05:00
//---
Nique_372
2026-11-06 10:40:44 -05:00
static void FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out);
Nique_372
2026-10-27 18:16:53 -05:00
};
Nique_372
2026-11-07 21:17:58 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
// #define TSNMQLART_RM_RISKAMANGEMENT_ELOGS
// no'del ptr
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
CRiskManagemet::CRiskManagemet(const ulong _magic, const int type)
Nique_372
2026-10-27 22:04:41 -05:00
:
//---
Nique_372
2026-10-28 22:50:57 -05:00
m_daily_profit(0.00), m_weekly_profit(0.00), m_monthly_profit(0.00), m_gross_profit(0.00),
Nique_372
2026-10-27 22:04:41 -05:00
m_last_day_time(0), m_last_weekly_time(0), m_last_monthly_time(0),
m_init_trade_time(0),
Nique_372
2026-11-07 21:17:58 -05:00
m_positions_size(0),
Nique_372
2026-10-28 13:32:56 -05:00
m_magic_number(_magic),
Nique_372
2026-10-29 16:46:31 -05:00
m_loss_profits_manager(NULL), m_lp_gmlpo(NULL),
Nique_372
2026-10-28 13:32:56 -05:00
//---
m_is_init(false), m_type(type)
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-27 22:04:41 -05:00
//---
m_trade.SetExpertMagicNumber(_magic);
Nique_372
2026-10-29 17:54:54 -05:00
m_trade.LogLevel(LOG_LEVEL_NO);
Nique_372
2026-10-27 18:16:53 -05:00
//---
m_chosen_balance = AccountInfoDouble(ACCOUNT_BALANCE);
Nique_372
2026-10-27 22:04:41 -05:00
ArrayInitialize(m_cached_mod, false);
Nique_372
2026-10-27 18:16:53 -05:00
//---
const bool ac_i = account_status.IsInitialized();
//--- Registramos la clase para recibir eventos
// Basicos
CBasicEvents::Register(&this, BASICEVENT_REG_ALL_FLAG); // OnNewDay, Week, Month
// Para trabajar con las posiciones
account_status.RegisterEvents(&this,
(ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION |
ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION |
ACCOUNT_STATUS_REG_FLAG_ON_WITHDRAWAL_DEPOSIT |
ACCOUNT_STATUS_REG_FLAG_ON_NEW_PROFIT |
(ac_i ? 0 : ACCOUNT_STATUS_REG_FLAG_ON_INIT_NEW_POS)
));
//---
if(ac_i) // Se crea luego de que se inicie
{
g_account_open_positions.GetPositionsFromMagic(_magic, m_positions, m_positions_size);
}
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CRiskManagemet::~CRiskManagemet()
{
//---
Nique_372
2026-10-28 18:01:47 -05:00
// CleanItems("RiskManagement"); no hace falta
Nique_372
2026-10-27 18:16:53 -05:00
//--- Registramos la clase para recibir eventos
// Basicos
if(CBasicEvents::IsActive())
CBasicEvents::Unregister(&this, BASICEVENT_REG_ALL_FLAG); // OnNewDay, Week, Month
// Account status
if(account_status.IsActive())
{
// Para trabajar con las posiciones
account_status.UnregisterEvents(&this,
(ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION |
ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION |
ACCOUNT_STATUS_REG_FLAG_ON_WITHDRAWAL_DEPOSIT |
ACCOUNT_STATUS_REG_FLAG_ON_NEW_PROFIT |
ACCOUNT_STATUS_REG_FLAG_ON_INIT_NEW_POS)
);
}
}
Nique_372
2026-10-27 22:04:41 -05:00
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
//| Function that will be executed once all the |
//| Maximum profit and loss have been added |
Nique_372
2026-10-27 22:04:41 -05:00
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
void CRiskManagemet::EndAddProfitLoss()
Nique_372
2026-10-27 22:04:41 -05:00
{
Nique_372
2026-10-28 13:32:56 -05:00
if(m_is_init)
return;
Nique_372
2026-10-29 17:44:49 -05:00
//---
m_lp_gmlpo = m_loss_profits_manager.Att(LP_GMLPO);
Nique_372
2026-10-28 13:32:56 -05:00
m_loss_profits_manager.SetValues();
Nique_372
2026-11-07 21:17:58 -05:00
//---
Nique_372
2026-10-28 13:32:56 -05:00
m_is_init = true;
Nique_372
2026-10-27 22:04:41 -05:00
}
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CRiskManagemet::OnInitNewPos(const ROnOpenPosition &position)
{
Nique_372
2026-10-27 22:04:41 -05:00
if(position.position.magic == m_magic_number || m_magic_number == NOT_MAGIC_NUMBER)
Nique_372
2026-10-27 18:16:53 -05:00
{
m_positions[m_positions_size++] = g_account_open_positions.m_last_created_position_pos; // Crece hacia arriba
}
}
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
//| Funciones para obtener tipos de ffunc |
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
FuncionLossProfitSuperate CRiskManagemet::GetSuperateFunc(const uint type) const
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-28 13:32:56 -05:00
if(type == LP_GMLPO)
{
return (FuncionLossProfitSuperate)LossProfitEmptyFuncionSup;
}
else
if(type <= LP_ML_PICO)
{
return (FuncionLossProfitSuperate)FNormIsSupertedLoss;
}
else // Profit
{
return (FuncionLossProfitSuperate)FNormIsSupertedProfit;
}
Nique_372
2026-10-27 18:16:53 -05:00
}
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
CLossProfitBaseLP* CRiskManagemet::CreateLossProfit(const uint type) const
Nique_372
2026-10-28 10:48:27 -05:00
{
switch(type)
{
case LP_GMLPO:
return new CLossLossGmlpo(m_magic_number);
case LP_MDL:
return new CLossLossMaxDaily(m_magic_number);
case LP_MWL:
return new CLossLossMaxWeekly(m_magic_number);
case LP_MML:
return new CLossLossMaxMon(m_magic_number);
case LP_ML:
return new CLossLossMax(m_magic_number);
case LP_ML_PICO:
return new CLossLossMaxDesdeArriba(m_magic_number);
case LP_MDP:
return new CLossProfitMaxDaily(m_magic_number);
case LP_MWP:
return new CLossProfitMaxWeekly(m_magic_number);
case LP_MMP:
return new CLossProfitMaxMon(m_magic_number);
case LP_MP:
return new CLossProfitMax(m_magic_number);
case LP_MP_BAJO:
return new CLossProfitMaxDesdeBaajo(m_magic_number);
default:
return NULL;
}
}
Nique_372
2026-10-28 13:32:56 -05:00
//+------------------------------------------------------------------+
const FTSNMQLArtRmPctgVal g_tsnmqlart_rm_riskman_fcalc[4] =
{
CRiskManagemet::FCalcPctg_Balance,
CRiskManagemet::FCalcPctg_GNeta,
CRiskManagemet::FCalcPctg_FreeMag,
CRiskManagemet::FCalcPctg_Equity,
};
//+------------------------------------------------------------------+
FTSNMQLArtRmPctgVal CRiskManagemet::GetCalcFunc(const uint type, ENUM_APPLIED_PERCENTAGES _applied, ENUM_RISK_CALCULATION_MODE _mode) const
{
Nique_372
2026-10-28 22:50:57 -05:00
return _mode == money ? (FTSNMQLArtRmPctgVal)FCalcVMoney : g_tsnmqlart_rm_riskman_fcalc[_applied];
Nique_372
2026-10-28 13:32:56 -05:00
}
Nique_372
2026-10-28 10:48:27 -05:00
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
//| |
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
Nique_372
2026-10-28 10:48:27 -05:00
bool CRiskManagemet::AddLP(double _calc_value, ENUM_APPLIED_PERCENTAGES _applied, ENUM_RISK_CALCULATION_MODE _mode, ENUM_TYPE_LOSS_PROFIT type, bool strict,
Nique_372
2026-10-27 22:04:41 -05:00
bool is_dynamic = false, string percentages_to_activate = NULL, string risks_to_be_applied = NULL)
Nique_372
2026-10-27 18:16:53 -05:00
{
//---
Nique_372
2026-10-28 10:48:27 -05:00
if(_calc_value <= 0.00)
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-27 22:04:41 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-02 22:16:21 -05:00
FastLog(FUNCION_ACTUAL, WARNING_TEXT, StringFormat("Invalid percentage %.2f for lost profit %s, will not be added to the main array", _calc_value, EnumToString(type)));
Nique_372
2026-10-27 22:04:41 -05:00
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-10-28 22:50:57 -05:00
return true; // ?¿
Nique_372
2026-10-27 18:16:53 -05:00
}
//---
Nique_372
2026-11-02 21:51:46 -05:00
if(_mode == percentage)
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-11-02 21:51:46 -05:00
if(_calc_value > 100.00)
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-05 17:09:00 -05:00
FastLog(FUNCION_ACTUAL, WARNING_TEXT, StringFormat("Percentage %.2f for %s exceeds 100%%, invalid percentage", _calc_value, EnumToString(type)));
Nique_372
2026-10-28 13:32:56 -05:00
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_INV_PCTG,
Nique_372
2026-11-07 21:17:58 -05:00
CBitsReinterprete::ToBasic<ulong, double>(_calc_value));
Nique_372
2026-11-02 21:51:46 -05:00
}
Nique_372
2026-11-05 12:56:42 -05:00
//---
Nique_372
2026-11-02 21:51:46 -05:00
TSNMQLART_RISKM_NORM_PERCERNTAGE_A(_calc_value);
Nique_372
2026-10-27 18:16:53 -05:00
}
//---
Nique_372
2026-10-28 10:48:27 -05:00
if(type >= LP_TOTAL || type < LP_GMLPO)
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-10-28 22:50:57 -05:00
FastLog(FUNCION_ACTUAL, ERROR_TEXT, StringFormat("Invalid maximum loss type: %s (index: %d)", EnumToString(type), type));
Nique_372
2026-10-28 13:32:56 -05:00
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_INV_TYPE_BASICLP, type);
Nique_372
2026-10-27 18:16:53 -05:00
}
//--- Creamos
Nique_372
2026-10-28 13:32:56 -05:00
const uint tt = uint(type);
Nique_372
2026-10-27 18:16:53 -05:00
//---
Nique_372
2026-10-28 13:32:56 -05:00
// Aqui no se pone un error dado que por defecto (clase base) NO TIRA errores
// lo unico seria la hija, por lo tanto debe de poner el error (dicha clase)
const FTSNMQLArtRmPctgVal fcalc = GetCalcFunc(tt, _applied, _mode);
if(fcalc == NULL)
return false;
const FuncionLossProfitSuperate fsup = GetSuperateFunc(tt);
if(fsup == NULL)
Nique_372
2026-10-27 18:16:53 -05:00
return false;
//---
Nique_372
2026-10-28 13:32:56 -05:00
CLossProfitBaseLP* lp = CreateLossProfit(tt); // implicto no falla (in range safe=type)
lp.Init(_calc_value, fsup, fcalc);
lp.Strict(strict);
lp.SetPtrF(GetPtrLossProfits());
Nique_372
2026-10-27 18:16:53 -05:00
//---
if(is_dynamic && percentages_to_activate != NULL && risks_to_be_applied != NULL)
{
Nique_372
2026-10-28 13:32:56 -05:00
if(!m_cached_mod[type])
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-11-05 12:56:42 -05:00
if(!lp.SetDynamic(percentages_to_activate, risks_to_be_applied, m_chosen_balance))
Nique_372
2026-10-28 13:32:56 -05:00
{
Nique_372
2026-11-05 12:56:42 -05:00
delete lp; // importante
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailWrap<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_SET_DYNAMIC, type); // Consecuencia de:
Nique_372
2026-10-28 13:32:56 -05:00
}
Nique_372
2026-11-05 12:56:42 -05:00
//---
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Dynamic maximum loss %s successfully configured", EnumToString(type)));
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-10-27 18:16:53 -05:00
}
else
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, StringFormat("Maximum loss %s already has an active modifier", EnumToString(type)));
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-05 12:56:42 -05:00
delete lp; // importante
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_ALREDY_MODI, type); // Consecuencia de:
Nique_372
2026-10-27 18:16:53 -05:00
}
}
else
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-07 21:17:58 -05:00
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Maximum loss %s added: %.2f%s", EnumToString(type),
(_mode == money ? _calc_value : _calc_value * 100.0), (_mode == money ? "money" : "%")));
Nique_372
2026-10-28 13:32:56 -05:00
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
}
//---
Nique_372
2026-11-05 12:56:42 -05:00
if(!m_loss_profits_manager.Add(lp))
Nique_372
2026-10-28 13:32:56 -05:00
{
Nique_372
2026-11-05 12:56:42 -05:00
delete lp; // importante
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailWrap<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_ADD_LOSSPROFITMAN, type); // Consecuencia de:
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-10-28 13:32:56 -05:00
//---
Nique_372
2026-10-27 18:16:53 -05:00
return true;
}
Nique_372
2026-10-28 13:32:56 -05:00
//+------------------------------------------------------------------+
bool CRiskManagemet::AddLP(CLossProfit *lp)
{
//---
if(!CheckPointer(lp))
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_LP_INV_PTR, 0);
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-10-28 13:32:56 -05:00
//---
Nique_372
2026-11-05 12:56:42 -05:00
if(!m_loss_profits_manager.Add(lp))
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailWrap<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_ADD_LOSSPROFITMAN, lp.m_type); // Consecuencia de:
Nique_372
2026-10-28 22:50:57 -05:00
//---
Nique_372
2026-10-28 13:32:56 -05:00
return true;
}
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
//| Function to add a risk modifier |
//+------------------------------------------------------------------+
bool CRiskManagemet::AddModificator(CExtraModifications *modificator)
{
//--- Check pointer
if(!CheckPointer(modificator))
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, "The risk modifier is null-invalid");
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PTR, 0);
Nique_372
2026-10-27 18:16:53 -05:00
}
//--- Property to be modified is invalid ?
Nique_372
2026-10-28 13:32:56 -05:00
const int loss_or_profit = modificator.m_property_to_modify;
Nique_372
2026-10-27 18:16:53 -05:00
if(loss_or_profit == WRONG_VALUE)
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, "The risk modifier does not modify any risk.");
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PROP, 0);
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-10-28 13:32:56 -05:00
//--- Is the loss_or_profit already dynamic ?
if(m_loss_profits_manager.Att(loss_or_profit).IsDynamicMode())
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, StringFormat("The property to be modified %d is already dynamic", loss_or_profit));
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_LP_IS_ALREDY_DYNCMODE, loss_or_profit);
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-10-28 13:32:56 -05:00
//---
if(m_cached_mod[loss_or_profit])
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, WARNING_TEXT, StringFormat("The property to be modified %d is already being modified", loss_or_profit));
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_PROP_IS_ALREDY_MODLP, loss_or_profit);
Nique_372
2026-10-27 18:16:53 -05:00
}
//---
Nique_372
2026-10-28 13:32:56 -05:00
// attt= hacemos un at en base al tipo no at normal
if(!modificator.SetPointer(m_loss_profits_manager.Att(loss_or_profit)))
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MODPROP_NOT_EQUALS, loss_or_profit);
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-10-28 13:32:56 -05:00
//---
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-11-02 21:51:46 -05:00
FastLog(FUNCION_ACTUAL, CAUTION_TEXT, StringFormat("The modifier '%s' is being added\nThis will modify the property '%d'",
modificator.m_hook_name, m_loss_profits_manager.Att(loss_or_profit).Name()));
Nique_372
2026-10-28 13:32:56 -05:00
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-10-27 18:16:53 -05:00
//---
Nique_372
2026-10-28 13:32:56 -05:00
m_cached_mod[loss_or_profit] = true; // usado
Nique_372
2026-11-07 21:17:58 -05:00
//---
if((modificator.m_events_flags & RISK_MANAGEMENT_EVENT_ON_INFO) != 0)
{
modificator.OnIBalance(m_chosen_balance);
modificator.OnMagic(m_magic_number);
}
//---
m_hooks.Add(modificator);
Nique_372
2026-10-27 18:16:53 -05:00
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CRiskManagemet::AddRmHook(IRiskManagementHook *hook)
{
//--- Check pointer
if(!CheckPointer(hook))
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_HOK_INV_POINTER, 0);
Nique_372
2026-11-07 21:17:58 -05:00
//---
if((hook.m_events_flags & RISK_MANAGEMENT_EVENT_ON_INFO) != 0)
{
hook.OnIBalance(m_chosen_balance);
hook.OnMagic(m_magic_number);
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-11-07 21:17:58 -05:00
Nique_372
2026-10-27 18:16:53 -05:00
//--- Add
m_hooks.Add(hook); // We use the fast version (we already did all the checkpointer checks etc.)
return true;
}
//+----------------------------------------------------------------------------------+
Nique_372
2026-10-27 22:04:41 -05:00
//| Get the ideal stop loss based on a specified lot and the maximum loss per m_trade |
Nique_372
2026-10-27 18:16:53 -05:00
//+----------------------------------------------------------------------------------+
Nique_372
2026-10-27 22:04:41 -05:00
__forceinline long CRiskManagemet::GetSL(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit, double& choosen_lot)
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-27 22:04:41 -05:00
return m_get_lote.MoneyToPoints(type, m_lp_gmlpo.GetValue(), entry_price, choosen_lot, deviation, stop_limit);
Nique_372
2026-10-27 18:16:53 -05:00
}
//+-----------------------------------------------------------------------------------------------+
//| Function to obtain the ideal lot based on the maximum loss per operation and the stop loss |
//+-----------------------------------------------------------------------------------------------+
Nique_372
2026-10-28 13:32:56 -05:00
// result=0.0=error (last error no actua ojo)
Nique_372
2026-10-27 18:16:53 -05:00
double CRiskManagemet::GetLote(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit)
{
if(m_type_get_lot == GET_LOT_BY_STOPLOSS_AND_RISK_PER_OPERATION)
{
Nique_372
2026-10-27 22:04:41 -05:00
const double max_lote = m_get_lote.GetMaxLote(type, entry_price, deviation, stop_limit); // We do not check max batch data that is done in GetLote... of CGetLote
double lot;
Nique_372
2026-10-28 13:32:56 -05:00
return m_get_lote.GetLoteByRiskPerOperationAndSL(max_lote, m_lp_gmlpo.GetValue(), m_nmlpo, m_StopLoss, lot) ? lot : 0.0;
Nique_372
2026-10-27 18:16:53 -05:00
}
else
Nique_372
2026-10-27 22:04:41 -05:00
// If it is less than the minimum batch, a message is printed in CGetLote
return m_get_lote.CalculateLoteSizeWVal(type, entry_price, deviation, stop_limit, m_lp_gmlpo.GetValue());
Nique_372
2026-10-27 18:16:53 -05:00
}
//+------------------------------------------------------------------+
//| Initial profit update |
//+------------------------------------------------------------------+
Nique_372
2026-10-29 08:05:14 -05:00
void CRiskManagemet::OnNewProfit(const datetime curr_time)
Nique_372
2026-10-27 18:16:53 -05:00
{
Nique_372
2026-10-27 22:04:41 -05:00
//---
const bool all = (m_magic_number == NOT_MAGIC_NUMBER);
//--- Date
m_last_day_time = account_status.last_day_time;
m_last_weekly_time = account_status.last_weekly_time;
m_last_monthly_time = account_status.last_monthly_time;
m_init_trade_time = (!all) ? curr_time : D'1972.01.01 00:00';
Nique_372
2026-10-27 18:16:53 -05:00
//--- Set internal profits
Nique_372
2026-10-27 22:04:41 -05:00
m_daily_profit = CHistoryMoneyUtils::GetNetProfitSince(all, m_magic_number, m_last_day_time);
m_weekly_profit = CHistoryMoneyUtils::GetNetProfitSince(all, m_magic_number, m_last_weekly_time);
m_gross_profit = CHistoryMoneyUtils::GetNetProfitSince(all, m_magic_number, m_init_trade_time);
m_monthly_profit = CHistoryMoneyUtils::GetNetProfitSince(all, m_magic_number, m_last_monthly_time);
Nique_372
2026-10-27 18:16:53 -05:00
//--- Info
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, INFO_TEXT, "New profits:");
Print("Daily Profit: ", m_daily_profit);
Print("Gross profit: ", m_gross_profit);
Print("Weekly Profit: ", m_weekly_profit);
Print("Monthly Profit: ", m_monthly_profit);
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-10-29 12:18:24 -05:00
Nique_372
2026-10-28 22:50:57 -05:00
//+------------------------------------------------------------------+
//| Function to update profits |
//+------------------------------------------------------------------+
void CRiskManagemet::UpdateProfit(const double profit)
{
//---
m_monthly_profit += profit;
m_daily_profit += profit;
m_weekly_profit += profit;
m_gross_profit += profit;
//---
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, INFO_TEXT, "New profits:");
Print("Daily Profit: ", m_daily_profit);
Print("Gross profit: ", m_gross_profit);
Print("Weekly Profit: ", m_weekly_profit);
Print("Monthly Profit: ", m_monthly_profit);
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
}
Nique_372
2026-10-27 18:16:53 -05:00
//+------------------------------------------------------------------+
//| OnTradeTransaction Event |
//+------------------------------------------------------------------+
void CRiskManagemet::OnOpenPosition(const ROnOpenPosition &pos)
{
Nique_372
2026-10-27 22:04:41 -05:00
if(m_magic_number == pos.position.magic || m_magic_number == NOT_MAGIC_NUMBER)
Nique_372
2026-10-27 18:16:53 -05:00
{
//--- If there are modifiers then execute the OnOpenPosition function
if(m_hooks.SizeOnOpenPosition() > 0)
Nique_372
2026-11-07 21:17:58 -05:00
m_hooks.OnOpenPosition(pos);
Nique_372
2026-10-27 18:16:53 -05:00
//--- Add the operation to positions opened by the Magic
m_positions[m_positions_size++] = g_account_open_positions.m_last_created_position_pos; // Crece hacia arriba
}
}
//+------------------------------------------------------------------+
void CRiskManagemet::OnClosePosition(const ROnClosePosition &pos, const int global_pos_index)
{
//---
if(TryRemoveFromArrayOfPos(global_pos_index))
{
//--- Update internal profits
Nique_372
2026-10-28 22:50:57 -05:00
UpdateProfit(pos.position.profit);
Nique_372
2026-10-27 18:16:53 -05:00
//--- Update risks (dynamic)
m_loss_profits_manager.CheckDynamic();
//--- If there are modifiers, execute OnOpenClosePosition
if(m_hooks.SizeOnClosePosition() > 0)
{
static ModifierOnOpenCloseStruct new_mod;
Nique_372
2026-10-27 22:04:41 -05:00
new_mod.profit_diario = m_daily_profit;
new_mod.profit_mensual = m_monthly_profit;
new_mod.profit_semanal = m_weekly_profit;
new_mod.profit_total = m_gross_profit;
Nique_372
2026-10-27 18:16:53 -05:00
Nique_372
2026-11-07 21:17:58 -05:00
//---
m_hooks.OnClosePosition(new_mod, pos);
Nique_372
2026-10-27 18:16:53 -05:00
}
}
Nique_372
2026-10-28 22:50:57 -05:00
// Setamos tanto si es o no nuestro
//--- Set the new GMLPO value
Nique_372
2026-10-29 16:46:31 -05:00
if(m_lp_gmlpo != NULL)
m_lp_gmlpo.Set(); // Empty check is done internally
Nique_372
2026-10-28 22:50:57 -05:00
Nique_372
2026-10-27 18:16:53 -05:00
// Partials are not necessary since we did that to ensure trans.position profit also counts the partial close, the other class already does that.
}
//+------------------------------------------------------------------+
//| Function that runs every new day |
//+------------------------------------------------------------------+
void CRiskManagemet::OnNewDay(const datetime curr_time)
{
Nique_372
2026-10-27 22:04:41 -05:00
m_daily_profit = 0.00;
m_last_day_time = curr_time;
Nique_372
2026-10-27 18:16:53 -05:00
}
//+------------------------------------------------------------------+
//| Function that runs every new week |
//+------------------------------------------------------------------+
void CRiskManagemet::OnNewWeek(const datetime curr_time)
{
Nique_372
2026-10-27 22:04:41 -05:00
m_last_weekly_time = curr_time;
m_weekly_profit = 0.00;
Nique_372
2026-10-27 18:16:53 -05:00
}
//+------------------------------------------------------------------+
//| Function that runs every new month |
//+------------------------------------------------------------------+
void CRiskManagemet::OnNewMonth(const datetime curr_time)
{
Nique_372
2026-10-27 22:04:41 -05:00
m_last_monthly_time = curr_time;
m_monthly_profit = 0.00;
Nique_372
2026-10-27 18:16:53 -05:00
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//--- Define dangerous, if disabled it could increase the risk strongly, for safety reasons do not comment on it
Nique_372
2026-11-01 15:00:25 -05:00
#ifndef RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
Nique_372
2026-10-27 18:16:53 -05:00
#define RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
Nique_372
2026-11-01 15:00:25 -05:00
#endif // RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
Nique_372
2026-10-27 18:16:53 -05:00
//---
Nique_372
2026-11-07 21:17:58 -05:00
void CRiskManagemet::OnWithdrawalDeposit(const double value)
Nique_372
2026-10-27 18:16:53 -05:00
{
// Function that is executed every time a device or profit occurs
//--- Uodate
#ifdef RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
m_chosen_balance += value;
Nique_372
2026-11-07 21:17:58 -05:00
m_loss_profits_manager.SetNewChossenBalanceForDynamicsAndSet(m_chosen_balance, true); // new chooosen dyncamis
m_hooks.OnIBalance(m_chosen_balance); // balance para los hooks
#else // RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
Nique_372
2026-10-27 18:16:53 -05:00
m_loss_profits_manager.SetValuesAndDynamic();
Nique_372
2026-11-07 21:17:58 -05:00
#endif // RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
Nique_372
2026-10-27 18:16:53 -05:00
}
Nique_372
2026-10-27 22:04:41 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CRiskManagemet::CloseAllOrders(uint flags)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
const ulong ticket = OrderGetTicket(i);
//---
ResetLastError();
if(OrderSelect(ticket))
{
const ulong magic = OrderGetInteger(ORDER_MAGIC);
Nique_372
2026-10-29 16:46:31 -05:00
const int bandera = MQLArticles_OrderToFlag(OrderGetInteger(ORDER_TYPE));
Nique_372
2026-10-27 22:04:41 -05:00
//---
if((bandera & flags) != 0 && (magic == m_magic_number || m_magic_number == NOT_MAGIC_NUMBER))
Nique_372
2026-10-29 16:46:31 -05:00
m_trade.OrderDelete(ticket);
Nique_372
2026-10-27 22:04:41 -05:00
}
else
{
Nique_372
2026-10-28 13:32:56 -05:00
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, StringFormat("Error al selecionar la order %I64u, ultimo error = %d", ticket, GetLastError()));
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
Nique_372
2026-10-27 22:04:41 -05:00
}
}
}
Nique_372
2026-10-28 10:48:27 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CRiskManagemet::TryRemoveFromArrayOfPos(const int global_pos_index)
{
//--- Find
int index = -1;
for(int i = 0; i < m_positions_size; i++)
{
if(m_positions[i] == global_pos_index)
{
index = i;
break;
}
}
//--- Check is invalid
if(index == -1)
Nique_372
2026-11-05 17:09:00 -05:00
return false; // NOTA: lo interno (QUE no se expone) es para NOSOTROS (this -> clase) por eso no hay error dado que no TIENE SENTIDO
Nique_372
2026-10-27 22:04:41 -05:00
//--- Reduce size
m_positions_size--;
//--- Move
for(int i = index; i < m_positions_size; i++)
{
m_positions[i] = m_positions[i + 1]; // Move the elements
}
//---
return true;
}
//+------------------------------------------------------------------+
//| Function to obtain the number of open positions |
//+------------------------------------------------------------------+
__forceinline int CRiskManagemet::GetPositions(uint flags) const
{
return g_account_open_positions.GetPositionsMask(m_positions, m_positions_size, flags);
}
Nique_372
2026-10-28 10:48:27 -05:00
Nique_372
2026-10-27 22:04:41 -05:00
//+---------------------------------------------------------------------------+
//| Function to close all positions opened by the magic number or by the user |
//+---------------------------------------------------------------------------+
__forceinline void CRiskManagemet::CloseAllPositions(uint flags = FLAG_CLOSE_ALL_LOSS | FLAG_CLOSE_ALL_PROFIT | FLAG_POSITION_TYPE_BUY | FLAG_POSITION_TYPE_SELL)
{
g_account_open_positions.CloseAllPositionMask(m_positions, m_positions_size, m_trade, flags);
}
Nique_372
2026-10-28 13:32:56 -05:00
Nique_372
2026-10-29 12:48:36 -05:00
Nique_372
2026-10-29 12:18:24 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
Nique_372
2026-11-05 17:09:00 -05:00
// Formatea la pila de errores (se lee de la capa mas alta hacia la raiz).
// Los codigos que son "envoltura" (SET_DYNAMIC, ADD_LOSSPROFITMAN) continuan con el FormatTrace de la capa de abajo.
Nique_372
2026-11-06 10:40:44 -05:00
static void CRiskManagemet::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
Nique_372
2026-10-29 12:18:24 -05:00
{
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHINI(out, trace_idx)
switch(trace[trace_idx].code)
Nique_372
2026-10-29 12:18:24 -05:00
{
case TSNMQLART_RISK_MANAGEMENT_ERR_NOT:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, "Not error", trace_idx)
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_INV_PCTG:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Invalid percentage [%.4f] for LP, must be in range (0.0 - 100.0]",
CBitsReinterprete::ToBasic<double, ulong>(trace[trace_idx].info)), trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_INV_TYPE_BASICLP:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Invalid type LP [%d], must be in range [%d, %d)", int(trace[trace_idx].info), LP_GMLPO, LP_TOTAL), trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_SET_DYNAMIC:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Error at set dynamic for LP type [%d], caused by:", int(trace[trace_idx].info)), trace_idx)
CLossProfit::FormatTrace(trace, trace_idx, out);
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_ALREDY_MODI:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("LP type [%d] already modified by other mod", int(trace[trace_idx].info)), trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_ADD_LOSSPROFITMAN:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Error add LP type [%d] to CLossProfitManager, caused by:", int(trace[trace_idx].info)), trace_idx)
CLossProfitManager::FormatTrace(trace, trace_idx, out);
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_LP_INV_PTR:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, "LP is invalid pointer", trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PTR:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, "Modifier invalid pointer", trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PROP:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, "Modifier is attempting to modify an invalid property (LP)", trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_LP_IS_ALREDY_DYNCMODE:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("The LP [%d] that you are attempting to modify is dynamic.", int(trace[trace_idx].info)), trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_PROP_IS_ALREDY_MODLP:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("The LP [%d] that the modifier is attempting to modify is already being modified by another modifier (only one at a time).",
int(trace[trace_idx].info)), trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_MODPROP_NOT_EQUALS:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("The property [%d] that `modifier` attempts to modify does not correspond to the one obtained by `CLossProfitManager`.",
int(trace[trace_idx].info)), trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
case TSNMQLART_RISK_MANAGEMENT_ERR_HOK_INV_POINTER:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, "Cannot add an invalid hook (invalid pointer)", trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
default:
Nique_372
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT(out, "Unknow error", trace_idx)
Nique_372
2026-10-29 12:18:24 -05:00
break;
}
Nique_372
2026-11-05 17:09:00 -05:00
}
Nique_372
2026-10-29 12:18:24 -05:00
Nique_372
2026-10-28 13:32:56 -05:00
//---
Nique_372
2026-10-27 18:16:53 -05:00
}
//+------------------------------------------------------------------+
#endif // MQLARTICLES_ACCOUNT_RM_RISKMANAGEMENT_CORE_CORE_MQH
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+