//+------------------------------------------------------------------+
//| 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 (período 20, desvio 2)
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;
// 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;
}
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.");
}
}
}
}
}
percebi quando o preço esta em uma tendencia por exemplo de venda por exemplo quando acontece o rompimento para venda e o robo faz varias ordens de venda e o preço vai no fluxo de venda e fica varios preços no positivo quando acontece de derrepente o preço retroceder o robo nao esta fechando as ordens positivas para garantir o lucro, eu quero que o robo feche imediatamente todas ordens positivas em lucro quando o preço chegar num total de todas ordens abertas quando take total chegar a pelo menos $20 e assim ir fechando as ordens positivas em aberto
Para implementar essa lógica em seu Expert Advisor, você quer monitorar todas as posições abertas e fechar as que estão em lucro assim que um certo limite de lucro total seja atingido, por exemplo, $20. Você precisará iterar sobre todas as posições abertas, calcular o lucro acumulado e fechar as posições quando o critério for atendido.
Aqui está como você pode implementar essa lógica na função OnTick():
cpp
//+------------------------------------------------------------------+
//| Função para fechar ordens lucrativas |
//+------------------------------------------------------------------+
void CloseProfitableOrders(double minProfit)
{
CTrade trade;
double totalProfit = 0.0;
// Iterar sobre todas as posições abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionSelect(i))
{
double profit = PositionGetDouble(POSITION_PROFIT);
// Acumular o lucro
totalProfit += profit;
// Fechar a posição se estiver em lucro e atingir ou exceder o lucro mínimo estabelecido
if (profit > 0 && totalProfit >= minProfit)
{
ulong ticket = PositionGetTicket(i);
if (trade.PositionClose(ticket))
{
Print("Posição lucrativa fechada. Ticket: ", ticket);
}
else
{
Print("Erro ao fechar posição lucrativa: ", GetLastError());
}
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// (sua lógica existente)
// Fechar ordens lucrativas se o lucro total for superior a $20
CloseProfitableOrders(20);
// (qualquer outra lógica existente pode continuar aqui)
}
// (restante do seu código)
Explicação:
CloseProfitableOrders(double minProfit): Essa função é responsável por iterar sobre todas as posições abertas, acumulando o lucro e fechando as posições lucrativas se o lucro acumulado de todas as posições abertas atingir ou exceder o valor definido por minProfit, que neste caso é $20.
CTrade trade; Cria um objeto de trade para gerenciar as operações.
PositionsTotal(): Retorna o número total de posições abertas.
PositionSelect(i): Seleciona a posição i para manipulação.
PositionGetDouble(POSITION_PROFIT): Retorna o lucro da posição selecionada.
totalProfit: Acumula o lucro total das posições abertas.
trade.PositionClose(ticket): Fecha a posição lucrativa atual.
Ao usar esta implementação, todas as ordens lucrativas serão verificadas e fechadas assim que o lucro total acumulado de todas as ordens abertas atinja ou exceda $20, garantindo que o lucro seja realizado em tendências favoráveis.
me entregue o codigo completo com as implementações:
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
//+------------------------------------------------------------------+
//| 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
// Configurações das Bandas de Bollinger (período 20, desvio 2)
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;
// 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;
}
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.");
}
}
}
}
}
Claro! Eu vou integrar a função para fechar posições lucrativas ao seu código. Segue o código completo com essa implementação:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
// Variáveis para armazenar rompimento anterior
bool lastBreakoutAlta = false;
bool lastBreakoutBaixa = false;
double breakoutHigh = 0.0;
double breakoutLow = 0.0;
//+------------------------------------------------------------------+
//| 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
}
//+------------------------------------------------------------------+
//| Função para fechar ordens lucrativas |
//+------------------------------------------------------------------+
void CloseProfitableOrders(double minProfit)
{
CTrade trade;
double totalProfit = 0.0;
// Iterar sobre todas as posições abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionSelect(i))
{
double profit = PositionGetDouble(POSITION_PROFIT);
// Acumular o lucro
totalProfit += profit;
// Fechar a posição se estiver em lucro e atingir ou exceder o lucro mínimo estabelecido
if (profit > 0 && totalProfit >= minProfit)
{
ulong ticket = PositionGetTicket(i);
if (trade.PositionClose(ticket))
{
Print("Posição lucrativa fechada. Ticket: ", ticket);
}
else
{
Print("Erro ao fechar posição lucrativa: ", GetLastError());
}
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
// Configurações das Bandas de Bollinger (período 20, desvio 2)
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;
// 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;
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
// Gerenciamento de trailing stop
ManageTrailingStop();
// Fechar ordens lucrativas se o lucro total for superior a $20
CloseProfitableOrders(20);
}
//+------------------------------------------------------------------+
//| Gerenciamento de trailing stop |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
CTrade trade;
// 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.");
}
}
}
}
}
Explicações:
CloseProfitableOrders: Esta função itera sobre todas as posições abertas e fecha as que estão em lucro, assim que o lucro total atinge ou ultrapassa $20.
OnTick: O loop principal do EA que chama CloseProfitableOrders a cada tick para garantir que as ordens em lucro sejam fechadas conforme a lógica estabelecida.
Com estas alterações, seu robô finalizará posições lucrativas ao atingir o limite estabelecido, garantindo a realização de ganhos durante as tendências de alta ou baixa.