0% found this document useful (0 votes)
47 views20 pages

RObo MT5

The document is a code for an Expert Advisor (EA) in MQL5, designed for automated trading on the MetaTrader 5 platform. It includes various configurations for trading parameters, time settings, risk management, and a user interface panel for displaying trading statistics. The EA manages trades based on specific conditions and indicators, providing functionalities like profit tracking, order management, and customizable settings for user preferences.

Uploaded by

Rogerio Vargas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views20 pages

RObo MT5

The document is a code for an Expert Advisor (EA) in MQL5, designed for automated trading on the MetaTrader 5 platform. It includes various configurations for trading parameters, time settings, risk management, and a user interface panel for displaying trading statistics. The EA manages trades based on specific conditions and indicators, providing functionalities like profit tracking, order management, and customizable settings for user preferences.

Uploaded by

Rogerio Vargas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 20

//+------------------------------------------------------------------+

//| ProjectName |
//| Copyright 2020, CompanyName |
//| http://www.companyname.net |
//+------------------------------------------------------------------+

#include "Library/DSLibraryMT5.mq5" //include Library


#include "Panel/DS Panel.mqh"
#include "Library/DSNews.mqh"
#resource "Indicadores\Indicador_Rogerio.ex5"
#include <trade/trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Expert\Money\MoneyFixedMargin.mqh>
CTrade m_trade;
CSymbolInfo m_symbol;
CAccountInfo m_account;
CDealInfo m_deal;
COrderInfo m_order;
CPositionInfo m_position;
enum ePermision
{
Compra,
Venda,
Compra_e_Venda
};

int bff_ind = INVALID_HANDLE;

CDSPanel *AppWindow; // painel

input int iMagic = 1; //Número Mágico


input string iEaComment = "EA_ROGÉRIO"; //Comentario

input group "Configurações de Horários"


input eTimeType iTimeType = serverE; //Tipo de horario 1
input string TradeStartTime = "00:00"; //Hora inicio 1
input string TradeStopTime = "23:30"; //Hora final 1

input eTimeType iTimeType2 = serverE; //Tipo de horario 2


input string TradeStartTime2 = "00:00"; //Hora inicio 2
input string TradeStopTime2 = "23:30"; //Hora final 2

input eTimeType iTimeType3 = serverE; //Tipo de horario 3


input string TradeStartTime3 = "00:00"; //Hora inicio 3
input string TradeStopTime3 = "23:30"; //Hora final 3

input eTimeType iTimeType4 = serverE; //Tipo de horario 4


input string TradeStartTime4 = "00:00"; //Hora inicio 4
input string TradeStopTime4 = "23:30"; //Hora final 4

input eTimeType iTimeTypeClose = serverE; //Tipo de horario de Fechamento


input string TradeStartTimeClose = "17:00"; //Horário para Encerramento de Todas As
Ordens Abertas
string TradeStopTimeClose = "23:30"; //Hora final 4

input group "Permissão"


input ePermision Permissao=Compra_e_Venda; //Permissão

input group "Inputs do Indicador";

input int Period1 = 72;


input int Period2 = 305;
input int Period3 = 1292;
input bool SempreVisivel = true;
input bool Fractais = true;

input group "Gerenciamento"


input double Lote=1; //Lote
input double TakeProfit=1500; // TakeProfit
input double StopLoss=3000;//StopLoss
input int Distancia_Minima=5000; //Distância Mínima
input int Distancia_Maxima=10000; //Distância Máxima

input group "Aguardar x velas após última ordem"


input int Aguardar_x_velas_apos_ultima_ordem=4;//Aguardar x velas após última ordem

input group "Fechar Ordem ao Final da Vela"


input bool Fechamento_ao_Final_da_Vela=false; // Fechar Ordem ao Final da Vela?

input group "Modo"


input bool Modo_Tendencia=false; // Modo Tendência?
input group "Pontos de Antecipação"
input int Pontos_Antecipacao=500;// Pontos de Antecipação

input group "Break Even"


input bool iUseBe = false; //Ativar Break Even
input int iDistanceBE = 80; //Distância ativar BE
input int iPointsProtected = 5; //Pontos para proteger

input group "Trail Stop"


input bool iUseTrail = false; //Ativar Trail
input int iDistanceTrail = 100; //Distância ativar Trail
input int iTrailJump = 5; //Proteção passos do trail

input group "Metas Finançeiras";


