double askPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
// Preço de velas
double open1 = iOpen(NULL, PERIOD_CURRENT, 0);
double close1 = iClose(NULL, PERIOD_CURRENT, 0);
double low1 = iLow(NULL, PERIOD_CURRENT, 0);
double high1 = iHigh(NULL, PERIOD_CURRENT, 0);
double open2 = iOpen(NULL, PERIOD_CURRENT, 1);
double close2 = iClose(NULL, PERIOD_CURRENT, 1);
double low2 = iLow(NULL, PERIOD_CURRENT, 1);
double high2 = iHigh(NULL, PERIOD_CURRENT, 1);
// Detectar Padrões
if (isBullishEngulfing(open2, close2, open1, close1)) // Exemplo de Engulfing Altista
{
// Fechar ordens de venda abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
{
if (!trade.PositionClose(ticket))
Print("Erro ao fechar a posição de venda: ", GetLastError());
}
}
// Abrir nova ordem de compra
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lotSize;
request.type = ORDER_TYPE_BUY;
request.price = NormalizeDouble(askPrice, _Digits);
request.tp = NormalizeDouble(askPrice + takeProfitPips * _Point, _Digits);
request.sl = NormalizeDouble(askPrice - stopLossPips * _Point, _Digits);
request.deviation = 3;
if (OrderSend(request, result))
Print("Ordem de Compra Executada com padrão Engulfing Altista!");
else
Print("Erro ao executar a ordem de compra: ", GetLastError());
}
else if (isBearishEngulfing(open2, close2, open1, close1)) // Exemplo de Engulfing Baixista
{
// Fechar ordens de compra abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
{
if (!trade.PositionClose(ticket))
Print("Erro ao fechar a posição de compra: ", GetLastError());
}
}
// Abrir nova ordem de venda
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lotSize;
request.type = ORDER_TYPE_SELL;
request.price = NormalizeDouble(bidPrice, _Digits);
request.tp = NormalizeDouble(bidPrice - takeProfitPips * _Point, _Digits);
request.sl = NormalizeDouble(bidPrice + stopLossPips * _Point, _Digits);
request.deviation = 3;
if (OrderSend(request, result))
Print("Ordem de Venda Executada com padrão Engulfing Baixista!");
else
Print("Erro ao executar a ordem de venda: ", GetLastError());
}
// Gestão de Posições com Trailing Stop
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket))
{
if (PositionGetString(POSITION_SYMBOL) == Symbol())
{
double profit = PositionGetDouble(POSITION_PROFIT);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentTP = PositionGetDouble(POSITION_TP);
bool positionModified = false;
if (profit > 0)
{
if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
{
double newSL = NormalizeDouble(askPrice - trailingStopPips * _Point, _Digits);
if (newSL > PositionGetDouble(POSITION_SL))
{
positionModified = trade.PositionModify(ticket, newSL, currentTP);
if (positionModified)
Print("Trailing Stop ajustado para: ", DoubleToString(newSL, _Digits));
}
}
else if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
{
double newSL = NormalizeDouble(bidPrice + trailingStopPips * _Point, _Digits);
if (newSL < PositionGetDouble(POSITION_SL))
{
positionModified = trade.PositionModify(ticket, newSL, currentTP);
if (positionModified)
Print("Trailing Stop ajustado para: ", DoubleToString(newSL, _Digits));
}
}
}
// Fechar a posição se o preço se mover muito contra ela
if (profit < -20 * _Point) // Usa um limite mais próximo para fechar rapidamente em perda
{
if (trade.PositionClose(ticket))
Print("Posição fechada rapidamente ao atingir limite de perda: Ticket ", IntegerToString(ticket));
else
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
}
aproveite as funções que ativam compra e venda no codigo acima e implemente no meu codigo abaixo que nao esta funcionando abertura e fechameto de ordens.
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips);
return(INIT_SUCCEEDED);
}
// ** Verifica se existe uma posição aberta e aplica as regras de fechamento e abertura **
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips); // Atualiza o alvo de lucro considerando o spread
if (sma20 > sma200) // Regra 1: Quando a média de 20 estiver acima da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (trade.PositionClose(positionTicket))
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200");
}
else
{
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200"))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200");
}
else
{
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
}
else if (sma20 < sma200) // Regra 2: Quando a média de 20 estiver abaixo da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (trade.PositionClose(positionTicket))
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200");
}
else
{
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200"))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200");
}
else
{
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
To adapt your code to open and close trades for bullish and bearish engulfing patterns, similar to the operations in the first code, let's first identify and define the variables necessary for these patterns. The example script uses functions isBullishEngulfing and isBearishEngulfing to detect bullish and bearish engulfing patterns, respectively. I'll integrate this detection logic into your OnTick function, while maintaining your existing logic for the SMA20 and SMA200 crossover strategy.
First, include the functions isBullishEngulfing and isBearishEngulfing at the beginning of your code:
Then, modify your OnTick function to incorporate these patterns:
cpp
void OnTick()
{
double sma20 = iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE);
double sma200 = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE);
double closePrice = iClose(NULL, 0, 0);
bool positionExists = false;
ENUM_POSITION_TYPE currentPositionType = POSITION_TYPE_BUY;
ulong positionTicket = 0;
if (PositionSelect(_Symbol))
{
positionTicket = PositionGetInteger(POSITION_TICKET);
currentPositionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
positionExists = true;
}
double takeProfitPrice;
// ** Get the previous two candles' open and close prices for pattern detection **
double open1 = iOpen(NULL, PERIOD_CURRENT, 0);
double close1 = iClose(NULL, PERIOD_CURRENT, 0);
double open2 = iOpen(NULL, PERIOD_CURRENT, 1);
double close2 = iClose(NULL, PERIOD_CURRENT, 1);
// Verifica padrões de engulfing
if (isBullishEngulfing(open2, close2, open1, close1)) {
if (positionExists && currentPositionType == POSITION_TYPE_SELL) {
if (trade.PositionClose(positionTicket)) {
Print("Venda fechada devido à formação de engolfamento altista");
} else {
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
if (!positionExists) {
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido à formação de engolfamento altista")) {
Print("Compra aberta após formação de engolfamento altista");
} else {
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
} else if (isBearishEngulfing(open2, close2, open1, close1)) {
if (positionExists && currentPositionType == POSITION_TYPE_BUY) {
if (trade.PositionClose(positionTicket)) {
Print("Compra fechada devido à formação de engolfamento baixista");
} else {
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
if (!positionExists) {
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido à formação de engolfamento baixista")) {
Print("Venda aberta após formação de engolfamento baixista");
} else {
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
}
// ** Also include your other SMA-based logic here, if they should coexist **
if (sma20 > sma200) // Regra 1: Quando a média de 20 estiver acima da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL) {
if (trade.PositionClose(positionTicket)) {
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200");
} else {
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
if (!positionExists) {
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200")) {
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200");
} else {
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
} else if (sma20 < sma200) // Regra 2: Quando a média de 20 estiver abaixo da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY) {
if (trade.PositionClose(positionTicket)) {
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200");
} else {
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
if (!positionExists) {
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200")) {
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200");
} else {
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
}
}
This modification introduces the engulfing pattern detection and integrates it into your trading logic. It ensures that existing positions are closed based on both the SMA strategy logic and the engulfing pattern signals before opening new potential positions according to detected patterns. Adjust the logic, profit targets, and conditions as needed based on your specific trading strategy and objectives.
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips);
return(INIT_SUCCEEDED);
}
// ** Verifica se existe uma posição aberta e aplica as regras de fechamento e abertura **
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips); // Atualiza o alvo de lucro considerando o spread
if (sma20 > sma200) // Regra 1: Quando a média de 20 estiver acima da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (trade.PositionClose(positionTicket))
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200");
}
else
{
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200"))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200");
}
else
{
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
}
else if (sma20 < sma200) // Regra 2: Quando a média de 20 estiver abaixo da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (trade.PositionClose(positionTicket))
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200");
}
else
{
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200"))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200");
}
else
{
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
Below is the complete altered code, which integrates the detection of bullish and bearish engulfing patterns into your existing trading strategy based on SMA crossovers:
cpp
//+------------------------------------------------------------------+
//| MyRobot.mq5 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#include <Trade/Trade.mqh>
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
// Funções para detecção dos padrões
bool isBullishEngulfing(double open1, double close1, double open2, double close2) {
return (close1 > open1) && (close2 < open2) && (open1 < close2) && (close1 > open2);
}
bool isBearishEngulfing(double open1, double close1, double open2, double close2) {
return (open1 > close1) && (open2 < close2) && (close2 > open1) && (close1 < open2);
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double sma20 = iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE);
double sma200 = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE);
double closePrice = iClose(NULL, 0, 0);
bool positionExists = false;
ENUM_POSITION_TYPE currentPositionType = POSITION_TYPE_BUY;
ulong positionTicket = 0;
if (PositionSelect(_Symbol))
{
positionTicket = PositionGetInteger(POSITION_TICKET);
currentPositionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
positionExists = true;
}
double takeProfitPrice;
// ** Get the previous two candles' open and close prices for pattern detection **
double open1 = iOpen(NULL, PERIOD_CURRENT, 0);
double close1 = iClose(NULL, PERIOD_CURRENT, 0);
double open2 = iOpen(NULL, PERIOD_CURRENT, 1);
double close2 = iClose(NULL, PERIOD_CURRENT, 1);
// Verifica padrões de engulfing
if (isBullishEngulfing(open2, close2, open1, close1)) {
if (positionExists && currentPositionType == POSITION_TYPE_SELL) {
if (trade.PositionClose(positionTicket)) {
Print("Venda fechada devido à formação de engolfamento altista");
} else {
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
if (!positionExists) {
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido à formação de engolfamento altista")) {
Print("Compra aberta após formação de engolfamento altista");
} else {
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
} else if (isBearishEngulfing(open2, close2, open1, close1)) {
if (positionExists && currentPositionType == POSITION_TYPE_BUY) {
if (trade.PositionClose(positionTicket)) {
Print("Compra fechada devido à formação de engolfamento baixista");
} else {
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
if (!positionExists) {
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido à formação de engolfamento baixista")) {
Print("Venda aberta após formação de engolfamento baixista");
} else {
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
}
// ** Also include your other SMA-based logic here, if they should coexist **
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips); // Atualiza o alvo de lucro considerando o spread
if (sma20 > sma200) // Regra 1: Quando a média de 20 estiver acima da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (trade.PositionClose(positionTicket))
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200");
}
else
{
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
if (!positionExists)
{
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200"))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200");
}
else
{
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
}
else if (sma20 < sma200) // Regra 2: Quando a média de 20 estiver abaixo da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (trade.PositionClose(positionTicket))
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200");
}
else
{
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
if (!positionExists)
{
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200"))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200");
}
else
{
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
}
}
//+------------------------------------------------------------------+
This complete code integrates both the detection of engulfing patterns and the SMA crossover logic. The code tries to open or close trades based on these detected patterns, as well as existing moving average conditions. Additionally, it adapts your profit targets across various trading instruments. Please ensure you test this code thoroughly in a demo environment before using it in a live setting, as trading on candlestick patterns can be prone to false signals.
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
// ** Get the previous two candles' open and close prices for pattern detection **
double open1 = iOpen(NULL, PERIOD_CURRENT, 0);
double close1 = iClose(NULL, PERIOD_CURRENT, 0);
double open2 = iOpen(NULL, PERIOD_CURRENT, 1);
double close2 = iClose(NULL, PERIOD_CURRENT, 1);
// Verifica padrões de engulfing
if (isBullishEngulfing(open2, close2, open1, close1)) {
if (positionExists && currentPositionType == POSITION_TYPE_SELL) {
if (trade.PositionClose(positionTicket)) {
Print("Venda fechada devido à formação de engolfamento altista");
} else {
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists) {
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido à formação de engolfamento altista")) {
Print("Compra aberta após formação de engolfamento altista");
} else {
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
} else if (isBearishEngulfing(open2, close2, open1, close1)) {
if (positionExists && currentPositionType == POSITION_TYPE_BUY) {
if (trade.PositionClose(positionTicket)) {
Print("Compra fechada devido à formação de engolfamento baixista");
} else {
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists) {
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido à formação de engolfamento baixista")) {
Print("Venda aberta após formação de engolfamento baixista");
} else {
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
}
// ** Also include your other SMA-based logic here, if they should coexist **
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips); // Atualiza o alvo de lucro considerando o spread
if (sma20 > sma200) // Regra 1: Quando a média de 20 estiver acima da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (trade.PositionClose(positionTicket))
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200");
}
else
{
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200"))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200");
}
else
{
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
}
else if (sma20 < sma200) // Regra 2: Quando a média de 20 estiver abaixo da de 200
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (trade.PositionClose(positionTicket))
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200");
}
else
{
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200"))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200");
}
else
{
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
regra1 - quando a media de 20 cruzar acima da media de 200 e a media de 20 ficar acima da media de 200 e o preço ficar a acima das duas medias de 20 e de 200 entao o robo precisa verificar se existe alguma ordem de venda aberta e fechar a ordem de venda, e em seguida abrir uma ordem de Compra.
regra2 - quando a media de 20 cruzar abaixo da media de 200 e a media de 20 ficar abaixo da media de 200 e o preço ficar a abaixo das duas medias de 20 e de 200 entao o robo precisa verificar se existe alguma ordem de Compra aberta e fechar a ordem de compra, e em seguida abrir uma ordem de Venda.
To implement the rules you've described, we need to modify the existing trading strategy for the SMA crossover logic. The rules specify conditions not only for the SMA crossover, but also for the price position relative to both moving averages. I'll adjust the logic to accommodate these specific requirements.
Here's how the code can be updated:
cpp
//+------------------------------------------------------------------+
//| MyRobot.mq5 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#include <Trade/Trade.mqh>
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double sma20 = iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE);
double sma200 = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE);
double closePrice = iClose(NULL, 0, 0);
bool positionExists = false;
ENUM_POSITION_TYPE currentPositionType = POSITION_TYPE_BUY;
ulong positionTicket = 0;
if (PositionSelect(_Symbol))
{
positionTicket = PositionGetInteger(POSITION_TICKET);
currentPositionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
positionExists = true;
}
double takeProfitPrice;
// ** Regra 1: SMA20 cruzar acima de SMA200 e preço acima de ambas **
if (sma20 > sma200 && closePrice > sma20 && closePrice > sma200)
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (trade.PositionClose(positionTicket))
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200 com preço acima de ambas");
}
else
{
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
if (!positionExists)
{
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200 com preço acima de ambas"))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200 com preço acima de ambas");
}
else
{
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
}
// ** Regra 2: SMA20 cruzar abaixo de SMA200 e preço abaixo de ambas **
else if (sma20 < sma200 && closePrice < sma20 && closePrice < sma200)
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (trade.PositionClose(positionTicket))
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200 com preço abaixo de ambas");
}
else
{
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
if (!positionExists)
{
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200 com preço abaixo de ambas"))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200 com preço abaixo de ambas");
}
else
{
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
}
}
//+------------------------------------------------------------------+
Key Changes Made:
Rule 1:
Triggered when SMA20 crosses above SMA200 and the price is above both SMAs.
Closes existing sell positions, if any, and opens a new buy position.
Rule 2:
Triggered when SMA20 crosses below SMA200 and the price is below both SMAs.
Closes existing buy positions, if any, and opens a new sell position.
The trader logic was refined to ensure conditions are examined before performing trading actions, aligned with your specified requirements.
Make sure to test the updated logic thoroughly in a controlled environment before applying it to live market conditions. It is crucial to check for correct position management in different market scenarios.
#include <Trade\Trade.mqh> // Inclusão da biblioteca de negociação
CTrade trade; // Criando uma instância da classe CTrade para gerenciar operações
double askPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
// Preço de velas
double open1 = iOpen(NULL, PERIOD_CURRENT, 0);
double close1 = iClose(NULL, PERIOD_CURRENT, 0);
double low1 = iLow(NULL, PERIOD_CURRENT, 0);
double high1 = iHigh(NULL, PERIOD_CURRENT, 0);
double open2 = iOpen(NULL, PERIOD_CURRENT, 1);
double close2 = iClose(NULL, PERIOD_CURRENT, 1);
double low2 = iLow(NULL, PERIOD_CURRENT, 1);
double high2 = iHigh(NULL, PERIOD_CURRENT, 1);
// Detectar Padrões
if (isBullishEngulfing(open2, close2, open1, close1)) // Exemplo de Engulfing Altista
{
// Fechar ordens de venda abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
{
if (!trade.PositionClose(ticket))
Print("Erro ao fechar a posição de venda: ", GetLastError());
}
}
// Abrir nova ordem de compra
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lotSize;
request.type = ORDER_TYPE_BUY;
request.price = NormalizeDouble(askPrice, _Digits);
request.tp = NormalizeDouble(askPrice + takeProfitPips * _Point, _Digits);
request.sl = NormalizeDouble(askPrice - stopLossPips * _Point, _Digits);
request.deviation = 3;
if (OrderSend(request, result))
Print("Ordem de Compra Executada com padrão Engulfing Altista!");
else
Print("Erro ao executar a ordem de compra: ", GetLastError());
}
else if (isBearishEngulfing(open2, close2, open1, close1)) // Exemplo de Engulfing Baixista
{
// Fechar ordens de compra abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket) && PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
{
if (!trade.PositionClose(ticket))
Print("Erro ao fechar a posição de compra: ", GetLastError());
}
}
// Abrir nova ordem de venda
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lotSize;
request.type = ORDER_TYPE_SELL;
request.price = NormalizeDouble(bidPrice, _Digits);
request.tp = NormalizeDouble(bidPrice - takeProfitPips * _Point, _Digits);
request.sl = NormalizeDouble(bidPrice + stopLossPips * _Point, _Digits);
request.deviation = 3;
if (OrderSend(request, result))
Print("Ordem de Venda Executada com padrão Engulfing Baixista!");
else
Print("Erro ao executar a ordem de venda: ", GetLastError());
}
// Gestão de Posições com Trailing Stop
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (PositionSelectByTicket(ticket))
{
if (PositionGetString(POSITION_SYMBOL) == Symbol())
{
double profit = PositionGetDouble(POSITION_PROFIT);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentTP = PositionGetDouble(POSITION_TP);
if (profit > 0)
{
if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
{
double newSL = NormalizeDouble(askPrice - trailingStopPips * _Point, _Digits);
if (newSL > PositionGetDouble(POSITION_SL))
{
trade.PositionModify(ticket, newSL, currentTP);
Print("Trailing Stop ajustado para: ", DoubleToString(newSL, _Digits));
}
}
else if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
{
double newSL = NormalizeDouble(bidPrice + trailingStopPips * _Point, _Digits);
if (newSL < PositionGetDouble(POSITION_SL))
{
trade.PositionModify(ticket, newSL, currentTP);
Print("Trailing Stop ajustado para: ", DoubleToString(newSL, _Digits));
}
}
}
if (profit > 100 * _Point)
{
if (trade.PositionClose(ticket))
Print("Posição lucrativa fechada: Ticket ", IntegerToString(ticket));
else
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
}
use a funcão que aciona abertura de compra e venda e fechamento de ordens do codigo acima e use isso para arrumar o codigo de baixo que nao fecha ordens nem altera atendencia quando existe cruzamento de medias e preço
como na regra que coloquei no codigo abaixo
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips);
return(INIT_SUCCEEDED);
}
// ** Regra 1: SMA20 cruzar acima de SMA200 e preço acima de ambas **
if (sma20 > sma200 && closePrice > sma20 && closePrice > sma200)
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (trade.PositionClose(positionTicket))
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200 com preço acima de ambas");
}
else
{
Print("Erro ao fechar posição de venda: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice + PipsToPoints(profitTargetPips); // Define o take profit para compra
if (trade.Buy(lotSize, NULL, closePrice, 0, takeProfitPrice, "Comprado devido ao cruzamento da SMA20 acima da SMA200 com preço acima de ambas"))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200 com preço acima de ambas");
}
else
{
Print("Erro ao abrir posição de compra: ", trade.ResultRetcode());
}
}
}
// ** Regra 2: SMA20 cruzar abaixo de SMA200 e preço abaixo de ambas **
else if (sma20 < sma200 && closePrice < sma20 && closePrice < sma200)
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (trade.PositionClose(positionTicket))
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200 com preço abaixo de ambas");
}
else
{
Print("Erro ao fechar posição de compra: ", trade.ResultRetcode());
return;
}
}
code
if (!positionExists)
{
takeProfitPrice = closePrice - PipsToPoints(profitTargetPips); // Define o take profit para venda
if (trade.Sell(lotSize, NULL, closePrice, 0, takeProfitPrice, "Vendido devido ao cruzamento da SMA20 abaixo da SMA200 com preço abaixo de ambas"))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200 com preço abaixo de ambas");
}
else
{
Print("Erro ao abrir posição de venda: ", trade.ResultRetcode());
}
}
To integrate the logic from the first code snippet into the second one, I'll ensure that we maintain the structure for both order opening and closing, following the rules specified for the SMA crossover and price conditions.
Here's how the second code should look after incorporating the necessary logic:
cpp
//+------------------------------------------------------------------+
//| MyRobot.mq5 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#include <Trade/Trade.mqh>
input double lotSize = 0.01; // Lote padrão
double profitTargetPips = 100.0; // Alvo de lucro em pips
double maxSpreadPips = 100.0; // Limite máximo de spread para abrir ordens
CTrade trade; // Cria um objeto para operações de trading
// Função para converter pips em pontos
double PipsToPoints(double pips)
{
return pips * _Point;
}
// Função para obter o spread atual em pips
double GetCurrentSpreadPips()
{
MqlTick tick;
if (SymbolInfoTick(_Symbol, tick))
{
double spreadPoints = tick.ask - tick.bid;
return spreadPoints / _Point; // Converte pontos para pips
}
return 0; // Retorna 0 em caso de erro
}
// Função para definir o alvo de lucro de acordo com o símbolo
void SetProfitTarget(double spreadPips)
{
if (_Symbol == "EURUSD" || _Symbol == "USDJPY" || _Symbol == "GBPJPY" ||
_Symbol == "AUDJPY" || _Symbol == "AUDUSD" || _Symbol == "NZDUSD" ||
_Symbol == "GBPUSD" || _Symbol == "USDCHF" || _Symbol == "USDCAD")
{
profitTargetPips = 10.0 + MathRand() % 11; // Entre 10 e 20 pips
}
else if (_Symbol == "NASDAQ" || _Symbol == "US100" || _Symbol == "US30" ||
_Symbol == "US500")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else if (_Symbol == "GOLD" || _Symbol == "XAUUSD")
{
profitTargetPips = 50.0 + MathRand() % 51; // Entre 50 e 100 pips
}
else
{
profitTargetPips = 100.0; // Valor padrão para outros ativos
}
profitTargetPips += spreadPips; // Adiciona o spread ao alvo de lucro
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
double currentSpreadPips = GetCurrentSpreadPips();
SetProfitTarget(currentSpreadPips);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
double askPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
double sma20 = iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE);
double sma200 = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE);
double closePrice = iClose(NULL, 0, 0);
bool positionExists = false;
ENUM_POSITION_TYPE currentPositionType = POSITION_TYPE_BUY;
ulong positionTicket = 0;
if (PositionSelect(_Symbol))
{
positionTicket = PositionGetInteger(POSITION_TICKET);
currentPositionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
positionExists = true;
}
// ** Regra 1: SMA20 cruzar acima de SMA200 e preço acima de ambas **
if (sma20 > sma200 && closePrice > sma20 && closePrice > sma200)
{
if (positionExists && currentPositionType == POSITION_TYPE_SELL)
{
if (!trade.PositionClose(positionTicket))
{
Print("Erro ao fechar posição de venda: ", GetLastError());
return;
}
else
{
Print("Venda fechada devido ao cruzamento da SMA20 acima da SMA200 com preço acima de ambas");
}
}
if (!positionExists)
{
double takeProfitPrice = NormalizeDouble(askPrice + PipsToPoints(profitTargetPips), _Digits);
double stopLossPrice = NormalizeDouble(askPrice - PipsToPoints(200), _Digits);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lotSize;
request.type = ORDER_TYPE_BUY;
request.price = askPrice;
request.tp = takeProfitPrice;
request.sl = stopLossPrice;
request.deviation = 3;
if (OrderSend(request, result))
{
Print("Compra aberta após SMA20 cruzar e ficar acima da SMA200 com preço acima de ambas");
}
else
{
Print("Erro ao abrir posição de compra: ", GetLastError());
}
}
}
// ** Regra 2: SMA20 cruzar abaixo de SMA200 e preço abaixo de ambas **
else if (sma20 < sma200 && closePrice < sma20 && closePrice < sma200)
{
if (positionExists && currentPositionType == POSITION_TYPE_BUY)
{
if (!trade.PositionClose(positionTicket))
{
Print("Erro ao fechar posição de compra: ", GetLastError());
return;
}
else
{
Print("Compra fechada devido ao cruzamento da SMA20 abaixo da SMA200 com preço abaixo de ambas");
}
}
if (!positionExists)
{
double takeProfitPrice = NormalizeDouble(bidPrice - PipsToPoints(profitTargetPips), _Digits);
double stopLossPrice = NormalizeDouble(bidPrice + PipsToPoints(200), _Digits);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lotSize;
request.type = ORDER_TYPE_SELL;
request.price = bidPrice;
request.tp = takeProfitPrice;
request.sl = stopLossPrice;
request.deviation = 3;
if (OrderSend(request, result))
{
Print("Venda aberta após SMA20 cruzar e ficar abaixo da SMA200 com preço abaixo de ambas");
}
else
{
Print("Erro ao abrir posição de venda: ", GetLastError());
}
}
}
}
Integration Details:
Order Management: Incorporated the logic for closing positions when the conditions are met to switch trends (e.g., closing sell positions when a buy signal is detected).
Standardization: Used the normalized price for setting take profit and stop loss, similarly to your original code.
Error Handling: Added error reporting through GetLastError() for clarity in the event of execution failures.
By following the logic from your initial request and integrating it with the SMA-based strategy, the above code should meet your specified conditions. Always ensure extensive testing, especially in backtesting and demo environments, before considering deploying strategies on live accounts.