1. Parâmetros de Entrada
#define ExtBotName "AK-47 Scalper EA" // Nome do Bot #define Version "1.00" //--- parâmetros de entrada extern string EASettings = "---------------------------------------------"; //-------- <Configurações do EA> -------- input int InpMagicNumber = 124656; //Número Mágico extern string TradingSettings = "---------------------------------------------"; //-------- <Configurações de Negociação> -------- input double Inpuser_lot = 0.01; //Lotes input double InpSL_Pips = 3.5; //Stoploss (em Pips) input double InpMax_spread = 0.5; //Spread máximo permitido (em Pips) (0 = flutuante) extern string MoneySettings = "---------------------------------------------"; //-------- <Configurações de Dinheiro> -------- input bool isVolume_Percent = true; //Permitir Volume Percentual input double InpRisk = 3; //Porcentagem de Risco do Saldo (%) input string TimeSettings = "---------------------------------------------"; //-------- <Configurações de Horário de Negociação> -------- input bool InpTimeFilter = true //Filtro de Horário de Negociação input int InpStartHour = 2; //Hora de Início input int InpStartMinute = 30; //Minuto de Início input int InpEndHour = 21; //Hora de Fim input int InpEndMinute = 0 //Minuto de Fim
2. Inicialização de Variáveis Locais
//--- Variáveis int Pips2Points; // slippage 3 pips 3=points 30=points double Pips2Double; // Stoploss 15 pips 0.015 0.0150 int InpMax_slippage = 3; // Slippage máximo permitido. bool isOrder = false; // abre apenas 1 ordem int slippage; string strComment = "";
3. Código Principal
a/ Função de Inicialização do Expert
int OnInit() { //--- //Detectar 3 ou 5 dígitos //Pip e ponto if (Digits % 2 == 1) { Pips2Double = _Point*10; Pips2Points = 10; slippage = 10* InpMax_slippage; } else { Pips2Double = _Point; Pips2Points = 1; slippage = InpMax_slippage; } //--- return(INIT_SUCCEEDED); }
b/ Função Tick do Expert
void OnTick() { //--- if(IsTradeAllowed() == false) { Comment("AK-47 EA\nNegociação não permitida."); return; } MqlDateTime structTime; TimeCurrent(structTime); structTime.sec = 0; //Define hora de início structTime.hour = InpStartHour; structTime.min = InpStartMinute; datetime timeStart = StructToTime(structTime); //Define hora de fim structTime.hour = InpEndHour; structTime.min = InpEndMinute; datetime timeEnd = StructToTime(structTime); double acSpread = MarketInfo(Symbol(), MODE_SPREAD); StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL); strComment = "\n" + ExtBotName + " - v." + (string)Version; strComment += "\nHora GMT = " + TimeToString(TimeGMT(),TIME_DATE|TIME_SECONDS); strComment += "\nHorário de Negociação = [" + (string)InpStartHour + "h" + (string)InpStartMinute + " --> " + (string)InpEndHour + "h" + (string)InpEndMinute + "]"; strComment += "\nSpread Atual = " + (string)acSpread + " Points"; strComment += "\nNível de Stop Atual = " + (string)StopLevel + " Points"; Comment(strComment); //Atualizar Valores UpdateOrders(); TrailingStop(); //Verificar Horário de Negociação if(InpTimeFilter) { if(TimeCurrent() >= timeStart && TimeCurrent() < timeEnd) { if(!isOrder) OpenOrder(); } } else { if(!isOrder) OpenOrder(); } }
3.1 Calcular sinal para enviar ordens
void OpenOrder(){ //int OrdType = OP_SELL;//-1; double TP = 0; double SL = 0; string comment = ExtBotName; //Calcular Lotes double lot1 = CalculateVolume(); //if(OrdType == OP_SELL){ double OpenPrice = NormalizeDouble(Bid - (StopLevel * _Point) - (InpSL_Pips/2) * Pips2Double, Digits); SL = NormalizeDouble(Ask + StopLevel * _Point + InpSL_Pips/2 * Pips2Double, Digits); if(CheckSpreadAllow()) //Verificar Spread { if(!OrderSend(_Symbol, OP_SELLSTOP, lot1, OpenPrice, slippage, SL, TP, comment, InpMagicNumber, 0, clrRed)) Print(__FUNCTION__,"--> Erro ao enviar ordem ",GetLastError()); } //} }
3.2 Calcular Volume
double CalculateVolume() { double LotSize = 0; if(isVolume_Percent == false) { LotSize = Inpuser_lot; } else { LotSize = (InpRisk) * AccountFreeMargin(); LotSize = LotSize /100000; double n = MathFloor(LotSize/Inpuser_lot); //Comment((string)n); LotSize = n * Inpuser_lot; if(LotSize < Inpuser_lot) LotSize = Inpuser_lot; if(LotSize > MarketInfo(Symbol(),MODE_MAXLOT)) LotSize = MarketInfo(Symbol(),MODE_MAXLOT); if(LotSize < MarketInfo(Symbol(),MODE_MINLOT)) LotSize = MarketInfo(Symbol(),MODE_MINLOT); } return(LotSize); }
3.3 O EA possui função de "Trailing Stop", O SL mudará a cada vez que o preço mudar (para baixo)
void TrailingStop() { for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if((OrderMagicNumber() == InpMagicNumber) && (OrderSymbol() == Symbol())) //_Symbol)) { //Para Ordem de Venda if(OrderType() == OP_SELL) { //--Calcular SL quando o preço mudar double SL_in_Pip = NormalizeDouble(OrderStopLoss() - (StopLevel * _Point) - Ask, Digits) / Pips2Double; if(SL_in_Pip > InpSL_Pips){ double newSL = NormalizeDouble(Ask + (StopLevel * _Point) + InpSL_Pips * Pips2Double, Digits); if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrRed)) { Print(__FUNCTION__,"--> Erro ao modificar a ordem ",GetLastError()); continue } } //Para Ordem de Venda a Mercado else if(OrderType() == OP_SELLSTOP) { double SL_in_Pip = NormalizeDouble(OrderStopLoss() - (StopLevel * _Point) - Ask, Digits) / Pips2Double; if(SL_in_Pip < InpSL_Pips/2){ double newOP = NormalizeDouble(Bid - (StopLevel * _Point) - (InpSL_Pips/2) * Pips2Double, Digits); double newSL = NormalizeDouble(Ask + (StopLevel * _Point) + (InpSL_Pips/2) * Pips2Double, Digits); if(!OrderModify(OrderTicket(), newOP, newSL, OrderTakeProfit(), 0, clrRed)) { Print(__FUNCTION__,"--> Erro ao modificar a Ordem Pendente!", GetLastError()); continue } } } } } }
Publicações relacionadas
- MACD Sample: Um Guia Prático para o Expert Advisor no MetaTrader 5
- Como Criar Sinais de Negociação com MQL5 Wizard Usando Estrelas da Manhã e da Noite + Estocástico
- MQL5 Wizard: Sinais de Negociação com Padrões Candlestick e RSI no MetaTrader 5
- MQL5 Wizard: Sinais de Negociação com Estrelas da Manhã/Noite + RSI para MetaTrader 5
- Baixe Todo o Histórico de Ticks de um Símbolo no MetaTrader 5