input bool iUseDailyTarger = false; //Ativar meta diária
input double Perda_Maxima_diaria = 1; // Perda Máxima diária financeira (%))
input double Ganho_Maximo_diario = 1; // Ganho Máximo diário financeira (%)
input group "Painel"
input bool iCreatPanel = true; //Criar painel
input int iDistancePanel = 70; //Afastamento do Painel
input int iWidithPanel = 470; //Largura do Painel
input int iHeightPanel = 430; //Altura do Painel
input color icolorProfit = clrGreenYellow;//Cor para lucro e compra
input color icolorLoss = clrOrangeRed;//Cor para prejuizo e venda

string eaStatus = "";


int waitOppositeChannel = -5;
bool lastTradeWin;
string lastTradeStatus = "" ;
static string lastStatus = "";
static bool galeActive = true;
static bool soroActive = true;
datetime currentTimeG = 0;
static bool canOpenPeding = false;

color rec_triple_h1=0;
color rec_triple_30=0;
int velas_loading=0;

int control_velas_ord=0;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{

fInitializeIndicators();

TimeType(currentTimeG,iTimeType);
Print("Hora atual init: ",currentTimeG, " tipo de
hora:",EnumToString(iTimeType));
// if(AccountModeReturn() != "Demo")
// {
// Alert("Somente conta demo");
// return(INIT_FAILED);
// }
ChartSetInteger(0, CHART_SHOW_GRID, false); // false to remove grid

//--- create timer


EventSetTimer(60);
//Painel
if(iCreatPanel)
{
if(CheckPointer(AppWindow) == POINTER_INVALID) //--- step 1
{
AppWindow = new CDSPanel;
if(CheckPointer(AppWindow) == POINTER_INVALID)
{
Print("falha na criação do painel");
return(INIT_FAILED);
}
}
else //--- step 2
{
delete AppWindow;
AppWindow = new CDSPanel;
if(CheckPointer(AppWindow) == POINTER_INVALID)
{
Print("falha na criação do painel");
return(INIT_FAILED);
}
}

if(!AppWindow.Create(0, "EA ROGÉRIO", 0, iDistancePanel, 50, iWidithPanel,


iHeightPanel))
return(INIT_FAILED);

//---Execução da aplicação
if(!AppWindow.Run())
{
return(INIT_FAILED);
}
AppWindow.BringToTop();
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
if(!MQLInfoInteger(MQL_TESTER))
{
AppWindow.Destroy(reason);
delete AppWindow;
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
string obj_name="";
int i=0;

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTick()
{
TesterHideIndicators(true);
//---
OrderCheckClass checkOrder(iMagic, 0, _Symbol);

//Update Panel
if(iCreatPanel)
{
datetime begin = (datetime)SymbolInfoInteger(NULL, SYMBOL_START_TIME), end =
(datetime)SymbolInfoInteger(NULL, SYMBOL_EXPIRATION_TIME); //expiration date
int countProfit = 0;
int countLoss = 0;
int countTotal = 0;
double porcentageWin = 0;

AppWindow.UpdateLabel1("Server Time", clrSteelBlue);


AppWindow.UpdateLabel2("Expiration Date");
AppWindow.UpdateLabel3("Ativo");
AppWindow.UpdateLabel4(TimeToString(TimeCurrent(), TIME_SECONDS));
AppWindow.UpdateLabel5(begin != end ? TimeToString(end, TIME_DATE) : "-");
AppWindow.UpdateLabel6(_Symbol);

AppWindow.UpdateLabel7("Local Time");
AppWindow.UpdateLabel8("Spread");
AppWindow.UpdateLabel9("Preço");
AppWindow.UpdateLabel10(TimeToString(TimeLocal(), TIME_SECONDS));
AppWindow.UpdateLabel11(IntegerToString(SymbolInfoInteger(_Symbol,
SYMBOL_SPREAD)));
AppWindow.UpdateLabel12(DoubleToString(Bid(), _Digits));

AppWindow.UpdateLabel13("Eficiência");
AppWindow.UpdateLabel14("Profit");

AppWindow.UpdateLabel15("Dia");
countProfit = DailyTotalOrders(iMagic, true, false, _Symbol);
countLoss = DailyTotalOrders(iMagic, false, true, _Symbol);
countTotal = DailyTotalOrders(iMagic, true, true, _Symbol);
countTotal > 0 ? porcentageWin = PorcentageCalc(countProfit, countTotal) :
porcentageWin = 0;
string resultPorcentage = "";
countTotal > 0 ? resultPorcentage = DoubleToString(porcentageWin, 0) + "%" :
resultPorcentage = "Aguardando";
AppWindow.UpdateLabel16(IntegerToString(countProfit) + "/" +
IntegerToString(countTotal) + "(" + resultPorcentage + ")", porcentageWin >= 0 ?
icolorProfit : icolorLoss);
AppWindow.UpdateLabel17(DoubleToString(DailyProfit(iMagic, 0, _Symbol), 2),
DailyProfit(iMagic, 0, _Symbol) >= 0 ? icolorProfit : icolorLoss);

AppWindow.UpdateLabel18("Semana");
countProfit = WeekTotalOrdersOnlyHistory(iMagic, true, false, _Symbol);
countLoss = WeekTotalOrdersOnlyHistory(iMagic, false, true, _Symbol);
countTotal = WeekTotalOrdersOnlyHistory(iMagic, true, true, _Symbol);
countTotal > 0 ? porcentageWin = PorcentageCalc(countProfit, countTotal) :
porcentageWin = 0;
resultPorcentage = "";
countTotal > 0 ? resultPorcentage = DoubleToString(porcentageWin, 0) + "%" :
resultPorcentage = "Aguardando";
AppWindow.UpdateLabel19(IntegerToString(countProfit) + "/" +
IntegerToString(countTotal) + "(" + resultPorcentage + ")", porcentageWin >= 0 ?
icolorProfit : icolorLoss);
AppWindow.UpdateLabel20(DoubleToString(WeekProfitOnlyHistory(iMagic,
_Symbol), 2), WeekProfitOnlyHistory(iMagic, _Symbol) >= 0 ? icolorProfit :
icolorLoss);

AppWindow.UpdateLabel21("Mês");
countProfit = MonthTotalOrdersOnlyHistory(iMagic, true, false, _Symbol);
countLoss = MonthTotalOrdersOnlyHistory(iMagic, false, true, _Symbol);
countTotal = MonthTotalOrdersOnlyHistory(iMagic, true, true, _Symbol);
countTotal > 0 ? porcentageWin = PorcentageCalc(countProfit, countTotal) :
porcentageWin = 0;
resultPorcentage = "";
countTotal > 0 ? resultPorcentage = DoubleToString(porcentageWin, 0) + "%" :
resultPorcentage = "Aguardando";
AppWindow.UpdateLabel22(IntegerToString(countProfit) + "/" +
IntegerToString(countTotal) + "(" + resultPorcentage + ")", porcentageWin >= 0 ?
icolorProfit : icolorLoss);
AppWindow.UpdateLabel23(DoubleToString(MonthProfitOnlyHistory(iMagic,
_Symbol), 2), MonthProfitOnlyHistory(iMagic, _Symbol) >= 0 ? icolorProfit :
icolorLoss);

AppWindow.UpdateLabel24("Total");
countProfit = TotalTotalOrdersOnlyHistory(iMagic, true, false, _Symbol);
countLoss = TotalTotalOrdersOnlyHistory(iMagic, false, true, _Symbol);
countTotal = TotalTotalOrdersOnlyHistory(iMagic, true, true, _Symbol);
countTotal > 0 ? porcentageWin = PorcentageCalc(countProfit, countTotal) :
porcentageWin = 0;
resultPorcentage = "";
countTotal > 0 ? resultPorcentage = DoubleToString(porcentageWin, 0) + "%" :
resultPorcentage = "Aguardando";
AppWindow.UpdateLabel25(IntegerToString(countProfit) + "/" +
IntegerToString(countTotal) + "(" + resultPorcentage + ")", porcentageWin >= 0 ?
icolorProfit : icolorLoss);
AppWindow.UpdateLabel26(DoubleToString(TotalProfitOnlyHistory(iMagic,
_Symbol), 2), TotalProfitOnlyHistory(iMagic, _Symbol) >= 0 ? icolorProfit :
icolorLoss);

AppWindow.UpdateLabel27("Tipo de Conta");
AppWindow.UpdateLabel28("Profit Aberto");
AppWindow.UpdateLabel29("Saldo de Conta");

AppWindow.UpdateLabel30(AccountMarginModeReturn() + " " +


AccountModeReturn());

AppWindow.UpdateLabel31(DoubleToString(checkOrder.circleTradeMagicRangePeriodProfit
Sum(), 2), checkOrder.circleTradeMagicRangePeriodProfitSum() >= 0 ? icolorProfit :
icolorLoss);
AppWindow.UpdateLabel32(DoubleToString(AccountBalance(), 2));

AppWindow.UpdateLabel33("Orders");
AppWindow.UpdateLabel34("Volume");
AppWindow.UpdateLabel35("Avg. Price");
AppWindow.UpdateLabel36("Points");
AppWindow.UpdateLabel37("Situation");

AppWindow.UpdateLabel38("Buy", clrSteelBlue);

AppWindow.UpdateLabel39(DoubleToString(checkOrder.circleTradeMagicRangePeriodLotsSu
mLiveType(OP_BUY), 2));

AppWindow.UpdateLabel40(DoubleToString(checkOrder.circleTradeMagicRangeAveragePrice
TypeOrUniversal(OP_BUY), _Digits), clrSteelBlue);

AppWindow.UpdateLabel41(IntegerToString(checkOrder.circleTradeMagicRangePointSumTyp
e(OP_BUY)), checkOrder.circleTradeMagicRangePointSumType(OP_BUY) >= 0 ?
icolorProfit : icolorLoss);

AppWindow.UpdateLabel42(DoubleToString(checkOrder.circleTradeMagicRangePeriodProfit
SumType(OP_BUY), 2) + AccountInfoString(ACCOUNT_CURRENCY),
checkOrder.circleTradeMagicRangePeriodProfitSumType(OP_BUY) >= 0 ? icolorProfit :
icolorLoss);

AppWindow.UpdateLabel43("Sell", clrLightSalmon);

AppWindow.UpdateLabel44(DoubleToString(checkOrder.circleTradeMagicRangePeriodLotsSu
mLiveType(OP_SELL), 2));

AppWindow.UpdateLabel45(DoubleToString(checkOrder.circleTradeMagicRangeAveragePrice
TypeOrUniversal(OP_SELL), _Digits), clrLightSalmon);

AppWindow.UpdateLabel46(IntegerToString(checkOrder.circleTradeMagicRangePointSumTyp
e(OP_SELL)), checkOrder.circleTradeMagicRangePointSumType(OP_SELL) >= 0 ?
icolorProfit : icolorLoss);

AppWindow.UpdateLabel47(DoubleToString(checkOrder.circleTradeMagicRangePeriodProfit
SumType(OP_SELL), 2) + " " + AccountInfoString(ACCOUNT_CURRENCY),
checkOrder.circleTradeMagicRangePeriodProfitSumType(OP_SELL) >= 0 ? icolorProfit :
icolorLoss);

AppWindow.UpdateLabel48("2025");
}

fTrade();
fTrail();
}

int velas__=0;
int velas_close=0;
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//---
//Update Panel
if(iCreatPanel)
{
AppWindow.ChartEvent(id, lparam, dparam, sparam);
}
}

//+------------------------------------------------------------------+

string token_triple_h1="";
string token_triple_m30="";

int velas_ord=0;

int velas_uni=0;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+

double rec_ind_1=0;
double rec_ind_2=0;
double rec_ind_3=0;
double rec_ind_4=0;
double rec_ind_5=0;
double rec_ind_6=0;

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void fTrade()
{

bool trade=true;

//rec_triple_h1= IcustomHandler(1,Triple_Handle_H1,1);

rec_ind_1=IcustomHandler(1,bff_ind,0);
rec_ind_2=IcustomHandler(1,bff_ind,1);
rec_ind_3=IcustomHandler(1,bff_ind,2);
rec_ind_4=IcustomHandler(1,bff_ind,3);
rec_ind_5=IcustomHandler(1,bff_ind,4);
rec_ind_6=IcustomHandler(1,bff_ind,5);

//+------------------------------------------------------------------+
static bool oneTradePerCandle = true;
bool hourResult = DailyHoursToTrade(TradeStartTime, TradeStopTime, iTimeType);
bool hourResult1 = DailyHoursToTrade(TradeStartTime2, TradeStopTime2,
iTimeType2);
bool hourResult2 = DailyHoursToTrade(TradeStartTime3, TradeStopTime3,
iTimeType3);
bool hourResult3 = DailyHoursToTrade(TradeStartTime4, TradeStopTime4,
iTimeType4);
bool hourResultClose = DailyHoursToTrade(TradeStartTimeClose,
TradeStopTimeClose, iTimeTypeClose);

OrderCheckClass checkOrder(iMagic, 0, _Symbol);


int countOrders = checkOrder.tradeCountsPairMagicRange();

int countBuyMarket = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUY);


int countSellMarket = checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELL);

int countBuyLimit = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYLIMIT);


int countSellLimit= checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLLIMIT);

