Las matemáticas de la volatilidad: Por qué el indicador GRI merece volver a su terminal de trading
Índice
- Introducción
- Implementación del indicador para MetaTrader 5
- Particularidades de la interpretación
- Prueba del indicador en un asesor experto
- Conclusión
Introducción
En el trading actual, no solo es importante determinar la dirección del movimiento del precio, sino también comprender hasta qué punto el mercado está "vivo" o es "caótico" en ese momento. Muchos operadores se enfrentan a situaciones en las que los indicadores estándar no ofrecen una respuesta clara: si cabe esperar un movimiento fuerte o si el mercado se encuentra en una fase de calma. Si se busca una herramienta sencilla y clara para evaluar la volatilidad y el "carácter caótico" del mercado, cabe destacar el indicador Gopalakrishnan Range Index (GRI), también conocido como Range of Chaos Index (ROCI).
El GRI se publicó por primera vez en enero de 2001 en la prestigiosa revista Technical Analysis of Stocks & Commodities (TASC). Su autora es Jayanthi Gopalakrishnan, una reconocida analista y editora de TASC. En aquel momento, el indicador se presentó como una forma sencilla de evaluar cuantitativamente el "carácter caótico" (rango) del movimiento del precio durante un período determinado. A pesar de su sencillez y claridad, el GRI no ha alcanzado una gran popularidad y rara vez se encuentra en las plataformas de negociación y estrategias actuales.
A lo largo de la historia del análisis técnico ha habido numerosos instrumentos que se crearon en una época en la que no existían ordenadores potentes ni algoritmos complejos. Se caracterizan por su sencillez, la claridad de su lógica y su versatilidad. Indicadores como el GRI pueden implementarse fácilmente en los terminales de trading actuales, y sus conceptos pueden adaptarse a las nuevas condiciones del mercado. A veces, precisamente las herramientas olvidadas se convierten en la clave del éxito cuando los métodos habituales dejan de dar el resultado deseado.
Implementación del indicador para MetaTrader 5
El GRI mide la magnitud de la variación del precio de cierre durante el periodo seleccionado (ChaoticPeriod), normalizando ese rango en una escala logarítmica.
Fórmula para calcular el indicador:
GRI = log10(High(Close, N) - Low(Close, N)) / log10(N)
donde:
- High(Close, N) — el valor máximo del precio de cierre en las últimas N barras,
- Low(Close, N) — el valor mínimo del precio de cierre en las últimas N barras,
- N: período de cálculo (ChaoticPeriod).
Lógica del cálculo:
- Para cada barra, calculamos los valores máximo y mínimo del precio de cierre de las últimas N barras.
- Calculamos el rango (la diferencia entre el máximo y el mínimo).
- Calculamos el logaritmo decimal del rango y lo dividimos por el logaritmo del período.
- Si el rango es igual a cero, el indicador devuelve 0.
Basándonos en las fórmulas y la lógica expuestas anteriormente, crearemos un indicador para MetaTrader 5:
//+------------------------------------------------------------------+ //| GRI.mq5 | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property indicator_separate_window #property indicator_buffers 1 #property indicator_plots 1 //--- plot GRI #property indicator_label1 "GRI" #property indicator_type1 DRAW_LINE #property indicator_color1 clrDodgerBlue #property indicator_style1 STYLE_SOLID #property indicator_width1 1 //--- input parameters input(name="ChaoticPeriod") int InpPeriod = 5; // Calculation period //--- indicator buffers double BufferGRI[]; //--- global variables int ExtPeriod; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- indicator buffers mapping SetIndexBuffer(0,BufferGRI,INDICATOR_DATA); ArraySetAsSeries(BufferGRI,true); // Buffer as a time series //--- Setting the indicator parameters ExtPeriod=(InpPeriod<2 ? 2 : InpPeriod); // Adjust the calculation period string short_name=StringFormat("GRI(%d)",ExtPeriod); // Define a short name IndicatorSetString(INDICATOR_SHORTNAME,short_name); // Set the short name IndicatorSetInteger(INDICATOR_DIGITS,_Digits); // Display accuracy //--- Completed successfully return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int32_t rates_total, const int32_t prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int32_t &spread[]) { //--- Close array as a time series ArraySetAsSeries(close,true); //--- Check the number of available bars if(rates_total<fmax(ExtPeriod,5)) return 0; //--- Check and calculate the number of bars to process int limit=rates_total-prev_calculated; //--- If this is the first launch or the historical data has changed if(limit>1) { limit=rates_total-ExtPeriod-1; // Start the calculation from the beginning of the historical data ArrayInitialize(BufferGRI,EMPTY_VALUE); // Initialize the indicator buffer with an empty value } //--- Main loop for(int i=limit;i>=0;i--) { //--- Calculate the closing price range over ExtPeriod bars int mx=ArrayMaximum(close,i,ExtPeriod); int mn=ArrayMinimum(close,i,ExtPeriod); if(mx==WRONG_VALUE || mn==WRONG_VALUE) return 0; //--- Maximum and minimum Close values over the ExtPeriod period double max=close[mx]; double min=close[mn]; double range = max-min; //--- Calculate and write the ExtPeriod-bar “degree of chaos” value to the buffer BufferGRI[i]=(range>0 ? MathLog(range)/MathLog((double)ExtPeriod) : 0); } //--- Return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+
Cuanto mayor sea el valor del GRI, más "caótica" (volátil) habrá sido la evolución del precio durante ese periodo. Si el rango es pequeño, el GRI tiende a cero.
Particularidades de la interpretación
En el cálculo del GRI realizado en el código anterior, los valores del indicador pueden ser tanto positivos como negativos. Esto se debe a que, cuando los rangos de precios son pequeños (range < 1), el logaritmo se vuelve negativo. Como consecuencia, la escala del indicador no tiene un límite inferior y depende de la volatilidad del instrumento y del periodo seleccionado, lo que plantea algunos problemas a la hora de interpretar automáticamente los valores del indicador.

Sin embargo, resulta más práctico disponer de un valor de referencia al determinar los valores del indicador. Para ello, se puede establecer el valor mínimo del indicador en cero (es decir, hacer que la escala comience en cero).
Para ello, se puede utilizar el logaritmo del rango desplazado:
GRI = log10(1 + High(Close, N) - Low(Close, N)) / log10(N)
Con esta fórmula, el cálculo del indicador será el siguiente:
//--- Main loop for(int i=limit;i>=0;i--) { //--- Calculate the range of closing prices over ExtPeriod bars int mx=ArrayMaximum(close,i,ExtPeriod); int mn=ArrayMinimum(close,i,ExtPeriod); if(mx==WRONG_VALUE || mn==WRONG_VALUE) return 0; //--- Maximum and minimum Close values over the ExtPeriod period double max=close[mx]; double min=close[mn]; double range = max-min; //--- Calculate and store in a buffer the "degree of chaos" value over ExtPeriod bars //BufferGRI[i]=(range>0 ? MathLog(range)/MathLog((double)ExtPeriod) : 0); // Arbitrary range BufferGRI[i] = MathLog(1.0 + range) / MathLog((double)ExtPeriod); // Value range from zero upward }
Ahora el indicador siempre tendrá valores mínimos que tienden a cero, lo que facilitará su interpretación sin necesidad de observarlo visualmente, ya que siempre hay un valor del que partir a la hora de calcular los valores umbral:

