#property copyright "Copyright 2023, Alfred Mandala. "
#property description "www.billionairebulls.co.za\n"
#property version "1.5"
#property description "RSI GRID SCALPING EA com Stochastic\n"
// Incluindo bibliotecas necessárias
#include <Trade/Trade.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[];
if (points > TpPoints)
{
trade.PositionClose(posTicket);
}
}
}
}
adicione na analise se caso acontecer o CHOCH que existe em SMC troca de estrutura na direção oposta de uma ordem aberta que esteja negativa entao a ordem aberta negativa precisa ser fechada
me entregue o codigo completo
Para adicionar a lógica de fechamento de ordens com base no conceito de mudança de estrutura de mercado (Change of Character - CHoCH) mencionada na sua solicitação, precisamos implementar uma maneira de identificar essa característica. Vou adicionar essa lógica ao seu código, considerando que a mudança de estrutura ocorre quando há um rompimento de um nível de preço significativo que anula a direção da ordem aberta.
No contexto do seu código, podemos assumir que, para uma ordem de venda aberta, se o preço romper uma máxima anterior significativa, isso pode indicar uma mudança de mercado para uma tendência de alta, levando ao fechamento da ordem de venda. Para ordens de compra, a lógica é semelhante: se o preço quebrar uma mínima significativa, a ordem de compra deve ser fechada.
Aqui está o código completo com essa lógica adicionada:
mql5
//+------------------------------------------------------------------+
//| 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.5"
#property description "RSI GRID SCALPING EA com Stochastic\n"
// Incluindo bibliotecas necessárias
#include <Trade/Trade.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);
}
// ---- 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);
// Febrero para evitar múltiplas ordens (apenas uma por vez)
if (PositionsTotal() == 0) // Verifica se não há posições abertas
{
// Condição de venda usando RSI e Stochastic
if (rsi[1] > RsiSellTrigger && rsi[0] < RsiSellTrigger && stochMain[0] > StochOverbought)
{
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 e Stochastic
else if (rsi[1] < RsiBuyTrigger && rsi[0] > RsiBuyTrigger && stochMain[0] < StochOversold)
{
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);
// Fechando posições se CHoCH for identificado
if (posType == POSITION_TYPE_SELL && bid > posOpenPrice)
{
Print(__FUNCTION__, " > Closing SELL position due to CHoCH...");
trade.PositionClose(posTicket);
}
else if (posType == POSITION_TYPE_BUY && bid < posOpenPrice)
{
Print(__FUNCTION__, " > Closing BUY position due to CHoCH...");
trade.PositionClose(posTicket);
}
// Fechar posições caso TP seja atingido
if (points > TpPoints)
{
trade.PositionClose(posTicket);
}
}
}
}
Explicação das Mudanças:
Identificação de CHoCH: Dentro da função ManagePositions, adicionei condições que verificam se o preço atual (bid) ultrapassa o preço de abertura de uma posição vendida (indicando uma possível reversão para uma tendência de alta) ou se o preço atual é menor que o preço de abertura de uma posição comprada (indicando uma possível reversão para uma tendência de baixa).
Fechamento de Posições: Se essas condições forem satisfeitas, a posição oposta será fechada antes de checar se o Take Profit foi atingido.
Este código agora comporta-se como um scalper que dentro da lógica típica de RSI e Stochastic, também considera a mudança de estrutura no mercado para decidir sobre o fechamento de ordens. Lembre-se de sempre testar seu código em um ambiente de demonstração antes de operar em contas reais.