//----------------------------------------------------------------------

if(iBars(NULL,PERIOD_CURRENT) > velas_close &&


Fechamento_ao_Final_da_Vela==true)
{
if(countBuyMarket > 0 || countSellMarket >0)
{
CloseOrderAll(iMagic,0,"");
}
velas_close=iBars(NULL,PERIOD_CURRENT);
}

if(hourResultClose==true)
{
if(countBuyMarket > 0 || countSellMarket >0)
{
CloseOrderAll(iMagic,0,"");
}
}

if(NewBar3())
{
if(countOrders > 0)
{
oneTradePerCandle = false; // case have a order block trade
}
else
{
oneTradePerCandle = true;
}
}

if(trade) //no news true


{

DeleteSellLimitIfBelow(iMagic,Distancia_Maxima);
DeleteBuyLimitIfAbove(iMagic,Distancia_Maxima);

if(countBuyMarket>0 || countSellMarket>0)
velas_ord=iBars(NULL,PERIOD_CURRENT)+Aguardar_x_velas_apos_ultima_ordem;

if(DailyControlTargetPercent(iUseDailyTarger, Ganho_Maximo_diario,
Perda_Maxima_diaria, true, true, iMagic, 0, iEaComment + " Fechamento meta diaria",
_Symbol)) // meta lucro ou loss
{
if(hourResult || hourResult1 || hourResult2 || hourResult3) // horario
{

if(Permissao == Compra_e_Venda || Permissao == Venda)


{
if(
countSellMarket==0
&& countBuyMarket==0
&& countBuyLimit==0
&& countSellLimit==0
&& iBars(NULL,PERIOD_CURRENT) > velas_ord

)
{

func_sell(Distancia_Minima,Distancia_Maxima,StopLoss,TakeProfit,Lote,Modo_Tendencia
,Pontos_Antecipacao);
}
}
if(Permissao == Compra_e_Venda || Permissao == Compra)
{

if(
countSellMarket==0
&& countBuyMarket==0
&& countBuyLimit==0
&& countSellLimit==0
&& iBars(NULL,PERIOD_CURRENT) > velas_ord

)
{

func_buy(Distancia_Minima,Distancia_Maxima,StopLoss,TakeProfit,Lote,Modo_Tendencia,
Pontos_Antecipacao);

}
//------------------------------------------------------------------------
---

}
else
{
eaStatus = "fora de hora";
}
}
else
{
eaStatus = "meta atingida";
}

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void fTrail()
{
OrderCheckClass checkOrder(iMagic, 0, _Symbol);
int countBuy = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUY); // order
count
int countSell = checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELL); // order
count
if(iUseBe && iDistanceBE > 0)
{
if(countBuy > 0)
{
double avaragePrice =
checkOrder.circleTradeMagicRangeAveragePriceTypeOrUniversal(OP_BUY);
checkOrder.BreakEven(iDistanceBE, iPointsProtected,false, false, false,
false, avaragePrice, BUY);

}
if(countSell > 0)
{
double avaragePrice =
checkOrder.circleTradeMagicRangeAveragePriceTypeOrUniversal(OP_SELL);
checkOrder.BreakEven(iDistanceBE, iPointsProtected, false, false, false,
false, avaragePrice, SELL);

}
}
if(iUseTrail && iDistanceTrail > 0)
{
if(countBuy > 0)
{
double avaragePrice =
checkOrder.circleTradeMagicRangeAveragePriceTypeOrUniversal(OP_BUY);
checkOrder.TrailStopStep(iDistanceTrail, iTrailJump, false,false,
avaragePrice, BUY);

}
if(countSell > 0)
{
double avaragePrice =
checkOrder.circleTradeMagicRangeAveragePriceTypeOrUniversal(OP_SELL);
checkOrder.TrailStopStep(iDistanceTrail, iTrailJump, false,false,
avaragePrice, SELL);

}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void fCloseTrade()
{
CloseOrderAllSymbol(iMagic, _Symbol, iEaComment + " zerar posição");
CloseOrderPeding(iMagic, 0, _Symbol, iEaComment + " zerar posição pendente");
}

//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool fInitializeIndicators()
{
// ::Indicators/
bff_ind = iCustom(_Symbol, PERIOD_CURRENT, "::Indicadores\
Indicador_Rogerio.ex5",Period1,Period2,Period3,SempreVisivel,Fractais);

if(bff_ind == INVALID_HANDLE)
{
Print("ERRO -> Falha na inicialização dos indicadores");
return(false);
}
return true;
}

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double UltimoLoteAberto_BUY(string symbol = NULL)
{
// Itera pelas ordens abertas
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS))
{
if(OrderType() == OP_BUY)
if(OrderSymbol() == symbol || symbol == NULL)
{
return OrderLots(); // Retorna o lote da última ordem encontrada
}
}
}
return 0; // Retorna 0 se nenhuma ordem for encontrada
}

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double UltimoLoteAberto_SELL(string symbol = NULL)
{
// Itera pelas ordens abertas
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS))
{
if(OrderType() == OP_SELL)
if(OrderSymbol() == symbol || symbol == NULL)
{
return OrderLots(); // Retorna o lote da última ordem encontrada
}
}
}
return 0; // Retorna 0 se nenhuma ordem for encontrada
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+

