| //+------------------------------------------------------------------+
|
| //| TradingLabS1.mq5 |
|
| //| Copyright 2025, Leo. |
|
| //| https://www.mql5.com/es/users/nique_372/news |
|
| //+------------------------------------------------------------------+
|
| #property copyright "Copyright 2025, Leo."
|
| #property link "https://www.mql5.com/es/users/nique_372/news"
|
| #property version "1.00"
|
| #property strict
|
|
|
|
|
| //+------------------------------------------------------------------+
|
| //| |
|
| //+------------------------------------------------------------------+
|
| #include "..\\..\\DefGlobal.mqh"
|
| #include "TradingLabS1.mqh"
|
| #include <TSN\\Std\\Basics\\Try.mqh>
|
|
|
| //+------------------------------------------------------------------+
|
| //| |
|
| //+------------------------------------------------------------------+
|
| sinput group "----------| General |----------"
|
| input ulong Magic = 35465; //Magic Number
|
| input bool Modifiied_Chart = true; //Modificar el grafico?
|
| input bool InpDrawObjects = true; //Draw objects
|
|
|
| sinput group ""
|
| sinput group "-------| Strategy |-------"
|
| input ENUM_VERBOSE_LOG_LEVEL log_level_strategy = VERBOSE_LOG_LEVEL_CAUTION; //Strategy log level:
|
| input ENUM_TIMEFRAMES timeframe_extern_Swing = PERIOD_M15;
|
|
|
| sinput group "-----| TP/SL by Fixed |-----"
|
| input ENUM_TYPE_TP_SL_FIXED inp_type_tp_sl_fixed = TP_SL_ATR; //Tipo de tp sl fjo:
|
| input bool InpUsarConfirmacionExtra = true; // Usar confirmacion extra
|
| input ENUM_BLOQUE_TO_USE InpBloqueToUse = USE_FVG; // Bloque para entrada
|
|
|
| sinput group "-- TP SL by Point"
|
| input long sl_point = 250; //Stop Loss In Points
|
| input long tp_point = 500; //Take Profit In Points
|
|
|
| sinput group "-- TP SL by Atr"
|
| input double inp_atr_multiplier_tp = 2.0; //Multiplicador del atr para el tp
|
| input double inp_atr_multiplier_sl = 2.0; //Multiplicador del atr para el sl
|
|
|
| sinput group "-- Ordenes --"
|
| input ulong max_deviation_ord = 100; //Maxima desviacion/slípagge de las ordenes en puntos
|
|
|
|
|
| sinput group ""
|
| sinput group "-------| Account Status |-------"
|
| input ENUM_VERBOSE_LOG_LEVEL log_level_account_status = VERBOSE_LOG_LEVEL_ALL; //(Account Status|Ticket Mangement) log level:
|
|
|
| sinput group ""
|
| sinput group "-------| Risk Management |-------"
|
| input TSN::ENUM_LOTE_TYPE Lote_Type = TSN::Dinamico; //Lote Type:
|
| input double lote = 0.1; //Lot size (only for fixed lot)
|
| input TSN::ENUM_MODE_RISK_MANAGEMENT risk_mode = TSN::risk_mode_personal_account; //type of risk management mode
|
| input TSN::ENUM_GET_LOT get_mode = TSN::GET_LOT_BY_STOPLOSS_AND_RISK_PER_OPERATION; //How to get the lot
|
| input double prop_firm_balance = 0; //If risk mode is Prop Firm FTMO, then put your ftmo account balance
|
| input ENUM_VERBOSE_LOG_LEVEL log_level_risk_management = VERBOSE_LOG_LEVEL_WARNINGS; //Risk Management log level:
|
|
|
| sinput group "- ML/Maxium loss/Maxima perdida -"
|
| input double percentage_or_money_ml_input = 0; //percentage or money (0 => not used ML)
|
| input TSN::ENUM_RISK_CALCULATION_MODE mode_calculation_ml = TSN::percentage; //Mode calculation Max Loss
|
| input TSN::ENUM_APPLIED_PERCENTAGES applied_percentages_ml = TSN::Balance; //ML percentage applies to:
|
|
|
| sinput group "- MWL/Maximum weekly loss/Perdida maxima semanal -"
|
| input double percentage_or_money_mwl_input = 0; //percentage or money (0 => not used MWL)
|
| input TSN::ENUM_RISK_CALCULATION_MODE mode_calculation_mwl = TSN::percentage; //Mode calculation Max weekly Loss
|
| input TSN::ENUM_APPLIED_PERCENTAGES applied_percentages_mwl = TSN::Balance;//MWL percentage applies to:
|
|
|
| sinput group "- MDL/Maximum daily loss/Perdida maxima diaria -"
|
| input double percentage_or_money_mdl_input = 0; //percentage or money (0 => not used MDL)
|
| input TSN::ENUM_RISK_CALCULATION_MODE mode_calculation_mdl = TSN::percentage; //Mode calculation Max daily loss
|
| input TSN::ENUM_APPLIED_PERCENTAGES applied_percentages_mdl = TSN::Balance;//MDL percentage applies to:
|
|
|
| sinput group "- GMLPO/Gross maximum loss per operation/Porcentaje a arriesgar por operacion -"
|
| input TSN::ENUM_OF_DYNAMIC_MODES_OF_GMLPO mode_gmlpo = TSN::DYNAMIC_GMLPO_FULL_CUSTOM; //Select GMLPO mode:
|
| input double percentage_or_money_gmlpo_input = 10.0; //percentage or money (0 => not used GMLPO)
|
| input TSN::ENUM_RISK_CALCULATION_MODE mode_calculation_gmlpo = TSN::percentage; //Mode calculation Max Loss per operation
|
| input TSN::ENUM_APPLIED_PERCENTAGES applied_percentages_gmlpo = TSN::Balance;//GMPLO percentage applies to:
|
|
|
| sinput group "-- Optional GMLPO settings, Dynamic GMLPO"
|
| sinput group "--- Full customizable dynamic GMLPO"
|
| input string note1 = "subtracted from your total balance to establish a threshold."; //This parameter determines a specific percentage that will be
|
| input string str_percentages_to_be_reviewed = "15,30,50"; //percentages separated by commas.
|
| input string note2 = "a new risk level will be triggered on your future trades: "; //When the current balance (equity) falls below this threshold
|
| input string str_percentages_to_apply = "10,20,25"; //percentages separated by commas.
|
| input string note3 = "0 in both parameters => do not use dynamic risk in gmlpo"; //Note:
|
|
|
| sinput group "--- Fixed dynamic GMLPO with parameters"
|
| sinput group "- 1 -"
|
| input string note1_1 = "subtracted from your total balance to establish a threshold."; //This parameter determines a specific percentage that will be
|
| input double inp_balance_percentage_to_activate_the_risk_1 = 2.0; //percentage 1 that will be exceeded to modify the risk separated by commas
|
| input string note2_1 = "a new risk level will be triggered on your future trades: "; //When the current balance (equity) falls below this threshold
|
| input double inp_percentage_to_be_modified_1 = 1.0;//new percentage 1 to which the gmlpo is modified
|
| sinput group "- 2 -"
|
| input double inp_balance_percentage_to_activate_the_risk_2 = 5.0;//percentage 2 that will be exceeded to modify the risk separated by commas
|
| input double inp_percentage_to_be_modified_2 = 0.7;//new percentage 2 to which the gmlpo is modified
|
| sinput group "- 3 -"
|
| input double inp_balance_percentage_to_activate_the_risk_3 = 7.0;//percentage 3 that will be exceeded to modify the risk separated by commas
|
| input double inp_percentage_to_be_modified_3 = 0.5;//new percentage 3 to which the gmlpo is modified
|
| sinput group "- 4 -"
|
| input double inp_balance_percentage_to_activate_the_risk_4 = 9.0;//percentage 4 that will be exceeded to modify the risk separated by commas
|
| input double inp_percentage_to_be_modified_4 = 0.33;//new percentage 4 1 to which the gmlpo is modified
|
|
|
| sinput group "-- MDP/Maximum daily profit/Maxima ganancia diaria --"
|
| input bool mdp_is_strict = true; //MDP is strict?
|
| input double percentage_or_money_mdp_input = 0; //percentage or money (0 => not used MDP)
|
| input TSN::ENUM_RISK_CALCULATION_MODE mode_calculation_mdp = TSN::percentage; //Mode calculation Max Daily Profit
|
| input TSN::ENUM_APPLIED_PERCENTAGES applied_percentages_mdp = TSN::Balance;//MDP percentage applies to:
|
|
|
|
|
| sinput group ""
|
| sinput group "-------| Trailing Stop |-------"
|
| input bool use_trailing_stop = false; // Enable trailing stop
|
| input TSN::ENUM_TSN_TRAILING_STOP_MODE_BASIC mode_trailing_stop = TSN::TRAILING_STOP_MODE_BASIC_ATR; // Select the indicator used for trailing stop
|
| input ENUM_VERBOSE_LOG_LEVEL log_level_trailing_stop = VERBOSE_LOG_LEVEL_ALL; // Trailing stop log level:
|
|
|
| sinput group "-- Trailing by Atr"
|
| input ENUM_TIMEFRAMES tsl_timeframe_atr = PERIOD_CURRENT; // Timeframe used for ATR calculation
|
| input int tsl_index_atr = 0; // Buffer index for ATR, typically 0
|
| input double tsl_atr_multiplier = 1.5; // ATR multiplier to set trailing distance from current price
|
| input int tsl_atr_period = 14; // ATR period used for calculation
|
|
|
| sinput group "-- Trailing by Prev Low/High"
|
| input ENUM_TIMEFRAMES tsl_timeframe_prev_low_high = PERIOD_CURRENT; // Timeframe used to find previous lows/highs
|
| input int tsl_index_prev_low_high = 1; // Index for calculating previous lows/highs
|
|
|
| sinput group "-- Trailing by Sar"
|
| input ENUM_TIMEFRAMES tsl_timeframe_sar = PERIOD_CURRENT; // Timeframe used for SAR calculation
|
| input int tsl_index_sar = 1; // Buffer index for SAR, typically 1
|
| input double tsl_sar_step = 0.02; // SAR step value
|
| input double tsl_sar_maximum = 0.20; // SAR maximum value
|
|
|
| sinput group "-- Trailing by MA"
|
| input ENUM_TIMEFRAMES tsl_timeframe_ma = PERIOD_CURRENT; // Timeframe used for Moving Average calculation
|
| input ENUM_MA_METHOD tsl_ma_method = MODE_EMA; // Moving Average method: EMA, SMA, etc.
|
| input int tsl_index_ma = 1; // Buffer index for Moving Average, typically 1
|
| input int tsl_ma_period = 14; // Period used for Moving Average calculation
|
|
|
| sinput group "-- Trailing by AMA"
|
| input ENUM_TIMEFRAMES tsl_timeframe_ama = PERIOD_CURRENT; // Timeframe used for AMA calculation
|
| input int tsl_index_ama = 1; // Buffer index for AMA, typically 1
|
| input int tsl_ama_period = 6; // AMA base period
|
| input int tsl_ama_fast_period = 6; // Fast moving average period
|
| input int tsl_ama_low_period = 50; // Slow moving average period
|
|
|
| sinput group "-- Trailing Fixed"
|
| input int tsl_fixed_start = 50; // Distance to start the fixed trailing stop
|
| input int tsl_fixed_step = 10; // Step size for adjusting the fixed trailing stop
|
|
|
| sinput group "-- Trailing by Swings"
|
| input ENUM_TIMEFRAMES tsl_swings_timeframe = PERIOD_CURRENT; // Timeframe used for swing detection
|
| input int tsl_swings_length = 4; // Length for detecting swing points
|
| input int tsl_swings_index = 1; // Buffer index for swing detection, typically 1
|
| input color tsl_color_bull_swing = clrGreen; // Color for bullish swing points
|
| input color tsl_color_bear_swing = clrRed; // Color for bearish swing points
|
|
|
|
|
| sinput group ""
|
| sinput group "--------------| Sessions |--------------"
|
| 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 "- London Sesion "
|
| input bool opera_london_open = true; //Operar london open?
|
| input char hora_london_incio_sesion = 6;// London start hour
|
| input char min_london_inicio_sesion = 0;// London start minute
|
| input char hora_london_fin_sesion = 9;// London end hour
|
| input char min_london_fin_sesion = 0;// London end minute
|
| input color clr_Rect_Sesion_london = C'204,234,255'; //color of London rectangle
|
| input color clr_line_Sesion_london = clrDodgerBlue; //color of London line
|
|
|
| sinput group "- New York Session "
|
| input bool opera_ny_morning = true; //Operar ny open?
|
| 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
|
|
|
| sinput group ""
|
| sinput group "-------| FVG |-------"
|
| input bool mostrar_la_mitad_imbalances = true; //show the middle line of (fvg-rdrb-imbalance-gap-bpr)?
|
| input int minutos_despues_mitigacion_eliminar_imbalances = 10; //minutes to delete the (fvg-rdrb-imbalance-gap-ifvg-bpr) after being invalidated
|
| input bool Fill_all_imbalance = true; //Fill (fvg - imbalance - gap - rdrb)?
|
| input ENUM_STYLE_DIBUJO_IMBALANCES style_draw_fvg = fvg_1_vela; // Fvg Drawing Style
|
| input color Color_FVG_alcista = C'171,222,165'; // choose bullish fvg color
|
| input color Color_FVG_bajista = C'248, 154,152'; // choose bearish fvg color
|
| input color mitad_Color_FVG_alcista = C'116,200,106'; //color of the middle line of the bullish fvg
|
| input color mitad_Color_FVG_bajista = C'243, 90,86'; //color of the middle line of the bearish fvg
|
| input ENUM_MODO_OBTENCION_IMBALANCE obtencion_type_fvg = defined_pattern; //fvg get mode
|
| input TSN::ENUM_MODE_DIFF mode_min_diff_fvg = TSN::MODE_DIFF_BY_ATR; //Choose the minimum difference type for the fvg:
|
| input string c111 = " is point or specify atr multipler (for a 14-period atr current)"; //Minimum height for the fvg in points if the difference mode
|
| input double atr_mul_or_dist_point_fvg = 0; //Atr multiplier or distance in points
|
|
|
|
|
| sinput group "------| Order Blocks |------"
|
| input int minutos_despues_mitigacion_eliminar_ob = 10; //minutes to delete the order block after being invalidated
|
| input bool mostar_la_mitad_ob = true; //show the middle line of an order block?
|
| input ENUM_ORDERBLOCKS_OBTENCIUON_TYPE mod_obtencion_obs = ORDER_BLOCKS_ALL; //Order blocks Obtaining mode
|
|
|
| sinput group "--| General properties of the order block rectangle"
|
| input bool fill_order_blocks = true; //Fill Order Blocks?
|
|
|
| sinput group "--| Bullish order block"
|
| input color Color_OrderBlock_Alcista = C'45,154,29'; // Choose the Bullish Order Block Color
|
| input color line_mitad_color_oba = clrDarkGreen; //color of the middle line of the bullish order blocks
|
| input ENUM_OB_STYLE price_1_oba = low; // choose price1 bullish order block
|
| input ENUM_OB_STYLE price_2_oba = high; // choose price2 bullish order block
|
|
|
| sinput group "--| Bearish order block"
|
| input color Color_OrderBlock_Bajista = C'249,95,57'; // Choose the Bearish Order Block Color
|
| input color line_mitad_color_obb = clrTomato; //color of the middle line of the bearish order blocks
|
| input ENUM_OB_STYLE price_1_obb = high; // choose price1 bearish order block
|
| input ENUM_OB_STYLE price_2_obb = low; // choose price2 bearish order block
|
|
|
| sinput group "--| Settings order block by sweeps"
|
| input int16_t lenth_order_block = 4; //Num bar of swings to identify swing points
|
| input ENUM_TYPE_ROPTRUA_CONFIRMAR_OB breakout_type_ob = BREAKUP_VELA_ROPTURA_SWING;// break type for order block by sweep
|
| input int max_espera_roptura_ob_sweep = 20; //maximum wait in bars to break a swing or open of a candle
|
|
|
| sinput group "--| Alerts"
|
| input bool enable_alert_ob = false; //Activate alerts when an order block is touched?
|
| input string type_alerts_ob = "Alert|Notification"; //Types of alerts when an order block is touched
|
|
|
| sinput group ""
|
| sinput group "-------| Swing |-------"
|
| input int16_t lenth_swing = 7;
|
|
|
| //+------------------------------------------------------------------+
|
| //| |
|
| //+------------------------------------------------------------------+
|
| CEstrategia strategy(Magic, _Symbol, _Period, 0, 0, max_deviation_ord);
|
|
|
| //---
|
| 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::CTrailingStopManager g_trailing_creator;
|
| uint g_trade_flags = 0;
|
| bool NewDay = false;
|
| TSN::CLossProfitManager g_loss_profit_manager; // LossProfitManager
|
| TSN::TrailingStopRun g_trailing_stop;
|
| //CChallengeSimulator challange_simulator;
|
| TSN::CAtrOptimizedZero g_atr_opt_zero(PERIOD_CURRENT, _Symbol, 14);
|
| //+------------------------------------------------------------------+
|
| //| Expert initialization function |
|
| //+------------------------------------------------------------------+
|
| int OnInit()
|
| {
|
| //--- Atr
|
| int pos_atr = ICTAtr_Create(_Period, _Symbol, 14, true);
|
| TSN::CAtr* atr_h = ICTAtr_GetAtrPointer(pos_atr);
|
| //sabmeos que _period = M5, el miniomo
|
|
|
| //--- 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(Modifiied_Chart)
|
| {
|
| 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);
|
| }
|
|
|
|
|
| //---
|
| swing_externo = new CSwingBarPure(); // Del tipo bar
|
| MqlParam params[];
|
| PureToParmas(lenth_swing, lenth_swing, MODE_SWING_NO_STRICT, params);
|
| swing_externo.Create(_Symbol, timeframe_extern_Swing, 0, 0, InpDrawObjects, params);
|
| swing_externo.SetProperties(clrBlue, clrRed, "H", "L", "Arial", 10, 12);
|
|
|
| //--- Bloque
|
| if(InpBloqueToUse == USE_FVG)
|
| {
|
| g_block = new CFvgBar(); // Creamos un puntero a g_block
|
| CFvgBar* fvg_bar = (CFvgBar *)g_block; // Cast
|
|
|
| fvg_bar.Create(_Symbol, _Period, 0, 0, InpDrawObjects);
|
| fvg_bar.Set(500, obtencion_type_fvg, style_draw_fvg, TSN::CreateDiffptr(mode_min_diff_fvg, _Symbol, atr_h, 1, atr_mul_or_dist_point_fvg));
|
| fvg_bar.SetGrapich(Color_FVG_alcista, Color_FVG_bajista, mitad_Color_FVG_alcista, mitad_Color_FVG_bajista, STYLE_SOLID, Fill_all_imbalance, 1, mostrar_la_mitad_imbalances,
|
| minutos_despues_mitigacion_eliminar_imbalances, 1, STYLE_DOT);
|
| }
|
| else
|
| {
|
| g_block = new COrderBlockBar();
|
| COrderBlockBar* ob_bar = (COrderBlockBar *)g_block;
|
|
|
| ob_bar.Create(_Symbol, _Period, 0, 0, InpDrawObjects);
|
|
|
| ob_bar.SetGrapich(Color_OrderBlock_Alcista, Color_OrderBlock_Bajista, line_mitad_color_oba, line_mitad_color_obb, STYLE_SOLID, fill_order_blocks, 1, mostar_la_mitad_ob,
|
| minutos_despues_mitigacion_eliminar_ob, 1, STYLE_DOT);
|
| ob_bar.SetTypeBusqueda(mod_obtencion_obs);
|
| ob_bar.SetStylesPrices(price_1_oba, price_1_obb, price_2_oba, price_2_obb);
|
| ob_bar.SetOrderBlockSweep(lenth_order_block, max_espera_roptura_ob_sweep, breakout_type_ob);
|
| ob_bar.Set(500);
|
| ob_bar.SetAlertas(enable_alert_ob, type_alerts_ob);
|
| }
|
|
|
| //--- Liquidez
|
| sweep.Initilize(_Period, _Symbol, 0, 0, false, 20);
|
|
|
| // Cremos el nivel de liquidez Swing
|
| sweep.CreateLiquidityLevel("Swings", clrRed, 1, STYLE_DASHDOTDOT); //Retorna 0
|
|
|
| //--- Sesiones
|
| if(opera_london_open)
|
| {
|
| //ADEVERTENICA, _period, no afecta en nada a las sesion esat se ejecutan cada vela M1
|
| CTradingSession* sesion_london = new CTradingSession();
|
| sesion_london.Create(_Symbol, _Period, 0, 0, InpDrawObjects, true, hora_london_incio_sesion, min_london_inicio_sesion, hora_london_fin_sesion, min_london_fin_sesion, "London");
|
| sesion_london.SetExtra(clr_line_Sesion_london, clr_line_Sesion_london, STYLE_SOLID, withd_lines_extra, typo_dibujado_session);
|
| sesion_london.SetGrapichStyles(style_rect_sessions, clr_Rect_Sesion_london, Width_rect, fill_rects_session);
|
| sesion.AddItemFast(sesion_london);
|
| }
|
|
|
| if(opera_ny_morning)
|
| {
|
| CTradingSession* sesion_ny = new CTradingSession();
|
| sesion_ny.Create(_Symbol, _Period, 0, 0, InpDrawObjects, true, hora_ny_incio_sesion, min_ny_inicio_sesion, hora_ny_fin_sesion, min_ny_fin_sesion, "Ny");
|
| sesion_ny.SetExtra(clr_line_Sesion_ny, clr_line_Sesion_ny, STYLE_SOLID, withd_lines_extra, typo_dibujado_session);
|
| sesion_ny.SetGrapichStyles(style_rect_sessions, clr_Rect_Sesion_ny, Width_rect, fill_rects_session);
|
| sesion.AddItemFast(sesion_ny);
|
| }
|
|
|
| if(sesion.Size() < 1)
|
| {
|
| FastLog(FUNCION_ACTUAL, FATAL_ERROR_TEXT, "Minimos se requiren 2 sesiones");
|
| return INIT_PARAMETERS_INCORRECT;
|
| }
|
|
|
|
|
| //--- Strategy
|
| strategy.AddLogFlags(log_level_strategy);
|
| strategy.SetAtrTP_SL(&g_atr_opt_zero, inp_atr_multiplier_tp, inp_atr_multiplier_sl);
|
| strategy.SetOperateMode(TR_BUY_SELL, inp_type_tp_sl_fixed);
|
| strategy.SetTP_SL(tp_point, sl_point);
|
| strategy.Set(InpUsarConfirmacionExtra);
|
| if(Lote_Type == TSN::Fijo)
|
| strategy.FixedLotSize(lote);
|
|
|
| //--- Risk management
|
| string _what = NULL;
|
| TSNSTD_TRY_INI
|
| {
|
| //--- Trailing stop
|
| if(use_trailing_stop)
|
| {
|
| g_trailing_creator.SetTrailingAMA(tsl_index_ama, tsl_timeframe_ama, tsl_ama_period, tsl_ama_low_period, tsl_ama_fast_period);
|
| g_trailing_creator.SetTrailingAtr(tsl_atr_period, tsl_atr_multiplier, tsl_timeframe_atr, tsl_index_atr);
|
| g_trailing_creator.SetTrailingFixed(tsl_fixed_start, tsl_fixed_step);
|
| g_trailing_creator.SetTrailingMa(tsl_index_ma, tsl_timeframe_ma, tsl_ma_period, tsl_ma_method);
|
| g_trailing_creator.SetTrailingPrev(tsl_timeframe_prev_low_high, tsl_index_prev_low_high);
|
| g_trailing_creator.SetTrailingSar(tsl_index_sar, tsl_timeframe_sar, tsl_sar_step, tsl_sar_maximum);
|
| g_trailing_creator.SetTrailingSwings(tsl_swings_timeframe, tsl_swings_index, 0, tsl_color_bull_swing, tsl_color_bear_swing, tsl_swings_length, 100);
|
| g_trailing_stop = g_trailing_creator.Create(mode_trailing_stop, Magic, _Symbol);
|
| TSNSTD_TRY_EF(g_trailing_stop.IsValid(), true,
|
| TSN::CErrorTrace::FormatTrace(_what))
|
| }
|
|
|
| TSN::CRiskManagementCreator manager;
|
| manager.SetPropirm(prop_firm_balance);
|
|
|
| //---
|
| TSN::MQLArtRMCreatorRes result = manager.GetRiskPointer(risk_mode, Magic, get_mode);
|
| TSNSTD_TRY_EF(result.ok, true,
|
| TSN::CErrorTrace::FormatTrace(_what))
|
|
|
| //---
|
| risk = result.ptr;
|
| risk.AddLogFlags(log_level_risk_management);
|
| risk.SetLossProfitManager(g_loss_profit_manager);
|
| CAutoCleaner::AddPtr(risk);
|
|
|
| // We set the parameters
|
| string to_apply = str_percentages_to_apply, to_modfied = str_percentages_to_be_reviewed;
|
|
|
| if(mode_gmlpo == TSN::DYNAMIC_GMLPO_FIXED_PARAMETERS)
|
| TSN::CRmFunctions::SetDynamicUsingFixedParameters(inp_balance_percentage_to_activate_the_risk_1, inp_balance_percentage_to_activate_the_risk_2, inp_balance_percentage_to_activate_the_risk_3
|
| , inp_balance_percentage_to_activate_the_risk_4, inp_percentage_to_be_modified_1, inp_percentage_to_be_modified_2, inp_percentage_to_be_modified_3, inp_percentage_to_be_modified_4
|
| , to_modfied, to_apply);
|
|
|
| //--- Maximum losses and profits
|
| TSNSTD_TRY_INI_S // nota: genera bool _err implicito
|
| {
|
| TSNSTD_TRY_SE(risk.AddLP(percentage_or_money_mdl_input, applied_percentages_mdl, mode_calculation_mdl, TSN::LP_MDL, true), true);
|
| TSNSTD_TRY_SE(risk.AddLP(percentage_or_money_gmlpo_input, applied_percentages_gmlpo, mode_calculation_gmlpo, TSN::LP_GMLPO, true, (mode_gmlpo != TSN::NO_DYNAMIC_GMLPO), to_modfied, to_apply), true);
|
| TSNSTD_TRY_SE(risk.AddLP(percentage_or_money_ml_input, applied_percentages_ml, mode_calculation_ml, TSN::LP_ML, true), true);
|
| TSNSTD_TRY_SE(risk.AddLP(percentage_or_money_mwl_input, applied_percentages_mwl, mode_calculation_mwl, TSN::LP_MWL, true), true);
|
| TSNSTD_TRY_SE(risk.AddLP(percentage_or_money_mdp_input, applied_percentages_mdp, mode_calculation_mdp, TSN::LP_MDP, mdp_is_strict), true);
|
| risk.EndAddProfitLoss(); //Ejecutar esto cada vez que se termina de setear las maximas peridas y gancnasias
|
| }
|
| 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;
|
| }
|
|
|
| //--- Inicilizamos la cuenta
|
| // challange_simulator.OnEndStatus();
|
| TSN::account_status.AddLogFlags(log_level_account_status);
|
| TSN::account_status.OnInitEvent();
|
|
|
| //---
|
| CAutoCleaner::AddFunction(TSN::CAccountStatus_Deinit);
|
| CAutoCleaner::AddFunction(CBasicEvents::Deinit);
|
| //---
|
| return(INIT_SUCCEEDED);
|
| }
|
|
|
| //+------------------------------------------------------------------+
|
| //| Expert deinitialization function |
|
| //+------------------------------------------------------------------+
|
| void OnDeinit(const int reason)
|
| {
|
| //---
|
| delete swing_externo;
|
| delete g_block;
|
| CAutoCleaner::Deinit(reason);
|
| }
|
|
|
| //+------------------------------------------------------------------+
|
| //| Expert tick function |
|
| //+------------------------------------------------------------------+
|
| void OnTick()
|
| {
|
| //---
|
| const datetime time_curr = TimeCurrent();
|
| g_new_bar_manager.Execute(time_curr);
|
| NewDay = false;
|
|
|
|
|
| //--- 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);
|
|
|
| //---
|
| if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_controler_w1)) //Limpiar para no acomular mucha memoria
|
| {
|
| CBasicEvents::OnNewWeek(time_curr);
|
| TSNMQLART_U_BEVENTS_MAN_REM_F(g_trade_flags, BASICEVENT_REG_FLAG_ON_NEW_WEEK);
|
|
|
| //--- Eliminacion de concpetos normales
|
| swing_externo.DeleteAll();
|
| g_block.DeleteAll();
|
| }
|
|
|
| //--- Nuevo mes, eliminacion de liquidez
|
| if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_bar_mn1))
|
| {
|
| sweep.DeleteAll();
|
| 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");
|
| strategy.OnInterupcion();
|
| }
|
| 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(risk_mode == TSN::risk_mode_propfirm_dynamic_daiy_loss)
|
| Print("The expert advisor lost the funding test");
|
| else
|
| Print("Maximum loss exceeded now");
|
|
|
| //---
|
| strategy.OnInterupcion();
|
| 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();
|
| strategy.OnInterupcion();
|
| TSNMQLART_U_BEVENTS_MAN_ADD_F(g_trade_flags, BASICEVENT_REG_FLAG_ON_NEW_DAY);
|
| Print("Excellent Maximum daily profit achieved");
|
| }
|
| }
|
| }
|
|
|
| //---
|
| if(use_trailing_stop)
|
| g_trailing_stop.OnTickEvent(time_curr);
|
|
|
| //--- Bloque 2 | Verifiacion
|
| if(TSNMQLART_U_BEVENTS_MAN_NO_TRADE_NOW(g_trade_flags))
|
| return;
|
|
|
| //---
|
| if(CNewBarManager_IsNewBarM1(g_new_bar_manager))
|
| {
|
| ICTGen_FuncionOnBarM1(NewDay, time_curr);
|
| sesion.OnNewBarM1();
|
|
|
| //---
|
| if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_controler_curr))
|
| {
|
| //--- Conceptos
|
| g_block.OnNewBar();
|
| swing_externo.OnNewBar();
|
|
|
| //--- Liquidez
|
| sweep.OnNewBarInit(time_curr);
|
| Liq_AddSwing();
|
| sweep.OnNewBarEnd();
|
|
|
| //---
|
| strategy.OnNewBar(time_curr);
|
| }
|
| }
|
| }
|
|
|
| //+------------------------------------------------------------------+
|
| //| TradeTransaction function |
|
| //+------------------------------------------------------------------+
|
| void OnTradeTransaction(const MqlTradeTransaction & trans,
|
| const MqlTradeRequest & request,
|
| const MqlTradeResult & result)
|
| {
|
| //---
|
| TSN::account_status.OnTradeTransactionEvent(trans);
|
| }
|
| //+------------------------------------------------------------------+
|