2026-08-28 22:40:45 -05:00
//+------------------------------------------------------------------+
//| Partials.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_POSMGMT_PARTIALS_MQH
# define MQLARTICLES_POSMGMT_PARTIALS_MQH
/ / + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
//| Include |
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
# include "..\\Account\\MoneyStatus\\Manager.mqh"
# include "..\\Account\\RM\\Bases\\Functions.mqh"
2026-11-05 17:09:00 -05:00
# include <TSN\\Std\\Basics\\ErrManager.mqh>
# include <TSN\\Std\\Misce\\BitReinterprete.mqh>
2026-08-28 22:40:45 -05:00
2026-09-12 19:41:52 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
namespace TSN
{
2026-08-28 22:40:45 -05:00
//+------------------------------------------------------------------+
//| Structures |
//+------------------------------------------------------------------+
2026-11-01 17:28:51 -05:00
// NOTA: como maximo se peude ejcutairon SHORT_MAX parciales (niveles) lo cual ya es una barbaridad diria
// asi qeu de media noramltte por posicon son 1-4 y quizas 4-7 paricales mas de eso ramente se usa
2026-09-12 19:41:52 -05:00
//---
2026-08-28 22:40:45 -05:00
struct TrackedPosition
{
2026-11-01 18:06:28 -05:00
double partials_price [ ] ;
2026-08-28 22:40:45 -05:00
ulong ticket ;
2026-10-30 13:24:14 -05:00
double current_price_to_sup ;
2026-08-28 22:40:45 -05:00
ENUM_POSITION_TYPE type ;
2026-11-01 17:28:51 -05:00
short current_partial_index ;
short try ;
2026-10-30 13:24:14 -05:00
//---
void RobarDe ( TrackedPosition & other )
{
2026-11-01 18:06:28 -05:00
ArraySwap ( this . partials_price , other . partials_price ) ;
2026-10-30 13:24:14 -05:00
this . ticket = other . ticket ;
this . current_price_to_sup = other . current_price_to_sup ;
this . type = other . type ;
this . current_partial_index = other . current_partial_index ;
2026-11-01 17:28:51 -05:00
this . try = other . try ;
2026-10-30 13:24:14 -05:00
}
2026-08-28 22:40:45 -05:00
} ;
2026-10-28 17:19:08 -05:00
//---
enum ENUM_TSNMQLART_PARTIALS_ERR
{
TSNMQLART_PARTIALS_ERR_NOT ,
//---
TSNMQLART_PARTIALS_ERR_INVALID_SIZE_CLOSE ,
TSNMQLART_PARTIALS_ERR_INVALID_SIZE_TPLEVELPERCE ,
2026-11-07 09:34:18 -05:00
TSNMQLART_PARTIALS_ERR_MALFORMED_VALUES , // algun valor del string no se pudo convertir (ToArr devuelve negativo)
2026-10-28 17:19:08 -05:00
TSNMQLART_PARTIALS_ERR_SIZE_CLOSE_TPLEVELPERCE_NOTEQ ,
2026-11-02 15:21:28 -05:00
TSNMQLART_PARTIALS_ERR_INVALID_VOLUME_TOCLOSE ,
TSNMQLART_PARTIALS_ERR_INVALID_TP_TOCLOSE ,
TSNMQLART_PARTIALS_ERR_FAILED_ADD_HASHMAP ,
2026-10-28 17:19:08 -05:00
//---
2026-10-29 16:46:31 -05:00
TSNMQLART_PARTIALS_ERR_ADD_SELECT_POS ,
2026-10-28 17:19:08 -05:00
TSNMQLART_PARTIALS_ERR_ADD_INV_SYMBOL ,
TSNMQLART_PARTIALS_ERR_ADD_INV_TP ,
} ;
2026-10-30 11:04:21 -05:00
//---
//--- Por defecto usaremos el round (para manteer compatiblidad)
# ifndef MQLART_POSMGMT_BPARTIALS_LOTROUND
# define MQLART_POSMGMT_BPARTIALS_LOTROUND(number, step ) TSNMQLART_ROUND_LOTSIZE_F ( MathRound , number , step )
# endif // MQLART_POSMGMT_BPARTIALS_LOTROUND
2026-08-28 22:40:45 -05:00
//+------------------------------------------------------------------+
//| Defines |
//+------------------------------------------------------------------+
2026-11-01 15:00:25 -05:00
# ifndef CPARCIAL_RESERVE_ARR
2026-11-01 17:28:51 -05:00
# define CPARCIAL_RESERVE_ARR ( 8 )
2026-11-01 15:00:25 -05:00
# endif // CPARCIAL_RESERVE_ARR
2026-11-01 17:28:51 -05:00
# ifndef CPARCIAL_DEFAULT_TRY
# define CPARCIAL_DEFAULT_TRY ( 4 )
# endif // CPARCIAL_DEFAULT_TRY
//---
2026-08-28 22:40:45 -05:00
# define PARTIAL_NO_APPLIED " 0 "
2026-10-28 17:19:08 -05:00
//#define TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-08-28 22:40:45 -05:00
//+------------------------------------------------------------------+
//| Class that implements partial closures |
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
class CBasicPartials : public CAccountGestor
2026-08-28 22:40:45 -05:00
{
private :
//--- General variables
ulong m_magic_number ; // Magic number used to apply partials only to certain operations
2026-09-12 19:41:52 -05:00
CTrade m_trade_executor ; // CTrade type instance to apply partials
2026-08-28 22:40:45 -05:00
bool m_auto ;
2026-11-01 17:28:51 -05:00
short m_try ;
2026-08-28 22:40:45 -05:00
//--- Symbol variables
string m_trading_symbol ; // Symbol from which minimum volume and volume step data will be obtained
double m_volume_step ; // Volume step
double m_minimum_volume ; // Minimum volume
int m_price_digits ; // Symbol digits
//--- Variables for partials
2026-11-01 17:28:51 -05:00
short m_max_partial_levels ; // Number of partials to take from each operation
2026-08-28 22:40:45 -05:00
2026-11-01 17:28:51 -05:00
int m_tracked_positions_s ; // Numero actual de posiciones trackeadas
int m_datas_r ; // Reservas generale
2026-10-30 13:24:14 -05:00
TrackedPosition m_tracked_positions [ ] ; // Array of operations to which partials will be applied
bool m_indices_to_remove [ ] ; // Indices to remove from the m_tracked_positions array
2026-08-28 22:40:45 -05:00
//--- Arrays to take, both arrays must be the same size.
double m_volume_percentages_to_close [ ] ;
double m_tp_level_percentages [ ] ;
//--- Temporary hashmap
2026-10-28 17:19:08 -05:00
static CHashMapFastP ( double , double , _fibbo ) s_temporary_hashmap ;
2026-10-30 13:24:14 -05:00
//---
void SetPartial ( const bool is_sell , const ulong pos_ticket , const double entry_price ,
const double position_tp , TrackedPosition & pos ) ;
2026-08-28 22:40:45 -05:00
public :
2026-10-28 17:19:08 -05:00
CBasicPartials ( ) ;
~ CBasicPartials ( ) ;
2026-08-28 22:40:45 -05:00
//--- Initialize function
2026-10-28 17:19:08 -05:00
bool Init ( ulong magic_number_ , const string & symbol_ , const string & volume_percentages_string , const string & tp_percentages_string ) ;
2026-08-28 22:40:45 -05:00
//--- Main function for position review
void CheckTrackedPositions ( ) ;
//--- Function that will be automatically invoked by account status each time a position is opened or closed
void OnOpenPosition ( const ROnOpenPosition & pos ) override final ;
void OnClosePosition ( const ROnClosePosition & pos , const int global_pos_index ) override final ;
2026-11-01 17:28:51 -05:00
//--- Info de posiciones
//- Add
// Function to add a position to the internal array manually (this is automatically invoked in OnOpen..... for all positions
2026-08-28 22:40:45 -05:00
// opened with the magic number and with a valid tp).
bool AddPositionToTrack ( ulong position_ticket , double position_tp , double entry_price ,
2026-10-24 22:43:15 -05:00
ENUM_POSITION_TYPE position_type , const string & symbol ) ;
2026-08-28 22:40:45 -05:00
bool AddPositionToTrack ( ulong position_ticket ) ;
2026-11-01 17:28:51 -05:00
//- Total
__forceinline int TotalPositions ( ) const { return m_tracked_positions_s ; }
__forceinline void GetPosition ( const int i , TrackedPosition & out ) { out = m_tracked_positions [ i ] ; }
//--- Config
2026-08-28 22:40:45 -05:00
// Auto mode
2026-10-29 12:48:36 -05:00
inline bool AutoMode ( ) const { return m_auto ; }
void AutoMode ( bool auto ) { m_auto = auto ; }
2026-11-01 17:28:51 -05:00
// Try (intenos en caso falle un modifiacino de paricla)
inline short Tries ( ) const { return m_try ; }
void Tries ( short v ) { m_try = v ; }
2026-08-28 22:40:45 -05:00
2026-11-01 17:28:51 -05:00
//--- Info
2026-08-28 22:40:45 -05:00
// Symbol
2026-10-29 12:48:36 -05:00
inline string Symbol ( ) const { return m_trading_symbol ; }
2026-08-28 22:40:45 -05:00
// Magic
2026-10-29 12:48:36 -05:00
inline ulong MagicNumber ( ) const { return m_magic_number ; }
2026-11-01 17:28:51 -05:00
//--- Error
2026-11-06 10:40:44 -05:00
static void FormatTrace ( const TSNErrorFrame & trace [ ] , int & trace_idx , string & out ) ;
2026-08-28 22:40:45 -05:00
} ;
//+------------------------------------------------------------------+
//| Constructor and Destructor |
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
CBasicPartials : : CBasicPartials ( )
2026-08-28 22:40:45 -05:00
:
2026-10-28 17:19:08 -05:00
//---
m_magic_number ( NOT_MAGIC_NUMBER ) , m_trading_symbol ( NULL ) , m_volume_step ( 0.00 ) ,
2026-11-01 17:28:51 -05:00
m_minimum_volume ( 0.00 ) , m_price_digits ( 0 ) , m_max_partial_levels ( 0 ) , m_auto ( true ) , m_try ( CPARCIAL_DEFAULT_TRY ) ,
2026-10-28 17:19:08 -05:00
2026-10-30 13:24:14 -05:00
//--- Sizes
m_datas_r ( CPARCIAL_RESERVE_ARR ) ,
m_tracked_positions_s ( 0 )
2026-08-28 22:40:45 -05:00
{
2026-10-29 20:10:16 -05:00
//---
m_trade_executor . LogLevel ( LOG_LEVEL_NO ) ;
2026-08-28 22:40:45 -05:00
//---
account_status . RegisterEvents ( & this , ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION ) ;
//---
2026-10-30 13:24:14 -05:00
: : ArrayResize ( m_tracked_positions , m_datas_r , m_datas_r ) ;
//---
: : ArrayResize ( m_indices_to_remove , m_datas_r , m_datas_r ) ;
: : ArrayInitialize ( m_indices_to_remove , false ) ;
2026-08-28 22:40:45 -05:00
}
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
CBasicPartials : : ~ CBasicPartials ( )
2026-08-28 22:40:45 -05:00
{
if ( account_status . IsActive ( ) )
account_status . UnregisterEvents ( & this , ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION ) ;
}
//+------------------------------------------------------------------+
//| Initialization function |
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
bool CBasicPartials ::Init ( ulong magic_number_ , const string & symbol_ , const string & volume_percentages_string , const string & tp_percentages_string )
2026-08-28 22:40:45 -05:00
{
//--- Set the variables
m_magic_number = magic_number_ ;
m_trading_symbol = symbol_ ;
m_volume_step = : : SymbolInfoDouble ( m_trading_symbol , SYMBOL_VOLUME_STEP ) ;
m_minimum_volume = : : SymbolInfoDouble ( m_trading_symbol , SYMBOL_VOLUME_MIN ) ;
m_price_digits = ( int ) : : SymbolInfoInteger ( m_trading_symbol , SYMBOL_DIGITS ) ;
2026-11-01 17:28:51 -05:00
//---
if ( m_magic_number ! = NOT_MAGIC_NUMBER )
m_trade_executor . SetExpertMagicNumber ( m_magic_number ) ;
2026-08-28 22:40:45 -05:00
//--- Convert strings to double arrays
2026-09-12 19:41:52 -05:00
int s = TSN : : CStringFunc : : ToArr < double , TSN : : CStringConvert > ( volume_percentages_string , m_volume_percentages_to_close , ' , ' ) ;
if ( s < 1 )
{
2026-11-07 09:34:18 -05:00
if ( s = = 0 ) // string vacio
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_INVALID_SIZE_CLOSE , 0 ) ;
// s < 0: valor mal formado, ToArr devuelve la posicion (en info: posicion | string << 32, 0 = volumenes)
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_MALFORMED_VALUES , ulong ( TSNSTD_STRFUNC_TOARR_REQPOS ( s ) ) | 0ULL < < 32 ) ;
2026-09-12 19:41:52 -05:00
}
2026-11-01 17:28:51 -05:00
: : ArrayResize ( m_volume_percentages_to_close , s ) ;
2026-08-28 22:40:45 -05:00
2026-10-28 17:19:08 -05:00
//---
2026-09-12 19:41:52 -05:00
s = TSN : : CStringFunc : : ToArr < double , TSN : : CStringConvert > ( tp_percentages_string , m_tp_level_percentages , ' , ' ) ;
if ( s < 1 )
2026-08-28 22:40:45 -05:00
{
2026-11-07 09:34:18 -05:00
if ( s = = 0 ) // string vacio
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_INVALID_SIZE_TPLEVELPERCE , 0 ) ;
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_MALFORMED_VALUES , ulong ( TSNSTD_STRFUNC_TOARR_REQPOS ( s ) ) | 1ULL < < 32 ) ; // 1 = niveles de tp
2026-08-28 22:40:45 -05:00
}
2026-11-01 17:28:51 -05:00
: : ArrayResize ( m_tp_level_percentages , s ) ;
2026-09-12 19:41:52 -05:00
2026-08-28 22:40:45 -05:00
//--- 3rd validation, we validate that both arrays are the same size
if ( m_volume_percentages_to_close .Size ( ) ! = m_tp_level_percentages .Size ( ) )
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_SIZE_CLOSE_TPLEVELPERCE_NOTEQ , ulong ( m_volume_percentages_to_close .Size ( ) ) | ulong ( m_tp_level_percentages .Size ( ) ) < < 32 ) ;
2026-08-28 22:40:45 -05:00
}
//--- Initial log only if "info" type log is enabled
2026-10-28 17:19:08 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog ( FUNCION_ACTUAL , INFO_TEXT , " Arrays before revision " ) ;
CRmFunctions : : PrintArrayAsTable ( m_tp_level_percentages ,
" Percentage of position where partials will be taken " , " percentages simplified " ) ;
CRmFunctions : : PrintArrayAsTable ( m_volume_percentages_to_close ,
" Percentage to take " , " percentages simplified " ) ;
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-08-28 22:40:45 -05:00
//--- Declaration of indices to remove and hashmap cleanup
2026-10-28 17:19:08 -05:00
s_temporary_hashmap . Clear ( ) ;
2026-09-12 19:41:52 -05:00
2026-08-28 22:40:45 -05:00
//--- Iteration and array cleanup
2026-09-12 19:41:52 -05:00
for ( int i = 0 ; i < s ; i + + )
2026-08-28 22:40:45 -05:00
{
2026-11-02 15:21:28 -05:00
if ( m_tp_level_percentages [ i ] < 0.00001 | | m_tp_level_percentages [ i ] > 100.0 )
2026-08-28 22:40:45 -05:00
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_INVALID_TP_TOCLOSE , CBitsReinterprete : : ToBasic < ulong , double > ( m_tp_level_percentages [ i ] ) ) ;
2026-08-28 22:40:45 -05:00
}
2026-11-02 15:21:28 -05:00
if ( m_volume_percentages_to_close [ i ] < 0.00001 | | m_volume_percentages_to_close [ i ] > 100.0 )
2026-08-28 22:40:45 -05:00
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_INVALID_VOLUME_TOCLOSE , CBitsReinterprete : : ToBasic < ulong , double > ( m_volume_percentages_to_close [ i ] ) ) ;
2026-08-28 22:40:45 -05:00
}
2026-11-02 15:21:28 -05:00
//---
2026-10-28 17:19:08 -05:00
if ( s_temporary_hashmap . ReserveSlot ( m_tp_level_percentages [ i ] ) )
2026-09-03 11:56:36 -05:00
{
2026-10-28 17:19:08 -05:00
const uint p = s_temporary_hashmap . m_last_pos_tbl ;
s_temporary_hashmap . m_table [ p ] . value = m_volume_percentages_to_close [ i ] ;
s_temporary_hashmap . m_table [ p ] . key = m_tp_level_percentages [ i ] ;
2026-09-03 11:56:36 -05:00
}
2026-08-28 22:40:45 -05:00
else
2026-09-03 11:56:36 -05:00
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_FAILED_ADD_HASHMAP , CBitsReinterprete : : ToBasic < ulong , double > ( m_tp_level_percentages [ i ] ) ) ;
2026-09-03 11:56:36 -05:00
}
2026-08-28 22:40:45 -05:00
}
2026-11-01 17:28:51 -05:00
//--- Removemos
: : ArrayResize ( m_tp_level_percentages , s ) ;
: : ArrayResize ( m_volume_percentages_to_close , s ) ;
m_max_partial_levels = ( short ) s ;
2026-09-12 19:41:52 -05:00
2026-11-01 17:28:51 -05:00
//--- Solo sort
2026-08-28 22:40:45 -05:00
: : ArraySort ( m_tp_level_percentages ) ;
//--- Final iteration
2026-11-01 17:28:51 -05:00
for ( short i = 0 ; i < m_max_partial_levels ; i + + )
2026-08-28 22:40:45 -05:00
{
double val ;
2026-10-28 17:19:08 -05:00
s_temporary_hashmap . TryGet ( m_tp_level_percentages [ i ] , val ) ;
2026-08-28 22:40:45 -05:00
2026-11-02 15:21:28 -05:00
//---
2026-11-01 18:06:28 -05:00
m_volume_percentages_to_close [ i ] = val / 100.0 ;
m_tp_level_percentages [ i ] / = 100.0 ;
2026-08-28 22:40:45 -05:00
}
//--- Final log
2026-10-28 17:19:08 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog ( FUNCION_ACTUAL , INFO_TEXT , " Arrays after revision " ) ;
CRmFunctions : : PrintArrayAsTable ( m_tp_level_percentages ,
" Percentage of position where partials will be taken " , " percentages simplified " ) ;
CRmFunctions : : PrintArrayAsTable ( m_volume_percentages_to_close ,
" Percentage to take " , " percentages simplified " ) ;
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-08-28 22:40:45 -05:00
return true ;
}
//+--------------------------------------------------------------------+
//| Function that runs every time a position is opened or closed |
//+--------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
void CBasicPartials : : OnOpenPosition ( const ROnOpenPosition & pos )
2026-08-28 22:40:45 -05:00
{
if ( m_auto & & ( pos . position . magic = = m_magic_number | | m_magic_number = = NOT_MAGIC_NUMBER ) )
{
2026-10-28 17:19:08 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog ( FUNCION_ACTUAL , INFO_TEXT , : : StringFormat ( " A trade has just been opened with ticket %I64u " , pos . position . ticket ) ) ;
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-08-28 22:40:45 -05:00
AddPositionToTrack ( pos . position . ticket , pos . position . tp , pos . position . open_price , pos . position . type ,
2026-10-24 22:43:15 -05:00
account_status . last_trans_symbol ) ;
2026-08-28 22:40:45 -05:00
}
}
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
void CBasicPartials : : OnClosePosition ( const ROnClosePosition & pos , const int global_pos_index )
2026-08-28 22:40:45 -05:00
{
2026-10-29 16:46:31 -05:00
//---
// Once the position is closed we verify if that ticket is in the internal array, if so the function
// will remove it.
const ulong p = pos . position . ticket ;
int index = -1 ;
for ( int i = 0 ; i < m_tracked_positions_s ; i + + )
2026-08-28 22:40:45 -05:00
{
2026-10-29 16:46:31 -05:00
if ( m_tracked_positions [ i ] . ticket = = p )
2026-08-28 22:40:45 -05:00
{
2026-10-29 16:46:31 -05:00
index = i ;
break ;
2026-08-28 22:40:45 -05:00
}
}
2026-10-29 16:46:31 -05:00
//---
if ( index = = -1 )
return ;
//---
2026-10-30 13:24:14 -05:00
if ( - - m_tracked_positions_s ! = index ) // opt: fast path en caso sea pop (caso comun a una sola op)
m_tracked_positions [ index ] . RobarDe ( m_tracked_positions [ m_tracked_positions_s ] ) ;
2026-08-28 22:40:45 -05:00
}
//+------------------------------------------------------------------+
//| Adds a position with a set of variables to the internal array |
//| Inputs: |
//| - position_ticket: position ticket. |
//| - position_tp: position takeprofit. |
//| - entry_price: position entry price. |
//| - position_type: position type (buy or sell) |
//| - symbol: position symbol |
//| |
//| Outputs: |
//| - If successful, it returns true; otherwise, it returns false. |
//| |
//| Notes: |
//| - The mentioned properties can be consulted with the native |
//| function: PositionGetDouble(...); |
//| - The position must have a valid tp. |
//| - The function does not check if the ticket is valid, so if |
//| you manually introduce an operation, its ticket must be valid. |
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
bool CBasicPartials : : AddPositionToTrack ( ulong position_ticket , double position_tp , double entry_price ,
ENUM_POSITION_TYPE position_type , const string & symbol )
2026-08-28 22:40:45 -05:00
{
2026-10-30 13:24:14 -05:00
//--- Checks
// Tp
if ( position_tp < = 0.00000000000001 ) // opt: chekeamos de los mas "faciles" a los mas complejos como un fast-path
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_ADD_INV_TP , CBitsReinterprete : : ToBasic < ulong , double > ( position_tp ) ) ;
2026-10-30 13:24:14 -05:00
}
// Simbolo
2026-08-28 22:40:45 -05:00
if ( symbol ! = m_trading_symbol )
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_ADD_INV_SYMBOL , position_ticket ) ; // Invalid symbol
2026-08-28 22:40:45 -05:00
}
2026-10-30 13:24:14 -05:00
//--- Check
// opt: reservamos
if ( m_tracked_positions_s > = m_datas_r )
2026-08-28 22:40:45 -05:00
{
2026-10-30 13:37:47 -05:00
const int old_r = m_datas_r ;
2026-10-30 13:24:14 -05:00
m_datas_r < < = 1 ; // Dupliucamos lo que tenemos
ArrayResize ( m_tracked_positions , m_datas_r , m_datas_r ) ;
ArrayResize ( m_indices_to_remove , m_datas_r , m_datas_r ) ;
2026-10-30 13:37:47 -05:00
for ( int i = old_r ; i < m_datas_r ; i + + ) // Iniciamos
2026-10-30 13:24:14 -05:00
m_indices_to_remove [ i ] = false ;
2026-08-28 22:40:45 -05:00
}
2026-10-30 13:24:14 -05:00
//--- Llenamos
// opt: resolvemos el array una vez
// opt: resolvemos el isell una vez
SetPartial ( position_type = = POSITION_TYPE_SELL , position_ticket ,
entry_price , position_tp , m_tracked_positions [ m_tracked_positions_s ] ) ;
//--- Aumentamos
m_tracked_positions_s + + ;
//--- Listo
return true ;
}
//+------------------------------------------------------------------+
void CBasicPartials : : SetPartial ( const bool is_sell , const ulong pos_ticket , const double entry_price ,
const double position_tp , TrackedPosition & pos )
{
2026-08-28 22:40:45 -05:00
//---
2026-11-01 17:44:41 -05:00
pos . try = m_try ;
2026-10-30 13:24:14 -05:00
pos . ticket = pos_ticket ;
pos . type = ( ENUM_POSITION_TYPE ) is_sell ;
pos . current_partial_index = 0 ;
2026-11-01 18:06:28 -05:00
: : ArrayResize ( pos . partials_price , m_max_partial_levels ) ;
2026-08-28 22:40:45 -05:00
//---
2026-10-30 13:24:14 -05:00
const double diff_tp_entry_price = is_sell ? ( entry_price - position_tp ) : ( position_tp - entry_price ) ; // diference entre el tp y entrey price
2026-08-28 22:40:45 -05:00
//---
2026-11-01 17:28:51 -05:00
for ( short i = 0 ; i < m_max_partial_levels ; i + + )
2026-08-28 22:40:45 -05:00
{
2026-10-30 13:24:14 -05:00
const double tp_dist = m_tp_level_percentages [ i ] * diff_tp_entry_price ;
2026-11-01 18:06:28 -05:00
//pos.tp_levels[i].volume_percentage_to_close = m_volume_percentages_to_close[i];
pos . partials_price [ i ] = entry_price + ( is_sell ? ( - tp_dist ) : ( tp_dist ) ) ;
2026-08-28 22:40:45 -05:00
}
//--- Log about the "tps" where partials will be taken
2026-10-28 17:19:08 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog ( " TPS: " , CAUTION_TEXT , FUNCION_ACTUAL ) ;
2026-11-01 18:06:28 -05:00
: : ArrayPrint ( pos . partials_price , m_price_digits , " | " ) ;
2026-10-28 17:19:08 -05:00
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-08-28 22:40:45 -05:00
//---
2026-11-01 18:06:28 -05:00
pos . current_price_to_sup = pos . partials_price [ 0 ] ; // opt: cachemoas y resolvemos una vez el precio a superar (en vez de varias veces)
2026-08-28 22:40:45 -05:00
}
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
bool CBasicPartials : : AddPositionToTrack ( ulong position_ticket )
2026-08-28 22:40:45 -05:00
{
if ( ! : : PositionSelectByTicket ( position_ticket ) )
2026-10-29 16:46:31 -05:00
{
2026-11-06 10:40:44 -05:00
return CErrorTrace : : FailInit < CBasicPartials > ( TSNMQLART_PARTIALS_ERR_ADD_SELECT_POS , position_ticket , : : GetLastError ( ) ) ;
2026-10-29 16:46:31 -05:00
}
2026-08-28 22:40:45 -05:00
//---
2026-11-01 17:28:51 -05:00
return AddPositionToTrack ( position_ticket , : : PositionGetDouble ( POSITION_TP ) , : : PositionGetDouble ( POSITION_PRICE_OPEN ) ,
ENUM_POSITION_TYPE ( : : PositionGetInteger ( POSITION_TYPE ) ) , : : PositionGetString ( POSITION_SYMBOL ) ) ;
2026-08-28 22:40:45 -05:00
}
//+------------------------------------------------------------------+
//| Function that will iterate over the m_partials array |
//| and if necessary will partially close the operation |
//+------------------------------------------------------------------+
2026-10-28 17:19:08 -05:00
void CBasicPartials : : CheckTrackedPositions ( void )
2026-08-28 22:40:45 -05:00
{
//--- If the internal array m_partials is empty we do an early exit.
2026-10-30 13:24:14 -05:00
if ( m_tracked_positions_s < 1 ) // opt: fast path en caso no haya posiciones
2026-08-28 22:40:45 -05:00
return ;
//---
2026-11-01 17:28:51 -05:00
const double ask = : : SymbolInfoDouble ( m_trading_symbol , SYMBOL_ASK ) ;
const double bid = : : SymbolInfoDouble ( m_trading_symbol , SYMBOL_BID ) ;
2026-08-28 22:40:45 -05:00
2026-10-30 13:24:14 -05:00
//--- opt: solo un booleano (no un int o array) como fastpath para eliminar o no
bool alredy_remove = false ;
//--- Macro de ayuda
2026-11-01 17:28:51 -05:00
// eliminar
# define TSNMQLART_BASICPARTIAL_REMOVE(IDX) \
m_indices_to_remove[IDX] = true; \
alredy_remove=true; \
// finalizar bien
2026-10-30 13:24:14 -05:00
# define TSNMQLART_BASICPARTIALS_FINISH \
if(current_level_index == m_max_partial_levels) \
{ \
2026-11-01 17:28:51 -05:00
TSNMQLART_BASICPARTIAL_REMOVE(i) \
2026-10-30 13:24:14 -05:00
} \
else \
2026-11-01 18:06:28 -05:00
m_tracked_positions[i].current_price_to_sup = m_tracked_positions[i].partials_price[current_level_index];
2026-10-30 13:24:14 -05:00
2026-08-28 22:40:45 -05:00
//--- Main iteration
for ( int i = 0 ; i < m_tracked_positions_s ; i + + )
{
2026-10-30 13:24:14 -05:00
// opt: Un maximo de dos acceso a array por cada posciones (fast)
//---
if ( ( m_tracked_positions [ i ] . type = = POSITION_TYPE_BUY ?
( ask > m_tracked_positions [ i ] . current_price_to_sup ) : ( bid < m_tracked_positions [ i ] . current_price_to_sup ) ) )
2026-08-28 22:40:45 -05:00
{
2026-10-30 13:24:14 -05:00
//---
const ulong current_ticket = m_tracked_positions [ i ] . ticket ; // Current position ticket
//---
// Failed to select the ticket
if ( ! : : PositionSelectByTicket ( current_ticket ) )
2026-08-28 22:40:45 -05:00
{
2026-10-28 17:19:08 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-10-30 13:24:14 -05:00
FastLog ( FUNCION_ACTUAL , ERROR_TEXT , : : StringFormat ( " Could not select ticket %I64u, last error = %d " , current_ticket , : : GetLastError ( ) ) ) ;
2026-10-28 17:19:08 -05:00
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-11-01 17:28:51 -05:00
//--- ya no tiene caso seguir intento (posiblemte se cerro la operacion) entonces solo la eliminamos del array de posiciones
TSNMQLART_BASICPARTIAL_REMOVE ( i )
2026-10-30 13:24:14 -05:00
continue ;
}
2026-08-28 22:40:45 -05:00
2026-10-30 13:24:14 -05:00
//---
2026-11-01 18:06:28 -05:00
short current_level_index = m_tracked_positions [ i ] . current_partial_index + + ;
2026-10-30 13:24:14 -05:00
//--- calculamos el lote
2026-11-02 15:21:28 -05:00
double volume_to_close = : : PositionGetDouble ( POSITION_VOLUME ) * m_volume_percentages_to_close [ current_level_index + + ] ; // Vol to close
2026-08-28 22:40:45 -05:00
2026-10-30 13:24:14 -05:00
//---
if ( volume_to_close < m_minimum_volume )
{
2026-10-28 17:19:08 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-10-30 13:24:14 -05:00
FastLog ( FUNCION_ACTUAL , ERROR_TEXT , : : StringFormat ( " The lot to take %f is less than the minimum lot %f " , volume_to_close , m_minimum_volume ) ) ;
2026-10-28 17:19:08 -05:00
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-10-30 13:24:14 -05:00
//---
TSNMQLART_BASICPARTIALS_FINISH
continue ;
2026-08-28 22:40:45 -05:00
}
2026-10-30 13:24:14 -05:00
//---
volume_to_close = MQLART_POSMGMT_BPARTIALS_LOTROUND ( volume_to_close , m_volume_step ) ;
2026-11-01 17:28:51 -05:00
if ( ! m_trade_executor . PositionClosePartial ( current_ticket , volume_to_close ) )
{
2026-11-01 17:44:41 -05:00
# ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog ( FUNCION_ACTUAL , ERROR_TEXT , : : StringFormat ( " Fallo al cerrar parcialemte %.*f lotes de la posicion = %I64u, ultimo err " ,
2026-11-06 19:35:48 -05:00
m_price_digits , volume_to_close , current_ticket , : : GetLastError ( ) ) ) ;
2026-11-01 17:44:41 -05:00
# endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
2026-11-02 15:21:28 -05:00
m_tracked_positions [ i ] . current_partial_index - - ; // rollback (caso raro)
2026-11-01 17:28:51 -05:00
if ( - - m_tracked_positions [ i ] . try < 0 )
{
TSNMQLART_BASICPARTIAL_REMOVE ( i )
}
continue ;
}
2026-10-30 13:24:14 -05:00
//---
TSNMQLART_BASICPARTIALS_FINISH
2026-08-28 22:40:45 -05:00
}
2026-10-30 13:24:14 -05:00
}
2026-08-28 22:40:45 -05:00
2026-10-30 13:24:14 -05:00
//--- fast path para ver si tenemos que eliminar o no
if ( ! alredy_remove )
return ;
2026-08-28 22:40:45 -05:00
2026-10-30 13:24:14 -05:00
//--- slow path
// opt: En vez de usar un array de indices se usa un array=mismo tamaño qeu el de posiciones
// para marcar (Eliminado o no) temporalmente asi la eliminacino de los arrays es o(n) en vez de o(m*n) y no siemrpe escribe o mueve (mas rapido)
// Ahora esto del swap creo que es seguro dado qeu siempre "valos jalando hacia la izquierda"
// por ejemplo aqui [0][1][2][3] si queremos eliminar 1 y 2 (ya no nos impora su valor)
// asi qeu la cadnea serria (salta 1 y 2) y luego w=1 rota 1<=>3 y queda bien
int w = 0 ;
for ( int r = 0 ; r < m_tracked_positions_s ; r + + )
{
if ( ! m_indices_to_remove [ r ] ) // opt: chekeo barato
{
if ( w ! = r ) // opt: robarde en vez de = para usar swaps en vez de pagar el costo de un cpy
m_tracked_positions [ w ] . RobarDe ( m_tracked_positions [ r ] ) ;
w + + ;
}
else
m_indices_to_remove [ r ] = false ; // Reiniciamos
2026-08-28 22:40:45 -05:00
}
2026-10-30 13:24:14 -05:00
m_tracked_positions_s = w ; // opt: zero arrayresize (solo hacia arriba), asi qeu solo modicaisno el tamaño "virtual"
2026-08-28 22:40:45 -05:00
2026-10-30 13:24:14 -05:00
//--- undef
# undef TSNMQLART_BASICPARTIALS_FINISH
2026-11-01 18:06:28 -05:00
# undef TSNMQLART_BASICPARTIAL_REMOVE
2026-08-28 22:40:45 -05:00
}
2026-10-29 12:48:36 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
2026-11-06 10:40:44 -05:00
static void CBasicPartials : : FormatTrace ( const TSNErrorFrame & trace [ ] , int & trace_idx , string & out )
2026-10-29 12:48:36 -05:00
{
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHINI ( out , trace_idx )
switch ( trace [ trace_idx ] . code )
2026-10-29 12:48:36 -05:00
{
case TSNMQLART_PARTIALS_ERR_NOT :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , " Not errors " , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
case TSNMQLART_PARTIALS_ERR_INVALID_SIZE_CLOSE :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , " Invalid size close arr values (must be > 0) " , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
case TSNMQLART_PARTIALS_ERR_INVALID_SIZE_TPLEVELPERCE :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , " Invalid size tplevel price values (must be > 0) " , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
2026-11-07 09:34:18 -05:00
case TSNMQLART_PARTIALS_ERR_MALFORMED_VALUES :
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Malformed double found in the string-comma-separated value [%s], expected position in the array = [%d] " ,
( ( trace [ trace_idx ] . info > > 32 ) = = 0 ? " volume percentages to close " : " tp level percentages " ) , int ( trace [ trace_idx ] . info ) ) , trace_idx )
break ;
2026-10-29 12:48:36 -05:00
case TSNMQLART_PARTIALS_ERR_SIZE_CLOSE_TPLEVELPERCE_NOTEQ :
2026-11-05 17:09:00 -05:00
{
const ulong v = trace [ trace_idx ] . info ;
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Arrays close and tplevel price must be equal size [close size = %d | tplevel size = %d] " , int ( v ) , int ( v > > 32 ) ) , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
2026-11-05 17:09:00 -05:00
}
2026-11-02 15:21:28 -05:00
case TSNMQLART_PARTIALS_ERR_INVALID_VOLUME_TOCLOSE :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Invalid volume %% [%.4f] found in string-comma-separated value, must be >0.0 and <=100.0 " ,
CBitsReinterprete : : ToBasic < double , ulong > ( trace [ trace_idx ] . info ) ) , trace_idx )
2026-11-02 15:21:28 -05:00
break ;
case TSNMQLART_PARTIALS_ERR_INVALID_TP_TOCLOSE :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Invalid tp close %% [%.4f] found in string-comma-separated value, must be >0.0 and <=100.0 " ,
CBitsReinterprete : : ToBasic < double , ulong > ( trace [ trace_idx ] . info ) ) , trace_idx )
2026-11-02 15:21:28 -05:00
break ;
case TSNMQLART_PARTIALS_ERR_FAILED_ADD_HASHMAP :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Fatal error, cannot add to hashmap tp close %% [%.4f] " ,
CBitsReinterprete : : ToBasic < double , ulong > ( trace [ trace_idx ] . info ) ) , trace_idx )
2026-11-02 15:21:28 -05:00
break ;
2026-10-29 16:46:31 -05:00
case TSNMQLART_PARTIALS_ERR_ADD_SELECT_POS :
2026-11-05 17:09:00 -05:00
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 )
2026-10-29 16:46:31 -05:00
break ;
2026-10-29 12:48:36 -05:00
case TSNMQLART_PARTIALS_ERR_ADD_INV_SYMBOL :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Failed add by invalid symbol [ticket = %I64u] (must be eqaul CBasicPartials::Simbolo value) " , trace [ trace_idx ] . info ) , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
case TSNMQLART_PARTIALS_ERR_ADD_INV_TP :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , StringFormat ( " Failed add by invalid tp [%.8f] (tp very small) " ,
CBitsReinterprete : : ToBasic < double , ulong > ( trace [ trace_idx ] . info ) ) , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
default :
2026-11-05 17:09:00 -05:00
TSNSTD_ERRMAN_PUSHOUT ( out , " Unknow error " , trace_idx )
2026-10-29 12:48:36 -05:00
break ;
}
}
2026-08-28 22:40:45 -05:00
//+-------------------------------------------------------------------------+
//| Receives 2 aligned pairs of tp - volume, as output sets |
//| the two strings passed by reference with the values separated by "," |
//+-------------------------------------------------------------------------+
void PartialSet ( bool use_partials , double volume_percentage1 , double tp_percentage1 , double volume_percentage2 , double tp_percentage2 ,
string & out_volume_percentages_string , string & out_tp_percentages_string )
{
if ( use_partials )
{
out_tp_percentages_string = : : StringFormat ( " %.2f, %.2f " , tp_percentage1 , tp_percentage2 ) ;
out_volume_percentages_string = : : StringFormat ( " %.2f, %.2f " , volume_percentage1 , volume_percentage2 ) ;
}
else
{
out_tp_percentages_string = " 0 " ;
out_volume_percentages_string = " 0 " ;
}
}
2026-10-28 17:19:08 -05:00
2026-10-29 12:48:36 -05:00
2026-10-28 17:19:08 -05:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
CHashMapFastP ( double , double , _fibbo ) CBasicPartials : : s_temporary_hashmap ( 32 ) ;
2026-09-12 19:41:52 -05:00
}
2026-08-28 22:40:45 -05:00
//+------------------------------------------------------------------+
# endif
//+------------------------------------------------------------------+