Claro! Abaixo está o código completo do seu Expert Advisor (EA), que agora inclui a lógica para detectar divergências no RSI. O código incorporado é uma versão melhorada e ajustada do seu EA original com a funcionalidade de divergência.
//+------------------------------------------------------------------+
//| AI RSI BB SCALPER.mq5 |
//| Alfr5d |
//| https://www.49design.co.za |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Alfred Mandala."
#property description "www.billionairebulls.co.za\n"
#property version "1.6"
#property description "RSI GRID SCALPING EA com Stochastic e Divergência\n"
// Incluindo bibliotecas necessárias
#include <Trade/Trade.mqh>
#include <Array.mqh>
// ---- INPUTS ----
input group "--- Trading Inputs ---";
input double Lots = 0.01; // Tamanho do Lote
input int TpPoints = 50; // Take Profit em pontos [m5-50p, h1-200p]
input int StopLossPoints = 500; // Stop Loss em pontos [Ex: 20 pontos]
input ENUM_TIMEFRAMES RsiTimeFrame = PERIOD_CURRENT; // Timeframe
input group "--- RSI Inputs ---";
input int RsiPeriods = 18; // Periodo do RSI
input ENUM_APPLIED_PRICE RsiAppPrice = PRICE_CLOSE; // Preço aplicado pelo RSI
input double RsiSellTrigger = 70; // Zona de Venda do RSI
input double RsiBuyTrigger = 30; // Zona de Compra do RSI
input group "--- Bollinger Bands Inputs ---";
input int BbPeriods = 23; // Períodos das BB
input double BbDeviation = 2.0; // Desvio
input double BbShift = 0; // Deslocamento
input group "--- Stochastic Inputs ---";
input int StochKPeriod = 5; // Período K do Stoch
input int StochDPeriod = 3; // Período D do Stoch
input int StochSlowing = 3; // Atraso do Stoch
input double StochOverbought = 80.0; // Nível de sobrecompra
input double StochOversold = 20.0; // Nível de sobrevenda
// ---- GLOBAL VARIABLES ----
int handleRsi, handleBb, handleStochastic;
double rsi[], bbUpper[], bbLower[], stochMain[];
// Instanciar classe de trade
CTrade trade;
// ---- EXPERT INIT ----
int OnInit()
{
handleRsi = iRSI(_Symbol, RsiTimeFrame, RsiPeriods, RsiAppPrice);
handleBb = iBands(_Symbol, PERIOD_CURRENT, BbPeriods, BbShift, BbDeviation, PRICE_CLOSE);
handleStochastic = iStochastic(_Symbol, PERIOD_CURRENT, StochKPeriod, StochDPeriod, StochSlowing, MODE_SMA, STO_LOWHIGH);
return (INIT_SUCCEEDED);
}
// ---- EXPERT DEINIT ----
void OnDeinit(const int reason)
{
IndicatorRelease(handleBb);
IndicatorRelease(handleRsi);
IndicatorRelease(handleStochastic);
}
// Função para obter o preço máximo em um array
double GetMaxPrice(double &prices[], int count) {
double maxPrice = prices[0];
for(int i = 1; i < count; i++) {
if(prices[i] > maxPrice) {
maxPrice = prices[i];
}
}
return maxPrice;
}
// Função para obter o preço mínimo em um array
double GetMinPrice(double &prices[], int count) {
double minPrice = prices[0];
for(int i = 1; i < count; i++) {
if(prices[i] < minPrice) {
minPrice = prices[i];
}
}
return minPrice;
}
// Função para verificar a divergência do RSI
bool CheckRsiDivergence(int numBars) {
double priceHigh[], priceLow[];
ArraySetAsSeries(priceHigh, true);
ArraySetAsSeries(priceLow, true);
// Copiar dados de preço
CopyHigh(_Symbol, RsiTimeFrame, 0, numBars, priceHigh);
CopyLow(_Symbol, RsiTimeFrame, 0, numBars, priceLow);
// Copiar dados de RSI
CopyBuffer(handleRsi, 0, 0, numBars, rsi);
double maxPrice = GetMaxPrice(priceHigh, numBars);
double minPrice = GetMinPrice(priceLow, numBars);
int lastPeak = -1, lastValley = -1;
// Encontrar o último pico e valle
for(int i = 0; i < numBars; i++) {
if(priceHigh[i] == maxPrice && (lastPeak == -1 || i > lastPeak)) {
lastPeak = i;
}
if(priceLow[i] == minPrice && (lastValley == -1 || i > lastValley)) {
lastValley = i;
}
}
// Verificar Divergência
if(lastPeak != -1 && rsi[lastPeak] < rsi[lastPeak + numBars]) {
return true; // Divergência de venda
}
if(lastValley != -1 && rsi[lastValley] > rsi[lastValley + numBars]) {
return true; // Divergência de compra
}
return false;
}
// ---- ON TICK FUNCTION ----
void OnTick()
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
CopyBuffer(handleBb, 1, 0, 1, bbUpper);
CopyBuffer(handleBb, 2, 0, 1, bbLower);
CopyBuffer(handleRsi, 0, 0, 2, rsi);
CopyBuffer(handleStochastic, 0, 0, 2, stochMain);
// Verifica se não há posições abertas
if (PositionsTotal() == 0)
{
// Verificar divergência
bool hasDivergence = CheckRsiDivergence(14); // Verifica divergência nos últimos 14 períodos
// Condição de venda usando RSI, Stochastic e divergência
if (rsi[1] > RsiSellTrigger && rsi[0] < RsiSellTrigger && stochMain[0] > StochOverbought && hasDivergence)
{
if (bid >= bbUpper[0])
{
Print(__FUNCTION__, " > SELL Signal...");
trade.Sell(Lots, _Symbol, bid, bid + StopLossPoints * _Point, bid - TpPoints * _Point);
}
}
// Condição de compra usando RSI, Stochastic e divergência
else if (rsi[1] < RsiBuyTrigger && rsi[0] > RsiBuyTrigger && stochMain[0] < StochOversold && hasDivergence)
{
if (bid <= bbLower[0])
{
Print(__FUNCTION__, " > BUY Signal...");
trade.Buy(Lots, _Symbol, bid, bid - StopLossPoints * _Point, bid + TpPoints * _Point);
}
}
}
// Lógica para fechamento de posições
ManagePositions();
Comment("\nRSI[0]: ", DoubleToString(rsi[0], 5),
"\nRSI[1]: ", DoubleToString(rsi[1], 5),
"\nStochastic: ", DoubleToString(stochMain[0], 2));
}
// --- Função para gerenciar posições abertas ---
void ManagePositions()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong posTicket = PositionGetTicket(i);
if (PositionSelectByTicket(posTicket))
{
ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE) PositionGetInteger(POSITION_TYPE);
double posOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
int points = (posType == POSITION_TYPE_BUY) ? (int)((bid - posOpenPrice) / _Point) : (int)((posOpenPrice - SymbolInfoDouble(_Symbol, SYMBOL_ASK)) / _Point);
if (points > TpPoints)
{
trade.PositionClose(posTicket);
}
}
}
}
Detalhes da Implementação:
-
Verificação de Divergência: A função CheckRsiDivergence analisa os preços e o RSI nas últimas 14 barras (ou o número que você desejar) para identificar a divergência.
-
Integração com Sinais de Compra e Venda: A verificação de divergência foi integrada às condições de negociações no método OnTick(), permitindo que a divergência complemente as decisões de compra e venda.
-
Comments e Prints: Deixei a lógica de comentários inalterada para fácil depuração.
Importante:
- Testes: Teste o EA em uma conta demo ou simulador antes de implementá-lo em uma conta real. A lógica de divergência pode precisar de ajustes dependendo das condições do mercado.
- Ajustes de Parâmetros: Você pode ajustar os parâmetros (como números de períodos) dependendo do seu estilo de trading e dos ativos que você está analisando.
Use o código como uma base e adapte-o conforme necessário para atender às suas necessidades específicas de trading!