forked from nique_372/MQLArticles
//+------------------------------------------------------------------+
| |
//| 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
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
// manager para los hooks
| |
#include "..\\Hooks\\Man.mqh"
| |
// defincion de extra mod
| |
#include "..\\LPMods\\Def.mqh"
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
namespace TSN
| |
{
| |
//+------------------------------------------------------------------+
| |
//| Clase Base CRiskManagement |
| |
//+------------------------------------------------------------------+
| |
class CRiskManagemet : public CAccountGestor
| |
{
| |
protected:
| |
//---
| |
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
| |
ENUM_GET_LOT m_type_get_lot;
| |
long m_StopLoss; //m_StopLoss
| |
| |
//--- Balances
| |
double m_chosen_balance;
| |
| |
//--- Manager (solo shared)
| |
CLossProfitManager* m_loss_profits_manager;
| |
CLossProfit* m_lp_gmlpo;
| |
| |
//--- Modifiers
| |
CRiskManagemeHookManager m_hooks;
| |
bool m_cached_mod[LOSSPROFIT_MANAGER_MAX_ITEMS]; // tabla: [typeLP -> is_modified?]
| |
| |
//---
| |
// 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
| |
| |
//---
| |
public:
| |
double m_pos_current_profit; // Profit curr
| |
| |
protected:
| |
//--- functions extra
| |
bool TryRemoveFromArrayOfPos(const int global_pos_index);
| |
| |
//--- Update profits function
| |
void UpdateProfit(const double profit);
| |
| |
//--- 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;
| |
| |
public:
| |
//--- Constructor and Destructor
| |
CRiskManagemet(const ulong _magic, const int type);
| |
~CRiskManagemet();
| |
| |
//--- Superated funcionts
| |
void SetLossProfitManager(CLossProfitManager& lp_manager) { m_loss_profits_manager = &lp_manager; }
| |
| |
//--- Mods
| |
bool AddModificator(CExtraModifications* modificator); // Modificator pointer
| |
__forceinline bool AddModificator(CExtraModifications &modificator) { return AddModificator(&modificator); }
| |
__forceinline bool IsModAlredyUsed(const int type) const { return m_cached_mod[type]; }
| |
| |
//--- General Hook
| |
bool AddRmHook(IRiskManagementHook* hook);
| |
__forceinline bool AddRmHook(IRiskManagementHook& hook) { return AddRmHook(&hook); }
| |
| |
//--- LP
| |
bool AddLP(CLossProfit* new_loss);
| |
// default version
| |
bool AddLP(double _calc_value, ENUM_APPLIED_PERCENTAGES _applied, ENUM_RISK_CALCULATION_MODE _mode, ENUM_TYPE_LOSS_PROFIT type, bool strict,
| |
bool is_dynamic = false, string percentages_to_activate = NULL, string risks_to_be_applied = NULL); // Loss
| |
//- finish
| |
void EndAddProfitLoss();
| |
| |
//--- 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
| |
void OnNewProfit(const datetime curr_time) override;
| |
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
| |
__forceinline long GetSL(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit, double& choosen_lot);
| |
| |
//--- Calculos (lote y sl) - (relacionados-getter\setter)
| |
// calulador principal de lote
| |
CGetLote* LotCalc() { return &m_get_lote; }
| |
| |
// tipo de obtencion
| |
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; }
| |
| |
// estimacion perdida (last)
| |
__forceinline double Nlmpo() const { return m_nmlpo; }
| |
| |
// stop loss
| |
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_; }
| |
| |
//--- General
| |
inline ulong MagicNumber() const { return m_magic_number; }
| |
| |
//--- Function to set general class parameters
| |
virtual bool SetGeneralParameters(const MqlParam ¶ms[]) = 0;
| |
| |
//--- 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);
| |
| |
//--- Calcular el profit actual
| |
__forceinline void CalcProfit() { m_pos_current_profit = g_account_open_positions.GetProfitMask(m_positions, m_positions_size); }
| |
| |
//--- Tipo
| |
__forceinline int Type() const { return m_type; }
| |
| |
//--- Ptr
| |
virtual void* GetPtrLossProfits() { return &this; }
| |
| |
//--- Punteros a funcion
| |
//-- is superated
| |
#ifdef MQLARTICLES_RM_MULTI_EA_MODE
| |
// usando profit especifico
| |
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
| |
// ussando profit general
| |
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; }
| |
#endif // MQLARTICLES_RM_MULTI_EA_MODE
| |
| |
//---
| |
// 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")
| |
| |
//-- calculos
| |
static __forceinline double FCalcVMoney(double calc_value, void* ptr) { return calc_value; }
| |
| |
// pctg
| |
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)); }
| |
| |
//---
| |
static void FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out);
| |
};
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
// #define TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
// no'del ptr
| |
//+------------------------------------------------------------------+
| |
//| Constructor |
| |
//+------------------------------------------------------------------+
| |
CRiskManagemet::CRiskManagemet(const ulong _magic, const int type)
| |
:
| |
//---
| |
m_daily_profit(0.00), m_weekly_profit(0.00), m_monthly_profit(0.00), m_gross_profit(0.00),
| |
m_last_day_time(0), m_last_weekly_time(0), m_last_monthly_time(0),
| |
m_init_trade_time(0),
| |
m_positions_size(0),
| |
m_magic_number(_magic),
| |
m_loss_profits_manager(NULL), m_lp_gmlpo(NULL),
| |
| |
//---
| |
m_is_init(false), m_type(type)
| |
{
| |
//---
| |
m_trade.SetExpertMagicNumber(_magic);
| |
m_trade.LogLevel(LOG_LEVEL_NO);
| |
| |
//---
| |
m_chosen_balance = AccountInfoDouble(ACCOUNT_BALANCE);
| |
ArrayInitialize(m_cached_mod, false);
| |
| |
//---
| |
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()
| |
{
| |
//---
| |
// CleanItems("RiskManagement"); no hace falta
| |
| |
//--- 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)
| |
);
| |
}
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| Function that will be executed once all the |
| |
//| Maximum profit and loss have been added |
| |
//+------------------------------------------------------------------+
| |
void CRiskManagemet::EndAddProfitLoss()
| |
{
| |
if(m_is_init)
| |
return;
| |
| |
//---
| |
m_lp_gmlpo = m_loss_profits_manager.Att(LP_GMLPO);
| |
m_loss_profits_manager.SetValues();
| |
| |
//---
| |
m_is_init = true;
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CRiskManagemet::OnInitNewPos(const ROnOpenPosition &position)
| |
{
| |
if(position.position.magic == m_magic_number || m_magic_number == NOT_MAGIC_NUMBER)
| |
{
| |
m_positions[m_positions_size++] = g_account_open_positions.m_last_created_position_pos; // Crece hacia arriba
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| Funciones para obtener tipos de ffunc |
| |
//+------------------------------------------------------------------+
| |
FuncionLossProfitSuperate CRiskManagemet::GetSuperateFunc(const uint type) const
| |
{
| |
if(type == LP_GMLPO)
| |
{
| |
return (FuncionLossProfitSuperate)LossProfitEmptyFuncionSup;
| |
}
| |
else
| |
if(type <= LP_ML_PICO)
| |
{
| |
return (FuncionLossProfitSuperate)FNormIsSupertedLoss;
| |
}
| |
else // Profit
| |
{
| |
return (FuncionLossProfitSuperate)FNormIsSupertedProfit;
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
CLossProfitBaseLP* CRiskManagemet::CreateLossProfit(const uint type) const
| |
{
| |
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;
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
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
| |
{
| |
return _mode == money ? (FTSNMQLArtRmPctgVal)FCalcVMoney : g_tsnmqlart_rm_riskman_fcalc[_applied];
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
bool CRiskManagemet::AddLP(double _calc_value, ENUM_APPLIED_PERCENTAGES _applied, ENUM_RISK_CALCULATION_MODE _mode, ENUM_TYPE_LOSS_PROFIT type, bool strict,
| |
bool is_dynamic = false, string percentages_to_activate = NULL, string risks_to_be_applied = NULL)
| |
{
| |
//---
| |
if(_calc_value <= 0.00)
| |
{
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
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)));
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
return true; // ?¿
| |
}
| |
| |
//---
| |
if(_mode == percentage)
| |
{
| |
if(_calc_value > 100.00)
| |
{
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
FastLog(FUNCION_ACTUAL, WARNING_TEXT, StringFormat("Percentage %.2f for %s exceeds 100%%, invalid percentage", _calc_value, EnumToString(type)));
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_INV_PCTG,
| |
CBitsReinterprete::ToBasic<ulong, double>(_calc_value));
| |
}
| |
| |
//---
| |
TSNMQLART_RISKM_NORM_PERCERNTAGE_A(_calc_value);
| |
}
| |
| |
//---
| |
if(type >= LP_TOTAL || type < LP_GMLPO)
| |
{
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT, StringFormat("Invalid maximum loss type: %s (index: %d)", EnumToString(type), type));
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_INV_TYPE_BASICLP, type);
| |
}
| |
| |
//--- Creamos
| |
const uint tt = uint(type);
| |
| |
//---
| |
// 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)
| |
return false;
| |
| |
//---
| |
CLossProfitBaseLP* lp = CreateLossProfit(tt); // implicto no falla (in range safe=type)
| |
lp.Init(_calc_value, fsup, fcalc);
| |
lp.Strict(strict);
| |
lp.SetPtrF(GetPtrLossProfits());
| |
| |
//---
| |
if(is_dynamic && percentages_to_activate != NULL && risks_to_be_applied != NULL)
| |
{
| |
if(!m_cached_mod[type])
| |
{
| |
if(!lp.SetDynamic(percentages_to_activate, risks_to_be_applied, m_chosen_balance))
| |
{
| |
delete lp; // importante
| |
return CErrorTrace::FailWrap<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_SET_DYNAMIC, type); // Consecuencia de:
| |
}
| |
| |
//---
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Dynamic maximum loss %s successfully configured", EnumToString(type)));
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
}
| |
else
| |
{
| |
#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
| |
delete lp; // importante
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_ALREDY_MODI, type); // Consecuencia de:
| |
}
| |
}
| |
else
| |
{
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
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" : "%")));
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
}
| |
| |
//---
| |
if(!m_loss_profits_manager.Add(lp))
| |
{
| |
delete lp; // importante
| |
return CErrorTrace::FailWrap<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_ADD_LOSSPROFITMAN, type); // Consecuencia de:
| |
}
| |
| |
//---
| |
return true;
| |
}
| |
//+------------------------------------------------------------------+
| |
bool CRiskManagemet::AddLP(CLossProfit *lp)
| |
{
| |
//---
| |
if(!CheckPointer(lp))
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_LP_INV_PTR, 0);
| |
| |
//---
| |
if(!m_loss_profits_manager.Add(lp))
| |
return CErrorTrace::FailWrap<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_ADD_LOSSPROFITMAN, lp.m_type); // Consecuencia de:
| |
| |
//---
| |
return true;
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| Function to add a risk modifier |
| |
//+------------------------------------------------------------------+
| |
bool CRiskManagemet::AddModificator(CExtraModifications *modificator)
| |
{
| |
//--- Check pointer
| |
if(!CheckPointer(modificator))
| |
{
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT, "The risk modifier is null-invalid");
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PTR, 0);
| |
}
| |
| |
//--- Property to be modified is invalid ?
| |
const int loss_or_profit = modificator.m_property_to_modify;
| |
if(loss_or_profit == WRONG_VALUE)
| |
{
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT, "The risk modifier does not modify any risk.");
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PROP, 0);
| |
}
| |
| |
//--- Is the loss_or_profit already dynamic ?
| |
if(m_loss_profits_manager.Att(loss_or_profit).IsDynamicMode())
| |
{
| |
#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
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_LP_IS_ALREDY_DYNCMODE, loss_or_profit);
| |
}
| |
| |
//---
| |
if(m_cached_mod[loss_or_profit])
| |
{
| |
#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
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MOD_PROP_IS_ALREDY_MODLP, loss_or_profit);
| |
}
| |
| |
//---
| |
// attt= hacemos un at en base al tipo no at normal
| |
if(!modificator.SetPointer(m_loss_profits_manager.Att(loss_or_profit)))
| |
{
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_MODPROP_NOT_EQUALS, loss_or_profit);
| |
}
| |
| |
//---
| |
#ifdef TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
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()));
| |
#endif // TSNMQLART_RM_RISKAMANGEMENT_ELOGS
| |
| |
//---
| |
m_cached_mod[loss_or_profit] = true; // usado
| |
| |
//---
| |
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);
| |
return true;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
bool CRiskManagemet::AddRmHook(IRiskManagementHook *hook)
| |
{
| |
//--- Check pointer
| |
if(!CheckPointer(hook))
| |
return CErrorTrace::FailInit<CRiskManagemet>(TSNMQLART_RISK_MANAGEMENT_ERR_HOK_INV_POINTER, 0);
| |
| |
//---
| |
if((hook.m_events_flags & RISK_MANAGEMENT_EVENT_ON_INFO) != 0)
| |
{
| |
hook.OnIBalance(m_chosen_balance);
| |
hook.OnMagic(m_magic_number);
| |
}
| |
| |
//--- Add
| |
m_hooks.Add(hook); // We use the fast version (we already did all the checkpointer checks etc.)
| |
return true;
| |
}
| |
| |
| |
//+----------------------------------------------------------------------------------+
| |
//| Get the ideal stop loss based on a specified lot and the maximum loss per m_trade |
| |
//+----------------------------------------------------------------------------------+
| |
__forceinline long CRiskManagemet::GetSL(ENUM_ORDER_TYPE type, double entry_price, ulong deviation, ulong stop_limit, double& choosen_lot)
| |
{
| |
return m_get_lote.MoneyToPoints(type, m_lp_gmlpo.GetValue(), entry_price, choosen_lot, deviation, stop_limit);
| |
}
| |
| |
//+-----------------------------------------------------------------------------------------------+
| |
//| Function to obtain the ideal lot based on the maximum loss per operation and the stop loss |
| |
//+-----------------------------------------------------------------------------------------------+
| |
// result=0.0=error (last error no actua ojo)
| |
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)
| |
{
| |
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;
| |
return m_get_lote.GetLoteByRiskPerOperationAndSL(max_lote, m_lp_gmlpo.GetValue(), m_nmlpo, m_StopLoss, lot) ? lot : 0.0;
| |
}
| |
else
| |
// 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());
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| Initial profit update |
| |
//+------------------------------------------------------------------+
| |
void CRiskManagemet::OnNewProfit(const datetime curr_time)
| |
{
| |
//---
| |
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';
| |
| |
//--- Set internal profits
| |
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);
| |
| |
//--- Info
| |
#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
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| 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
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| OnTradeTransaction Event |
| |
//+------------------------------------------------------------------+
| |
void CRiskManagemet::OnOpenPosition(const ROnOpenPosition &pos)
| |
{
| |
if(m_magic_number == pos.position.magic || m_magic_number == NOT_MAGIC_NUMBER)
| |
{
| |
//--- If there are modifiers then execute the OnOpenPosition function
| |
if(m_hooks.SizeOnOpenPosition() > 0)
| |
m_hooks.OnOpenPosition(pos);
| |
| |
//--- 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
| |
UpdateProfit(pos.position.profit);
| |
| |
//--- Update risks (dynamic)
| |
m_loss_profits_manager.CheckDynamic();
| |
| |
//--- If there are modifiers, execute OnOpenClosePosition
| |
if(m_hooks.SizeOnClosePosition() > 0)
| |
{
| |
static ModifierOnOpenCloseStruct new_mod;
| |
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;
| |
| |
//---
| |
m_hooks.OnClosePosition(new_mod, pos);
| |
}
| |
}
| |
| |
// Setamos tanto si es o no nuestro
| |
//--- Set the new GMLPO value
| |
if(m_lp_gmlpo != NULL)
| |
m_lp_gmlpo.Set(); // Empty check is done internally
| |
| |
// 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)
| |
{
| |
m_daily_profit = 0.00;
| |
m_last_day_time = curr_time;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| Function that runs every new week |
| |
//+------------------------------------------------------------------+
| |
void CRiskManagemet::OnNewWeek(const datetime curr_time)
| |
{
| |
m_last_weekly_time = curr_time;
| |
m_weekly_profit = 0.00;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| Function that runs every new month |
| |
//+------------------------------------------------------------------+
| |
void CRiskManagemet::OnNewMonth(const datetime curr_time)
| |
{
| |
m_last_monthly_time = curr_time;
| |
m_monthly_profit = 0.00;
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
//--- Define dangerous, if disabled it could increase the risk strongly, for safety reasons do not comment on it
| |
#ifndef RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
| |
#define RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
| |
#endif // RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
| |
| |
//---
| |
void CRiskManagemet::OnWithdrawalDeposit(const double value)
| |
{
| |
// Function that is executed every time a device or profit occurs
| |
//--- Uodate
| |
#ifdef RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
| |
m_chosen_balance += value;
| |
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
| |
m_loss_profits_manager.SetValuesAndDynamic();
| |
#endif // RISK_MANAGEMENT_UPDATE_CHOSEN_BALANCE_DEPOSIT_WITDRAWAL
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
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);
| |
const int bandera = MQLArticles_OrderToFlag(OrderGetInteger(ORDER_TYPE));
| |
| |
//---
| |
if((bandera & flags) != 0 && (magic == m_magic_number || m_magic_number == NOT_MAGIC_NUMBER))
| |
m_trade.OrderDelete(ticket);
| |
}
| |
else
| |
{
| |
#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
| |
}
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
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)
| |
return false; // NOTA: lo interno (QUE no se expone) es para NOSOTROS (this -> clase) por eso no hay error dado que no TIENE SENTIDO
| |
| |
//--- 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);
| |
}
| |
| |
//+---------------------------------------------------------------------------+
| |
//| 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);
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
// 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.
| |
static void CRiskManagemet::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
| |
{
| |
TSNSTD_ERRMAN_PUSHINI(out, trace_idx)
| |
switch(trace[trace_idx].code)
| |
{
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_NOT:
| |
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)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_INV_TYPE_BASICLP:
| |
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)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_SET_DYNAMIC:
| |
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);
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_ALREDY_MODI:
| |
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("LP type [%d] already modified by other mod", int(trace[trace_idx].info)), trace_idx)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_ADD_LOSSPROFITMAN:
| |
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);
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_LP_INV_PTR:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "LP is invalid pointer", trace_idx)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PTR:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Modifier invalid pointer", trace_idx)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_INV_PROP:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Modifier is attempting to modify an invalid property (LP)", trace_idx)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_LP_IS_ALREDY_DYNCMODE:
| |
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("The LP [%d] that you are attempting to modify is dynamic.", int(trace[trace_idx].info)), trace_idx)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_MOD_PROP_IS_ALREDY_MODLP:
| |
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)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_MODPROP_NOT_EQUALS:
| |
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)
| |
break;
| |
case TSNMQLART_RISK_MANAGEMENT_ERR_HOK_INV_POINTER:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Cannot add an invalid hook (invalid pointer)", trace_idx)
| |
break;
| |
default:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Unknow error", trace_idx)
| |
break;
| |
}
| |
}
| |
| |
//---
| |
}
| |
//+------------------------------------------------------------------+
| |
#endif // MQLARTICLES_ACCOUNT_RM_RISKMANAGEMENT_CORE_CORE_MQH
| |
//+------------------------------------------------------------------+
| |
| |
//+------------------------------------------------------------------+
|