bool func_sell(double pontos_abaixo, double distancia_maxima, double


stop_loss_pontos, double take_profit_pontos, double lote, bool modo_tendencia,
double pontos_antecipacao)
{
static ulong ticket_pendente = 0;
static int vela_anterior = -1;
static double rec_anterior = 0;

double recs[6];
for(int i = 0; i < 6; i++)
recs[i] = IcustomHandler(0, bff_ind, i);

double close_price = iClose(_Symbol, PERIOD_CURRENT, 0);


int vela_atual = iBarShift(_Symbol, PERIOD_CURRENT, TimeCurrent());

double rec_mais_proximo = 0;
double menor_distancia = distancia_maxima * _Point;

for(int i = 0; i < 6; i++)


{
double distancia = recs[i] - close_price;
if(distancia > pontos_abaixo * _Point && distancia <= menor_distancia)
{
menor_distancia = distancia;
rec_mais_proximo = recs[i];
}
}

double tick_size = MarketInfo(_Symbol, MODE_TICKSIZE);


rec_mais_proximo = NormalizeDouble(MathRound(rec_mais_proximo / tick_size) *
tick_size, _Digits);

int tipo_ordem;
bool ordem_buy = false;
if (rec_mais_proximo > close_price) // Região acima do preço
{
rec_mais_proximo -= pontos_antecipacao * _Point;
if (modo_tendencia)
{
tipo_ordem = OP_BUYSTOP;
ordem_buy = true;
}
else
{
tipo_ordem = OP_SELLLIMIT;
}
}
else // Região abaixo do preço
{
rec_mais_proximo += pontos_antecipacao * _Point;
if (modo_tendencia)
{
tipo_ordem = OP_SELLSTOP;
}
else
{
tipo_ordem = OP_SELLLIMIT;
}
}

if(vela_atual != vela_anterior)
{
if(rec_mais_proximo != rec_anterior ||
(ticket_pendente > 0 && OrderSelect(ticket_pendente, SELECT_BY_TICKET) &&
OrderType() == tipo_ordem &&
close_price - OrderOpenPrice() > distancia_maxima * _Point))
{
if(ticket_pendente > 0 && OrderSelect(ticket_pendente, SELECT_BY_TICKET))
{
if(!OrderDelete(ticket_pendente))
Print("Erro ao deletar ordem pendente: ", GetLastError());
}
ticket_pendente = 0;
rec_anterior = 0;
}
vela_anterior = vela_atual;
}

if(rec_mais_proximo != 0 && menor_distancia <= distancia_maxima * _Point)


{
bool ordem_existente = false;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) &&
OrderType() == tipo_ordem &&
OrderSymbol() == _Symbol &&
OrderOpenPrice() == rec_mais_proximo)
{
ordem_existente = true;
ticket_pendente = OrderTicket();
break;
}
}

