Beobachten
1
0
Fork
Du hast bereits einen Fork von MQLArticles erstellt
0
MQLArticles/Account/RM/LossProfit/Bases/Base.mqh
Nique_372 Nique_372 87640cc853
2026-11-07 21:17:58 -05:00
785 Zeilen
30 KiB
MQL5
//+------------------------------------------------------------------+
//| Base.mqh |
//| Copyright 2025, Niquel Mendoza. |
//| https://www.mql5.com/es/users/nique_372 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Niquel Mendoza."
#property link "https://www.mql5.com/es/users/nique_372"
#property strict
#ifndef MQLARTICLES_ACCOUNT_RM_LOSSPROFIT_BASES_BASE_MQH
#define MQLARTICLES_ACCOUNT_RM_LOSSPROFIT_BASES_BASE_MQH
//+------------------------------------------------------------------+
//| Include |
//+------------------------------------------------------------------+
#include "Def.mqh"
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
namespace TSN
{
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
// Clase base qeu represtna una maxima perdida\ganancia.. aparte de tambien representar a GLMPO (dinero ariessgoad por op)
// Esta clase base no implemta el caculol solo da una clase base..
//+------------------------------------------------------------------+
//| CLossProfit Class |
//+------------------------------------------------------------------+
class CLossProfit : public CAccountGestor
{
public:
const bool m_active_hook_on_superated;
const int m_type; // Type of maximum loss or profit.
const ENUM_LOSS_PROFIT m_type_loss_or_profit; // Tipo (Loss\Profit\GMLPO)
protected:
//--- Principales
double m_value;
double m_calculation_value;
//---
uint8_t m_dync_type; // Function for dynamic risk
double m_initial_calc_value; // Initial calc value
double m_saved_value; // Valor base
FuncionLossProfitSuperate m_f_check_sup; // Funcion custom que chekea si se ha superado
FTSNMQLArtRmPctgVal m_f_calc_val; // Calcular valor
const ulong m_magic_number; // Numero magico para filtrar
//---
void* m_ptr_f; // Ptr al superar
//--- Dynamic risk
Dynamic_LossProfit m_dynamic_lp; // Structure containing the % to exceed and risks to apply
double m_chosen_balance; // Chosen initial balance
int m_index_cambio; // Change index between positives and negatives
int m_size_dynamic; // Size of changes
bool m_min_val_is; // Minimum value exceeded
bool m_max_val_is; // Maximum value exceeded
int m_pos_derecha; // Current position on right
int m_pos_izquierda; // Current position on left
double m_new_balance_to_overcome; // Next balance to overcome
// Cache for dynamic risk parameters
string m_cache_percentages_to_activate;
string m_cache_risks_to_be_applied;
//---
bool ProccesDynamic(double& balance_to_activate_the_risk[], double& risk_to_be_adjusted[]);
//---
virtual void OnSuperated() {}
//---
static CHashMapFastP(double, double, _fibbo) s_balance_risk_map; // HashMap for dynamic risk (percentages to exceed and new risk percentage)
//---
void CheckPositives();
void CheckNegatives();
void CheckNegativesAndPositives();
public:
//--- Constructor
CLossProfit(const int type, const bool act_hook, const ulong magic, const ENUM_LOSS_PROFIT tt);
~CLossProfit() {}
//--- Inits (setteo base)
void Init(double _calc_value, FuncionLossProfitSuperate fsup, FTSNMQLArtRmPctgVal fval);
bool SetDynamic(const string& percentages_to_activate, const string& risks_to_be_applied, double _chosen_balance);
bool SetDynamic(double _chosen_balance);
void SetPtrF(void* ptr) { m_ptr_f = ptr; }
//--- Dynamic risk
// Verifies and checks if the risk can be modified (only works in dynamic risk)
__forceinline void CheckAndModifyThePercentage();
// Returns true if the risk is dynamic
inline bool IsDynamicMode() const { return m_dync_type < TSNMQLART_ACCST_RMLP_DYNCTYPE_INV; }
//--- General getters
// Returns true if the "maximum loss or profit" has been exceeded
bool IsSuperated();
inline string Name() const { return TSN_MQLART_RM_LP_NAME(m_type); } // Nombre
//--- Functions to work with the (Percentage | Value | Profit) of the "maximum loss or profit"
// Set value with calc value
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
__forceinline void Set()
{
m_value = m_f_calc_val(m_calculation_value, m_ptr_f);
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Valor calculado para = %s, es = %.2f", Name(), m_value));
}
#else
__forceinline void Set() { m_value = m_f_calc_val(m_calculation_value, m_ptr_f); }
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
// Initial calc value (percentage or money)
inline double GetInitialCalcValue() const { return m_initial_calc_value; }
inline void SetInitialCalcValue() { m_calculation_value = m_initial_calc_value; } // Setter
// Current value
__forceinline double GetValue() const { return m_value; }
void SetValue(double val) { m_value = val; }
// Calc value if mode is:
// percentage: represet the percentage
// money: fixed money
inline double GetCalcValue() const { return m_calculation_value; }
void SetCalcValue(double val) { m_calculation_value = val; }
// Saved value
inline double GetSavedValue() const { return m_saved_value; }
void SetSavedValue() { m_saved_value = m_value; }
// Magic number
__forceinline ulong MagicNumber() const { return m_magic_number; }
//---
static void FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out);
};
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CLossProfit::CLossProfit(const int type, const bool act_hook, const ulong magic, const ENUM_LOSS_PROFIT tt)
:
//--- Basico
m_type(type), m_type_loss_or_profit(tt), m_magic_number(magic),
//---
m_initial_calc_value(0.00), m_saved_value(0.00), m_ptr_f(NULL),
//--- Hook
m_active_hook_on_superated(act_hook),
//--- Riesgo dinamico
m_min_val_is(false), m_max_val_is(false), m_pos_derecha(0), m_pos_izquierda(0), m_dync_type(TSNMQLART_ACCST_RMLP_DYNCTYPE_INV),
m_index_cambio(0), m_chosen_balance(0.00),
m_new_balance_to_overcome(0.00), m_cache_percentages_to_activate(NULL), m_cache_risks_to_be_applied(NULL),
//--- Extra ptr funcs
m_f_check_sup(NULL), m_f_calc_val(NULL)
{
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CLossProfit::IsSuperated(void)
{
if(m_f_check_sup(m_value, m_saved_value, m_ptr_f))
{
if(m_active_hook_on_superated)
OnSuperated();
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CLossProfit::Init(double _calc_value, FuncionLossProfitSuperate fsup, FTSNMQLArtRmPctgVal fval)
{
//---
m_initial_calc_value = _calc_value;
m_calculation_value = _calc_value;
m_value = 0.00;
//---
m_f_calc_val = fval;
m_f_check_sup = fsup;
}
//+------------------------------------------------------------------+
//| Establecer el riesgo dinamico |
//+------------------------------------------------------------------+
bool CLossProfit::SetDynamic(double _chosen_balance)
{
if(m_cache_percentages_to_activate == NULL || m_cache_risks_to_be_applied == NULL)
return CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_CACHE, 0); // fallo de cache
// devolvemos el de abajo
return SetDynamic(m_cache_percentages_to_activate, m_cache_risks_to_be_applied, _chosen_balance);
}
//+------------------------------------------------------------------+
bool CLossProfit::SetDynamic(const string& percentages_to_activate, const string& risks_to_be_applied, double _chosen_balance)
{
//---
m_dync_type = TSNMQLART_ACCST_RMLP_DYNCTYPE_INV;
//---
m_size_dynamic = TSN::CStringFunc::ToArr<double, TSN::CStringConvert>(percentages_to_activate, m_dynamic_lp.balance_to_activate_the_risk, ',');
if(m_size_dynamic < 1)
return m_size_dynamic == 0 ?
CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_SIZE, 0) :
CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_MALFORMED_VALUES, (ulong)TSNSTD_STRFUNC_TOARR_REQPOS(m_size_dynamic) | 0ULL << 32);
// resize
ArrayResize(m_dynamic_lp.balance_to_activate_the_risk, m_size_dynamic);
//---
m_size_dynamic = TSN::CStringFunc::ToArr<double, TSN::CStringConvert>(risks_to_be_applied, m_dynamic_lp.risk_to_be_adjusted, ',');
if(m_size_dynamic < 1)
return m_size_dynamic == 0 ?
CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_SIZE, 0) :
CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_MALFORMED_VALUES, (ulong)TSNSTD_STRFUNC_TOARR_REQPOS(m_size_dynamic) | 1ULL << 32);
// resize
ArrayResize(m_dynamic_lp.risk_to_be_adjusted, m_size_dynamic);
//---
if(m_dynamic_lp.balance_to_activate_the_risk.Size() != m_dynamic_lp.risk_to_be_adjusted.Size())
return CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_SIZE_NOT_EQ_ARRS,
ulong(m_dynamic_lp.balance_to_activate_the_risk.Size()) | ulong(m_dynamic_lp.risk_to_be_adjusted.Size()) << 32
);
//--- Cache values
m_cache_percentages_to_activate = percentages_to_activate;
m_cache_risks_to_be_applied = risks_to_be_applied;
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, "Arrays before revision");
CRmFunctions::PrintArrayAsTable(m_dynamic_lp.balance_to_activate_the_risk,
"Negative percentages to modify the risk", "balance");
CRmFunctions::PrintArrayAsTable(m_dynamic_lp.risk_to_be_adjusted,
"Risk to be adjusted", "new risk");
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
m_chosen_balance = _chosen_balance;
//---
return ProccesDynamic(m_dynamic_lp.balance_to_activate_the_risk, m_dynamic_lp.risk_to_be_adjusted);
}
//+------------------------------------------------------------------+
bool CLossProfit::ProccesDynamic(double &balance_to_activate_the_risk[], double &risk_to_be_adjusted[])
{
//---
s_balance_risk_map.Clear();
//---
#define TSN_MQLART_RM_LP_PDYN_F_POS (1)
#define TSN_MQLART_RM_LP_PDYN_F_NEG (2)
#define TSN_MQLART_RM_LP_PDYN_F_ALL (TSN_MQLART_RM_LP_PDYN_F_POS|TSN_MQLART_RM_LP_PDYN_F_NEG)
//--- Agrupamos de apares.. y un clean previo antes del sort
uint f = 0;
for(int i = 0 ; i < m_size_dynamic; i++)
{
//---
const double v = balance_to_activate_the_risk[i];
if(v == 0.0 || v > 100.0 || v < -100.0)
return CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_VALUE_DYNC_PCTG, CBitsReinterprete::ToBasic<ulong, double>(v));
//---
if(s_balance_risk_map.ReserveSlot(v))
{
const uint p = s_balance_risk_map.m_last_pos_tbl;
s_balance_risk_map.m_table[p].key = v;
s_balance_risk_map.m_table[p].value = risk_to_be_adjusted[i];
}
else
return CErrorTrace::FailInit<CLossProfit>(TSNMQLART_RM_LP_RES_LPDYNC_ERR_DYN_PCTG_ADD_HASHMAP, 0);
//---
f |= TSN_MQLART_RM_LP_PDYN_F_POS + (v < 0.0);
}
//--- Sort
ArraySort(balance_to_activate_the_risk);
//---
for(int i = 0 ; i < m_size_dynamic; i++)
{
//---
const double prev_value_bal = balance_to_activate_the_risk[i]; // balance
double value; // riesgo a cambiar
s_balance_risk_map.TryGet(prev_value_bal, value);
//---
// Caluclomaso ya el porcentaje "final" dado qeu el previo era [0-100]
risk_to_be_adjusted[i] = TSNMQLART_RISKM_NORM_PERCERNTAGE(value);
//---
// buscmaos aquel indice en el cual ya este pos acutal sea pos pero el previo neg (este indice seira como el cambio)
if(i < (m_size_dynamic - 1) && f == TSN_MQLART_RM_LP_PDYN_F_ALL && (balance_to_activate_the_risk[i] < 0.0 && balance_to_activate_the_risk[i + 1] > 0.0))
m_index_cambio = i;
//---
// Tambien calculoasmo el balance a "superar"
balance_to_activate_the_risk[i] = (m_chosen_balance + (m_chosen_balance * (prev_value_bal / 100.0)));
}
//---
m_min_val_is = false;
m_max_val_is = false;
//---
if(f == TSN_MQLART_RM_LP_PDYN_F_NEG) // Solo negativos
{
m_pos_izquierda = m_size_dynamic - 1; // desde arriba a abajo
m_new_balance_to_overcome = MAX_VAL_DEFINES_CLOSS_PROFIT;
m_dync_type = TSNMQLART_ACCST_RMLP_DYNCTYPE_NEG;
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("[Elegido = Negativo] izq = %d", m_pos_izquierda));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
else
if(f == TSN_MQLART_RM_LP_PDYN_F_POS) // Solo positivos
{
m_pos_derecha = 0; // empeiza en el primer indice
m_new_balance_to_overcome = MIN_VAL_DEFINES_CLOSE_PROFIT;
m_dync_type = TSNMQLART_ACCST_RMLP_DYNCTYPE_POS;
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, "[Elegido = Positivo] pos drch = 0");
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
else // combinacion
{
m_pos_derecha = m_index_cambio + 1; // Sumamos 1 para que sea pos
m_pos_izquierda = m_index_cambio; // Tal cual apunta abajo
m_dync_type = TSNMQLART_ACCST_RMLP_DYNCTYPE_NEG_POS;
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("[Elegido = Pos y Neg] pos drch = %d, pos izqr", m_pos_derecha, m_pos_izquierda));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, "Arrays ready");
CRmFunctions::PrintArrayAsTable(balance_to_activate_the_risk,
"Percentages to modify the risk", "balance");
//---
double temp[];
ArrayResize(temp, m_size_dynamic);
for(int i = 0; i < m_size_dynamic; i++)
temp[i] = risk_to_be_adjusted[i] * 100.0;
CRmFunctions::PrintArrayAsTable(temp,
"Risk to be adjusted", "new risk");
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
return true;
}
//+------------------------------------------------------------------+
//| Checks and modifies the percentage |
//+------------------------------------------------------------------+
void CLossProfit::CheckAndModifyThePercentage(void)
{
//--- despacho
switch(m_dync_type)
{
case TSNMQLART_ACCST_RMLP_DYNCTYPE_NEG:
{
CheckNegatives();
break;
}
case TSNMQLART_ACCST_RMLP_DYNCTYPE_POS:
{
CheckPositives();
break;
}
case TSNMQLART_ACCST_RMLP_DYNCTYPE_NEG_POS:
{
CheckNegativesAndPositives();
break;
}
default:
{
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, StringFormat("Risk %s is not allowed to use dynamic risk", TSN_MQLART_RM_LP_NAME(m_type)));
Remover();
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
break;
}
}
}
//+------------------------------------------------------------------+
//| Funciones estaticas para chekear y modficar el porcentaje |
//+------------------------------------------------------------------+
// Aqui la idea es ir subiendo hasta que no se pueda mas luego cuando caemos tambien..
// 1. en caso el min value aun no se supere (vamos bien) entonces veriamso si almenos e account eq de ahora
// es mayor a la posicon izquieda en caso sea cierto hace falta saber por cuanto? aárte tenemoque que indenficair "donde cae"
// haste la cuenta de que tenemos 3 nivlees para modicar eisgo en un blanace de 10k y por lo tnato 3 riesogs (+default) que usar
// 10k 10.5k 11k 12k
// <- inicial ] [ 0 ] [ 1 ] [ 2 ->
// entonces en los niveles o cajas que tineen a "infinito" por debajo del balnce base o por encima usaran ya un resigo "fijo"
// con esto en mente continuemso, last seira 3-1 = 2 esto dado qeu en cada "paso" buscarmeos rnago asi que para no salirnos de rango eso
// por ejemplo el primer paso buscamos si equity cae en la "caja #0" osea si es mayor 10.5k pero menor o iqual 11k
// En caso digmoas caiga en ese rango salimos con cayo_en_rango=True (se consiguio) si se consiguo entonces
// seteamos el calcvalue con el riesgo configuradon con indice 0 (1-1) nota que restmoas uno dad que ahora mismo pozizq pro el post inc
// aumento
// ahora el balance a superar "por abajo" lo volvemos a configurar esta vez en el "piso" osea 10.5k en este caso ...
// y en caso cayo_en_rango=false solo se da en las siguintes condicion
// asumeindo qeu size_dynacmis siempre es valido cuando se llama osea miimo como un valor
// entonces:
// - size_dynamic=1: con ese valor last=0 por lo qeu no iteraria y cayo_en_rango=false (usaria el maximo)
// - size_dynamic>1 && se superaron todos los valores posibles por lo tanto m_pos_derecha=size-1
void CLossProfit::CheckPositives()
{
//---
const double account_equity = AccountInfoDouble(ACCOUNT_EQUITY);
//---
if(!m_max_val_is && account_equity > m_dynamic_lp.balance_to_activate_the_risk[m_pos_derecha]) //toca aumentar riesgo o parar
{
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Se ha superado el balance %.2f (idx=%d)",
m_dynamic_lp.balance_to_activate_the_risk[m_pos_derecha], m_pos_derecha));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
bool cayo_en_rango = false;
const int last = m_size_dynamic - 1;
//---
while(m_pos_derecha < last)
{
if(m_dynamic_lp.balance_to_activate_the_risk[++m_pos_derecha] >= account_equity)
{
cayo_en_rango = true;
break;
}
}
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("El indice correspondiente es (idx=%d)",
m_pos_derecha));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
if(cayo_en_rango)
{
m_new_balance_to_overcome = m_dynamic_lp.balance_to_activate_the_risk[m_pos_derecha - 1];
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_derecha - 1];
}
else
{
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_derecha]; //llegamos al maximo asignamos el maximo posible
m_new_balance_to_overcome = m_dynamic_lp.balance_to_activate_the_risk[m_pos_derecha];
m_max_val_is = true; //llegamos al maximo
}
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Nuevo calc value = %.2f | Nuevo 'piso' = %.2f",
m_calculation_value, m_new_balance_to_overcome));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
return;
}
//--- Abajo
if(account_equity < m_new_balance_to_overcome) //toca disminir riesgo o parar
{
bool cayo_en_rango = false;
while(m_pos_derecha > 0)
{
if(account_equity >= m_dynamic_lp.balance_to_activate_the_risk[--m_pos_derecha])
{
cayo_en_rango = true;
break;
}
}
//---
if(cayo_en_rango)
{
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_derecha];
m_new_balance_to_overcome = m_dynamic_lp.balance_to_activate_the_risk[m_pos_derecha];
m_pos_derecha++; // buscamos nuevo "techo"
}
else // cayo por debajo del nivel 0, m_pos_derecha es 0 aqui por lo tanto se sigue buscando se nivel
{
m_new_balance_to_overcome = MIN_VAL_DEFINES_CLOSE_PROFIT;
m_calculation_value = m_initial_calc_value; //n os pasamos del miinimo entonces aisgnamos el porcentake inicial
}
m_max_val_is = false; //Reseteamos, ahora si es pobible aumentar el riesgo
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Nuevo calc value = %.2f | Nuevo 'piso' = %.2f | poz drc = %d",
m_calculation_value, m_new_balance_to_overcome, m_pos_derecha));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
}
//+------------------------------------------------------------------+
void CLossProfit::CheckNegatives()
{
//---
const double account_equity = AccountInfoDouble(ACCOUNT_EQUITY);
//---
if(!m_min_val_is && account_equity < m_dynamic_lp.balance_to_activate_the_risk[m_pos_izquierda]) //toca aumentar riesgo o parar
{
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Se ha superado el balance %.2f (idx=%d)",
m_dynamic_lp.balance_to_activate_the_risk[m_pos_izquierda], m_pos_izquierda));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
bool cayo_en_rango = false;
while(m_pos_izquierda > 0)
{
if(account_equity >= m_dynamic_lp.balance_to_activate_the_risk[--m_pos_izquierda])
{
cayo_en_rango = true;
break;
}
}
//---
int i = m_pos_izquierda;
if(cayo_en_rango)
i++; // el cuerpo apunta abajo (el real) pero este i que sera el que usamos apunta a previous
else
m_min_val_is = true;
//---
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[i];
m_new_balance_to_overcome = m_dynamic_lp.balance_to_activate_the_risk[i]; //arriba
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Nuevo calc value = %.2f | idx = %d",
m_calculation_value, m_pos_izquierda));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
//---
return;
}
//--- Recuperandose
if(account_equity > m_new_balance_to_overcome) //toca disminir riesgo o parar
{
const int last = m_size_dynamic - 1;
bool cayo_en_rango = false;
while(m_pos_izquierda < last)
{
if(m_dynamic_lp.balance_to_activate_the_risk[++m_pos_izquierda] >= account_equity)
{
cayo_en_rango = true;
break;
}
}
//---
if(cayo_en_rango)
{
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_izquierda]; //usa el riesgo de aqui
m_new_balance_to_overcome = m_dynamic_lp.balance_to_activate_the_risk[m_pos_izquierda--];
// pos izq qeuda apuntabadno abajr
}
else //nos pasmaos entonces, riesgo inicial
{
m_calculation_value = m_initial_calc_value; // En este caso si o si es porcentaje
m_new_balance_to_overcome = MAX_VAL_DEFINES_CLOSS_PROFIT;
}
//---
m_min_val_is = false; //llegamos al maximo
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Nuevo calc value = %.2f | Nuevo 'techo' = %.2f | idx= %d",
m_calculation_value, m_new_balance_to_overcome, m_pos_izquierda));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
}
//+------------------------------------------------------------------+
// 0 1 2
// 9k 9.5k 10k 13k
// [ ] [ ] [ ]
//
void CLossProfit::CheckNegativesAndPositives()
{
//---
const double account_equity = AccountInfoDouble(ACCOUNT_EQUITY);
//---
if(!m_min_val_is && account_equity < m_dynamic_lp.balance_to_activate_the_risk[m_pos_izquierda])
{
if(m_max_val_is)
m_pos_derecha++; //size + 1, y luego en while ya se ve la direfencia de 1
//---
bool cayo_en_rango = false;
//---
while(m_pos_izquierda > 0)
{
m_pos_derecha--; // reducimos tambien pero este va "uno adelantado" en caso sea "pico"
if(account_equity >= m_dynamic_lp.balance_to_activate_the_risk[--m_pos_izquierda])
{
cayo_en_rango = true;
break;
}
}
//---
if(cayo_en_rango) // Solo si estabamos en almeons un proceso de bajada
{
// en caso venimos de haber subido fuera de indexcambio > y pos izq es igual a idx cambio entonces usremos el "normal calc value"
if(m_pos_izquierda == m_index_cambio)
m_calculation_value = m_initial_calc_value;
else // de lo contrario
// ahora en caso estemos por debajo usamos +1 dado que izq se qeudo apuntao abajo...
// si estmaos en linea "positiva" usamos tal cual
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_izquierda + (m_pos_izquierda < m_index_cambio)];
}
else
{
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_izquierda];
m_min_val_is = true; //llegamos al minimo
m_pos_derecha = m_pos_izquierda; // ahora esperamos superar esto para cambiar..
}
//--- reset
m_max_val_is = false;
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Nuevo calc value = %.2f | pos izq = %d | pos drc = %d",
m_calculation_value, m_pos_izquierda, m_pos_derecha));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
//--- En caso se supere
// 0 1 2 3
// 8k 9k 10k 11k 12k
//.. ] [ ] [ ] [ ] [ ...
if(!m_max_val_is && account_equity > m_dynamic_lp.balance_to_activate_the_risk[m_pos_derecha]) //toca disminir riesgo o parar
{
if(m_min_val_is)
m_pos_izquierda--; //-1
//---
const int last = m_size_dynamic - 1;
bool cayo_en_rango = false;
//---
while(m_pos_derecha < last)
{
m_pos_izquierda++;
if(m_dynamic_lp.balance_to_activate_the_risk[++m_pos_derecha] >= account_equity)
{
cayo_en_rango = true;
break;
}
}
//---
if(cayo_en_rango)
{
if(m_pos_izquierda == m_index_cambio) // si cae aqui entonces usamso el normal
m_calculation_value = m_initial_calc_value;
else // no cae ahi entonces el riesgo de los arrays
// 1. en caso pos dereca sea mayor a index cambio entonces esta en su "fase" - 1
// 2. de lo conrtario tal cual esta bien dado qeu apunta al siguiente
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_derecha - (m_pos_derecha > m_index_cambio)];
}
else //nos pasmaos entonces, riesgo inicial
{
m_calculation_value = m_dynamic_lp.risk_to_be_adjusted[m_pos_derecha]; //maximo
m_max_val_is = true; //llegamos al maximo
m_pos_izquierda = m_pos_derecha;// mismo
}
//--- reset
m_min_val_is = false;
//---
#ifdef MORE_INFO_LOSS_PROFIT_DEFINE
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Nuevo calc value = %.2f | pos izq = %d | pos drc = %d",
m_calculation_value, m_pos_izquierda, m_pos_derecha));
#endif // MORE_INFO_LOSS_PROFIT_DEFINE
}
//---
//PrintFormat("%d - %d - cambio en: %d",m_pos_izquierda,m_pos_derecha, m_index_cambio);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
static void CLossProfit::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
{
TSNSTD_ERRMAN_PUSHINI(out, trace_idx)
switch(trace[trace_idx].code)
{
case TSNMQLART_RM_LP_RES_OK:
TSNSTD_ERRMAN_PUSHOUT(out, "Not error", trace_idx)
break;
case TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_SIZE:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Set dynamic error, invalid size [%s] (must be > 0)", (trace[trace_idx].info ? "to_be_apllied" : "percentage_to_active")), trace_idx)
break;
case TSNMQLART_RM_LP_RES_LPDYNC_ERR_MALFORMED_VALUES:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Malformed double find in parse str-comma-separated value [%s], expected position int arr = [%d]",
((trace[trace_idx].info >> 32) == 0 ? "percentage to active" : "risk to be applied"), int(trace[trace_idx].info)), trace_idx)
break;
case TSNMQLART_RM_LP_RES_LPDYNC_ERR_SIZE_NOT_EQ_ARRS:
{
const ulong v = trace[trace_idx].info;
const int bal_s = int(v);
const int risk_ajusted_s = int(v >> 32);
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Dynamic LP Error, arrays must be equal [balance active size = %d | risk ajusted size = %d]", bal_s, risk_ajusted_s), trace_idx)
break;
}
case TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_CACHE:
TSNSTD_ERRMAN_PUSHOUT(out, "Invalid cache, first call SetDynamic with full parameters", trace_idx)
break;
case TSNMQLART_RM_LP_RES_LPDYNC_ERR_INVALID_VALUE_DYNC_PCTG:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Invalid dinamyc str-comma-separetd, An invalid value [%.4f] was found for the balance percentage to be modified, must be in [-100.0, 100.0] and != 0.0."
, CBitsReinterprete::ToBasic<double, ulong>(trace[trace_idx].info)), trace_idx)
break;
case TSNMQLART_RM_LP_RES_LPDYNC_ERR_DYN_PCTG_ADD_HASHMAP:
TSNSTD_ERRMAN_PUSHOUT(out, "Fatal error, could not add hashmap pctg balance", trace_idx)
break;
default:
TSNSTD_ERRMAN_PUSHOUT(out, "Unkwnow error", trace_idx)
break;
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
CHashMapFastP(double, double, _fibbo) CLossProfit::s_balance_risk_map(64);
//---
}
//+------------------------------------------------------------------+
#endif // MQLARTICLES_ACCOUNT_RM_LOSSPROFIT_BASES_BASE_MQH