주시
1
0
포크
이미 MQLArticles을(를) 포크했습니다
0
원본 프로젝트 nique_372/MQLArticles
MQLArticles/PosMgmt/Partials.mqh
Nique_372 Nique_372 e4715a4e1c
2026-11-07 09:34:18 -05:00
685 라인
28 KiB
MQL5
이 파일에는 보이지 않는 유니코드 문자가 포함되어 있습니다

이 파일에는 사람이 구별할 수 없지만 컴퓨터에서는 다르게 처리될 수 있는 눈에 보이지 않는 유니코드 문자가 포함되어 있습니다. 이것이 의도적인 것이라고 생각되면 이 경고를 무시해도 됩니다. Esc 버튼을 사용하여 공개하세요.

//+------------------------------------------------------------------+
//| 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 |
//+------------------------------------------------------------------+
#include "..\\Account\\MoneyStatus\\Manager.mqh"
#include "..\\Account\\RM\\Bases\\Functions.mqh"
#include <TSN\\Std\\Basics\\ErrManager.mqh>
#include <TSN\\Std\\Misce\\BitReinterprete.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
namespace TSN
{
//+------------------------------------------------------------------+
//| Structures |
//+------------------------------------------------------------------+
// 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
//---
struct TrackedPosition
{
double partials_price[];
ulong ticket;
double current_price_to_sup;
ENUM_POSITION_TYPE type;
short current_partial_index;
short try;
//---
void RobarDe(TrackedPosition& other)
{
ArraySwap(this.partials_price, other.partials_price);
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;
this.try = other.try;
}
};
//---
enum ENUM_TSNMQLART_PARTIALS_ERR
{
TSNMQLART_PARTIALS_ERR_NOT,
//---
TSNMQLART_PARTIALS_ERR_INVALID_SIZE_CLOSE,
TSNMQLART_PARTIALS_ERR_INVALID_SIZE_TPLEVELPERCE,
TSNMQLART_PARTIALS_ERR_MALFORMED_VALUES, // algun valor del string no se pudo convertir (ToArr devuelve negativo)
TSNMQLART_PARTIALS_ERR_SIZE_CLOSE_TPLEVELPERCE_NOTEQ,
TSNMQLART_PARTIALS_ERR_INVALID_VOLUME_TOCLOSE,
TSNMQLART_PARTIALS_ERR_INVALID_TP_TOCLOSE,
TSNMQLART_PARTIALS_ERR_FAILED_ADD_HASHMAP,
//---
TSNMQLART_PARTIALS_ERR_ADD_SELECT_POS,
TSNMQLART_PARTIALS_ERR_ADD_INV_SYMBOL,
TSNMQLART_PARTIALS_ERR_ADD_INV_TP,
};
//---
//--- 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
//+------------------------------------------------------------------+
//| Defines |
//+------------------------------------------------------------------+
#ifndef CPARCIAL_RESERVE_ARR
#define CPARCIAL_RESERVE_ARR (8)
#endif // CPARCIAL_RESERVE_ARR
#ifndef CPARCIAL_DEFAULT_TRY
#define CPARCIAL_DEFAULT_TRY (4)
#endif // CPARCIAL_DEFAULT_TRY
//---
#define PARTIAL_NO_APPLIED "0"
//#define TSNMQLART_PARTIALS_ENABLE_ELOGS
//+------------------------------------------------------------------+
//| Class that implements partial closures |
//+------------------------------------------------------------------+
class CBasicPartials : public CAccountGestor
{
private:
//--- General variables
ulong m_magic_number; // Magic number used to apply partials only to certain operations
CTrade m_trade_executor; // CTrade type instance to apply partials
bool m_auto;
short m_try;
//--- 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
short m_max_partial_levels; // Number of partials to take from each operation
int m_tracked_positions_s; // Numero actual de posiciones trackeadas
int m_datas_r; // Reservas generale
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
//--- Arrays to take, both arrays must be the same size.
double m_volume_percentages_to_close[];
double m_tp_level_percentages[];
//--- Temporary hashmap
static CHashMapFastP(double, double, _fibbo) s_temporary_hashmap;
//---
void SetPartial(const bool is_sell, const ulong pos_ticket, const double entry_price,
const double position_tp, TrackedPosition& pos);
public:
CBasicPartials();
~CBasicPartials();
//--- Initialize function
bool Init(ulong magic_number_, const string& symbol_, const string& volume_percentages_string, const string& tp_percentages_string);
//--- 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;
//--- Info de posiciones
//- Add
// Function to add a position to the internal array manually (this is automatically invoked in OnOpen..... for all positions
// opened with the magic number and with a valid tp).
bool AddPositionToTrack(ulong position_ticket, double position_tp, double entry_price,
ENUM_POSITION_TYPE position_type, const string& symbol);
bool AddPositionToTrack(ulong position_ticket);
//- Total
__forceinline int TotalPositions() const { return m_tracked_positions_s; }
__forceinline void GetPosition(const int i, TrackedPosition& out) { out = m_tracked_positions[i]; }
//--- Config
// Auto mode
inline bool AutoMode() const { return m_auto; }
void AutoMode(bool auto) { m_auto = auto; }
// Try (intenos en caso falle un modifiacino de paricla)
inline short Tries() const { return m_try; }
void Tries(short v) { m_try = v; }
//--- Info
// Symbol
inline string Symbol() const { return m_trading_symbol; }
// Magic
inline ulong MagicNumber() const { return m_magic_number; }
//--- Error
static void FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out);
};
//+------------------------------------------------------------------+
//| Constructor and Destructor |
//+------------------------------------------------------------------+
CBasicPartials::CBasicPartials()
:
//---
m_magic_number(NOT_MAGIC_NUMBER), m_trading_symbol(NULL), m_volume_step(0.00),
m_minimum_volume(0.00), m_price_digits(0), m_max_partial_levels(0), m_auto(true), m_try(CPARCIAL_DEFAULT_TRY),
//--- Sizes
m_datas_r(CPARCIAL_RESERVE_ARR),
m_tracked_positions_s(0)
{
//---
m_trade_executor.LogLevel(LOG_LEVEL_NO);
//---
account_status.RegisterEvents(&this, ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION);
//---
::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);
}
//+------------------------------------------------------------------+
CBasicPartials::~CBasicPartials()
{
if(account_status.IsActive())
account_status.UnregisterEvents(&this, ACCOUNT_STATUS_REG_FLAG_ON_OPEN_POSITION | ACCOUNT_STATUS_REG_FLAG_ON_CLOSE_POSITION);
}
//+------------------------------------------------------------------+
//| Initialization function |
//+------------------------------------------------------------------+
bool CBasicPartials::Init(ulong magic_number_, const string& symbol_, const string& volume_percentages_string, const string& tp_percentages_string)
{
//--- 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);
//---
if(m_magic_number != NOT_MAGIC_NUMBER)
m_trade_executor.SetExpertMagicNumber(m_magic_number);
//--- Convert strings to double arrays
int s = TSN::CStringFunc::ToArr<double, TSN::CStringConvert>(volume_percentages_string, m_volume_percentages_to_close, ',');
if(s < 1)
{
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);
}
::ArrayResize(m_volume_percentages_to_close, s);
//---
s = TSN::CStringFunc::ToArr<double, TSN::CStringConvert>(tp_percentages_string, m_tp_level_percentages, ',');
if(s < 1)
{
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
}
::ArrayResize(m_tp_level_percentages, s);
//--- 3rd validation, we validate that both arrays are the same size
if(m_volume_percentages_to_close.Size() != m_tp_level_percentages.Size())
{
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);
}
//--- Initial log only if "info" type log is enabled
#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
//--- Declaration of indices to remove and hashmap cleanup
s_temporary_hashmap.Clear();
//--- Iteration and array cleanup
for(int i = 0; i < s; i++)
{
if(m_tp_level_percentages[i] < 0.00001 || m_tp_level_percentages[i] > 100.0)
{
return CErrorTrace::FailInit<CBasicPartials>(TSNMQLART_PARTIALS_ERR_INVALID_TP_TOCLOSE, CBitsReinterprete::ToBasic<ulong, double>(m_tp_level_percentages[i]));
}
if(m_volume_percentages_to_close[i] < 0.00001 || m_volume_percentages_to_close[i] > 100.0)
{
return CErrorTrace::FailInit<CBasicPartials>(TSNMQLART_PARTIALS_ERR_INVALID_VOLUME_TOCLOSE, CBitsReinterprete::ToBasic<ulong, double>(m_volume_percentages_to_close[i]));
}
//---
if(s_temporary_hashmap.ReserveSlot(m_tp_level_percentages[i]))
{
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];
}
else
{
return CErrorTrace::FailInit<CBasicPartials>(TSNMQLART_PARTIALS_ERR_FAILED_ADD_HASHMAP, CBitsReinterprete::ToBasic<ulong, double>(m_tp_level_percentages[i]));
}
}
//--- Removemos
::ArrayResize(m_tp_level_percentages, s);
::ArrayResize(m_volume_percentages_to_close, s);
m_max_partial_levels = (short)s;
//--- Solo sort
::ArraySort(m_tp_level_percentages);
//--- Final iteration
for(short i = 0; i < m_max_partial_levels; i++)
{
double val;
s_temporary_hashmap.TryGet(m_tp_level_percentages[i], val);
//---
m_volume_percentages_to_close[i] = val / 100.0;
m_tp_level_percentages[i] /= 100.0;
}
//--- Final log
#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
return true;
}
//+--------------------------------------------------------------------+
//| Function that runs every time a position is opened or closed |
//+--------------------------------------------------------------------+
void CBasicPartials::OnOpenPosition(const ROnOpenPosition &pos)
{
if(m_auto && (pos.position.magic == m_magic_number || m_magic_number == NOT_MAGIC_NUMBER))
{
#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
AddPositionToTrack(pos.position.ticket, pos.position.tp, pos.position.open_price, pos.position.type,
account_status.last_trans_symbol);
}
}
//+------------------------------------------------------------------+
void CBasicPartials::OnClosePosition(const ROnClosePosition &pos, const int global_pos_index)
{
//---
// 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++)
{
if(m_tracked_positions[i].ticket == p)
{
index = i;
break;
}
}
//---
if(index == -1)
return;
//---
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]);
}
//+------------------------------------------------------------------+
//| 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. |
//+------------------------------------------------------------------+
bool CBasicPartials::AddPositionToTrack(ulong position_ticket, double position_tp, double entry_price,
ENUM_POSITION_TYPE position_type, const string& symbol)
{
//--- Checks
// Tp
if(position_tp <= 0.00000000000001) // opt: chekeamos de los mas "faciles" a los mas complejos como un fast-path
{
return CErrorTrace::FailInit<CBasicPartials>(TSNMQLART_PARTIALS_ERR_ADD_INV_TP, CBitsReinterprete::ToBasic<ulong, double>(position_tp));
}
// Simbolo
if(symbol != m_trading_symbol)
{
return CErrorTrace::FailInit<CBasicPartials>(TSNMQLART_PARTIALS_ERR_ADD_INV_SYMBOL, position_ticket); // Invalid symbol
}
//--- Check
// opt: reservamos
if(m_tracked_positions_s >= m_datas_r)
{
const int old_r = m_datas_r;
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);
for(int i = old_r; i < m_datas_r; i++) // Iniciamos
m_indices_to_remove[i] = false;
}
//--- 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)
{
//---
pos.try = m_try;
pos.ticket = pos_ticket;
pos.type = (ENUM_POSITION_TYPE)is_sell;
pos.current_partial_index = 0;
::ArrayResize(pos.partials_price, m_max_partial_levels);
//---
const double diff_tp_entry_price = is_sell ? (entry_price - position_tp) : (position_tp - entry_price); // diference entre el tp y entrey price
//---
for(short i = 0; i < m_max_partial_levels; i++)
{
const double tp_dist = m_tp_level_percentages[i] * diff_tp_entry_price;
//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));
}
//--- Log about the "tps" where partials will be taken
#ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog("TPS: ", CAUTION_TEXT, FUNCION_ACTUAL);
::ArrayPrint(pos.partials_price, m_price_digits, " | ");
#endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
//---
pos.current_price_to_sup = pos.partials_price[0]; // opt: cachemoas y resolvemos una vez el precio a superar (en vez de varias veces)
}
//+------------------------------------------------------------------+
bool CBasicPartials::AddPositionToTrack(ulong position_ticket)
{
if(!::PositionSelectByTicket(position_ticket))
{
return CErrorTrace::FailInit<CBasicPartials>(TSNMQLART_PARTIALS_ERR_ADD_SELECT_POS, position_ticket, ::GetLastError());
}
//---
return AddPositionToTrack(position_ticket, ::PositionGetDouble(POSITION_TP), ::PositionGetDouble(POSITION_PRICE_OPEN),
ENUM_POSITION_TYPE(::PositionGetInteger(POSITION_TYPE)), ::PositionGetString(POSITION_SYMBOL));
}
//+------------------------------------------------------------------+
//| Function that will iterate over the m_partials array |
//| and if necessary will partially close the operation |
//+------------------------------------------------------------------+
void CBasicPartials::CheckTrackedPositions(void)
{
//--- If the internal array m_partials is empty we do an early exit.
if(m_tracked_positions_s < 1) // opt: fast path en caso no haya posiciones
return;
//---
const double ask = ::SymbolInfoDouble(m_trading_symbol, SYMBOL_ASK);
const double bid = ::SymbolInfoDouble(m_trading_symbol, SYMBOL_BID);
//--- opt: solo un booleano (no un int o array) como fastpath para eliminar o no
bool alredy_remove = false;
//--- Macro de ayuda
// eliminar
#define TSNMQLART_BASICPARTIAL_REMOVE(IDX) \
m_indices_to_remove[IDX] = true; \
alredy_remove=true; \
// finalizar bien
#define TSNMQLART_BASICPARTIALS_FINISH \
if(current_level_index == m_max_partial_levels) \
{ \
TSNMQLART_BASICPARTIAL_REMOVE(i) \
} \
else \
m_tracked_positions[i].current_price_to_sup = m_tracked_positions[i].partials_price[current_level_index];
//--- Main iteration
for(int i = 0; i < m_tracked_positions_s; i++)
{
// 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)))
{
//---
const ulong current_ticket = m_tracked_positions[i].ticket; // Current position ticket
//---
// Failed to select the ticket
if(!::PositionSelectByTicket(current_ticket))
{
#ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, ::StringFormat("Could not select ticket %I64u, last error = %d", current_ticket, ::GetLastError()));
#endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
//--- ya no tiene caso seguir intento (posiblemte se cerro la operacion) entonces solo la eliminamos del array de posiciones
TSNMQLART_BASICPARTIAL_REMOVE(i)
continue;
}
//---
short current_level_index = m_tracked_positions[i].current_partial_index++;
//--- calculamos el lote
double volume_to_close = ::PositionGetDouble(POSITION_VOLUME) * m_volume_percentages_to_close[current_level_index++]; // Vol to close
//---
if(volume_to_close < m_minimum_volume)
{
#ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, ::StringFormat("The lot to take %f is less than the minimum lot %f", volume_to_close, m_minimum_volume));
#endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
//---
TSNMQLART_BASICPARTIALS_FINISH
continue;
}
//---
volume_to_close = MQLART_POSMGMT_BPARTIALS_LOTROUND(volume_to_close, m_volume_step);
if(!m_trade_executor.PositionClosePartial(current_ticket, volume_to_close))
{
#ifdef TSNMQLART_PARTIALS_ENABLE_ELOGS
FastLog(FUNCION_ACTUAL, ERROR_TEXT, ::StringFormat("Fallo al cerrar parcialemte %.*f lotes de la posicion = %I64u, ultimo err",
m_price_digits, volume_to_close, current_ticket, ::GetLastError()));
#endif // TSNMQLART_PARTIALS_ENABLE_ELOGS
m_tracked_positions[i].current_partial_index--; // rollback (caso raro)
if(--m_tracked_positions[i].try < 0)
{
TSNMQLART_BASICPARTIAL_REMOVE(i)
}
continue;
}
//---
TSNMQLART_BASICPARTIALS_FINISH
}
}
//--- fast path para ver si tenemos que eliminar o no
if(!alredy_remove)
return;
//--- 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
}
m_tracked_positions_s = w; // opt: zero arrayresize (solo hacia arriba), asi qeu solo modicaisno el tamaño "virtual"
//--- undef
#undef TSNMQLART_BASICPARTIALS_FINISH
#undef TSNMQLART_BASICPARTIAL_REMOVE
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
static void CBasicPartials::FormatTrace(const TSNErrorFrame &trace[], int &trace_idx, string &out)
{
TSNSTD_ERRMAN_PUSHINI(out, trace_idx)
switch(trace[trace_idx].code)
{
case TSNMQLART_PARTIALS_ERR_NOT:
TSNSTD_ERRMAN_PUSHOUT(out, "Not errors", trace_idx)
break;
case TSNMQLART_PARTIALS_ERR_INVALID_SIZE_CLOSE:
TSNSTD_ERRMAN_PUSHOUT(out, "Invalid size close arr values (must be > 0)", trace_idx)
break;
case TSNMQLART_PARTIALS_ERR_INVALID_SIZE_TPLEVELPERCE:
TSNSTD_ERRMAN_PUSHOUT(out, "Invalid size tplevel price values (must be > 0)", trace_idx)
break;
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;
case TSNMQLART_PARTIALS_ERR_SIZE_CLOSE_TPLEVELPERCE_NOTEQ:
{
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)
break;
}
case TSNMQLART_PARTIALS_ERR_INVALID_VOLUME_TOCLOSE:
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)
break;
case TSNMQLART_PARTIALS_ERR_INVALID_TP_TOCLOSE:
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)
break;
case TSNMQLART_PARTIALS_ERR_FAILED_ADD_HASHMAP:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Fatal error, cannot add to hashmap tp close %% [%.4f]",
CBitsReinterprete::ToBasic<double, ulong>(trace[trace_idx].info)), trace_idx)
break;
case TSNMQLART_PARTIALS_ERR_ADD_SELECT_POS:
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_PARTIALS_ERR_ADD_INV_SYMBOL:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Failed add by invalid symbol [ticket = %I64u] (must be eqaul CBasicPartials::Simbolo value)", trace[trace_idx].info), trace_idx)
break;
case TSNMQLART_PARTIALS_ERR_ADD_INV_TP:
TSNSTD_ERRMAN_PUSHOUT(out, StringFormat("Failed add by invalid tp [%.8f] (tp very small)",
CBitsReinterprete::ToBasic<double, ulong>(trace[trace_idx].info)), trace_idx)
break;
default:
TSNSTD_ERRMAN_PUSHOUT(out, "Unknow error", trace_idx)
break;
}
}
//+-------------------------------------------------------------------------+
//| 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";
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
CHashMapFastP(double, double, _fibbo) CBasicPartials::s_temporary_hashmap(32);
}
//+------------------------------------------------------------------+
#endif
//+------------------------------------------------------------------+