OrderCheckClass checkOrder(iMagic, 0, _Symbol);


int countOrders = checkOrder.tradeCountsPairMagicRange();

int countSellLimit =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLLIMIT);
int countSellStop =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLSTOP);
int countBuyStop = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYSTOP);

if(!ordem_existente && countSellLimit == 0 && countSellStop == 0 &&


countBuyStop == 0)
{
double stop_loss, take_profit;
if (ordem_buy)
{
stop_loss = stop_loss_pontos > 0 ? NormalizeDouble(rec_mais_proximo -
stop_loss_pontos * _Point, _Digits) : 0;
take_profit = take_profit_pontos > 0 ? NormalizeDouble(rec_mais_proximo
+ take_profit_pontos * _Point, _Digits) : 0;
}
else
{
stop_loss = stop_loss_pontos > 0 ? NormalizeDouble(rec_mais_proximo +
stop_loss_pontos * _Point, _Digits) : 0;
take_profit = take_profit_pontos > 0 ? NormalizeDouble(rec_mais_proximo
- take_profit_pontos * _Point, _Digits) : 0;
}
if(iBars(NULL,PERIOD_CURRENT) > control_velas_ord){
ticket_pendente = OrderSend(_Symbol, tipo_ordem, lote, rec_mais_proximo,
3, stop_loss, take_profit, "Ordem Pendente", iMagic, 0, CLR_NONE);
control_velas_ord=iBars(NULL,PERIOD_CURRENT);
}
vela_anterior = vela_atual;
if(ticket_pendente < 0)
{
Print("Erro ao criar ordem pendente: ", GetLastError());
return false;
}
}
}

