derivato da nique_372/MQLArticles
//+------------------------------------------------------------------+
| |
//| TrailingBase.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_TSL_BASIC_TRAILINGBASE_MQH
| |
#define MQLARTICLES_POSMGMT_TSL_BASIC_TRAILINGBASE_MQH
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
#include "TrailingDef.mqh"
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
namespace TSN
| |
{
| |
//+------------------------------------------------------------------+
| |
//| Clase principal CTrailingStop |
| |
//+------------------------------------------------------------------+
| |
class CTrailingStop : public CAccountGestor
| |
{
| |
protected:
| |
//--- general
| |
ENUM_TIMEFRAMES m_timeframe;
| |
string m_symbol;
| |
CTrade m_trade;
| |
ulong m_magic;
| |
| |
//---
| |
const int m_type; // Tipo de trailing stop
| |
| |
//---
| |
bool m_automatic;
| |
| |
//--- symbol cache info
| |
double m_trade_stops_levels;
| |
int m_digits;
| |
double m_point_value;
| |
| |
//--- trailing info
| |
const ENUM_TYPE_EXECUTION_TSL m_exec_type;
| |
const int16_t m_number_of_parameters;
| |
| |
//--- trailign data
| |
int m_trailings_s;
| |
int m_trailings_r;
| |
InfoTrailing m_trailings[];
| |
| |
//---
| |
virtual inline double GetPricePositionSell(double curr_price) const { return 0.00; }
| |
virtual inline double GetPricePositionBuy(double curr_price) const { return 0.00; }
| |
virtual void Add(ulong ticket, double open_price, ENUM_POSITION_TYPE pos_type, double sl_price);
| |
| |
//---
| |
virtual void DeleteAll() { }
| |
virtual void OnOpenPos() { }
| |
virtual void OnCloseAllPosition() { }
| |
virtual void OnInitOpenPosition() { }
| |
virtual void OnSymbolChange();
| |
| |
public:
| |
CTrailingStop(const int16_t nparams, ENUM_TYPE_EXECUTION_TSL exet, const int type);
| |
~CTrailingStop();
| |
| |
//--- Trabajo con posiciones (añadir\eliminar\clear)
| |
// nivel 1 (bajo no chekea nada)
| |
void AddPosicion(const ulong ticket, const double open_price,
| |
const ENUM_POSITION_TYPE pos_type, const double sl_price);
| |
// nivel 2 (alto con cheking integrado)
| |
bool AddPosicion(const ulong ticket);
| |
// eliminar
| |
bool Delete(const ulong ticket);
| |
// clear
| |
void CleanTrailings();
| |
| |
//---
| |
void OnOpenPosition(const ROnOpenPosition &pos) override final;
| |
void OnClosePosition(const ROnClosePosition &pos, const int global_pos_index) override final;
| |
| |
//---
| |
virtual void TrailingStop();
| |
virtual void OnNewBar() {}
| |
| |
//--- Establecer las variables
| |
virtual bool SetVariables(const MqlParam ¶ms[]) = 0;
| |
| |
//--- Configurar el modo automatico
| |
void AutomaticMode(bool automatico) { m_automatic = automatico; }
| |
inline bool AutomaticMode() const { return m_automatic; }
| |
| |
//--- Getters puros
| |
__forceinline int Type() const { return m_type; }
| |
__forceinline bool AreThereAnOpenOperations() const { return m_trailings_s > 0; }
| |
__forceinline ENUM_TYPE_EXECUTION_TSL GetExecution() const { return m_exec_type; }
| |
inline int16_t NumberOfParameters() const { return m_number_of_parameters; }
| |
inline ENUM_TIMEFRAMES Timeframe() const { return m_timeframe; }
| |
inline CTrade* TradePtr() { return &m_trade; }
| |
| |
| |
//--- Getter+Setter
| |
// Numero magico
| |
inline ulong Magic() const { return m_magic; }
| |
void Magic(ulong value);
| |
| |
// Simbolo
| |
inline string Simbolo() const { return m_symbol; }
| |
void Simbolo(const string& symbol);
| |
| |
//--- Error
| |
static void FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out);
| |
};
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
CTrailingStop::CTrailingStop(const int16_t nparams, ENUM_TYPE_EXECUTION_TSL exet, const int type)
| |
:
| |
//---
| |
m_automatic(true),
| |
m_trailings_s(0),
| |
m_trailings_r(TSNMQLA_CTRAILING_STOP_RESERVE_ARR),
| |
m_magic(NOT_MAGIC_NUMBER),
| |
m_symbol(_Symbol),
| |
m_timeframe(_Period),
| |
m_number_of_parameters(nparams),
| |
m_exec_type(exet),
| |
m_type(type)
| |
{
| |
//---
| |
account_status.RegisterEvents(&this, ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION);
| |
| |
//---
| |
if(m_magic != NOT_MAGIC_NUMBER)
| |
m_trade.SetExpertMagicNumber(m_magic);
| |
| |
//---
| |
m_trade.LogLevel(LOG_LEVEL_NO);
| |
| |
//---
| |
ArrayResize(m_trailings, m_trailings_r, m_trailings_r);
| |
| |
//---
| |
OnSymbolChange();
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
CTrailingStop::~CTrailingStop()
| |
{
| |
if(account_status.IsActive())
| |
account_status.UnregisterEvents(&this, ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION);
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::CleanTrailings(void)
| |
{
| |
//---
| |
m_trailings_s = 0;
| |
//---
| |
OnCloseAllPosition();
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::Add(ulong ticket, double open_price, ENUM_POSITION_TYPE pos_type, double sl_price)
| |
{
| |
TSNMQLA_TRAILING_CHECK_R
| |
m_trailings[m_trailings_s].open_price = open_price;
| |
m_trailings[m_trailings_s].ticket = ticket;
| |
m_trailings[m_trailings_s].last_stop_loss_price = sl_price;
| |
m_trailings[m_trailings_s++].pos_type = pos_type;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::AddPosicion(const ulong ticket, const double open_price, const ENUM_POSITION_TYPE pos_type,
| |
const double sl_price)
| |
{
| |
//--- Añadimos interno
| |
Add(ticket, open_price, pos_type, sl_price);
| |
//--- Chekeamos
| |
if(m_trailings_s == 1)
| |
OnInitOpenPosition();
| |
else
| |
OnOpenPos();
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
bool CTrailingStop::AddPosicion(const ulong ticket)
| |
{
| |
//---
| |
::ResetLastError();
| |
| |
//---
| |
if(!PositionSelectByTicket(ticket))
| |
return CErrorTrace::FailInit<CTrailingStop>(GENBYELO_TS_ERR_SELECT_POSITION, ticket, ::GetLastError());
| |
if(PositionGetString(POSITION_SYMBOL) != m_symbol)
| |
return CErrorTrace::FailInit<CTrailingStop>(GENBYELO_TS_ERR_SYMBOL_IS_NOT_A_CONFIGURED, ticket);
| |
| |
//---
| |
AddPosicion(ticket, PositionGetDouble(POSITION_PRICE_OPEN),
| |
(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE), PositionGetDouble(POSITION_SL));
| |
return true;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::OnOpenPosition(const ROnOpenPosition &pos)
| |
{
| |
//---
| |
if(!m_automatic || m_symbol != account_status.last_trans_symbol)
| |
return;
| |
//---
| |
if(pos.position.magic == m_magic || m_magic == NOT_MAGIC_NUMBER)
| |
{
| |
AddPosicion(pos.position.ticket, pos.position.open_price,
| |
pos.position.type, pos.position.sl);
| |
}
| |
}
| |
| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::OnClosePosition(const ROnClosePosition &pos, const int global_pos_index)
| |
{
| |
Delete(pos.position.ticket);
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
bool CTrailingStop::Delete(const ulong ticket)
| |
{
| |
//---
| |
int index = -1;
| |
for(int i = 0; i < m_trailings_s; i++)
| |
{
| |
if(m_trailings[i].ticket == ticket)
| |
{
| |
index = i;
| |
break;
| |
}
| |
}
| |
| |
//---
| |
if(index == -1)
| |
return CErrorTrace::FailInit<CTrailingStop>(GENBYELO_TS_ERR_POSITION_NOT_FOUND, ticket);
| |
| |
//---
| |
if(--m_trailings_s != index)
| |
m_trailings[index] = m_trailings[m_trailings_s];
| |
| |
//---
| |
if(m_trailings_s == 0)
| |
OnCloseAllPosition();
| |
| |
//---
| |
return true;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::TrailingStop(void)
| |
{
| |
//---
| |
if(m_trailings_s < 1)
| |
return;
| |
| |
//---
| |
const double ask = SymbolInfoDouble(m_symbol, SYMBOL_ASK);
| |
const double bid = SymbolInfoDouble(m_symbol, SYMBOL_BID);
| |
| |
//---
| |
for(int i = 0; i < m_trailings_s; i++)
| |
{
| |
if(m_trailings[i].pos_type == POSITION_TYPE_BUY)
| |
{
| |
const double stoplosnuevo = GetPricePositionBuy(bid);
| |
if(stoplosnuevo <= 0.000000001)
| |
continue;
| |
| |
//--- Verificacion
| |
const double s_temp = bid - m_trade_stops_levels; //ask - spread - stop_levels (usando el bid eliminamos el uso del spread)
| |
if(!TSNMQLA_TrailignStop_CheckStopLossSafeCompra(s_temp, stoplosnuevo))
| |
continue;
| |
| |
//--- Seleccion de ticket
| |
#ifndef GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
ResetLastError();
| |
#endif // GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
| |
if(!PositionSelectByTicket(m_trailings[i].ticket))
| |
{
| |
#ifndef GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT,
| |
StringFormat("Error inselecting position = %I64u, last err = %d", m_trailings[i].ticket, ::GetLastError()));
| |
#endif // GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
continue;
| |
}
| |
| |
//--- Cambio de SL
| |
const double stoplosactual = m_trailings[i].last_stop_loss_price;
| |
if((stoplosnuevo > stoplosactual || stoplosactual == 0) && stoplosnuevo > m_trailings[i].open_price)
| |
{
| |
if(m_trade.PositionModify(m_trailings[i].ticket, stoplosnuevo, PositionGetDouble(POSITION_TP)))
| |
{
| |
m_trailings[i].last_stop_loss_price = stoplosnuevo;
| |
}
| |
#ifndef GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
else
| |
{
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT,
| |
StringFormat("Error in modify position [BUY] = %I64u, new stop = %.*f, curr stop = %.*f",
| |
m_trailings[i].ticket, m_digits, stoplosnuevo, m_digits, stoplosactual));
| |
}
| |
#endif // GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
}
| |
}
| |
else
| |
{
| |
const double stoplosnuevo = GetPricePositionSell(ask);
| |
if(stoplosnuevo <= 0.000000001)
| |
continue;
| |
| |
//--- Verificacion
| |
const double s_temp = ask + m_trade_stops_levels; //bid + spread + stop_levels (usando el ask eliminamos el uso del spread)
| |
if(!TSNMQLA_TrailignStop_CheckStopLossSafeVenta(s_temp, stoplosnuevo))
| |
continue;
| |
| |
//--- Seleccion de ticket
| |
#ifndef GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
ResetLastError();
| |
#endif // GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
| |
if(!PositionSelectByTicket(m_trailings[i].ticket))
| |
{
| |
#ifndef GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT,
| |
StringFormat("Error in selecting position = %I64u, last err = %d", m_trailings[i].ticket, ::GetLastError()));
| |
#endif // GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
continue;
| |
}
| |
| |
//--- Modificacion
| |
const double stoplosactual = m_trailings[i].last_stop_loss_price;
| |
if((stoplosnuevo < stoplosactual || stoplosactual == 0) && stoplosnuevo < m_trailings[i].open_price)
| |
{
| |
if(m_trade.PositionModify(m_trailings[i].ticket, stoplosnuevo, PositionGetDouble(POSITION_TP)))
| |
{
| |
m_trailings[i].last_stop_loss_price = stoplosnuevo;
| |
}
| |
#ifndef GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
else
| |
{
| |
FastLog(FUNCION_ACTUAL, ERROR_TEXT,
| |
StringFormat("Error in modify position [SELL] = %I64u, new stop = %.*f, curr stop = %.*f",
| |
m_trailings[i].ticket, m_digits, stoplosnuevo, m_digits, stoplosactual));
| |
}
| |
#endif // GENBYLEO_TRAILINGSTOP_DESACTIVE_ERR_LOGS
| |
}
| |
}
| |
}
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::Magic(ulong value)
| |
{
| |
m_trade.SetExpertMagicNumber(value);
| |
m_magic = value;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::Simbolo(const string &symbol)
| |
{
| |
m_symbol = symbol;
| |
OnSymbolChange();
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
void CTrailingStop::OnSymbolChange(void)
| |
{
| |
m_point_value = SymbolInfoDouble(m_symbol, SYMBOL_POINT);
| |
m_digits = (int)SymbolInfoInteger(m_symbol, SYMBOL_DIGITS);
| |
m_trade_stops_levels = SymbolInfoInteger(m_symbol, SYMBOL_TRADE_STOPS_LEVEL) * m_point_value;
| |
}
| |
| |
//+------------------------------------------------------------------+
| |
//| |
| |
//+------------------------------------------------------------------+
| |
static void CTrailingStop::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
| |
{
| |
TSNSTD_ERRMAN_PUSHINI(out, trace_idx)
| |
switch(trace[trace_idx].code)
| |
{
| |
case GENBYELO_TS_ERR_NOT:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Not error", trace_idx)
| |
break;
| |
case GENBYELO_TS_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 GENBYELO_TS_ERR_SYMBOL_IS_NOT_A_CONFIGURED:
| |
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("The symbol of the position [ticket = %I64u] is not the one configured in the trailing stop", trace[trace_idx].info), trace_idx)
| |
break;
| |
case GENBYELO_TS_ERR_POSITION_NOT_FOUND:
| |
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Position not found in the trailing stop [ticket = %I64u]", trace[trace_idx].info), trace_idx)
| |
break;
| |
default:
| |
TSNSTD_ERRMAN_PUSHOUT(out, "Unknow error", trace_idx)
| |
break;
| |
}
| |
}
| |
| |
//---
| |
}
| |
//---
| |
#endif // MQLARTICLES_POSMGMT_TSL_BASIC_TRAILINGBASE_MQH
|