//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
code
Assistant
User
Assistant
// Configurações das Bandas de Bollinger
int bbPeriod = 20;
double bbDeviation = 2.0;
// Obtenção das Bandas de Bollinger
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
// Verifique se o handle é válido
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
// Inicializar os buffers das bandas de Bollinger
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
// Preencher os buffers
if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
return;
}
// Preço atual e range da vela
double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
double priceLow = iLow(_Symbol, PERIOD_M2, 0);
double priceClose = iClose(_Symbol, PERIOD_M2, 0);
double range = priceHigh - priceLow;
// Objeto para enviar ordens
CTrade trade;
// Verificar se há uma ordem aberta
if (!orderOpened) {
// Atualizar informações de rompimento e confirmação
if (lastBreakoutAlta && priceClose > breakoutHigh)
{
double slBuy = priceClose - 10 * _Point;
if (trade.Buy(lotSize, _Symbol, slBuy))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutAlta = false;
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (lastBreakoutBaixa && priceClose < breakoutLow)
{
double slSell = priceClose + 10 * _Point;
if (trade.Sell(lotSize, _Symbol, slSell))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutBaixa = false;
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Verificar rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
}
// Verificar rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
}
}
// Fechar ordem se o preço estiver perto da linha do meio da Banda de Bollinger
if (orderOpened)
{
if (priceClose >= bollingerMiddle[0] - 3 * _Point && priceClose <= bollingerMiddle[0] + 3 * _Point)
{
if (trade.PositionClose(orderTicket))
{
Print("Posição fechada porque o preço chegou perto da linha central da Banda de Bollinger.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
// Gerenciamento de trailing stop
ManageTrailingStop();
// Itera sobre todas as posições abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (ticket > 0 && PositionSelect(ticket))
{
double currentSL = PositionGetDouble(POSITION_SL);
double currentTP = PositionGetDouble(POSITION_TP);
double lastLow = iLow(_Symbol, PERIOD_M2, 1);
double lastHigh = iHigh(_Symbol, PERIOD_M2, 1);
// Verificar se é uma posição de compra aberta e atualizar Stop Loss
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
if (lastLow > currentSL || currentSL == 0.0)
{
trade.PositionModify(ticket, lastLow, currentTP);
Print("Stop Loss atualizado para posição de compra.");
}
}
// Verificar se é uma posição de venda aberta e atualizar Stop Loss
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
if (lastHigh < currentSL || currentSL == 0.0)
{
trade.PositionModify(ticket, lastHigh, currentTP);
Print("Stop Loss atualizado para posição de venda.");
}
}
}
}
}
vamos simplificar o codigo acima, invez de usar banda de bolinger vamos usar apenas uma media de SMA 20 periodos simples. e quando o preço cruzar acima da media de 20 e a vela que romper fechar acima da media de 20 e proxima vela fecha acima da maxima da vela anterior entao abra uma ordem de compra caso tenha alguma ordem em abertura ela sera fechada antes da abertura da nova ordem assim como ja acontece no codigo do robo,
e quando o preço cruzar abaixo da media de 20 e a vela que romper fechar abaixo da media de 20 e proxima vela fechar abaixo da maxima da vela anterior entao abra uma ordem de venda caso tenha alguma ordem em abertura ela sera fechada antes da abertura da nova ordem.
To simplify the existing EA (Expert Advisor) with the newly specified logic, you can use a simple moving average (SMA) for a 20-period instead of Bollinger Bands and check for crossovers and confirmations as specified. Below is the modified code:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Variáveis para preço
double priceHigh = iHigh(_Symbol, PERIOD_M2, 1);
double priceLow = iLow(_Symbol, PERIOD_M2, 1);
double priceClose = iClose(_Symbol, PERIOD_M2, 1);
// Variáveis para a média móvel simples (SMA)
double sma[3];
int smaPeriod = 20;
// Obter os valores da SMA
int smaHandle = iMA(_Symbol, PERIOD_M2, smaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(smaHandle, 0, 1, 3, sma) <= 0) {
Print("Erro ao copiar buffer da SMA: ", GetLastError());
return;
}
// Verificar se há uma ordem aberta
if (orderOpened && trade.PositionClose(0))
{
Print("Ordem aberta existente fechada.");
orderOpened = false;
orderTicket = 0;
}
double previousHigh = iHigh(_Symbol, PERIOD_M2, 2);
double previousLow = iLow(_Symbol, PERIOD_M2, 2);
double previousClose = iClose(_Symbol, PERIOD_M2, 2);
// Configuração de ordens de compra e venda
if (priceClose > sma[1] && previousClose < sma[2] && priceClose > previousHigh) {
if (trade.Buy(lotSize, _Symbol)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (priceClose < sma[1] && previousClose > sma[2] && priceClose < previousLow) {
if (trade.Sell(lotSize, _Symbol)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
Key Modifications:
SMA Calculation:
Instead of using Bollinger Bands, we calculated a 20-period simple moving average (SMA).
Order Opening Logic:
For buy orders, the logic checks if the current candle 1 item's close (priceClose) is greater than its SMA value (sma[1]) and if the previous period's close was below the previous SMA (sma[2]). If these conditions are met, it places a buy order.
For sell orders, the opposite conditions are checked.
Order Management:
Before opening a new order, any existing open order is closed.
This keeps the strategy consistent with the crossover confirmation as described.
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
// Variáveis para a média móvel simples (SMA)
double sma[3];
int smaPeriod = 20;
// Obter os valores da SMA
int smaHandle = iMA(_Symbol, PERIOD_M2, smaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(smaHandle, 0, 1, 3, sma) <= 0) {
Print("Erro ao copiar buffer da SMA: ", GetLastError());
return;
}
// Verificar se há uma ordem aberta
if (orderOpened && trade.PositionClose(0))
{
Print("Ordem aberta existente fechada.");
orderOpened = false;
orderTicket = 0;
}
double previousHigh = iHigh(_Symbol, PERIOD_M2, 2);
double previousLow = iLow(_Symbol, PERIOD_M2, 2);
double previousClose = iClose(_Symbol, PERIOD_M2, 2);
// Configuração de ordens de compra e venda
if (priceClose > sma[1] && previousClose < sma[2] && priceClose > previousHigh) {
if (trade.Buy(lotSize, _Symbol)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (priceClose < sma[1] && previousClose > sma[2] && priceClose < previousLow) {
if (trade.Sell(lotSize, _Symbol)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
precisa colocar trailing stop e nao esta ativando o fechamento da ordem quando o preço encosta na media 20
To address the issues you mentioned, we need to enhance the Expert Advisor (EA) by adding a trailing stop mechanism and ensuring the order is closed when the price touches the 20-period SMA. Here's how you can implement these features:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
input double trailingStopDistance = 10.0; // Distance for trailing stop in points
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(){
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick(){
// Variáveis para preço
double priceHigh = iHigh(_Symbol, PERIOD_M2, 1);
double priceLow = iLow(_Symbol, PERIOD_M2, 1);
double priceClose = iClose(_Symbol, PERIOD_M2, 1);
// Atendimento da função SMA
double sma[3];
int smaPeriod = 20;
// Obter os valores da SMA
int smaHandle = iMA(_Symbol, PERIOD_M2, smaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (smaHandle == INVALID_HANDLE || CopyBuffer(smaHandle, 0, 1, 3, sma) <= 0) {
Print("Erro ao copiar buffer da SMA: ", GetLastError());
return;
}
// Verificar e gerenciar trailing stop
ManageTrailingStop();
// Fechar ordem se o preço encostar na SMA
if (orderOpened && ((priceClose >= sma[1]) && (trade.PositionClose(orderTicket)))) {
Print("Fechamento de ordem devido ao preço ter encostado na SMA.");
orderOpened = false;
orderTicket = 0;
}
double previousHigh = iHigh(_Symbol, PERIOD_M2, 2);
double previousLow = iLow(_Symbol, PERIOD_M2, 2);
double previousClose = iClose(_Symbol, PERIOD_M2, 2);
// Configuração de ordens de compra e venda
if (priceClose > sma[1] && previousClose < sma[2] && priceClose > previousHigh) {
if (orderOpened) trade.PositionClose(orderTicket); // Fechar ordem existente antes de abrir uma nova
if (trade.Buy(lotSize, _Symbol)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (priceClose < sma[1] && previousClose > sma[2] && priceClose < previousLow) {
if (orderOpened) trade.PositionClose(orderTicket); // Fechar ordem existente antes de abrir uma nova
if (trade.Sell(lotSize, _Symbol)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Gerenciamento de trailing stop |
//+------------------------------------------------------------------+
void ManageTrailingStop(){
for (int i = PositionsTotal() - 1; i >= 0; i--) {
ulong ticket = PositionGetTicket(i);
if (ticket > 0 && PositionSelectByTicket(ticket)) {
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
double currentSL = PositionGetDouble(POSITION_SL);
double trailingStop = trailingStopDistance * _Point;
// Trailing Stop para ordens de compra
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
double newSL = currentPrice - trailingStop;
if ((newSL > currentSL) || (currentSL == 0.0)) {
trade.PositionModify(ticket, newSL, 0.0);
Print("Trailing Stop atualizado para ordem de compra.");
}
}
// Trailing Stop para ordens de venda
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
double newSL = currentPrice + trailingStop;
if ((newSL < currentSL) || (currentSL == 0.0)) {
trade.PositionModify(ticket, newSL, 0.0);
Print("Trailing Stop atualizado para ordem de venda.");
}
}
}
}
}
Key Enhancements:
Trailing Stop:
Implemented a trailing stop mechanism that adjusts the stop loss to follow the market movement by a specified number of points (trailingStopDistance).
Order Closure on SMA Touch:
Orders will now be closed if the price closes close to or touches the SMA.
Position Management:
Ensures any existing open positions are closed before opening a new one, following the same buy/sell conditions.
Adjusting Parameters:
You can modify trailingStopDistance to suit your trading strategy, representing the trailing stop loss in points.