rec_anterior = rec_mais_proximo;
return true;
}

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void PrintRecs()
{
double rec_ind_1 = IcustomHandler(0, bff_ind, 0);
double rec_ind_2 = IcustomHandler(0, bff_ind, 1);
double rec_ind_3 = IcustomHandler(0, bff_ind, 2);
double rec_ind_4 = IcustomHandler(0, bff_ind, 3);
double rec_ind_5 = IcustomHandler(0, bff_ind, 4);
double rec_ind_6 = IcustomHandler(0, bff_ind, 5);

// Exibir os valores no gráfico


Comment(
"rec_ind_1: ", rec_ind_1, "\n",
"rec_ind_2: ", rec_ind_2, "\n",
"rec_ind_3: ", rec_ind_3, "\n",
"rec_ind_4: ", rec_ind_4, "\n",
"rec_ind_5: ", rec_ind_5, "\n",
"rec_ind_6: ", rec_ind_6
);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void DeleteSellLimitIfBelow(int magicNumber, int pointsBelow)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
// Verifica se é uma ordem pendente de venda (Sell Limit)
if( OrderMagicNumber() == magicNumber)
{
double price = OrderOpenPrice();
double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);

// Calcula a diferença em pontos


double diffPoints = (price - currentPrice) / _Point;

// Verifica se o preço atual está abaixo do limite


if(diffPoints >= pointsBelow)
{
// Tenta deletar a ordem
if(OrderDelete(OrderTicket()))
{
Print("Ordem Sell Limit deletada: Ticket ", OrderTicket());
}
else
{
Print("Erro ao deletar ordem Sell Limit: Ticket ", OrderTicket(),
", Erro: ", GetLastError());
}
}
}
}
}
}

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void DeleteBuyLimitIfAbove(int magicNumber, int pointsAbove)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
// Verifica se é uma ordem pendente de compra (Buy Limit)
if( OrderMagicNumber() == magicNumber)
{
double price = OrderOpenPrice();
double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// Calcula a diferença em pontos
double diffPoints = (currentPrice - price) / _Point;

// Verifica se o preço atual está acima do limite


if(diffPoints >= pointsAbove)
{
// Tenta deletar a ordem
if(OrderDelete(OrderTicket()))
{
Print("Ordem Buy Limit deletada: Ticket ", OrderTicket());
}
else
{
Print("Erro ao deletar ordem Buy Limit: Ticket ", OrderTicket(),
", Erro: ", GetLastError());
}
}
}
}
}
}

