forked from nique_372/MQLArticles
//+------------------------------------------------------------------+
| |
//| BEBase.mqh |
| |
//| Copyright 2026, Niquel Mendoza. |
| |
//| https://www.mql5.com |
| |
//+------------------------------------------------------------------+
| |
#property copyright "Copyright 2026, Niquel Mendoza."
| |
#property link "https://www.mql5.com"
| |
#property strict
| |
| |
#ifndef MQLARTICLES_POSMGMT_BE_BASE_BEBASE_MQH
| |
#define MQLARTICLES_POSMGMT_BE_BASE_BEBASE_MQH
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
#include "Def.mqh"
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
namespace TSN
| |
{
| |
//+------------------------------------------------------------------+
| |
//| Main class to apply break even |
| |
//+------------------------------------------------------------------+
| |
class CBreakEvenBase : public CAccountGestor
| |
{
| |
protected:
| |
//---
| |
CTrade m_trade; // CTrade object
| |
string m_symbol; // current m_symbol
| |
double m_point_value; // value of the set m_symbol point
| |
ulong m_magic; // m_magic number of positions to make break even
| |
bool m_automatic; // Automatic
| |
int m_be_try; // Intenos en caso de fallo de modificacion de posicion
| |
| |
//---
| |
position_be m_pos_be[]; // array of positions of type Positions
| |
bool m_pos_be_remove[]; // parallel to m_pos_be (same size): true = remove after BreakEven(), always false between calls
| |
int m_pos_be_s;
| |
int m_pos_be_r;
| |
| |
public:
| |
const uint m_num_params; // Number of parameters the class needs
| |
| |
| |
public:
| |
CBreakEvenBase(const string& symbol_, const ulong magic_, const uint nparams);
| |
~CBreakEvenBase();
| |
| |
| |
//--- Posiciones (manejo)
| |
//- Add
| |
virtual bool Add(ulong post_ticket, double open_price, double sl_price, ENUM_POSITION_TYPE
| |
position_type, datetime open_time, const string& sym) = 0;
| |
bool Add(ulong position_ticket);
| |
| |
//- Remove
| |
bool Remove(ulong ticket);
| |
| |
//- Total
| |
__forceinline int TotalPositions() const { return m_pos_be_s; }
| |
| |
//- Obtener una posicion (+info)
| |
void GetPosition(const int i, position_be& pos) const { pos = m_pos_be[i]; }
| |
__forceinline double GetPositionBePrice(const int i) const { return m_pos_be[i].breakeven_price; }
| |
__forceinline double GetPositionPriceToSup(const int i) const { return m_pos_be[i].price_to_beat; }
| |
| |
//--- Main function
| |
void BreakEven();
| |
| |
//--- Eventos
| |
void OnOpenPosition(const ROnOpenPosition &pos) override final;
| |
void OnClosePosition(const ROnClosePosition &pos, const int global_pos_index) override final;
| |
| |
//--- Config
| |
// General
| |
virtual bool Set(const BreakEvenParams ¶ms[]) = 0;
| |
// Automatico
| |
inline bool Automatic() const { return m_automatic; }
| |
void Automatic(bool auto) { m_automatic = auto; }
| |
// Intentos
| |
inline int BeTry() const { return m_be_try; }
| |
void BeTry(int v) { m_be_try = v; }
| |
| |
//--- Info
| |
inline string Simbolo() const { return m_symbol; }
| |
inline ulong Magic() const { return m_magic; }
| |
| |
//--- Errores
| |
// Formatea los errores de la base y (por el rango >= TSNMQLART_BE_TYPES_ERR_START) tambien los de los tipos (Imp)
| |
static void FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out);
| |
};
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| Contructor \ Destructor |
| |
//+------------------------------------------------------------------+
| |
CBreakEvenBase::CBreakEvenBase(const string& symbol_, const ulong magic_, const uint nparams)
| |
:
| |
//---
| |
m_automatic(true), m_magic(magic_), m_symbol(symbol_), m_point_value(SymbolInfoDouble(symbol_, SYMBOL_POINT)),
| |
m_num_params(nparams),
| |
| |
//---
| |
m_pos_be_s(0), m_pos_be_r(CBREAKEVEN_RESERVE_ARR), m_be_try(CBREAKEVEN_DEFAULT_POS_MOD_TRY)
| |
{
| |
//---
| |
if(magic_ != NOT_MAGIC_NUMBER)
| |
m_trade.SetExpertMagicNumber(magic_);
| |
| |
//---
| |
m_trade.LogLevel(LOG_LEVEL_NO);
| |
| |
//---
| |
account_status.RegisterEvents(&this, ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION);
| |
| |
//---
| |
::ArrayResize(m_pos_be, CBREAKEVEN_RESERVE_ARR, CBREAKEVEN_RESERVE_ARR);
| |
::ArrayResize(m_pos_be_remove, CBREAKEVEN_RESERVE_ARR, CBREAKEVEN_RESERVE_ARR);
| |
::ArrayInitialize(m_pos_be_remove, false);
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
CBreakEvenBase::~CBreakEvenBase()
| |
{
| |
if(account_status.IsActive())
| |
account_status.UnregisterEvents(&this, ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION);
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
bool CBreakEvenBase::Add(ulong position_ticket)
| |
{
| |
//---
| |
ResetLastError();
| |
if(!PositionSelectByTicket(position_ticket))
| |
return CErrorTrace::FailInit<CBreakEvenBase>(TSNMQLART_BE_ERR_SELECT_POSITION, position_ticket, ::GetLastError());
| |
| |
//---
| |
return Add(position_ticket, PositionGetDouble(POSITION_PRICE_OPEN), PositionGetDouble(POSITION_SL), ENUM_POSITION_TYPE(PositionGetInteger(POSITION_TYPE)),
| |
PositionGetInteger(POSITION_TIME), PositionGetString(POSITION_SYMBOL)); // en caso falle ya pone el error (o deberia)
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
bool CBreakEvenBase::Remove(ulong ticket)
| |
{
| |
//---
| |
int index = -1;
| |
for(int i = 0; i < m_pos_be_s; i++)
| |
{
| |
if(m_pos_be[i].ticket == ticket)
| |
{
| |
index = i;
| |
break;
| |
}
| |
}
| |
| |
//---
| |
if(index == -1)
| |
return CErrorTrace::FailInit<CBreakEvenBase>(TSNMQLART_BE_ERR_POSITION_NOT_FOUND, ticket);
| |
| |
//---
| |
if(--m_pos_be_s != index)
| |
m_pos_be[index] = m_pos_be[m_pos_be_s];
| |
| |
//---
| |
return true;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| OnTradeTransactionEvent |
| |
//+------------------------------------------------------------------+
| |
void CBreakEvenBase::OnOpenPosition(const ROnOpenPosition &pos)
| |
{
| |
if(m_automatic && (m_magic == pos.position.magic || m_magic == NOT_MAGIC_NUMBER))
| |
{
| |
// NOTA: el resultado se ignora a proposito. Un Add que falla aqui (ej. otro simbolo) es normal y reinicia la pila global
| |
// de errores (CErrorTrace), asi que la pila puede traer un error "normal" si se lee sin un fallo reciente.
| |
if(Add(pos.position.ticket, pos.position.open_price, pos.position.sl, pos.position.type,
| |
pos.position.open_time, account_status.last_trans_symbol))
| |
{
| |
#ifdef TSNMQLART_POSMGMT_BE_ELOGS
| |
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Ticket %I64u has been added to the array of positions", pos.position.ticket));
| |
#endif // TSNMQLART_POSMGMT_BE_ELOGS
| |
}
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
void CBreakEvenBase::OnClosePosition(const ROnClosePosition &pos, const int global_pos_index)
| |
{
| |
if(Remove(pos.position.ticket))
| |
{
| |
#ifdef TSNMQLART_POSMGMT_BE_ELOGS
| |
FastLog(FUNCION_ACTUAL, CAUTION_TEXT, StringFormat("Ticket %I64u has been removed from the positions array, breakeven could not be applied",
| |
pos.position.ticket));
| |
#endif // TSNMQLART_POSMGMT_BE_ELOGS
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| Function to make break even |
| |
//+------------------------------------------------------------------+
| |
void CBreakEvenBase::BreakEven(void)
| |
{
| |
//---
| |
if(m_pos_be_s < 1)
| |
return;
| |
| |
const double ask = SymbolInfoDouble(m_symbol, SYMBOL_ASK);
| |
const double bid = SymbolInfoDouble(m_symbol, SYMBOL_BID);
| |
| |
//--- opt: solo un booleano como fastpath para eliminar o no
| |
bool already_remove = false;
| |
| |
//---
| |
#ifdef TSNMQLART_POSMGMT_BE_ELOGS
| |
#define TSNMQLART_BE_LOG_ERR(msg) FastLog(FUNCION_ACTUAL, ERROR_TEXT, StringFormat(msg, ticket, ::GetLastError()));
| |
#else
| |
#define TSNMQLART_BE_LOG_ERR(msg)
| |
#endif // TSNMQLART_POSMGMT_BE_ELOGS
| |
| |
//---
| |
#define TSNMQLART_POSMGMT_BE_DEL(IDX) \
| |
m_pos_be_remove[IDX] = true; \
| |
already_remove = true;
| |
| |
| |
//---
| |
for(int i = 0 ; i < m_pos_be_s; i++)
| |
{
| |
if(m_pos_be[i].type == POSITION_TYPE_BUY ? (ask >= m_pos_be[i].price_to_beat) : (bid <= m_pos_be[i].price_to_beat))
| |
{
| |
//---
| |
ResetLastError();
| |
const ulong ticket = m_pos_be[i].ticket;
| |
if(!PositionSelectByTicket(ticket))
| |
{
| |
//--- eliminarla ya no tiene caso seguir
| |
TSNMQLART_POSMGMT_BE_DEL(i)
| |
| |
//--- log
| |
TSNMQLART_BE_LOG_ERR("Fallo al selecionar el ticket = %I64u, ultimo error = %d")
| |
continue;
| |
}
| |
| |
//--- Intentamos modificar (caso feliz se ejecuta)
| |
if(m_trade.PositionModify(ticket, m_pos_be[i].breakeven_price, PositionGetDouble(POSITION_TP)))
| |
{
| |
TSNMQLART_POSMGMT_BE_DEL(i)
| |
continue;
| |
}
| |
| |
//--- Fallo entonces reintentamos..
| |
// osea que si try es 1 entonces se intenta una vez mas pero si es 0 --0=-1 asi qeu directo se "elimina"
| |
if(--m_pos_be[i].try < 0) // un intento menos
| |
{
| |
TSNMQLART_POSMGMT_BE_DEL(i)
| |
}
| |
TSNMQLART_BE_LOG_ERR("Fallo al modificar la posicion = %I64u, ultimo error = %d")
| |
}
| |
}
| |
| |
//--- fast path para ver si tenemos que eliminar o no
| |
if(!already_remove)
| |
return;
| |
| |
//--- slow path: compactacion en una sola pasada O(n), reiniciando las marcas (struct plano, basta la asignacion)
| |
int w = 0;
| |
for(int r = 0; r < m_pos_be_s; r++)
| |
{
| |
if(!m_pos_be_remove[r])
| |
{
| |
if(w != r)
| |
m_pos_be[w] = m_pos_be[r];
| |
w++;
| |
}
| |
else
| |
m_pos_be_remove[r] = false;
| |
}
| |
m_pos_be_s = w; // opt: solo cambiamos el tamaño "virtual"
| |
| |
//--- undef
| |
#undef TSNMQLART_BE_LOG_ERR
| |
#undef TSNMQLART_POSMGMT_BE_DEL
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
static void CBreakEvenBase::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
| |
{
| |
//--- Errores de los tipos de breakeven (Imp)
| |
if(trace[trace_idx].code >= TSNMQLART_BE_TYPES_ERR_START)
| |
{
| |
CBasicBEFormater::FormatTrace(trace, trace_idx, out);
| |
return;
| |
}
| |
| |
//--- Propios de la base
| |
TSNSTD_ERRMAN_PUSHINI(out, trace_idx)
| |
switch(trace[trace_idx].code)
| |
{
| |
case TSNMQLART_BE_ERR_NOT:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Not error", trace_idx)
| |
break;
| |
case TSNMQLART_BE_ERR_SELECT_POSITION:
| |
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Error in select position [ticket = %I64u] last err = %d", trace[trace_idx].info, trace[trace_idx].mql_err), trace_idx)
| |
break;
| |
case TSNMQLART_BE_ERR_POSITION_NOT_FOUND:
| |
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Position not found in the breakeven [ticket = %I64u]", trace[trace_idx].info), trace_idx)
| |
break;
| |
default:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Unknow error", trace_idx)
| |
break;
| |
}
| |
}
| |
| |
//---
| |
}
| |
| |
#endif // MQLARTICLES_POSMGMT_BE_BASE_BEBASE_MQH
|