//+------------------------------------------------------------------+ // MyRobot.mq5 //…
- User
//+------------------------------------------------------------------+ //| MyRobot.mq5 | //| Copyright 2023, MetaQuotes Software Corp. | //| https://www.metaquotes.net/ | //+------------------------------------------------------------------+ #include <Trade/Trade.mqh> input double lotSize = 0.1; // Lote padrão
CTrade trade; // Cria um objeto para operações de trading
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- }
//+------------------------------------------------------------------+ //| 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);
// Variável para armazenar o tipo de posição atual ENUM_POSITION_TYPE currentPositionType = POSITION_TYPE_BUY; // Inicializa como compra por padrão bool positionExists = false; // Variável para verificar se existe uma posição
// Verifica se já existe uma posição aberta if (PositionsTotal() > 0) { ulong positionTicket = PositionGetTicket(0); if (PositionSelectByTicket(positionTicket)) { currentPositionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); positionExists = true; // Marca que existe uma posição } }
// Condição para abrir ordem de compra if (sma200 < closePrice && closePrice > sma20 && !positionExists) { trade.Buy(lotSize, NULL, closePrice, 0, 0, "Comprado por cruzar SMA20"); // Abre ordem de compra } else if (sma200 < closePrice && closePrice > sma20 && positionExists && currentPositionType == POSITION_TYPE_SELL) { trade.PositionClose(_Symbol); // Fecha a posição de venda existente trade.Buy(lotSize, NULL, closePrice, 0, 0, "Comprado por cruzar SMA20"); // Abre ordem de compra }
// Condição para abrir ordem de venda if (sma200 > closePrice && closePrice < sma20 && !positionExists) { trade.Sell(lotSize, NULL, closePrice, 0, 0, "Vendido por cruzar SMA20"); // Abre ordem de venda } else if (sma200 > closePrice && closePrice < sma20 && positionExists && currentPositionType == POSITION_TYPE_BUY) { trade.PositionClose(_Symbol); // Fecha a posição de compra existente trade.Sell(lotSize, NULL, closePrice, 0, 0, "Vendido por cruzar SMA20"); // Abre ordem de venda } } //+------------------------------------------------------------------+
- Assistant
- User
- Assistant
- User
- Assistant