//+------------------------------------------------------------------+ //| Ea.mq5 | //| 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 version "1.00" #property strict //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ #include "Main.mqh" //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ sinput group "----------| General |----------" input ulong InpMagic = 35465; // Magic Number input bool InpModifiedChart = true; // Modificar el grafico? input bool InpDrawObjects = true; // Draw objects sinput group "" sinput group "-------| Strategy |-------" input ENUM_VERBOSE_LOG_LEVEL InpStrategyLogLevel = VERBOSE_LOG_LEVEL_CAUTION; // Strategy log level sinput group "-----| De la estrategia |-----" input string InpStrategyFibboLevels = "0.00,0.50,1.0"; input string InpStrategyFibboColors = "clrRed,clrWhite,clrRed"; input double InpStrategyFibboChooseLevel = 0.50; sinput group "-----| TP/SL |-----" input ENUM_TYPE_TP_SL_FIXED InpStrategyTypeTpSl = TP_SL_ATR; // Tipo de TP/SL sinput group "-- TP SL by Point" input long InpStrategySlPoint = 250; // Stop Loss en puntos input long InpStrategyTpPoint = 500; // Take Profit en puntos sinput group "-- TP SL by ATR" input double InpStrategyAtrMultiplierTp = 2.0; // Multiplicador del ATR para el TP input double InpStrategyAtrMultiplierSl = 2.0; // Multiplicador del ATR para el SL sinput group "-----| Ordenes |-----" input ulong InpStrategyMaxDeviationOrders = 100; //Maxima desviacion/slípagge de las ordenes en puntos sinput group "" sinput group "-------| Account Status |-------" input ENUM_VERBOSE_LOG_LEVEL InpAccountStatusLogLevel = VERBOSE_LOG_LEVEL_ERROR_ONLY; //(Account Status|Ticket Mangement) log level: sinput group "" sinput group "-------| Risk Management |-------" input TSN::ENUM_LOTE_TYPE InpRmLoteType = TSN::Dinamico; //Lote Type: input double InpRmLote = 0.1; //Lot size (only for fixed lot) input TSN::ENUM_MODE_RISK_MANAGEMENT InpRmRiskMode = TSN::risk_mode_personal_account; //type of risk management mode input TSN::ENUM_GET_LOT InpRmGetMode = TSN::GET_LOT_BY_STOPLOSS_AND_RISK_PER_OPERATION; //How to get the lot input double InpRmPropFirmBalance = 0; //If risk mode is Prop Firm FTMO, then put your ftmo account balance input ENUM_VERBOSE_LOG_LEVEL InpRmLogLevel = VERBOSE_LOG_LEVEL_ERROR_ONLY; //Risk Management log level: sinput group "- ML/Maximum loss/Maximum loss -" input double InpRmPercentageOrMoneyMl = 0; //percentage or money (0 => not used ML) input TSN::ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMl = TSN::percentage; //Mode calculation Max Loss input TSN::ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMl = TSN::Balance; //ML percentage applies to: sinput group "- MWL/Maximum weekly loss/Maximum weekly loss -" input double InpRmPercentageOrMoneyMwl = 0; //percentage or money (0 => not used MWL) input TSN::ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMwl = TSN::percentage; //Mode calculation Max weekly Loss input TSN::ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMwl = TSN::Balance;//MWL percentage applies to: sinput group "- MDL/Maximum daily loss/Maximum daily loss -" input double InpRmPercentageOrMoneyMdl = 3.0; //percentage or money (0 => not used MDL) input TSN::ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMdl = TSN::percentage; //Mode calculation Max daily loss input TSN::ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMdl = TSN::Balance;//MDL percentage applies to: sinput group "- GMLPO/Gross maximum loss per CanTradetion/Percentage to risk per CanTradetion -" input TSN::ENUM_OF_DYNAMIC_MODES_OF_GMLPO InpRmModeGmlpo = TSN::NO_DYNAMIC_GMLPO; //Select GMLPO mode: input double InpRmPercentageOrMoneyGmlpo = 2.0; //percentage or money (0 => not used GMLPO) input TSN::ENUM_RISK_CALCULATION_MODE InpRmModeCalculationGmlpo = TSN::percentage; //Mode calculation Max Loss per CanTradetion input TSN::ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesGmlpo = TSN::Balance;//GMPLO percentage applies to: sinput group "-- Optional GMLPO settings, Dynamic GMLPO" sinput group "--- Full customizable dynamic GMLPO" input string InpRmNote1 = "subtracted from your total balance to establish a threshold."; //This parameter determines a specific percentage that will be input string InpRmStrPercentagesToBeReviewed = "15,30,50"; //percentages separated by commas. input string InpRmNote2 = "a new risk level will be triggered on your future trades: "; //When the current balance (equity) falls below this threshold input string InpRmStrPercentagesToApply = "10,20,25"; //percentages separated by commas. input string InpRmNote3 = "0 in both parameters => do not use dynamic risk in gmlpo"; //Note: sinput group "--- Fixed dynamic GMLPO with parameters" sinput group "- 1 -" input string InpRmNote11 = "subtracted from your total balance to establish a threshold."; //This parameter determines a specific percentage that will be input double InpRmBalancePercentageToActivateTheRisk1 = 2.0; //percentage 1 that will be exceeded to modify the risk separated by commas input string InpRmNote21 = "a new risk level will be triggered on your future trades: "; //When the current balance (equity) falls below this threshold input double InpRmPercentageToBeModified1 = 1.0;//new percentage 1 to which the gmlpo is modified sinput group "- 2 -" input double InpRmBalancePercentageToActivateTheRisk2 = 5.0;//percentage 2 that will be exceeded to modify the risk separated by commas input double InpRmPercentageToBeModified2 = 0.7;//new percentage 2 to which the gmlpo is modified sinput group "- 3 -" input double InpRmBalancePercentageToActivateTheRisk3 = 7.0;//percentage 3 that will be exceeded to modify the risk separated by commas input double InpRmPercentageToBeModified3 = 0.5;//new percentage 3 to which the gmlpo is modified sinput group "- 4 -" input double InpRmBalancePercentageToActivateTheRisk4 = 9.0;//percentage 4 that will be exceeded to modify the risk separated by commas input double InpRmPercentageToBeModified4 = 0.33;//new percentage 4 1 to which the gmlpo is modified sinput group "-- MDP/Maximum daily profit/Maximum daily profit --" input bool InpRmMdpIsStrict = true; //MDP is strict? input double InpRmPercentageOrMoneyMdp = 11.0; //percentage or money (0 => not used MDP) input TSN::ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMdp = TSN::percentage; //Mode calculation Max Daily Profit input TSN::ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMdp = TSN::Balance;//MDP percentage applies to: sinput group "" sinput group "-------| Swing Zz |-------" input int16_t InpSwingZzLenth = 5; sinput group "" sinput group "-------| Soportes y Resistencias |-------" input int range_obt_s_r = 500; //Rango de obtecion sinput group "" sinput group "--- Objetos Graficos" input int width_s_r_lines = 1; //Ancho de las lineas de s/r input ENUM_LINE_STYLE style_lines_s_r = STYLE_SOLID; //Estilo de las lineas de s/r input color color_resistencia = clrBlue; //Color de la linea de resistencia input color color_soporte = clrRed; //Color de la linea del soporte sinput group "--- Obtencion" input int8_t min_toques_s_r = 2; //Toques minimos input int16_t max_toques_s_tr = 5; //Toques maximos para invalidar un s_r input int16_t periodo_maximo_minimo = 12; //Periodo del maximo/minimo input ENUM_GET_SWING type_get_swing_s_r = PURE_SWINGS; //Eliga como obtener los max y min: sinput group "" sinput group "--- Maxima diferecia para el cambio" input TSN::ENUM_MODE_DIFF modo_diff_inverse_s_r = TSN::MODE_DIFF_BY_ATR; //Modo para calcular la minima difrerencia para el cambio input double atr_multiplier_s_r_inverse_or_points = 0.95;//Multiplicador del atr (14 periodos) o puntos fijos sinput group "" sinput group "--- Maxima diferecia para encontrar maximo o minimos que coinciden" input TSN::ENUM_MODE_DIFF modo_diff_range_s_r = TSN::MODE_DIFF_BY_ATR; //Modo para calcular la minima difrerencia para el cambio input double atr_multiplier_s_r_range_or_points = 0.95; //Multiplicador del atr (14 periodos) o puntos fijos sinput group "" sinput group "-------| Sessiones |-------" input ENUM_TYPE_DRAW_RANGE_SESSION typo_dibujado_session = draw_session_range_lines_and_rect; //Session drawing type input bool fill_rects_session = true; //fill the session rectangles input int withd_lines_extra = 2; //Extra Line Witdh (if Session Draw type is Rectange and line) input int Width_rect = 1; //Rectangle Sessions Width input ENUM_LINE_STYLE style_rect_sessions = STYLE_SOLID; //rect line style sinput group "- New York Session " input char hora_ny_incio_sesion = 11;// New York Morning start hour input char min_ny_inicio_sesion = 0;// New York Morning start minute input char hora_ny_fin_sesion = 15;// New York Morning end hour input char min_ny_fin_sesion = 0;// New York Morning end minute input color clr_Rect_Sesion_ny = C'230,235,251'; //color of New York Morning rectangle input color clr_line_Sesion_ny = clrRoyalBlue; //color of New York Morning line //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ CEstrategia strategy(InpMagic, _Symbol, InpDrawObjects, _Period, 0, 0, InpStrategyMaxDeviationOrders); //--- int8_t idx_controler_w1 = INVALID_INDEX; int8_t idx_controler_curr = INVALID_INDEX; int8_t idx_bar_controlerd1 = INVALID_INDEX; int8_t idx_bar_mn1 = INVALID_INDEX; //--- TSN::CLossProfitManager g_loss_profit_manager; // LossProfitManager TSN::CAtrOptimizedZero g_atr_opt_zero(PERIOD_CURRENT, _Symbol, 14); bool NewDay = false; uint g_trade_flags = 0; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- Atr int pos_atr = ICTAtr_Create(_Period, _Symbol, 14, true); TSN::CAtr* atr_h = ICTAtr_GetAtrPointer(pos_atr); //--- Registramos timeframes g_new_bar_manager.GetPosExecute(PERIOD_D1, idx_bar_controlerd1); g_new_bar_manager.GetPosExecute(_Period, idx_controler_curr); g_new_bar_manager.GetPosExecute(PERIOD_W1, idx_controler_w1); g_new_bar_manager.GetPosExecute(PERIOD_MN1, idx_bar_mn1); //--- if(InpModifiedChart) { long chart_id = ChartID(); // Obtén el ID del gráfico actual // Ocultar la cuadrícula ChartSetInteger(chart_id, CHART_SHOW_GRID, false); ChartSetInteger(chart_id, CHART_COLOR_BACKGROUND, C'255,255,255'); // Fondo blanco ChartSetInteger(chart_id, CHART_COLOR_FOREGROUND, clrBlack); // Texto y escalas negras ChartSetInteger(chart_id, CHART_COLOR_CHART_UP, C'38,166,154'); // Velas alcistas color verde azulado ChartSetInteger(chart_id, CHART_COLOR_CHART_DOWN, C'239,83,80'); // Velas bajistas color rojo ChartSetInteger(chart_id, CHART_COLOR_CANDLE_BULL, C'38,166,154'); // Cuerpo de las velas alcistas ChartSetInteger(chart_id, CHART_COLOR_CANDLE_BEAR, C'239,83,80'); // Cuerpo de las velas bajistas ChartSetInteger(chart_id, CHART_COLOR_CHART_LINE, clrDarkSeaGreen); // Línea de tendencia ChartSetInteger(chart_id, CHART_COLOR_VOLUME, C'38,166,154'); // Color de los volúmenes ChartSetInteger(chart_id, CHART_COLOR_BID, C'38,166,154'); // Línea de oferta ChartSetInteger(chart_id, CHART_COLOR_ASK, C'239,83,80'); // Línea de demanda ChartSetInteger(chart_id, CHART_COLOR_LAST, C'156,186,240'); // Último precio ChartSetInteger(chart_id, CHART_COLOR_STOP_LEVEL, C'239,83,80'); // Líneas de stop ChartSetInteger(chart_id, CHART_SHOW_VOLUMES, true); // Actualizar el gráfico ChartRedraw(chart_id); } //--- g_session.Create(_Symbol, _Period, 0, 0, InpDrawObjects, true, hora_ny_incio_sesion, min_ny_inicio_sesion, hora_ny_fin_sesion, min_ny_fin_sesion, "Ny"); g_session.SetExtra(clr_line_Sesion_ny, clr_line_Sesion_ny, STYLE_SOLID, withd_lines_extra, typo_dibujado_session); g_session.SetGrapichStyles(style_rect_sessions, clr_Rect_Sesion_ny, Width_rect, fill_rects_session); //--- MqlParam params[]; ZZToParams(InpSwingZzLenth, 500, false, params); g_zz.Create(_Symbol, _Period, 0, 0, InpDrawObjects, params); g_zz.SetProperties(clrBlue, clrRed, "H", "L", "Arial", 10, 10); //--- g_support_resistence.Create(_Symbol, _Period, 0, 0, InpDrawObjects); g_support_resistence.SetProperties(min_toques_s_r, max_toques_s_tr, periodo_maximo_minimo, type_get_swing_s_r, range_obt_s_r); g_support_resistence.SetDiffInverse(TSN::CreateDiffptr(modo_diff_inverse_s_r, _Symbol, atr_h, 0, atr_multiplier_s_r_inverse_or_points)); g_support_resistence.SetDiffMaxDiffRange(TSN::CreateDiffptr(modo_diff_inverse_s_r, _Symbol, atr_h, 0, atr_multiplier_s_r_range_or_points)); g_support_resistence.SetGrapich(color_resistencia, color_soporte, style_lines_s_r, width_s_r_lines, 8, "Arial"); //--- Estrategia strategy.AddLogFlags(InpStrategyLogLevel); strategy.SetAtrTP_SL(&g_atr_opt_zero, InpStrategyAtrMultiplierTp, InpStrategyAtrMultiplierSl); strategy.SetOperateMode(TR_BUY_SELL, InpStrategyTypeTpSl); strategy.SetTP_SL(InpStrategySlPoint, InpStrategyTpPoint); if(InpRmLoteType == TSN::Fijo) strategy.FixedLotSize(InpRmLote); //--- Risk management string _what = NULL; TSNSTD_TRY_INI { //--- Strategy (fibbo) TSNSTD_TRY_EF(strategy.Init(clrRed, InpStrategyFibboChooseLevel, InpStrategyFibboLevels, InpStrategyFibboColors), true, TSN::CErrorTrace::FormatTrace(_what)) //--- Risk management TSN::CRiskManagementCreator manager; manager.SetPropirm(InpRmPropFirmBalance); //--- TSN::MQLArtRMCreatorRes result = manager.GetRiskPointer(InpRmRiskMode, InpMagic, InpRmGetMode); TSNSTD_TRY_EF(result.ok, true, TSN::CErrorTrace::FormatTrace(_what)) //--- risk = result.ptr; risk.AddLogFlags(InpRmLogLevel); risk.SetLossProfitManager(g_loss_profit_manager); CAutoCleaner::AddPtr(risk); // We set the parameters string to_apply = InpRmStrPercentagesToApply, to_modfied = InpRmStrPercentagesToBeReviewed; if(InpRmModeGmlpo == TSN::DYNAMIC_GMLPO_FIXED_PARAMETERS) TSN::CRmFunctions::SetDynamicUsingFixedParameters(InpRmBalancePercentageToActivateTheRisk1, InpRmBalancePercentageToActivateTheRisk2, InpRmBalancePercentageToActivateTheRisk3 , InpRmBalancePercentageToActivateTheRisk4, InpRmPercentageToBeModified1, InpRmPercentageToBeModified2, InpRmPercentageToBeModified3, InpRmPercentageToBeModified4 , to_modfied, to_apply); //--- Maximum losses and profits TSNSTD_TRY_INI_S // nota: genera bool _err implicito { TSNSTD_TRY_SE(risk.AddLP(InpRmPercentageOrMoneyMdl, InpRmAppliedPercentagesMdl, InpRmModeCalculationMdl, TSN::LP_MDL, true), true); TSNSTD_TRY_SE(risk.AddLP(InpRmPercentageOrMoneyGmlpo, InpRmAppliedPercentagesGmlpo, InpRmModeCalculationGmlpo, TSN::LP_GMLPO, true, (InpRmModeGmlpo != TSN::NO_DYNAMIC_GMLPO), to_modfied, to_apply), true); TSNSTD_TRY_SE(risk.AddLP(InpRmPercentageOrMoneyMl, InpRmAppliedPercentagesMl, InpRmModeCalculationMl, TSN::LP_ML, true), true); TSNSTD_TRY_SE(risk.AddLP(InpRmPercentageOrMoneyMwl, InpRmAppliedPercentagesMwl, InpRmModeCalculationMwl, TSN::LP_MWL, true), true); TSNSTD_TRY_SE(risk.AddLP(InpRmPercentageOrMoneyMdp, InpRmAppliedPercentagesMdp, InpRmModeCalculationMdp, TSN::LP_MDP, InpRmMdpIsStrict), true); risk.EndAddProfitLoss(); // Execute this every time we finish setting the maximum losses and profits } TSNSTD_TRY_END; //--- TSNSTD_TRY_N_EF(_err, true, TSN::CErrorTrace::FormatTrace(_what)) } TSNSTD_TRY_END; //--- if(_what != NULL) // error final { FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, _what); return INIT_FAILED; } //--- We initialize the account TSN::account_status.AddLogFlags(InpAccountStatusLogLevel); TSN::account_status.OnInitEvent(); //--- CAutoCleaner::AddFunction(TSN::CAccountStatus_Deinit); CAutoCleaner::AddFunction(CBasicEvents::Deinit); //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- CAutoCleaner::Deinit(reason); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- const datetime time_curr = TimeCurrent(); NewDay = false; g_new_bar_manager.Execute(time_curr); //--- Bloque 1 | Control diario if(CNewBarManager_IsNewBarM1(g_new_bar_manager)) { //--- Nuevo dia if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_bar_controlerd1)) { CBasicEvents::OnNewDay(time_curr); TSNMQLART_U_BEVENTS_MAN_REM_F(g_trade_flags, BASICEVENT_REG_FLAG_ON_NEW_DAY); //--- Nueva semana if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_controler_w1)) { CBasicEvents::OnNewWeek(time_curr); TSNMQLART_U_BEVENTS_MAN_REM_F(g_trade_flags, BASICEVENT_REG_FLAG_ON_NEW_WEEK); } //--- Nuevo mes if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_bar_mn1)) { CBasicEvents::OnNewMonth(time_curr); // no uso tradeflags dado que no hay parametros para un Monthly.. pero si lo hubiera: //TSNMQLART_U_BEVENTS_MAN_REM_F(g_trade_flags, BASICEVENT_REG_FLAG_ON_NEW_MON); } //--- NewDay = true; } } //--- if(TSN::account_status_positions_open) { #ifdef MQLARTICLES_RM_MULTI_EA_MODE risk.CalcProfit(); #else // MQLARTICLES_RM_MULTI_EA_MODE ACCOUNTSTATUS_ONEVERYTICK #endif // MQLARTICLES_RM_MULTI_EA_MODE if(TSNMQLART_U_BEVENTS_MAN_TRADE_NOW(g_trade_flags)) { if(g_loss_profit_manager.MaxLossIsSuperated()) { const int type = g_loss_profit_manager.GetLastLossSuperatedType(); if(type < TSN::LP_ML) { risk.CloseAllPositions(); // anadimos segun corresponda TSNMQLART_U_BEVENTS_MAN_ADD_F(g_trade_flags, TSNMQLART_RM_LP_M_BEVENTS_F_LOSS(type)); Print(TSN::g_mqarticles_lp_str_names[type], " is superated now"); } else // Manejo de las demas perdidas (aqui tambien entra pico, como no lo tenemos "agregado" no importa, pero si estuviera habria que manejar un caso especial) { if(InpRmRiskMode == TSN::risk_mode_propfirm_dynamic_daiy_loss) Print("The expert advisor lost the funding test"); else Print("Maximum loss exceeded now"); //--- risk.CloseAllPositions(); Remover(); } } else if(g_loss_profit_manager.MaxProfitIsSuperated()) { // NOTA: no se comprueba el tipo dado que ahora mismo solo hay un profit agregado (MDP). // Si hubieran mas se haria algo similar a la rama de losses. risk.CloseAllPositions(); TSNMQLART_U_BEVENTS_MAN_ADD_F(g_trade_flags, BASICEVENT_REG_FLAG_ON_NEW_DAY); Print("Excellent Maximum daily profit achieved"); } } } //--- Bloque 2 | Verifiacion if(TSNMQLART_U_BEVENTS_MAN_NO_TRADE_NOW(g_trade_flags)) return; //--- Bloque 4 | Estrategia // La estrucutra de como ejecutar OnNewBar debe de ir asi // 1ero deberan de ir las funcion FuncionOnBar y OnTick (estas actulizan los ticks internos de cada instancia) if(CNewBarManager_IsNewBarM1(g_new_bar_manager)) { ICTGen_FuncionOnBarM1(NewDay, time_curr); g_session.OnNewBarM1(); if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_controler_curr)) { strategy.OnNewBar(time_curr); } } } //+------------------------------------------------------------------+ //| TradeTransaction function | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction & trans, const MqlTradeRequest & request, const MqlTradeResult & result) { //--- TSN::account_status.OnTradeTransactionEvent(trans); } //+------------------------------------------------------------------+