bool func_buy(double pontos_acima, double distancia_maxima, double


stop_loss_pontos, double take_profit_pontos, double lote, bool modo_tendencia,
double pontos_antecipacao)
{
static ulong ticket_pendente = 0;
static int vela_anterior = -1;
static double rec_anterior = 0;

double recs[6];
for(int i = 0; i < 6; i++)
recs[i] = IcustomHandler(0, bff_ind, i);

double close_price = iClose(_Symbol, PERIOD_CURRENT, 0);


int vela_atual = iBarShift(_Symbol, PERIOD_CURRENT, TimeCurrent());

double rec_mais_proximo = 0;
double menor_distancia = distancia_maxima * _Point;

for(int i = 0; i < 6; i++)


{
double distancia = close_price - recs[i];
if(distancia > pontos_acima * _Point && distancia <= menor_distancia)
{
menor_distancia = distancia;
rec_mais_proximo = recs[i];
}
}

double tick_size = MarketInfo(_Symbol, MODE_TICKSIZE);


rec_mais_proximo = NormalizeDouble(MathRound(rec_mais_proximo / tick_size) *
tick_size, _Digits);

int tipo_ordem;
bool ordem_buy = false;
if (rec_mais_proximo < close_price) // Região abaixo do preço
{
rec_mais_proximo -= pontos_antecipacao * _Point;
if (modo_tendencia)
{
tipo_ordem = OP_SELLSTOP;
}
else
{
tipo_ordem = OP_BUYLIMIT;
ordem_buy = true;
}
}
else // Região acima do preço
{
rec_mais_proximo += pontos_antecipacao * _Point;
if (modo_tendencia)
{
tipo_ordem = OP_BUYSTOP;
ordem_buy = true;
}
else
{
tipo_ordem = OP_BUYLIMIT;
}
}

if(vela_atual != vela_anterior)
{
if(rec_mais_proximo != rec_anterior ||
(ticket_pendente > 0 && OrderSelect(ticket_pendente, SELECT_BY_TICKET) &&
OrderType() == tipo_ordem &&
OrderOpenPrice() - close_price > distancia_maxima * _Point))
{
if(ticket_pendente > 0 && OrderSelect(ticket_pendente, SELECT_BY_TICKET))
{
if(!OrderDelete(ticket_pendente))
Print("Erro ao deletar ordem pendente: ", GetLastError());
}
ticket_pendente = 0;
rec_anterior = 0;
}
vela_anterior = vela_atual;
}

if(rec_mais_proximo != 0 && menor_distancia <= distancia_maxima * _Point)


{
bool ordem_existente = false;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) &&
OrderType() == tipo_ordem &&
OrderSymbol() == _Symbol &&
OrderOpenPrice() == rec_mais_proximo)
{
ordem_existente = true;
ticket_pendente = OrderTicket();
break;
}
}

