MQLArticles/PosMgmt/BE/Base/BEBase.mqh
327 行
12 KiB
MQL5
Nique_372
2026-10-29 11:36:56 -05:00
//+------------------------------------------------------------------+
//| 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
Nique_372
2026-11-01 17:28:51 -05:00
int m_be_try; // Intenos en caso de fallo de modificacion de posicion
Nique_372
2026-10-29 11:36:56 -05:00
//---
position_be m_pos_be[]; // array of positions of type Positions
Nique_372
2026-10-30 13:24:14 -05:00
bool m_pos_be_remove[]; // parallel to m_pos_be (same size): true = remove after BreakEven(), always false between calls
Nique_372
2026-10-29 11:36:56 -05:00
int m_pos_be_s;
int m_pos_be_r;
Nique_372
2026-10-29 17:44:49 -05:00
public:
const uint m_num_params; // Number of parameters the class needs
Nique_372
2026-10-29 11:36:56 -05:00
public:
Nique_372
2026-10-29 12:18:18 -05:00
CBreakEvenBase(const string& symbol_, const ulong magic_, const uint nparams);
Nique_372
2026-10-29 11:36:56 -05:00
~CBreakEvenBase();
Nique_372
2026-11-01 17:28:51 -05:00
//--- Posiciones (manejo)
//- Add
Nique_372
2026-10-29 11:36:56 -05:00
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);
Nique_372
2026-11-01 17:28:51 -05:00
//- Remove
Nique_372
2026-10-29 11:36:56 -05:00
bool Remove(ulong ticket);
Nique_372
2026-11-01 17:28:51 -05:00
//- Total
__forceinline int TotalPositions() const { return m_pos_be_s; }
Nique_372
2026-11-01 17:44:41 -05:00
//- 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; }
Nique_372
2026-11-01 17:28:51 -05:00
//--- Main function
Nique_372
2026-10-29 11:36:56 -05:00
void BreakEven();
Nique_372
2026-11-01 17:28:51 -05:00
//--- Eventos
Nique_372
2026-10-29 11:36:56 -05:00
void OnOpenPosition(const ROnOpenPosition &pos) override final;
void OnClosePosition(const ROnClosePosition &pos, const int global_pos_index) override final;
Nique_372
2026-11-01 17:28:51 -05:00
//--- Config
// General
Nique_372
2026-10-29 11:36:56 -05:00
virtual bool Set(const BreakEvenParams &params[]) = 0;
Nique_372
2026-11-01 17:28:51 -05:00
// 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; }
Nique_372
2026-10-29 11:36:56 -05:00
Nique_372
2026-11-01 17:28:51 -05:00
//--- Info
inline string Simbolo() const { return m_symbol; }
inline ulong Magic() const { return m_magic; }
//--- Errores
Nique_372
2026-11-05 17:37:12 -05:00
// Formatea los errores de la base y (por el rango >= TSNMQLART_BE_TYPES_ERR_START) tambien los de los tipos (Imp)
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-29 11:36:56 -05:00
};
//+------------------------------------------------------------------+
//| Contructor \ Destructor |
//+------------------------------------------------------------------+
Nique_372
2026-10-29 12:18:18 -05:00
CBreakEvenBase::CBreakEvenBase(const string& symbol_, const ulong magic_, const uint nparams)
Nique_372
2026-10-29 11:36:56 -05:00
:
//---
m_automatic(true), m_magic(magic_), m_symbol(symbol_), m_point_value(SymbolInfoDouble(symbol_, SYMBOL_POINT)),
Nique_372
2026-11-05 17:37:12 -05:00
m_num_params(nparams),
Nique_372
2026-10-29 11:36:56 -05:00
//---
Nique_372
2026-11-01 17:28:51 -05:00
m_pos_be_s(0), m_pos_be_r(CBREAKEVEN_RESERVE_ARR), m_be_try(CBREAKEVEN_DEFAULT_POS_MOD_TRY)
Nique_372
2026-10-29 11:36:56 -05:00
{
//---
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);
Nique_372
2026-10-30 13:24:14 -05:00
::ArrayResize(m_pos_be_remove, CBREAKEVEN_RESERVE_ARR, CBREAKEVEN_RESERVE_ARR);
::ArrayInitialize(m_pos_be_remove, false);
Nique_372
2026-10-29 11:36:56 -05:00
}
//+------------------------------------------------------------------+
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))
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CBreakEvenBase>(TSNMQLART_BE_ERR_SELECT_POSITION, position_ticket, ::GetLastError());
Nique_372
2026-10-29 11:36:56 -05:00
//---
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)
Nique_372
2026-11-06 10:40:44 -05:00
return CErrorTrace::FailInit<CBreakEvenBase>(TSNMQLART_BE_ERR_POSITION_NOT_FOUND, ticket);
Nique_372
2026-10-29 11:36:56 -05:00
//---
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)
{
Nique_372
2026-10-29 20:10:16 -05:00
if(m_automatic && (m_magic == pos.position.magic || m_magic == NOT_MAGIC_NUMBER))
Nique_372
2026-10-29 11:36:56 -05:00
{
Nique_372
2026-11-05 17:37:12 -05:00
// 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.
Nique_372
2026-10-29 20:10:16 -05:00
if(Add(pos.position.ticket, pos.position.open_price, pos.position.sl, pos.position.type,
pos.position.open_time, account_status.last_trans_symbol))
Nique_372
2026-10-29 11:36:56 -05:00
{
#ifdef TSNMQLART_POSMGMT_BE_ELOGS
Nique_372
2026-10-29 20:10:16 -05:00
FastLog(FUNCION_ACTUAL, INFO_TEXT, StringFormat("Ticket %I64u has been added to the array of positions", pos.position.ticket));
Nique_372
2026-10-29 11:36:56 -05:00
#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);
Nique_372
2026-10-30 13:24:14 -05:00
//--- opt: solo un booleano como fastpath para eliminar o no
bool already_remove = false;
Nique_372
2026-11-01 16:53:39 -05:00
//---
Nique_372
2026-10-30 13:24:14 -05:00
#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)
Nique_372
2026-11-01 16:53:39 -05:00
#endif // TSNMQLART_POSMGMT_BE_ELOGS
Nique_372
2026-10-30 13:24:14 -05:00
Nique_372
2026-11-01 17:28:51 -05:00
//---
#define TSNMQLART_POSMGMT_BE_DEL(IDX) \
m_pos_be_remove[IDX] = true; \
already_remove = true;
Nique_372
2026-10-29 11:36:56 -05:00
//---
for(int i = 0 ; i < m_pos_be_s; i++)
{
Nique_372
2026-10-30 13:24:14 -05:00
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))
Nique_372
2026-11-01 16:53:39 -05:00
{
//---
ResetLastError();
Nique_372
2026-11-02 15:21:28 -05:00
const ulong ticket = m_pos_be[i].ticket;
Nique_372
2026-11-01 16:53:39 -05:00
if(!PositionSelectByTicket(ticket))
{
Nique_372
2026-11-01 17:28:51 -05:00
//--- eliminarla ya no tiene caso seguir
TSNMQLART_POSMGMT_BE_DEL(i)
//--- log
Nique_372
2026-11-01 16:53:39 -05:00
TSNMQLART_BE_LOG_ERR("Fallo al selecionar el ticket = %I64u, ultimo error = %d")
continue;
}
Nique_372
2026-11-02 21:51:46 -05:00
//--- Intentamos modificar (caso feliz se ejecuta)
if(m_trade.PositionModify(ticket, m_pos_be[i].breakeven_price, PositionGetDouble(POSITION_TP)))
Nique_372
2026-11-01 16:53:39 -05:00
{
Nique_372
2026-11-02 21:51:46 -05:00
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)
Nique_372
2026-11-01 16:53:39 -05:00
}
Nique_372
2026-11-02 21:51:46 -05:00
TSNMQLART_BE_LOG_ERR("Fallo al modificar la posicion = %I64u, ultimo error = %d")
Nique_372
2026-11-01 16:53:39 -05:00
}
Nique_372
2026-10-30 13:24:14 -05:00
}
Nique_372
2026-10-29 11:36:56 -05:00
Nique_372
2026-10-30 13:24:14 -05:00
//--- fast path para ver si tenemos que eliminar o no
if(!already_remove)
return;
Nique_372
2026-10-29 11:36:56 -05:00
Nique_372
2026-10-30 13:24:14 -05:00
//--- 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++;
Nique_372
2026-10-29 11:36:56 -05:00
}
else
Nique_372
2026-10-30 13:24:14 -05:00
m_pos_be_remove[r] = false;
Nique_372
2026-10-29 11:36:56 -05:00
}
Nique_372
2026-10-30 13:24:14 -05:00
m_pos_be_s = w; // opt: solo cambiamos el tamaño "virtual"
Nique_372
2026-10-29 11:36:56 -05:00
Nique_372
2026-10-30 13:24:14 -05:00
//--- undef
#undef TSNMQLART_BE_LOG_ERR
Nique_372
2026-11-01 17:28:51 -05:00
#undef TSNMQLART_POSMGMT_BE_DEL
Nique_372
2026-10-29 11:36:56 -05:00
}
Nique_372
2026-11-05 17:37:12 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
Nique_372
2026-11-06 10:40:44 -05:00
static void CBreakEvenBase::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
Nique_372
2026-11-05 17:37:12 -05:00
{
//--- 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;
}
}
Nique_372
2026-10-29 11:36:56 -05:00
//---
}
#endif // MQLARTICLES_POSMGMT_BE_BASE_BEBASE_MQH