input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]))
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Coloque um tipo de stoploss movel ou faça que o trailing stop tambem faça esse outro tipo de proteção abaixo
as vezes uma vela de força ou outras seguintes acaba voltando e fazendo stopar e dando prejuizo.
caso isso aconteça e acontecer de retroceder cerca de 30% da vela de força ou mercado retroceder 30% querendo fazer um tipo de reversao momentania encerre a operação para evitar percas
Para incorporar um sistema de stop loss móvel que fecha a posição se o preço retroceder 30% de uma vela de força, você pode adicionar uma lógica para verificar o tamanho da vela de força e calcular um nível de stop loss com base em um retrocesso de 30%. Aqui está uma maneira de implementar isso no seu código existente:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
// Função para calcular o tamanho da vela de força
double CalcForceCandleSize(double open, double close) {
return MathAbs(close - open);
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double fastSma[1], slowSma[1];
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double priceOpen = iOpen(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
double forceCandleSize = CalcForceCandleSize(priceOpen, priceClose);
double retracementLevel = forceCandleSize * 0.3;
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]) ||
(positionType == POSITION_TYPE_BUY && priceClose < priceOpen - retracementLevel * pointSize) ||
(positionType == POSITION_TYPE_SELL && priceClose > priceOpen + retracementLevel * pointSize))
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Explicação
Função CalcForceCandleSize: Esta função calcula o tamanho da vela com base nas diferenças entre o preço de fechamento e o preço de abertura. Ela é usada para determinar o tamanho da vela de força.
Retracement Check: Quando uma posição está aberta, o código verifica se o preço atual retrocedeu 30% do tamanho da vela de força (movendo-se contra a direção esperada).
Fechar uma Posição: Se o preço retroceder mais de 30%, a posição é fechada para evitar perdas adicionais.
Este código assegura que se houver uma mudança rápida na direção do mercado após uma vela de força, a posição é fechada para mitigar potenciais perdas.
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]))
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
precisa ter takeprofit automatico a cada 20 pontos de lucro para garantir os lucros
Para implementar um take profit automático a cada 20 pontos de lucro e garantir os lucros, você pode adicionar um cálculo para determinar o nível de take profit quando uma nova posição é aberta. Vamos adicionar isso ao seu código. O take profit será calculado a partir do preço de entrada mais ou menos 20 pontos, dependendo do tipo de posição (compra ou venda).
Abaixo está a versão ajustada do código:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
input double takeProfitPoints = 20; // Distância em pontos para o take profit
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double fastSma[1], slowSma[1];
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]))
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
double takeProfitPrice = priceClose + takeProfitPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
double takeProfitPrice = priceClose - takeProfitPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Alterações Feitas
Cálculo de Take Profit: Para cada nova posição, agora calculamos e definimos um take profit usando takeProfitPoints * pointSize.
Uso de trade.Buy e trade.Sell com takeProfitPrice: As funções Buy e Sell agora incluem o preço de take profit calculado.
Isso fará com que, sempre que você abrir uma nova posição, um take profit seja automaticamente ajustado a 20 pontos do preço de entrada, garantindo assim os lucros se o mercado se mover a seu favor.
sempre que o preço retorne e enconste na media de 20 encerre a operação para evitar percas caso a media de 200 esteja longe para uma posivel reversao
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
input double takeProfitPoints = 20; // Distância em pontos para o take profit
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]))
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
double takeProfitPrice = priceClose + takeProfitPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
double takeProfitPrice = priceClose - takeProfitPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Para adicionar a lógica de fechar uma posição quando o preço retorna e toca a média móvel de 20 períodos, especialmente se a média móvel de 200 períodos estiver distante, vou incluir verificações adicionais no trecho do seu código.
Aqui está o código atualizado, com essa nova regra de saída implementada:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
input double takeProfitPoints = 20; // Distância em pontos para o take profit
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double fastSma[1], slowSma[1];
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem ou preço tocar a SMA de 20
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]) ||
(positionType == POSITION_TYPE_BUY && priceClose <= fastSma[0]) ||
(positionType == POSITION_TYPE_SELL && priceClose >= fastSma[0]))
{
// Verifique a distância entre as SMAs para confirmar reversão potencial
if (MathAbs(fastSma[0] - slowSma[0]) > (slowSmaPeriod / 2) * pointSize)
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
double takeProfitPrice = priceClose + takeProfitPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
double takeProfitPrice = priceClose - takeProfitPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Explicações das Alterações
Fechamento com Base na SMA de 20: Agora, uma posição é fechada se o preço tocar a média móvel rápida de 20 e a média móvel lenta de 200 estiver a uma distância significativa (como uma verificação adicional de que uma reversão imediata completa não é esperada).
Lembre-se de testar este código em um ambiente adequado, como uma conta demo, para garantir que ele funciona conforme o esperado e que se adapta bem às condições específicas do mercado em que você está operando.
modifique para quando encostar na media de 20 somente pode fechar a operação se o preço estiver positivo quando esteja negativo deixar a ordem aberta até voltar a pelo menos 10 a 30pips positivo
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
input double takeProfitPoints = 20; // Distância em pontos para o take profit
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
double positionStopLoss = PositionGetDouble(POSITION_SL);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem ou preço tocar a SMA de 20
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]) ||
(positionType == POSITION_TYPE_BUY && priceClose <= fastSma[0]) ||
(positionType == POSITION_TYPE_SELL && priceClose >= fastSma[0]))
{
// Verifique a distância entre as SMAs para confirmar reversão potencial
if (MathAbs(fastSma[0] - slowSma[0]) > (slowSmaPeriod / 2) * pointSize)
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < positionStopLoss)
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
double takeProfitPrice = priceClose + takeProfitPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
double takeProfitPrice = priceClose - takeProfitPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Para implementar a lógica desejada onde uma posição só é fechada quando o preço toca a média móvel de 20 e está em lucro, ou volta para um lucro de pelo menos 10 a 30 pips, será necessário ajustar a parte do código que faz o fechamento da posição. Aqui está a versão ajustada do código:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20; // Período para a média móvel rápida
input int slowSmaPeriod = 200; // Período para a média móvel lenta
input double stopLossPoints = 6500.0; // Distância do stop loss em pontos
input double trailingStart = 30; // Distância em pontos para iniciar o trailing stop
input double trailingStep = 10; // Passo do trailing stop em pontos
input double takeProfitPoints = 20; // Distância em pontos para o take profit
input double minProfitPoints = 10; // Mínimo de pontos de lucro para permitir fechamento
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double fastSma[1], slowSma[1];
// Obtenha valor do SMA rápido
int fastSmaHandle = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandle, 0, 0, 1, fastSma) <= 0)
{
Print("Erro ao copiar buffer do SMA rápido: ", GetLastError());
return;
}
// Obtenha valor do SMA lento
int slowSmaHandle = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(slowSmaHandle, 0, 0, 1, slowSma) <= 0)
{
Print("Erro ao copiar buffer do SMA lento: ", GetLastError());
return;
}
double priceClose = iClose(_Symbol, PERIOD_H1, 0);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Verificar se uma ordem aberta deve ser fechada ou ajustada
if (PositionSelect(_Symbol))
{
long positionType = PositionGetInteger(POSITION_TYPE);
double positionPriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
// Calcular lucro atual em pontos
double currentProfitPoints = (priceClose - positionPriceOpen) / pointSize;
if (positionType == POSITION_TYPE_SELL)
currentProfitPoints = (positionPriceOpen - priceClose) / pointSize;
// Fechar ordem se as condições de mercado se inverterem ou preço tocar a SMA de 20 com lucro
if ((positionType == POSITION_TYPE_BUY && fastSma[0] < slowSma[0]) ||
(positionType == POSITION_TYPE_SELL && fastSma[0] > slowSma[0]))
{
if (trade.PositionClose(_Symbol))
{
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if ((positionType == POSITION_TYPE_BUY && priceClose <= fastSma[0] && currentProfitPoints >= minProfitPoints) ||
(positionType == POSITION_TYPE_SELL && priceClose >= fastSma[0] && currentProfitPoints >= minProfitPoints))
{
// Fecha posição apenas se estiver em lucro mínimo estabelecido
if (trade.PositionClose(_Symbol))
{
Print("Ordem fechada após tocar na média móvel de 20 com lucro.");
orderOpened = false;
orderTicket = 0;
}
else
{
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (currentProfitPoints > trailingStart)
{
// Aplicar o trailing stop
if (positionType == POSITION_TYPE_BUY)
{
double newStopLoss = priceClose - trailingStep * pointSize;
if (newStopLoss > PositionGetDouble(POSITION_SL))
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para compra: ", newStopLoss);
}
}
else if (positionType == POSITION_TYPE_SELL)
{
double newStopLoss = priceClose + trailingStep * pointSize;
if (newStopLoss < PositionGetDouble(POSITION_SL))
{
trade.PositionModify(PositionGetInteger(POSITION_TICKET), newStopLoss, 0);
Print("Trailing stop ajustado para venda: ", newStopLoss);
}
}
}
}
else
{
// Configurações de ordens de compra e venda
if (fastSma[0] > slowSma[0] && priceClose > fastSma[0])
{
double stopLossPrice = priceClose - stopLossPoints * pointSize;
double takeProfitPrice = priceClose + takeProfitPoints * pointSize;
if (trade.Buy(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
else if (fastSma[0] < slowSma[0] && priceClose < fastSma[0])
{
double stopLossPrice = priceClose + stopLossPoints * pointSize;
double takeProfitPrice = priceClose - takeProfitPoints * pointSize;
if (trade.Sell(lotSize, _Symbol, priceClose, stopLossPrice, takeProfitPrice))
{
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Alterações Realizadas
Regra de Fechamento com SMA de 20: Modificada a lógica para fechar a posição se o preço tocar a média móvel de 20 apenas quando o lucro atual em pontos é maior ou igual a minProfitPoints.
Controle de Lucro Mínimo: Adicionada uma verificação para garantir que apenas posições com lucro de ao menos 10 pips sejam fechadas ao tocar na média móvel de 20, evitando sair prematuramente de posições quando em perda.
Este código ajustado garante maior controle sobre quando fechar posições, só o fazendo sob critérios que limitam as perdas. Certifique-se de testar adequadamente em um ambiente seguro antes de aplicar em uma conta real.