Los valores elevados del GRI (picos bruscos en el gráfico del indicador) indican que, durante el periodo seleccionado, el mercado fue muy volátil y se produjeron fuertes movimientos del precio. Esto puede ser un indicio del inicio o la continuación de una tendencia, de la publicación de noticias importantes o, simplemente, de una fase de gran actividad en el mercado.
Los valores bajos del GRI (tramos planos, cercanos a cero) indican que el mercado se encuentra en una fase de consolidación, de "calma", en la que el precio se mueve dentro de un rango estrecho. En momentos como estos, suele observarse la ausencia de una tendencia clara.
Hay otro aspecto que me gustaría señalar y corregir. Este cálculo da como resultado valores del indicador demasiado bajos:
BufferGRI[i] = MathLog(1.0 + range) / MathLog((double)ExtPeriod); // A range of values from zero upward
Para facilitar la configuración de los valores umbral, es mejor expresarlos en una escala acorde con los puntos del símbolo. Para ello, basta con dividir el valor final entre el valor de Point:
BufferGRI[i] = (MathLog(1.0 + range)/MathLog((double)ExtPeriod))/_Point; // A range of values from zero upward
Al calcular el indicador de esta forma y utilizarlo en el asesor experto, se podrán introducir valores como 10, 50, 100, 150, etc., en la configuración del asesor experto. Es más cómodo que introducir valores fraccionarios pequeños.
Veamos algunos casos prácticos de aplicación del indicador.
- Filtrado de señales de otros indicadores.
El GRI puede utilizarse como filtro en estrategias de seguimiento de tendencias; por ejemplo, para abrir operaciones solo cuando el GRI supere un nivel determinado, lo que indica la presencia de volatilidad y potencial de movimiento. - Búsqueda de puntos de entrada y salida.
Un pico del GRI tras un largo periodo de calma puede señalar el inicio de un nuevo movimiento y constituir un punto de entrada. Por el contrario, una caída brusca del GRI tras un fuerte movimiento puede indicar el fin del impulso, lo que supone un motivo para realizar beneficios. - Determinación de la fase del mercado.
Si el GRI se mantiene bajo durante un periodo prolongado, lo más probable es que se trate de un mercado lateral. En estos periodos, es mejor evitar las estrategias de seguimiento de tendencias y recurrir a métodos pensados para operar dentro de un rango. - Adaptación de los parámetros de los sistemas de trading.
Es posible modificar dinámicamente los parámetros de otros indicadores o asesores expertos en función del valor actual del GRI; por ejemplo, aumentar el stop loss y el take profit cuando la volatilidad es alta y reducirlos cuando es baja.
El indicador solo tiene un parámetro configurable: el período de cálculo (ChaoticPeriod).
Un período corto (3–5) hace que el indicador sea más sensible a los picos locales, mientras que un período largo (10–20) suaviza los valores y muestra cambios más generales en la volatilidad.
Para determinar los estados del indicador, es necesario seleccionar los valores umbral adecuados de GRI. Los niveles óptimos del indicador pueden variar en función del instrumento y del marco temporal. Se recomienda realizar un análisis visual del historial y seleccionar niveles que distingan claramente las fases de alta y baja volatilidad.
Para aumentar la precisión de las señales, es necesario utilizar el GRI junto con indicadores de tendencia y osciladores.
No conviene utilizar el GRI como única fuente de señales, ya que solo indica hasta qué punto el movimiento del precio es “caótico”, pero no su dirección.
Se recomienda probar el indicador con datos históricos y ajustar los parámetros a su estilo de trading y al instrumento utilizado.
Intentemos desarrollar un sistema de trading sencillo utilizando este indicador y probémoslo en un asesor experto.
Probamos el indicador en el asesor experto
Para probar el indicador GRI, crearemos un asesor experto que opere siguiendo las señales de dos medias móviles: la TEMA y la AMA. La idea del sistema de trading será la siguiente: la TEMA muestra la dirección del movimiento (al alza o a la baja), mientras que la AMA filtra las señales, confirmándolas mediante la posición del precio respecto a su línea.
El indicador GRI se utilizará como filtro del estado del mercado: si, según el indicador, el mercado está activo (la volatilidad está aumentando o comienza un nuevo impulso de aumento de la volatilidad), se permite operar. Si la volatilidad del mercado empieza a disminuir, la actividad se atenúa o la volatilidad cae durante varios períodos consecutivos, se prohíbe operar.
El asesor experto funcionará según la siguiente lógica:
- Si la TEMA sube y el precio se sitúa por encima de la AMA ascendente, se trata de una señal de compra.
- Si la TEMA baja y el precio se sitúa por debajo de la AMA descendente, se trata de una señal de venta.
- Antes de abrir una operación, se comprueba la situación del mercado según el GRI. Si el indicador muestra un aumento o el inicio de un aumento de la volatilidad, se abre una posición en la dirección de las medias móviles.
Si la volatilidad desciende o el mercado es lateral, el asesor experto no opera. - El stop loss y el take profit se calculan automáticamente a partir de los valores de los indicadores Bollinger Bands y ATR, respectivamente, o bien se utilizan los valores establecidos en puntos.
De este modo, el asesor experto solo abrirá posiciones cuando haya una señal confirmada de las medias móviles y el mercado esté activo según el indicador GRI. Esto permitirá evitar operar en las fases "inactivas" del mercado o cuando su actividad se esté atenuando, y operar en los momentos en los que es más probable que se produzca un movimiento. El filtrado de señales mediante el GRI se podrá desactivar, lo que permitirá realizar pruebas sobre un tramo de datos históricos tanto con este filtrado como sin él.
Se podrán abrir simultáneamente posiciones en ambas direcciones: tanto largas como cortas. El asesor experto no supervisará si el mercado es lateral o presenta una tendencia, ni los cambios de la tendencia actual, ni su presencia o ausencia. La dirección de la posición se determinará en función de dos medias móviles, y la decisión de entrar en el mercado en esa dirección dependerá del estado del indicador GRI (si el filtro está activado).
Analicemos el código del asesor experto en su totalidad:
//+------------------------------------------------------------------+ //| ExpGRI_AMA_TEMA.mq5 | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" //+------------------------------------------------------------------+ //| Included files | //+------------------------------------------------------------------+ #include <Trade\Trade.mqh> #include <Arrays\ArrayLong.mqh> //+------------------------------------------------------------------+ //| Enumerations | //+------------------------------------------------------------------+ //--- GRI states enum ENUM_GRI_STATE { GRI_STATE_UNKNOWN, // No data available GRI_STATE_FLAT, // Low volatility GRI_STATE_VOLATILITY_HIGH, // High volatility GRI_STATE_GROWING, // Volatility is rising GRI_STATE_FALLING, // Volatility is falling GRI_STATE_TURN_TO_GROW, // Transition to increasing volatility GRI_STATE_TURN_TO_FALL // Transition to declining volatility }; //--- Types of moving average signals enum ENUM_SIGNAL_TYPE { SIGNAL_TYPE_NONE, // No signal SIGNAL_TYPE_LONG, // Buy signal SIGNAL_TYPE_SHORT, // Sell signal SIGNAL_TYPE_CLOSE, // Signal to close positions }; //--- Position structure struct SData { CArrayLong list_tickets; // List of open position tickets double total_volume; // Total volume of open positions }; //--- Position data structure by type struct SDataPositions { SData Buy; // Buy position data SData Sell; // Sell position data } Data; //+------------------------------------------------------------------+ //| Macro definitions | //+------------------------------------------------------------------+ #define DATA_COUNT 3 // Amount of data obtained from the indicators (3 and more) #define ENV_ATTEMPTS 3 // Number of environment retrieval attempts #define ENV_WAIT_ATTEMPT 1000 // Number of milliseconds spent on waiting for environment update #define SPREAD_MLTP 3 // Spread multiplier for stop order distance //+------------------------------------------------------------------+ //| Input parameters | //+------------------------------------------------------------------+ //--- GRI input int InpPeriodGRI = 9; /* GRI calculation period */ input bool InpUseGRI = true; /* Use GRI filtering */ input double InpThresholdGRI = 50.0; /* GRI volatility threshold */ //--- TEMA - indicates the trading direction input int InpPeriodTEMA = 14; /* TEMA calculation period */ input ENUM_APPLIED_PRICE InpPriceTEMA = PRICE_CLOSE; /* TEMA applied price */ input int InpShiftTEMA = 0; /* TEMA shift */ //--- AMA - filters signals based on whether the price is above or below it input int InpPeriodAMA = 9; /* AMA calculation period */ input int InpFastEmaAMA = 2; /* AMA fast EMA period */ input int InpSlowEmaAMA = 30; /* AMA slow EMA period */ input ENUM_APPLIED_PRICE InpPriceAMA = PRICE_CLOSE; /* AMA applied price */ input int InpShiftAMA = 0; /* AMA shift */ //--- BB - sets stops based on values input int InpPeriodBB = 58; /* BB calculation period */ input double InpDeviationBB = 2.0; /* BB deviations */ input int InpShiftBB = 0; /* BB shift */ input ENUM_APPLIED_PRICE InpPriceBB = PRICE_CLOSE; /* BB applied price */ //--- ATR - calculates the take profit size based on the value input int InpPeriodATR = 64; /* ATR calculation period */ //--- Trading input double InpVolume = 0.1; /* Position volume */ sinput ulong InpDeviation = 10; /* Slippage (in points) */ sinput ulong InpMagic = 123456; /* Magic number */ input int InpStopLoss = -1; /* Stop loss (in points), 0 - none, -1 - half of BB */ input int InpTakeProfit = -1; /* Take profit (in points), 0 - none, -1 - ATR value */ input double InpSLMltp = 2.6; /* Stop-loss size multiplier, if SL == -1 */ input double InpTPMltp = 1.3; /* Take-profit size multiplier, if TP == -1 */ //+------------------------------------------------------------------+ //| Global variables | //+------------------------------------------------------------------+ CTrade trade; // Trading class object int handle_gri; // GRI indicator handle int handle_tema; // TEMA indicator handle int handle_ama; // AMA indicator handle int handle_bb; // BB indicator handle int handle_atr; // ATR indicator handle double gri[DATA_COUNT]={}; // Array of GRI values double tema[DATA_COUNT]={}; // Array of TEMA values double ama[DATA_COUNT]={}; // Array of AMA values double bb0[DATA_COUNT]={}; // Array of BB values, buffer 0 (Upper) double bb1[DATA_COUNT]={}; // Array of BB values, buffer 1 (Lower) double bb2[DATA_COUNT]={}; // Array of BB values, buffer 2 (Middle) double atr[DATA_COUNT]={}; // Array of ATR values MqlRates prc[DATA_COUNT]={}; // Array of prices and times //--- GRI int period_gri; // GRI calculation period //--- TEMA int period_tema; // TEMA calculation period //--- AMA int period_ama; // AMA calculation period int fast_ema_ama; // AMA fast EMA period int slow_ema_ama; // AMA slow EMA period //--- BB int period_bb; // BB calculation period double deviation_bb; // BB deviations int shift_bb; // BB shift //--- ATR int period_atr; // ATR calculation period //--- double lot; // Position volume int prev_total; // Number of positions at the previous check string program_name; // Program name bool netto; // Netting account flag //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- If the account is not a hedging account, set a flag and report that the EA will not operate correctly netto=false; if(AccountInfoInteger(ACCOUNT_MARGIN_MODE)!=ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) { Print("The EA is designed for use on a hedging account. Correct operation on a netting account is not guaranteed."); netto=true; } //--- Set and adjust the indicator input variables //--- GRI period_gri=(InpPeriodGRI<1 ? 5 : InpPeriodGRI); //--- TEMA period_tema=(InpPeriodTEMA<1 ? 14 : InpPeriodTEMA); //--- AMA period_ama=(InpPeriodAMA<1 ? 9 : InpPeriodAMA); fast_ema_ama=(InpFastEmaAMA<1 ? 2 : InpFastEmaAMA); slow_ema_ama=(InpSlowEmaAMA<1 ? 30 : InpSlowEmaAMA); //--- BB period_bb=(InpPeriodBB<2 ? 20 : InpPeriodBB); deviation_bb=InpDeviationBB; shift_bb=InpShiftBB; //--- ATR period_atr=(InpPeriodATR<1 ? 14 : InpPeriodATR); //--- Initialize the arrays of indicator values ArrayInitialize(gri,EMPTY_VALUE); ArrayInitialize(tema,EMPTY_VALUE); ArrayInitialize(bb0,EMPTY_VALUE); ArrayInitialize(bb1,EMPTY_VALUE); ArrayInitialize(bb2,EMPTY_VALUE); ArrayInitialize(atr,EMPTY_VALUE); ZeroMemory(prc); //--- Create indicator handles //--- GRI handle_gri=iCustom(Symbol(),PERIOD_CURRENT,"GRI",period_gri); if(handle_gri==INVALID_HANDLE) { PrintFormat("%s: Failed to create handle for custom GRI(%d) indicator",__FUNCTION__,period_gri); return INIT_FAILED; } //--- TEMA handle_tema=iTEMA(Symbol(),PERIOD_CURRENT,period_tema,InpShiftTEMA,InpPriceTEMA); if(handle_tema==INVALID_HANDLE) { PrintFormat("%s: Failed to create iTEMA(%d) handle",__FUNCTION__,period_tema); return INIT_FAILED; } //--- AMA handle_ama=iAMA(Symbol(),PERIOD_CURRENT,period_ama,fast_ema_ama,slow_ema_ama,InpShiftAMA,InpPriceAMA); if(handle_ama==INVALID_HANDLE) { PrintFormat("%s: Failed to create iAMA(%d,%d,%d) handle",__FUNCTION__,period_ama,fast_ema_ama,slow_ema_ama); return INIT_FAILED; } //--- BB handle_bb=iBands(Symbol(),PERIOD_CURRENT,period_bb,InpShiftBB,InpDeviationBB,InpPriceBB); if(handle_bb==INVALID_HANDLE) { PrintFormat("%s: Failed to create iBands(%d,%d,%.3f,%s) handle",__FUNCTION__,period_bb,shift_bb,deviation_bb,EnumToString(InpPriceBB)); return INIT_FAILED; } //--- ATR handle_atr=iATR(Symbol(),PERIOD_CURRENT,period_atr); if(handle_atr==INVALID_HANDLE) { PrintFormat("%s: Failed to create iATR(%d) handle",__FUNCTION__,period_atr); return INIT_FAILED; } //--- Program name and number of positions at the previous check program_name=MQLInfoString(MQL_PROGRAM_NAME); prev_total=0; //--- Automatic setting of the order filling type trade.SetTypeFilling(GetTypeFilling()); //--- Set the magic number trade.SetExpertMagicNumber(InpMagic); //--- Set slippage trade.SetDeviationInPoints(InpDeviation); //--- Set the lot size with adjustment of the entered value lot=CorrectLots(InpVolume); //--- Completed successfully PrintFormat("%s::%s: Initialization was successful",program_name,__FUNCTION__); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- Get data for three bars of indicators and prices into arrays if(!CopyIndicatorsData() || !CopyPricesData()) return; //--- Fill the position ticket lists int positions_total=PositionsTotal(); if(prev_total!=positions_total) { if(!FillingListTickets(Symbol(),InpMagic)) return; prev_total=positions_total; } //--- Get signals from indicators ENUM_SIGNAL_TYPE signal_tema=SignalTEMA(); // Upward/downward direction (SIGNAL_TYPE_LONG/SIGNAL_TYPE_SHORT) ENUM_SIGNAL_TYPE signal_ama =SignalAMA(); // Price above/below (SIGNAL_TYPE_LONG/SIGNAL_TYPE_SHORT) //--- The signals from TEMA and AMA must match (TEMA: direction; AMA: price position (above/below)) ENUM_SIGNAL_TYPE signal=(signal_tema==signal_ama ? signal_tema : SIGNAL_TYPE_NONE); //--- If GRI filtering is enabled if(InpUseGRI) { //--- Adjust the signal based on the GRI state signal=SignalCorrectionByGRI(signal); //--- Adjust the signal based on the GRI volatility threshold if(!IsHighVolatility(InpThresholdGRI) && signal!=SIGNAL_TYPE_CLOSE) signal=SIGNAL_TYPE_NONE; } //--- Trade based on signals TradeProcess(signal); } //+------------------------------------------------------------------+ //| Retrieve OHLCTV values for three bars | //+------------------------------------------------------------------+ bool CopyPricesData(void) { ResetLastError(); if(CopyRates(Symbol(),PERIOD_CURRENT,0,DATA_COUNT,prc)!=DATA_COUNT) { PrintFormat("%s: Failed to get price Open data. Error %d",__FUNCTION__,GetLastError()); return false; } return true; } //+------------------------------------------------------------------+ //| Retrieve GRI values for three bars | //+------------------------------------------------------------------+ bool CopyGRIData(void) { ResetLastError(); if(CopyBuffer(handle_gri,0,0,DATA_COUNT,gri)!=DATA_COUNT) { PrintFormat("%s: Failed to get GRI data. Error %d",__FUNCTION__,GetLastError()); return false; } return true; } //+------------------------------------------------------------------+ //| Retrieve TEMA values for three bars | //+------------------------------------------------------------------+ bool CopyTEMAData(void) { ResetLastError(); if(CopyBuffer(handle_tema,0,0,DATA_COUNT,tema)!=DATA_COUNT) { PrintFormat("%s: Failed to get TEMA data. Error %d", __FUNCTION__, GetLastError()); return false; } return true; } //+------------------------------------------------------------------+ //| Retrieve TEMA values for three bars | //+------------------------------------------------------------------+ bool CopyAMAData(void) { ResetLastError(); if(CopyBuffer(handle_ama,0,0,DATA_COUNT,ama)!=DATA_COUNT) { PrintFormat("%s: Failed to get AMA data. Error %d", __FUNCTION__, GetLastError()); return false; } return true; } //+------------------------------------------------------------------+ //| Retrieve BB values for three bars | //+------------------------------------------------------------------+ bool CopyBBData(void) { ResetLastError(); if(CopyBuffer(handle_bb,UPPER_BAND,0,DATA_COUNT,bb0)!=DATA_COUNT) { PrintFormat("%s: Failed to get BB Upper Line data. Error %d",__FUNCTION__,GetLastError()); return false; } if(CopyBuffer(handle_bb,LOWER_BAND,0,DATA_COUNT,bb1)!=DATA_COUNT) { PrintFormat("%s: Failed to get BB Lower Line data. Error %d",__FUNCTION__,GetLastError()); return false; } if(CopyBuffer(handle_bb,BASE_LINE,0,DATA_COUNT,bb2)!=DATA_COUNT) { PrintFormat("%s: Failed to get BB Base Line data. Error %d",__FUNCTION__,GetLastError()); return false; } return true; } //+------------------------------------------------------------------+ //| Retrieve ATR values for three bars | //+------------------------------------------------------------------+ bool CopyATRData(void) { ResetLastError(); if(CopyBuffer(handle_atr,0,0,DATA_COUNT,atr)!=DATA_COUNT) { PrintFormat("%s: Failed to get ATR data. Error %d",__FUNCTION__,GetLastError()); return false; } return true; } //+------------------------------------------------------------------+ //| Retrieve indicator values for three bars | //+------------------------------------------------------------------+ bool CopyIndicatorsData(void) { bool res=CopyTEMAData(); // Result of retrieving TEMA data res &=CopyAMAData(); // Result of retrieving AMA data res &=CopyGRIData(); // Result of retrieving GRI data res &=CopyBBData(); // Result of retrieving BB data res &=CopyATRData(); // Result of retrieving ATR data return res; } //+------------------------------------------------------------------+ //| Return the Open price from the array by time series index (0–2) | //+------------------------------------------------------------------+ double PriceOpen(const int index) { return(index<0 || index>DATA_COUNT-1 ? 0 : prc[DATA_COUNT-index-1].open); } //+------------------------------------------------------------------+ //|Return the High price from the array by time series index (0–2) | //+------------------------------------------------------------------+ double PriceHigh(const int index) { return(index<0 || index>DATA_COUNT-1 ? 0 : prc[DATA_COUNT-index-1].high); } //+------------------------------------------------------------------+ //| Return the Low price from the array by time series index (0–2) | //+------------------------------------------------------------------+ double PriceLow(const int index) { return(index<0 || index>DATA_COUNT-1 ? 0 : prc[DATA_COUNT-index-1].low); } //+------------------------------------------------------------------+ //| Return the Close price from the array by time series index (0–2) | //+------------------------------------------------------------------+ double PriceClose(const int index) { return(index<0 || index>DATA_COUNT-1 ? 0 : prc[DATA_COUNT-index-1].close); } //+------------------------------------------------------------------+ //| Return the bar time from the array by time series index (0–2) | //+------------------------------------------------------------------+ datetime Time(const int index) { return(index<0 || index>DATA_COUNT-1 ? 0 : prc[DATA_COUNT-index-1].time); } //+------------------------------------------------------------------+ //| Return GRI data from the array by time series index (0–2) | //+------------------------------------------------------------------+ double GRI(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : gri[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| Return TEMA data from the array by time series index (0–2) | //+------------------------------------------------------------------+ double TEMA(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : tema[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| Return AMA data from the array by time series index (0–2) | //+------------------------------------------------------------------+ double AMA(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : ama[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| Return BB Upper data from the array by time series index (0–2) | //+------------------------------------------------------------------+ double BBUpper(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : bb0[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| Return BB Lower data from the array by timeseries index (0–2) | //+------------------------------------------------------------------+ double BBLower(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : bb1[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| Return BB Middle data from the array by timeseries index (0–2) | //+------------------------------------------------------------------+ double BBMiddle(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : bb2[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| Return half the BB width in points | //+------------------------------------------------------------------+ int HalfSizeBB(const int index) { double up=BBUpper(index); double dn=BBLower(index); if(up==EMPTY_VALUE || dn==EMPTY_VALUE) return 0; return (int)round(((up-dn)*0.5)/Point()); } //+------------------------------------------------------------------+ //| Return ATR data from the array by timeseries index (0–2) | //+------------------------------------------------------------------+ double ATR(const int index) { return(index<0 || index>DATA_COUNT-1 ? EMPTY_VALUE : atr[DATA_COUNT-index-1]); } //+------------------------------------------------------------------+ //| GRI state | //+------------------------------------------------------------------+ ENUM_GRI_STATE GRIState(void) { //--- Get GRI data double gri0=GRI(0); double gri1=GRI(1); double gri2=GRI(2); //--- Error retrieving data: no signal if(gri0==EMPTY_VALUE || gri1==EMPTY_VALUE || gri2==EMPTY_VALUE) return GRI_STATE_UNKNOWN; //--- Volatility is rising if(gri0>gri1 && gri1>gri2) return GRI_STATE_GROWING; //--- Volatility is declining if(gri0<gri1 && gri1<gri2) return GRI_STATE_FALLING; //--- Transition to increasing volatility (previously declining/flat, now rising) if(gri0>gri1 && gri1<=gri2) return GRI_STATE_TURN_TO_GROW; //--- Transition to declining volatility (previously rising/flat, now declining) if(gri0<gri1 && gri1>=gri2) return GRI_STATE_TURN_TO_FALL; //--- Flat/range-bound market return GRI_STATE_FLAT; } //+------------------------------------------------------------------+ //| Adjust the signal based on the GRI state | //+------------------------------------------------------------------+ ENUM_SIGNAL_TYPE SignalCorrectionByGRI(const ENUM_SIGNAL_TYPE signal_type) { //--- Current signal ENUM_SIGNAL_TYPE signal=signal_type; //--- Adjust the current signal depending on the GRI state ENUM_GRI_STATE state =GRIState(); switch(state) { //--- Transition to increasing volatility case GRI_STATE_TURN_TO_GROW : // Here, the signal remains unchanged, // but the start of the increase could be handled in some other way break; //--- Volatility is rising case GRI_STATE_GROWING : // Here, the signal remains unchanged, // but this constant growth can also be handled in some other way break; //--- High volatility case GRI_STATE_VOLATILITY_HIGH : // Here, the signal remains unchanged, // but high volatility can also be handled in some other way break; //--- Transition to declining volatility case GRI_STATE_TURN_TO_FALL : signal=SIGNAL_TYPE_NONE; // No signal // There is simply no signal here, // but this state can be handled differently, // for example, here you can close part of the position or move the stop to breakeven, // or do both break; //--- Volatility is falling case GRI_STATE_FALLING : signal=SIGNAL_TYPE_NONE; // No signal // There is simply no signal here, // but this state can be handled differently, // for example, enable a trailing stop or close positions: //signal=SIGNAL_TYPE_CLOSE; // Signal to close all positions (volatility has been declining for three consecutive bars) break; //--- Low volatility case GRI_STATE_FLAT : signal=SIGNAL_TYPE_NONE; // No signal // There is simply no signal here, // but this state can be handled differently, // for example, you can place pending orders here break; //--- GRI_STATE_UNKNOWN Error retrieving data default: signal=SIGNAL_TYPE_NONE; // No signal break; } return signal; } //+------------------------------------------------------------------+ //| GRI volatility threshold exceeded | //+------------------------------------------------------------------+ bool IsHighVolatility(double threshold) { //--- Retrieving GRI data double gri0=GRI(0); //--- Data retrieval error - false if(gri0==EMPTY_VALUE) return false; return(gri0>=threshold); } //+------------------------------------------------------------------+ //| TEMA signal | //+------------------------------------------------------------------+ ENUM_SIGNAL_TYPE SignalTEMA(void) { double tema0=TEMA(0); double tema1=TEMA(1); //--- Error - no signal if(tema0==EMPTY_VALUE || tema1==EMPTY_VALUE) return SIGNAL_TYPE_NONE; //--- Buy signal: TEMA is rising if(tema0>tema1) return SIGNAL_TYPE_LONG; //--- Sell signal: TEMA is falling if(tema0<tema1) return SIGNAL_TYPE_SHORT; //--- No signal return SIGNAL_TYPE_NONE; } //+------------------------------------------------------------------+ //| AMA signal | //+------------------------------------------------------------------+ ENUM_SIGNAL_TYPE SignalAMA(void) { double ama0=AMA(0); double ama1=AMA(1); double price=PriceClose(0); //--- Error - no signal if(ama0==EMPTY_VALUE || ama1==EMPTY_VALUE || price==0) return SIGNAL_TYPE_NONE; //--- Buy signal: price is above AMA, and AMA is rising if(price>ama0 && ama0>ama1) return SIGNAL_TYPE_LONG; //--- Sell signal: price is below AMA, and AMA is falling if(price<ama0 && ama0<ama1) return SIGNAL_TYPE_SHORT; //--- No signal return SIGNAL_TYPE_NONE; } //+------------------------------------------------------------------+ //| Return the order execution type matching type, | //| if it is available for the symbol; otherwise, a valid option | //| /ru/forum/170952/page4#comment_4128864 | //+------------------------------------------------------------------+ ENUM_ORDER_TYPE_FILLING GetTypeFilling(const ENUM_ORDER_TYPE_FILLING type=ORDER_FILLING_RETURN) { const ENUM_SYMBOL_TRADE_EXECUTION exe_mode=(ENUM_SYMBOL_TRADE_EXECUTION)::SymbolInfoInteger(Symbol(),SYMBOL_TRADE_EXEMODE); const int filling_mode=(int)::SymbolInfoInteger(Symbol(),SYMBOL_FILLING_MODE); return((filling_mode==0 || (type>=ORDER_FILLING_RETURN) || ((filling_mode &(type+1))!=type+1)) ? (((exe_mode==SYMBOL_TRADE_EXECUTION_EXCHANGE) || (exe_mode==SYMBOL_TRADE_EXECUTION_INSTANT)) ? ORDER_FILLING_RETURN :((filling_mode==SYMBOL_FILLING_IOC) ? ORDER_FILLING_IOC : ORDER_FILLING_FOK)) : type); } //+------------------------------------------------------------------+ //| Return a valid lot size | //+------------------------------------------------------------------+ double CorrectLots(const double lots,const bool to_min_correct=true) { double min=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN); double max=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX); double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP); return(to_min_correct ? VolumeRoundToSmaller(lots,min,max,step) : VolumeRoundToCorrect(lots,min,max,step)); } //+------------------------------------------------------------------+ //| Return the nearest valid lot size | //+------------------------------------------------------------------+ double VolumeRoundToCorrect(const double volume,const double min,const double max,const double step) { return(step==0 ? min : fmin(fmax(round(volume/step)*step,min),max)); } //+------------------------------------------------------------------+ //| Return the nearest lower valid lot size | //+------------------------------------------------------------------+ double VolumeRoundToSmaller(const double volume,const double min,const double max,const double step) { return(step==0 ? min : fmin(fmax(floor(volume/step)*step,min),max)); } //+---------------------------------------------------------------------------------------+ //| Return a flag indicating that the total volume on the account has not been exceeded | //+---------------------------------------------------------------------------------------+ bool CheckLotForLimitAccount(const ENUM_POSITION_TYPE position_type,const double volume) { double lots_limit=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_LIMIT); if(lots_limit==0) return true; double total_volume=(position_type==POSITION_TYPE_BUY ? Data.Buy.total_volume : Data.Sell.total_volume); return(total_volume+volume<=lots_limit); } //+------------------------------------------------------------------+ //| Return the valid StopLoss relative to StopLevel | //+------------------------------------------------------------------+ double CorrectStopLoss(const ENUM_POSITION_TYPE position_type,const int stop_loss) { if(stop_loss==0) return 0; double pt=Point(); double price=(position_type==POSITION_TYPE_BUY ? SymbolInfoDouble(Symbol(),SYMBOL_ASK) : SymbolInfoDouble(Symbol(),SYMBOL_BID)); int lv=StopLevel(), dg=Digits(); return(position_type==POSITION_TYPE_BUY ? NormalizeDouble(fmin(price-lv*pt,price-stop_loss*pt),dg) : NormalizeDouble(fmax(price+lv*pt,price+stop_loss*pt),dg)); } //+------------------------------------------------------------------+ //| Return the valid TakeProfit relative to StopLevel | //+------------------------------------------------------------------+ double CorrectTakeProfit(const ENUM_POSITION_TYPE position_type,const int take_profit) { if(take_profit==0) return 0; double pt=Point(); double price=(position_type==POSITION_TYPE_BUY ? SymbolInfoDouble(Symbol(),SYMBOL_ASK) : SymbolInfoDouble(Symbol(),SYMBOL_BID)); int lv=StopLevel(), dg=Digits(); return(position_type==POSITION_TYPE_BUY ? NormalizeDouble(fmax(price+lv*pt,price+take_profit*pt),dg) : NormalizeDouble(fmin(price-lv*pt,price-take_profit*pt),dg)); } //+------------------------------------------------------------------+ //| Return the calculated StopLevel | //+------------------------------------------------------------------+ int StopLevel(void) { int sp=(int)SymbolInfoInteger(Symbol(),SYMBOL_SPREAD); int lv=(int)SymbolInfoInteger(Symbol(),SYMBOL_TRADE_STOPS_LEVEL); return(lv==0 ? sp*SPREAD_MLTP : lv); } //+------------------------------------------------------------------+ //| Return an "undefined" trading environment state | //+------------------------------------------------------------------+ bool IsUncertainStateEnv(const string symbol_name,const ulong magic_number) { //--- In the tester, the trading environment state is always valid if(MQLInfoInteger(MQL_TESTER)) return false; //--- In a loop over the number of orders int total=OrdersTotal(); for(int i=total-1; i>=0; i--) { //--- Select an order to retrieve its properties if(OrderGetTicket(i)==0) continue; //--- If the order's magic number does not match the target one, skip it if(OrderGetInteger(ORDER_MAGIC)!=magic_number) continue; //--- If the order type is neither Buy nor Sell, skip it ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); if(type!=ORDER_TYPE_BUY && type!=ORDER_TYPE_SELL) continue; //--- If the order symbol matches the target symbol, but the order has no position ID entry, //--- This means that the data for the opening position has not yet been added to the order history. //--- This is an undefined trading environment state—return true if(!OrderGetInteger(ORDER_POSITION_ID) && OrderGetString(ORDER_SYMBOL)==symbol_name) return true; } //--- The trading environment is valid return false; } //+------------------------------------------------------------------+ //| Check the trading environment state | //+------------------------------------------------------------------+ bool CheckUncertainStateEnv(const string symbol_name,const ulong magic_number,const int attempts,const int wait) { //--- If the trading environment is valid, return true if(IsUncertainStateEnv(symbol_name,magic_number)) return true; //--- Make ENV_ATTEMPTS attempts to obtain a valid trading environment, waiting ENV_WAIT_ATTEMPT between attempts int n=0; while(!IsStopped() && n<attempts && IsUncertainStateEnv(symbol_name,magic_number)) { n++; Sleep(wait); } //--- If the trading environment is still undefined after the wait is complete, report this and return `false` if(n>=attempts && IsUncertainStateEnv(symbol_name,magic_number)) { PrintFormat("%s: Uncertain state of the environment. Please try again.",__FUNCTION__); return false; } //--- The environment is valid return true; } //+------------------------------------------------------------------+ //| Fill arrays of position tickets | //+------------------------------------------------------------------+ bool FillingListTickets(const string symbol_name,const ulong magic_number) { //--- If the trading environment is not valid, return false if(!CheckUncertainStateEnv(symbol_name,magic_number,ENV_ATTEMPTS,ENV_WAIT_ATTEMPT)) return false; //--- Clear the lists and initialize the variables Data.Buy.list_tickets.Clear(); Data.Sell.list_tickets.Clear(); Data.Buy.total_volume=0; Data.Sell.total_volume=0; //--- In the loop over open positions int total=PositionsTotal(); for(int i=total-1; i>WRONG_VALUE; i--) { //--- Select the position to retrieve its properties ulong ticket=PositionGetTicket(i); if(ticket==0) continue; //--- If the magic number or symbol does not match those passed to the function, continue if(PositionGetInteger(POSITION_MAGIC)!=InpMagic || PositionGetString(POSITION_SYMBOL)!=symbol_name) continue; //--- Get the position type and volume ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); double volume=PositionGetDouble(POSITION_VOLUME); //--- Depending on the position type, add the ticket and volume to the corresponding lists if(type==POSITION_TYPE_BUY) { Data.Buy.list_tickets.Add(ticket); Data.Buy.total_volume+=volume; } //--- POSITION_TYPE_SELL else { Data.Sell.list_tickets.Add(ticket); Data.Sell.total_volume+=volume; } } //--- Completed successfully return true; } //+------------------------------------------------------------------+ //| Return the number of Buy positions | //+------------------------------------------------------------------+ int TotalBuy(void) { return Data.Buy.list_tickets.Total(); } //+------------------------------------------------------------------+ //| Return the number of Sell positions | //+------------------------------------------------------------------+ int TotalSell(void) { return Data.Sell.list_tickets.Total(); } //+------------------------------------------------------------------+ //| Return the most recently added position ticket by type | //+------------------------------------------------------------------+ ulong LastAddedTicket(const ENUM_POSITION_TYPE type) { return(type==POSITION_TYPE_BUY ? (TotalBuy()>0 ? Data.Buy.list_tickets.At(0) : 0) : (TotalSell()>0 ? Data.Sell.list_tickets.At(0) : 0)); } //+------------------------------------------------------------------+ //| Return the bar number on which the position was opened | //+------------------------------------------------------------------+ int PositionBar(const ulong ticket) { //--- Select a position by ticket ResetLastError(); if(!PositionSelectByTicket(ticket)) { PrintFormat("%s: Failed to select position by ticket #%I64u. Error %d",__FUNCTION__,ticket,GetLastError()); return -1; } //--- Get the position opening time and symbol datetime time=(datetime)PositionGetInteger(POSITION_TIME); string symbol=PositionGetString(POSITION_SYMBOL); //--- Return the bar number based on the time the position was opened return iBarShift(symbol,PERIOD_CURRENT,time); } //+------------------------------------------------------------------------+ //| Return whether the specified position was opened on the current bar | //+------------------------------------------------------------------------+ bool IsPresentPosOnCurrentBar(const ENUM_POSITION_TYPE type) { ulong ticket=LastAddedTicket(type); return(ticket>0 ? PositionBar(ticket)==0 : false); } //+------------------------------------------------------------------+ //| Return the opening price of a position by ticket | //+------------------------------------------------------------------+ double PositionPriceOpen(const ulong ticket) { //--- Check the ticket if(ticket==0) return 0; //--- Select a position by ticket ResetLastError(); if(!PositionSelectByTicket(ticket)) { PrintFormat("%s: Failed to select position by ticket #%I64u. Error %d",__FUNCTION__,ticket,GetLastError()); return 0; } //--- Return the position opening price return PositionGetDouble(POSITION_PRICE_OPEN); } //+------------------------------------------------------------------+ //| Close Buy positions | //+------------------------------------------------------------------+ bool CloseBuy(void) { int total=TotalBuy(); bool res=true; for(int i=total-1; i>=0; i--) { ulong ticket=Data.Buy.list_tickets.At(i); if(ticket==NULL) continue; if(!trade.PositionClose(ticket,InpDeviation)) res=false; } return res; } //+------------------------------------------------------------------+ //| Close Sell positions | //+------------------------------------------------------------------+ bool CloseSell(void) { int total=TotalSell(); bool res=true; for(int i=total-1; i>=0; i--) { ulong ticket=Data.Sell.list_tickets.At(i); if(ticket==NULL) continue; if(!trade.PositionClose(ticket,InpDeviation)) res=false; } return res; } //+------------------------------------------------------------------+ //| Open a position | //+------------------------------------------------------------------+ bool OpenPosition(const string symbol_name,const ENUM_POSITION_TYPE type,const double volume,const string comment) { //--- Calculate values for stop orders int bb=int(HalfSizeBB(0)*InpSLMltp); double atrd=ATR(0); int atrp=(atrd!=EMPTY_VALUE ? int(round(atrd*InpTPMltp/Point())) : 0); double sl=(InpStopLoss==0 ? 0 : (InpStopLoss<0 ? (bb!=0 ? CorrectStopLoss(type,bb) : 0) : CorrectStopLoss(type,InpStopLoss))); double tp=(InpTakeProfit==0 ? 0 : (InpStopLoss<0 ? (atrp!=0 ? CorrectTakeProfit(type,atrp) : 0) : CorrectTakeProfit(type,InpTakeProfit))); //--- On a netting account, removing stop orders if(netto) sl=tp=0; //--- Get prices MqlTick tick={}; if(!SymbolInfoTick(symbol_name,tick)) { PrintFormat("%s: Unable to get prices"); return false; } //--- Check and retrieve the normalized lot size for the position being opened double ll=trade.CheckVolume(symbol_name,volume,(type==POSITION_TYPE_BUY ? tick.ask : tick.bid),(ENUM_ORDER_TYPE)type); if(ll==0) { PrintFormat("%s: Error. CheckVolume() returned a zero lot",__FUNCTION__); return false; } //--- Check the limit on the maximum total volume of open positions on the account if(!CheckLotForLimitAccount(type,ll)) { PrintFormat("%s: CheckLotForLimitAccount() returned an error",__FUNCTION__); return false; } //--- There may be a situation where a trade order has already been submitted but has not yet been fully processed, //--- which may result in opening a duplicate position. //--- If the trading environment is invalid, return false if(!CheckUncertainStateEnv(symbol_name,InpMagic,ENV_ATTEMPTS,ENV_WAIT_ATTEMPT)) return false; //--- Wait to obtain a valid trading environment may take some time //--- Get the prices again if(!SymbolInfoTick(symbol_name,tick)) { PrintFormat("%s: Unable to get prices"); return false; } //--- Return the result of sending the trade request to the server return(type==POSITION_TYPE_BUY ? trade.Buy(ll,symbol_name,tick.ask,sl,tp,comment) : trade.Sell(ll,symbol_name,tick.bid,sl,tp,comment)); } //+------------------------------------------------------------------+ //| Trading process | //+------------------------------------------------------------------+ void TradeProcess(const ENUM_SIGNAL_TYPE signal) { //--- No signal — exit if(signal==SIGNAL_TYPE_NONE) return; //--- Signal to close if(signal==SIGNAL_TYPE_CLOSE) { CloseBuy(); CloseSell(); } //--- Buy signal if(signal==SIGNAL_TYPE_LONG) { //--- If there is no open Buy position on this bar if(!IsPresentPosOnCurrentBar(POSITION_TYPE_BUY)) { //--- Get the price of the last open Buy position double price_last=PositionPriceOpen(LastAddedTicket(POSITION_TYPE_BUY)); //--- If this is the very first Buy position, or the opening price is better than the previous position's opening price— //--- Send a request to open a Buy position if(price_last==0 || price_last>SymbolInfoDouble(Symbol(),SYMBOL_ASK)) { //--- If the position has been opened, update the lists of open position tickets if(OpenPosition(Symbol(),POSITION_TYPE_BUY,lot,"")) FillingListTickets(Symbol(),InpMagic); } } } //--- Sell signal if(signal==SIGNAL_TYPE_SHORT) { //--- If there is no open Sell position on this bar if(!IsPresentPosOnCurrentBar(POSITION_TYPE_SELL)) { //--- Get the price of the last open Sell position double price_last=PositionPriceOpen(LastAddedTicket(POSITION_TYPE_SELL)); //--- If this is the very first Sell position, or the opening price is better than the previous position's opening price— //--- Send a request to open a Sell position if(price_last<SymbolInfoDouble(Symbol(),SYMBOL_ASK)) { //--- If the position has been opened, update the lists of open position tickets if(OpenPosition(Symbol(),POSITION_TYPE_SELL,lot,"")) FillingListTickets(Symbol(),InpMagic); } } } } //+------------------------------------------------------------------+
Este asesor experto se ha creado a partir del "Asesor experto sencillo basado en los indicadores WPR, Bollinger Bands y ATR" de CodeBase. La lógica principal y las soluciones del código están comentadas y, creo, son fáciles de entender. En cualquier caso, se puede plantear cualquier duda en los comentarios del artículo.
Guardemos el asesor experto en la carpeta \MQL5\Experts\STOCKS_COMMODITIES\Gopalakrishnan Range Index\ con el nombre ExpGRI_AMA_TEMA.mq5.
Compilemos el asesor experto y desactivemos en la configuración el filtrado por GRI

