RObo MT5
RObo MT5
//| ProjectName |
//| Copyright 2020, CompanyName |
//| http://www.companyname.net |
//+------------------------------------------------------------------+
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
//---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.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.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);
//----------------------------------------------------------------------
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;
}
}
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
{
)
{
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
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double recs[6];
for(int i = 0; i < 6; i++)
recs[i] = IcustomHandler(0, bff_ind, i);
double rec_mais_proximo = 0;
double menor_distancia = distancia_maxima * _Point;
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;
}
int countSellLimit =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLLIMIT);
int countSellStop =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLSTOP);
int countBuyStop = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYSTOP);
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);
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
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;
double recs[6];
for(int i = 0; i < 6; i++)
recs[i] = IcustomHandler(0, bff_ind, i);
double rec_mais_proximo = 0;
double menor_distancia = distancia_maxima * _Point;
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;
}
int countBuyLimit =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYLIMIT);
int countBuyStop = checkOrder.tradeCountsPairMagicRangeOrderType(OP_BUYSTOP);
int countSellStop =
checkOrder.tradeCountsPairMagicRangeOrderType(OP_SELLSTOP);
rec_anterior = rec_mais_proximo;
return true;
}
void CloseAllOrders()
{
int totalOrders = PositionsTotal(); // Obtém o número total de posições abertas
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);
}
}
}
}