OrderCheckClass checkOrder(iMagic, 0, _Symbol);


int countOrders = checkOrder.tradeCountsPairMagicRange();

int countBuyLimit =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYLIMIT);
int countBuyStop = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYSTOP);
int countSellStop =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLSTOP);

if(!ordem_existente && countBuyLimit == 0 && countBuyStop == 0 &&


countSellStop == 0)
{
double stop_loss, take_profit;
if (ordem_buy)
{
stop_loss = stop_loss_pontos > 0 ? NormalizeDouble(rec_mais_proximo -
stop_loss_pontos * _Point, _Digits) : 0;
take_profit = take_profit_pontos > 0 ? NormalizeDouble(rec_mais_proximo
+ take_profit_pontos * _Point, _Digits) : 0;
}
else
{
stop_loss = stop_loss_pontos > 0 ? NormalizeDouble(rec_mais_proximo +
stop_loss_pontos * _Point, _Digits) : 0;
take_profit = take_profit_pontos > 0 ? NormalizeDouble(rec_mais_proximo
- take_profit_pontos * _Point, _Digits) : 0;
}
if(iBars(NULL,PERIOD_CURRENT) > control_velas_ord){
ticket_pendente = OrderSend(_Symbol, tipo_ordem, lote, rec_mais_proximo,
5, stop_loss, take_profit, "Ordem Pendente", iMagic, 0, CLR_NONE);
control_velas_ord=iBars(NULL,PERIOD_CURRENT);
}
vela_anterior = vela_atual;
if(ticket_pendente < 0)
{
Print("Erro ao criar ordem pendente: ", GetLastError());
return false;
}
}
}

rec_anterior = rec_mais_proximo;
return true;
}

void CloseAllOrders()
{
int totalOrders = PositionsTotal(); // Obtém o número total de posições abertas

for (int i = totalOrders - 1; i >= 0; i--) // Percorre as posições de trás para


frente
{
ulong ticket = PositionGetTicket(i); // Obtém o ticket da posição
if (ticket > 0)
{
double lotSize = PositionGetDouble(POSITION_VOLUME); // Obtém o tamanho do
lote
ENUM_POSITION_TYPE positionType =
(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);

MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);

request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.symbol = PositionGetString(POSITION_SYMBOL);
request.volume = lotSize;
request.magic = PositionGetInteger(POSITION_MAGIC);
request.deviation = 10;
request.type_filling = ORDER_FILLING_IOC;
request.type = (positionType == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL :
ORDER_TYPE_BUY; // Fecha a ordem invertendo o tipo

if (!OrderSend(request, result))
{
Print("Erro ao fechar ordem: ", result.comment);
}
else
{
Print("Ordem fechada com sucesso: Ticket ", ticket);
}
}
}
}

You might also like