y ejecutemos la prueba en el marco temporal H4, en el modo de modelado de todos los ticks, para EURUSD y durante el período comprendido entre el 1 de enero de 2024 y el 5 de enero de 2026.
El resultado será el siguiente gráfico de pruebas:

Ahora activaremos el filtrado de señales según el indicador GRI

y volveremos a ejecutar las pruebas con los mismos parámetros. Obtendremos el siguiente gráfico de pruebas:

Cuando se realizan entradas únicamente en un mercado activo (con filtrado de señales según el GRI), la diferencia con respecto a la prueba sin filtrado de señales es claramente apreciable. Sí, aquí ocurre exactamente lo mismo que cuando se realizan pruebas sin filtro de volatilidad: hay días de operaciones rentables y días con pérdidas. No obstante, se aprecia que la duración de los períodos con pérdidas es menor que la de los períodos con beneficios. Y si tenemos en cuenta que el sistema de trading sigue claramente una estrategia de seguimiento de tendencias y que carece de una lógica para distinguir entre una tendencia y un mercado lateral, podemos concluir que el uso del indicador GRI ha dado un resultado positivo en el intervalo de datos históricos seleccionado.
Para que el asesor experto funcione correctamente, es necesario que el indicador GRI se encuentre en la misma carpeta que el asesor experto; por ejemplo, \MQL5\Experts\STOCKS_COMMODITIES\Gopalakrishnan Range Index\.
Conclusión
En el mundo del análisis financiero, la búsqueda de la innovación nos lleva a menudo a buscar algoritmos complejos, a adentrarnos en las redes neuronales y a buscar soluciones poco convencionales, mientras que las ideas que han resistido el paso del tiempo quedan relegadas a un segundo plano. La implementación de Gopalakrishnan Range Index para MetaTrader 5 demuestra que lo que funcionaba hace décadas no pierde su relevancia, sino que simplemente requiere una forma de aplicación más moderna.
Esto es una prueba más de que todo lo nuevo es algo antiguo que se había olvidado. Al recuperar esta herramienta de los archivos de la revista Technical Analysis of Stocks & Commodities y llevarla a los terminales de trading de los operadores actuales, no solo rendimos homenaje a la historia, sino que también obtenemos un método fiable para evaluar la volatilidad, libre de ruido de mercado superfluo y que ha resistido la prueba del tiempo.
En resumen, cabe destacar que el GRI es un claro ejemplo de cómo los conceptos matemáticos fundamentales de los años 90 cobran nueva vida en la era del trading algorítmico. A menudo, las herramientas más eficaces no son las que utilizan las fórmulas más complejas, sino las que se basan en la lógica básica del comportamiento del precio. La incorporación de este indicador a la plataforma MetaTrader 5 nos recuerda que, antes de buscar el "Santo Grial" en los últimos avances, conviene echar un vistazo a los clásicos. Al fin y al cabo, a menudo ya se había encontrado una buena solución; simplemente teníamos que adaptarla a la potencia de cálculo actual.
Todos los archivos del indicador y del asesor experto se adjuntan al artículo para su estudio independiente.
El código fuente completo del proyecto, con todos los archivos descritos en el artículo, está disponible en el repositorio.
Traducción del ruso hecha por MetaQuotes Ltd.
Artículo original: /ru/articles/20795
Advertencia: todos los derechos de estos materiales pertenecen a MetaQuotes Ltd. Queda totalmente prohibido el copiado total o parcial.
Este artículo ha sido escrito por un usuario del sitio web y refleja su punto de vista personal. MetaQuotes Ltd. no se responsabiliza de la exactitud de la información ofrecida, ni de las posibles consecuencias del uso de las soluciones, estrategias o recomendaciones descritas.
Yo lo bloquearía por algo así :-)
Porque no hay respuesta a la pregunta planteada en el tema, no hay peticiones por parte de nadie, pero sí hay una loca y sombría maraña de código. Así es el sueldo de un moderador.
De todos modos, antes de utilizar el indicador hay que comprender cuál es su significado físico. En este indicador, tanto el numerador como el denominador contienen logaritmos. ¿Qué impide utilizar la función exponencial? De ese modo, el significado del indicador queda más claro: la velocidad media «winsorizada». Se puede ir aún más allá y medir esta velocidad para todos los valores de la serie. Entonces se obtiene una imagen como esta.