EasySbAi/Ea.mq5
Nique_372 a537ad80ea
Some checks failed
/ test_eas (push) Has been cancelled
2026-04-12 08:37:47 -05:00

729 lines
68 KiB
MQL5

//+------------------------------------------------------------------+
//| 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
//#define CSM_DEBUG_ELIMIACIONES
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#include "Core\\DefGlobal.mqh"
#include "Core\\Strategy.mqh"
#include <TSN\\MqlCI\\BackRes.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
sinput group "----------| General |----------"
input ulong InpMagic = 35465; // Magic Number
input bool InpModifiedChart = true; // Modificar el grafico?
//---
sinput group ""
sinput group "-------| Strategy |-------"
input ENUM_VERBOSE_LOG_LEVEL InpStrategyLogLevel = VERBOSE_LOG_LEVEL_CAUTION; // Strategy log level
sinput group "-----| TP/SL Type |-----"
input ENUM_TPSL_GENERAL InpStrategyTypeTpSlGeneral = TPSL_GENERAL_TYPE_USE_FULL_AI; // General type tp\sl
sinput group "-----| Entrada |-----"
input ENUM_STRATEGY_ENTRY InpStrategyGeneralEntry = STRATEGY_TYPE_ENTRY_WITH_AI; // Tipo de ejecucion de estrategia
sinput group "-- Confirmacion final ---"
input ENUM_EST_ENTRADA InpStrategyEntryType = ENTRADA_BB_OB; // Confirmacion para entrar al mercado
sinput group "-----| Generic TP/SL |-----"
input ENUM_TYPE_TP_SL_FIXED InpStrategyTypeTpSl = TP_SL_ATR; // Tipo de TP/SL generico
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 "-----| Ai |-----"
input int InpStrategyAiIdx = 0 ; // Select Idx
input bool InpStrategyAiGenerateDataMode = true; // Is in generate data mode ?
input bool InpStrategyAiCommonFolder=true; // Data in common folder ?
sinput group "-- Ai entry --"
input double InpStrategyAiMinTreshold = 0.5; // Ai min treshold proba for entry
//---
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 ENUM_LOTE_TYPE InpRmLoteType = Dinamico; //Lote Type:
input double InpRmLote = 0.1; //Lot size (only for fixed lot)
input ENUM_MODE_RISK_MANAGEMENT InpRmRiskMode = risk_mode_personal_account; //type of risk management mode
input ENUM_GET_LOT InpRmGetMode = 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 ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMl = percentage; //Mode calculation Max Loss
input ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMl = 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 ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMwl = percentage; //Mode calculation Max weekly Loss
input ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMwl = 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 ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMdl = percentage; //Mode calculation Max daily loss
input ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMdl = Balance;//MDL percentage applies to:
sinput group "- GMLPO/Gross maximum loss per CanTradetion/Percentage to risk per CanTradetion -"
input ENUM_OF_DYNAMIC_MODES_OF_GMLPO InpRmModeGmlpo = NO_DYNAMIC_GMLPO; //Select GMLPO mode:
input double InpRmPercentageOrMoneyGmlpo = 2.0; //percentage or money (0 => not used GMLPO)
input ENUM_RISK_CALCULATION_MODE InpRmModeCalculationGmlpo = percentage; //Mode calculation Max Loss per CanTradetion
input ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesGmlpo = 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 ENUM_RISK_CALCULATION_MODE InpRmModeCalculationMdp = percentage; //Mode calculation Max Daily Profit
input ENUM_APPLIED_PERCENTAGES InpRmAppliedPercentagesMdp = Balance;//MDP percentage applies to:
//---
sinput group ""
sinput group "-------| Sesion operativa |-------"
input ENUM_TYPE_DRAW_RANGE_SESSION InpOperativeSessionDrawStyle = draw_session_range_lines_and_rect;
input string InpOperativeSessionName = "Session operativa";
input int InpOperativeSessionStartHour = 10;
input int InpOperativeSessionStartMinute = 0;
input int InpOperativeSessionEndHour = 14;
input int InpOperativeSessionEndMinute = 0;
input color InpOperativeSessionLineColor = clrBlue;
input color InpOperativeSessionRectColor = clrAliceBlue;
//---
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 ""
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 ENUM_MODE_DIFF mode_min_diff_fvg = 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 ""
sinput group "------| Breaker Blocks |------"
input int minutos_eliminar_breaker_block = 30; //minutes to delete breaker blocks after being invalidated
sinput group "--- Configuration of Breaker blocks per sweep "
input int16_t lenth_swings_bb = 4; //High and low swing (number of candles)
input int max_esperar_roptura_bb_swep = 45; //Maximum wait to break the high/low swing after the sweep
sinput group "--| General properties of breaker blocks rectangles"
input bool fill_breaker_block = false;//Fill breaker block ?
input ENUM_LINE_STYLE style_brekare_block = STYLE_SOLID;//breaker block rectangle line style
sinput group "--| Bullish breaker block"
input color color_breaker_block_alcista = C'112,209,153'; //bullish breaker block color
input color color_breaker_block_alcista_mitad = C'121,253,160'; //color of the middle line of the bullish breaker block
sinput group "--| Bearish breaker block"
input color color_breaker_block_bajista = C'248,158,92';//bearish breaker block color
input color color_breaker_block_bajista_mitad = C'233,140,56';//color of the middle line of the bearish breaker block
//---
sinput group ""
sinput group "-------| Bos/ChoCh |-------"
input MODE_BUSQUEDA_SWING mode_swings_bos_choch = MODE_SWING_STRICT; //Swing find mode
input int16_t lenth_bos_choch = 2; //High and low swing (number of candles)
input color clr_Bos = C'99,148,148'; // choose the color of the bullish bos (line and text)
input color clr_Choch = C'99,148,148'; // choose the color of the bullish Choch (line and text)
input color clr_Choch_2 = C'233,116,116'; // choose the color of the bearish bos (line and text)
input color clr_Bos_2 = C'233,116,116'; // choose the color of the bearish Choch (line and text)
input int max_espera_bos_choch = 30; //Choose the maximum wait for the bos and choch (in bars)
input ENUM_LINE_STYLE line_style_bos_choch = STYLE_DOT; // Choch and Bos Line Style
//---
sinput group "-------| News |-------"
input ENUM_VERBOSE_LOG_LEVEL log_level_news = VERBOSE_LOG_LEVEL_ALL; //Log level news:
sinput group "--| General"
input datetime fecha_desde_incio_noticias = D'2005.01.01'; //Start date for calendar data collection (equal to generated csv files)
input uint8_t seg_antes_despues = 5; //Segundos antes y depues para operar noticias
sinput group "--| Objetos graficos"
input string type_draw_events = "Line|Event"; //Tipo de dibujado de los eventos
input color color_eventos_high = clrRed; //Color de los eventos de alta impotancia
input color color_eventos_low = clrSilver; //Color de los eventos de baja impotancia
input color color_eventos_mid = C'0xF8,0xDA,0x07'; //Color de los eventos de media impotancia
input color color_eventos_none = C'0x8A,0x84,0x8A'; //Color de los eventos de ninguna impotancia
input int16_t width_events = 1; //Ancho de los eventos
//---
sinput group "-- For CI"
input bool InpCIGenerateOutputResFile = false;
//+------------------------------------------------------------------+
//| Parametros base |
//+------------------------------------------------------------------+
// Tipo de entrada
ENUM_EST_ENTRADA InpStrategyEntryType_opt = InpStrategyEntryType;
// Sesión operativa
int InpOperativeSessionStartHour_opt = InpOperativeSessionStartHour;
int InpOperativeSessionStartMinute_opt = InpOperativeSessionStartMinute;
int InpOperativeSessionEndHour_opt = InpOperativeSessionEndHour;
int InpOperativeSessionEndMinute_opt = InpOperativeSessionEndMinute;
// Order Blocks
ENUM_ORDERBLOCKS_OBTENCIUON_TYPE mod_obtencion_obs_opt = mod_obtencion_obs;
int16_t lenth_order_block_opt = lenth_order_block;
ENUM_TYPE_ROPTRUA_CONFIRMAR_OB breakout_type_ob_opt = breakout_type_ob;
int max_espera_roptura_ob_sweep_opt = max_espera_roptura_ob_sweep;
ENUM_OB_STYLE price_1_oba_opt = price_1_oba;
ENUM_OB_STYLE price_2_oba_opt = price_2_oba;
ENUM_OB_STYLE price_1_obb_opt = price_1_obb;
ENUM_OB_STYLE price_2_obb_opt = price_2_obb;
// FVG
ENUM_MODO_OBTENCION_IMBALANCE obtencion_type_fvg_opt = obtencion_type_fvg;
ENUM_MODE_DIFF mode_min_diff_fvg_opt = mode_min_diff_fvg;
double atr_mul_or_dist_point_fvg_opt = atr_mul_or_dist_point_fvg;
// Breaker Blocks
int16_t lenth_swings_bb_opt = lenth_swings_bb;
int max_esperar_roptura_bb_swep_opt = max_esperar_roptura_bb_swep;
// Bos/ChoCh
MODE_BUSQUEDA_SWING mode_swings_bos_choch_opt = mode_swings_bos_choch;
int16_t lenth_bos_choch_opt = lenth_bos_choch;
int max_espera_bos_choch_opt = max_espera_bos_choch;
// News
uint8_t seg_antes_despues_opt = seg_antes_despues;
//+------------------------------------------------------------------+
//| Variables globales |
//+------------------------------------------------------------------+
CEstrategia strategy(InpMagic, _Symbol, _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;
//---
bool g_ai_enable = false;
bool NewDay = false;
bool CanTrade = true;
const CLossProfitManager* g_loss_profit_manager;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Atr
CAtr* atr_h = CIctLibAtrManager::GetAtr(_Period);
//--- 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);
}
//--- Estrategia
CAtrUltraOptimized* atr_ultra = new CAtrUltraOptimized();
atr_ultra.SetVariables(PERIOD_CURRENT, _Symbol, 0, 14);
atr_ultra.SetInternalPointer();
strategy.AddLogFlags(InpStrategyLogLevel);
strategy.SetAtrTP_SL(atr_ultra, InpStrategyAtrMultiplierTp, InpStrategyAtrMultiplierSl);
strategy.SetOperateMode(TR_BUY_SELL, InpStrategyTypeTpSl);
strategy.SetTP_SL(InpStrategySlPoint, InpStrategyTpPoint);
if(InpRmLoteType == Fijo)
strategy.FixedLotSize(InpRmLote);
strategy.InitAiFlags(InpStrategyTypeTpSlGeneral, InpStrategyGeneralEntry);
//--- Calenadario
if((g_ai_enable = strategy.UseAi()))
{
datetime desde = fecha_desde_incio_noticias;
datetime hasta = iTime(_Symbol, PERIOD_D1, 0);
CiNewsLeo_AddLogFlags(log_level_news);
g_calendar.FilterBySymbol(_Symbol);
// Añadimos paises
g_calendar.AddCountryByEventList(COUNTRY_CODE_USA, cadena_USD);
// Set
g_calendar.SetCalendar(desde, hasta);
g_calendar.SetConfigEvents(type_draw_events, color_eventos_mid, color_eventos_low, color_eventos_none, color_eventos_high, width_events, STYLE_SOLID);
g_calendar.SetNoticiasChecker(seg_antes_despues_opt, 10);
}
//---
CSetFile* set_file = NULL;
if(InpStrategyAiGenerateDataMode)
strategy.InitAiTraining(30, InpStrategyAiCommonFolder);
else
{
ConfigDependencyAiStrBase config_in;
config_in.label = "label";
config_in.label_id = InpStrategyAiIdx;
config_in.timeframe = _Period;
config_in.symbol_folder = "XAUUSD";
config_in.comon_folder = InpStrategyAiCommonFolder;
//InpStrategyAiIdx
strategy.InitAiLive(30, InpStrategyAiMinTreshold, InpStrategyTypeTpSlGeneral, InpStrategyGeneralEntry, set_file, config_in);
}
//---
// Cambiamos de valor si es que hay SetFile
if(set_file != NULL)
{
FastLog(FUNCION_ACTUAL, INFO_TEXT, "Modificando valores de parametros, dado que se eligio el modo ia");
#define PARAM_ASSING(A, FUNC) A##_opt = FUNC(#A)
PARAM_ASSING(InpStrategyEntryType, set_file.ReadParamValueInteger<ENUM_EST_ENTRADA>);
PARAM_ASSING(InpOperativeSessionStartHour, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(InpOperativeSessionStartMinute, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(InpOperativeSessionEndHour, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(InpOperativeSessionEndMinute, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(mod_obtencion_obs, set_file.ReadParamValueInteger<ENUM_ORDERBLOCKS_OBTENCIUON_TYPE>);
PARAM_ASSING(lenth_order_block, set_file.ReadParamValueInteger<int16_t>);
PARAM_ASSING(breakout_type_ob, set_file.ReadParamValueInteger<ENUM_TYPE_ROPTRUA_CONFIRMAR_OB>);
PARAM_ASSING(max_espera_roptura_ob_sweep, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(price_1_oba, set_file.ReadParamValueInteger<ENUM_OB_STYLE>);
PARAM_ASSING(price_2_oba, set_file.ReadParamValueInteger<ENUM_OB_STYLE>);
PARAM_ASSING(price_1_obb, set_file.ReadParamValueInteger<ENUM_OB_STYLE>);
PARAM_ASSING(price_2_obb, set_file.ReadParamValueInteger<ENUM_OB_STYLE>);
PARAM_ASSING(obtencion_type_fvg, set_file.ReadParamValueInteger<ENUM_MODO_OBTENCION_IMBALANCE>);
PARAM_ASSING(mode_min_diff_fvg, set_file.ReadParamValueInteger<ENUM_MODE_DIFF>);
PARAM_ASSING(atr_mul_or_dist_point_fvg, set_file.ReadParamValueReal<double>);
PARAM_ASSING(lenth_swings_bb, set_file.ReadParamValueInteger<int16_t>);
PARAM_ASSING(max_esperar_roptura_bb_swep, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(mode_swings_bos_choch, set_file.ReadParamValueInteger<MODE_BUSQUEDA_SWING>);
PARAM_ASSING(lenth_bos_choch, set_file.ReadParamValueInteger<int16_t>);
PARAM_ASSING(max_espera_bos_choch, set_file.ReadParamValueInteger<int>);
PARAM_ASSING(seg_antes_despues, set_file.ReadParamValueInteger<uint8_t>);
#undef PARAM_ASSING // PARAM_ASSING
}
//--- BosChoch
g_bos_choch.Create(_Symbol, _Period);
g_bos_choch.SetGrapich(clr_Choch, clr_Bos, clr_Choch_2, clr_Bos_2, line_style_bos_choch);
g_bos_choch.Init(lenth_bos_choch_opt, clrRed, clrBlue, "Arial", 8, false, max_espera_bos_choch_opt, mode_swings_bos_choch_opt, false, 500);
//--- Sesion operativa
g_sesion.Create(_Symbol, _Period, 0, 0, true, true, InpOperativeSessionStartHour_opt, InpOperativeSessionStartMinute_opt, InpOperativeSessionEndHour_opt, InpOperativeSessionEndMinute_opt,
InpOperativeSessionName);
g_sesion.SetExtra(InpOperativeSessionLineColor, InpOperativeSessionLineColor, STYLE_SOLID, 1, InpOperativeSessionDrawStyle);
g_sesion.SetGrapichStyles(STYLE_SOLID, InpOperativeSessionRectColor, 1, true);
//---
switch(InpStrategyEntryType_opt)
{
case ENTRADA_OB_FVG:
{
g_bloque1 = new COrderBlockBar();
COrderBlockBar* ob = (COrderBlockBar*)g_bloque1;
ob.Create(_Symbol, _Period, 0, 0, true);
ob.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.SetTypeBusqueda(mod_obtencion_obs_opt);
ob.SetStylesPrices(price_1_oba_opt, price_1_obb_opt, price_2_oba_opt, price_2_obb_opt);
ob.SetOrderBlockSweep(lenth_order_block_opt, max_espera_roptura_ob_sweep_opt, breakout_type_ob_opt);
ob.Set(500);
//---
g_bloque2 = new CFvgBar();
CFvgBar* fvg = (CFvgBar*)g_bloque2;
fvg.Create(_Symbol, _Period);
fvg.Set(500, obtencion_type_fvg_opt, style_draw_fvg, CreateDiffptr(mode_min_diff_fvg_opt, _Symbol, atr_h, 1, atr_mul_or_dist_point_fvg_opt));
fvg.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);
break;
}
case ENTRADA_FVG_BB:
{
g_bloque1 = new CBreakerBlocks();
CBreakerBlocks* new_breaker = (CBreakerBlocks*)g_bloque1;
new_breaker.CreateSweep(_Symbol, _Period, 0, 0, true);
new_breaker.SetGrapich(color_breaker_block_alcista, color_breaker_block_bajista, color_breaker_block_alcista_mitad, color_breaker_block_bajista_mitad, style_brekare_block, fill_breaker_block,
1, true, minutos_eliminar_breaker_block);
new_breaker.SetBreakerBySwing(lenth_swings_bb_opt, max_esperar_roptura_bb_swep_opt);
//---
g_bloque2 = new CFvgBar();
CFvgBar* fvg = (CFvgBar*)g_bloque2;
fvg.Create(_Symbol, _Period);
fvg.Set(500, obtencion_type_fvg_opt, style_draw_fvg, CreateDiffptr(mode_min_diff_fvg_opt, _Symbol, atr_h, 1, atr_mul_or_dist_point_fvg_opt));
fvg.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);
break;
}
case ENTRADA_BB_OB:
{
g_bloque1 = new COrderBlockBar();
COrderBlockBar* ob = (COrderBlockBar*)g_bloque1;
ob.Create(_Symbol, _Period, 0, 0, true);
ob.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.SetTypeBusqueda(mod_obtencion_obs_opt);
ob.SetStylesPrices(price_1_oba_opt, price_1_obb_opt, price_2_oba_opt, price_2_obb_opt);
ob.SetOrderBlockSweep(lenth_order_block_opt, max_espera_roptura_ob_sweep_opt, breakout_type_ob_opt);
ob.Set(500);
//---
g_bloque2 = new CBreakerBlocks();
CBreakerBlocks* new_breaker = (CBreakerBlocks*)g_bloque2;
new_breaker.CreateSweep(_Symbol, _Period, 0, 0, true);
new_breaker.SetGrapich(color_breaker_block_alcista, color_breaker_block_bajista, color_breaker_block_alcista_mitad, color_breaker_block_bajista_mitad, style_brekare_block, fill_breaker_block,
1, true, minutos_eliminar_breaker_block);
new_breaker.SetBreakerBySwing(lenth_swings_bb_opt, max_esperar_roptura_bb_swep_opt);
break;
}
default:
FastLog(FUNCION_ACTUAL, ERROR_TEXT, "Tipo de entrada invalido");
return INIT_PARAMETERS_INCORRECT;
}
//---
CAutoCleaner::AddPtr(g_bloque1);
CAutoCleaner::AddPtr(g_bloque2);
//--- Risk management
CRiskPointer* manager = new CRiskPointer(InpMagic, InpRmGetMode);
manager.SetPropirm(InpRmPropFirmBalance);
risk = manager.GetRiskPointer(InpRmRiskMode);
risk.AddLogFlags(InpRmLogLevel);
risk.SetLote(CreateLotePtr(_Symbol));
// We set the parameters
string to_apply = InpRmStrPercentagesToApply, to_modfied = InpRmStrPercentagesToBeReviewed;
if(InpRmModeGmlpo == DYNAMIC_GMLPO_FIXED_PARAMETERS)
SetDynamicUsingFixedParameters(InpRmBalancePercentageToActivateTheRisk1, InpRmBalancePercentageToActivateTheRisk2, InpRmBalancePercentageToActivateTheRisk3
, InpRmBalancePercentageToActivateTheRisk4, InpRmPercentageToBeModified1, InpRmPercentageToBeModified2, InpRmPercentageToBeModified3, InpRmPercentageToBeModified4
, to_modfied, to_apply);
risk.AddLoss(InpRmPercentageOrMoneyMdl, InpRmAppliedPercentagesMdl, InpRmModeCalculationMdl, LP_MDL, true);
risk.AddLoss(InpRmPercentageOrMoneyGmlpo, InpRmAppliedPercentagesGmlpo, InpRmModeCalculationGmlpo, LP_GMLPO, true, (InpRmModeGmlpo != NO_DYNAMIC_GMLPO), to_modfied, to_apply);
risk.AddLoss(InpRmPercentageOrMoneyMl, InpRmAppliedPercentagesMl, InpRmModeCalculationMl, LP_ML, true);
risk.AddLoss(InpRmPercentageOrMoneyMwl, InpRmAppliedPercentagesMwl, InpRmModeCalculationMwl, LP_MWL, true);
risk.AddProfit(InpRmPercentageOrMoneyMdp, InpRmAppliedPercentagesMdp, InpRmModeCalculationMdp, LP_MDP, InpRmMdpIsStrict);
risk.EndAddProfitLoss(); // Execute this every time we finish setting the maximum losses and profits
g_loss_profit_manager = risk.GetLossProfitManager();
// We finish by adding it
CAutoCleaner::AddPtr(risk);
// We delete the temporary pointer
delete manager;
//--- We initialize the account
account_status.AddLogFlags(InpAccountStatusLogLevel);
account_status.OnInitEvent();
//---
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))
{
if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_bar_controlerd1))
{
CBasicEvents::OnNewDay(time_curr);
//--- Calendario
if(g_ai_enable)
{
g_calendar.OnNewDay();
if(g_calendar.GetEventsToday(g_calendar_events))
{
CNewsEvents::OnNewsToday(g_calendar_events);
}
}
//---
if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_controler_w1)) //Limpiar para no acomular mucha memoria
{
CBasicEvents::OnNewWeek(time_curr);
}
//--- Nuevo mes, eliminacion de liquidez
if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_bar_mn1))
CBasicEvents::OnNewMonth(time_curr);
//---
CanTrade = true;
NewDay = true;
}
}
//---
if(account_status_positions_open)
{
CAccountStatus_OnTickEvent
if(CanTrade)
{
if(g_loss_profit_manager.MaxLossIsSuperated())
{
const int type = g_loss_profit_manager.GetLastLossSuperatedType();
if(type == LP_ML)
{
if(InpRmRiskMode == risk_mode_propfirm_dynamic_daiy_loss)
{
Print("The expert advisor lost the funding test");
}
else
{
Print("Maximum loss exceeded now");
}
//---
Remover();
}
else
if(type == LP_MDL)
{
Print("Maximum daily loss exceeded now");
}
//---
strategy.OnInterupcion();
risk.CloseAllPositions();
CanTrade = false;
}
else
if(g_loss_profit_manager.MaxProfitIsSuperated())
{
if(g_loss_profit_manager.GetLastProfitSuperatedType() != LP_MDP)
return;
//---
strategy.OnInterupcion();
risk.CloseAllPositions();
Print("Excellent Maximum daily profit achieved");
CanTrade = false;
}
}
}
//--- Bloque 2 | Verifiacion
if(!CanTrade) // Si se superaron los limites de MDL, o MDP enotnces no CanTrader
return;
///--- Solo ejeuctar si la ia esta habilitada
if(g_ai_enable)
{
//--- Calendario
g_calendar.OnTickEvent(time_curr);
// Principal
if(g_calendar.NewsIsComming())
{
const int res = g_calendar.GetEvents(g_calendar_events, false); // Aqui no hace falta obtener los eventos
if(res == EVENTOS_NO_SE_OBTUVIERON_LA_BANDERA_DE_OBTENCION_ES_FALSA || res == EVENTOS_OBTENIDOS_EXITOSAMENTE)
{
CNewsEvents::OnNews(g_calendar_events, res, time_curr);
}
//CiNews_RevisedInformation(Porcentage_Events);
g_calendar.OnEndNews();
ArrayResize(g_calendar_events, 0);
}
}
//---
if(CNewBarManager_IsNewBarM1(g_new_bar_manager))
{
ICTGen_FuncionOnBarM1(NewDay, time_curr);
g_sesion.OnNewBarM1();
//---
strategy.OnNewBarM1(time_curr);
//---
if(CNewBarManager_IsNewBar(g_new_bar_manager, idx_controler_curr))
{
//--- Dado que el timeframe es inmutalbe y siempre es curr entonces lo ponemos aqui
g_bloque1.OnNewBar();
g_bloque2.OnNewBar();
g_bos_choch.OnNewBar();
//---
strategy.OnNewBar(time_curr);
}
}
}
//+------------------------------------------------------------------+
//| TradeTransaction function |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction & trans,
const MqlTradeRequest & request,
const MqlTradeResult & result)
{
//---
account_status.OnTradeTransactionEvent(trans);
}
//+------------------------------------------------------------------+
//| Tester function |
//+------------------------------------------------------------------+
double OnTester()
{
//---
if(InpCIGenerateOutputResFile)
{
// Especifico para el CI
BackRes backre;
backre.Collect();
backre.Save("EasySbAiCI\\ComunicationTester\\back_test.bin", false);
}
//---
return(0.00);
}
//+------------------------------------------------------------------+