Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

robo para automação em finanças metatrade5 #1

Open
Mau2009 opened this issue Jul 20, 2024 · 0 comments
Open

robo para automação em finanças metatrade5 #1

Mau2009 opened this issue Jul 20, 2024 · 0 comments

Comments

@Mau2009
Copy link

Mau2009 commented Jul 20, 2024

olá, sou novo na programação e não estou conseguindo finalizar o codigo desse problema.
toda ajuda agradeço
#property version "1.00"
#property strict

input double PriceTrigger = 10; // Gatilho de movimento de preço em pips
input int MinTimeWindow = 5; // Janela de tempo mínima em minutos
input int MaxTimeWindow = 60; // Janela de tempo máxima em minutos
input double MartingaleMultiplier = 2.0; // Multiplicador Martingale
input double TrailingStop = 20; // Trailing stop em pips
input double StopLoss = 30; // Stop-loss em pips
input double TakeProfit = 50; // Take profit em pips
input bool SessionEnabled = true; // Ativar/Desativar configurações da sessão
input bool WeekdaySettingsEnabled = true; // Ativar/Desativar configurações de dias úteis
input bool AutoRiskManagement = true; // Gestão financeira automática
input double RiskPerTrade = 2.0; // Risco por operação em % do saldo da conta
input double ManualLotSize = 0.1; // Tamanho do lote manual
input bool NFACOMP = false; // Compatível com NFA/FIFO
input string CustomComment = "MyRobot"; // Comentário personalizado
input int MagicNumber = 123456; // Número mágico
input double Slippage = 3; // Desvio máximo em pips
input double ManualPipValue = 0.0; // Valor do Pip Manual (substituir)

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
EventSetTimer(60); // Define o timer para verificar a cada 60 segundos
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
EventKillTimer(); // Mata o timer ao finalizar
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
static datetime lastTradeTime = 0;
static double initialTradePrice = 0;
static int initialTradeDirection = 0;

if (TimeCurrent() - lastTradeTime < MinTimeWindow * 60) return; // Aguarda a janela de tempo mínima

double currentPrice = iClose(_Symbol, PERIOD_M1, 0);

// Se não há ordens abertas, verifica o gatilho
if (OrdersTotal() == 0)
{
if (CheckPriceTrigger(currentPrice))
{
initialTradePrice = currentPrice;
initialTradeDirection = GetTradeDirection();
OpenTrade(initialTradeDirection, currentPrice);
lastTradeTime = TimeCurrent();
}
}
else
{
ManageOpenTrades(currentPrice);
}
}
//+------------------------------------------------------------------+
//| Abre uma nova ordem de negociação |
//+------------------------------------------------------------------+
void OpenTrade(int direction, double price)
{
double lotSize = CalculateLotSize();
double sl = direction == OP_BUY ? price - StopLoss * Point() : price + StopLoss * Point();
double tp = direction == OP_BUY ? price + TakeProfit * Point() : price - TakeProfit * Point();

int ticket = OrderSend(_Symbol, direction, lotSize, price, Slippage, sl, tp, CustomComment, MagicNumber, 0, clrNONE);
if (ticket < 0)
{
Print("Erro ao abrir ordem: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Verifica e abre uma nova ordem Martingale |
//+------------------------------------------------------------------+
void ManageOpenTrades(double currentPrice)
{
double totalProfit = GetCurrentProfit();

for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
int direction = OrderType();
double openPrice = OrderOpenPrice();

     if (direction == OP_BUY && currentPrice < openPrice - PriceTrigger * Point() || 
         direction == OP_SELL && currentPrice > openPrice + PriceTrigger * Point())
       {
        double newLotSize = OrderLots() * MartingaleMultiplier;
        int newDirection = direction == OP_BUY ? OP_SELL : OP_BUY;
        OpenTrade(newDirection, currentPrice);
       }
     else if (totalProfit >= TakeProfit * Point())
       {
        CloseAllTrades();
       }
    }
 }

}
//+------------------------------------------------------------------+
//| Calcula o tamanho do lote |
//+------------------------------------------------------------------+
double CalculateLotSize()
{
if (AutoRiskManagement)
{
double accountBalance = AccountBalance();
double riskAmount = accountBalance * (RiskPerTrade / 100);
double lotSize = riskAmount / (StopLoss * PointValue());
return NormalizeDouble(lotSize, 2);
}
else
{
return ManualLotSize;
}
}
//+------------------------------------------------------------------+
//| Verifica o gatilho de preço |
//+------------------------------------------------------------------+
bool CheckPriceTrigger(double currentPrice)
{
static double previousPrice = 0;

if (previousPrice == 0)
{
previousPrice = currentPrice;
return false;
}

double priceChange = MathAbs(currentPrice - previousPrice) / Point();
previousPrice = currentPrice;

return priceChange >= PriceTrigger;
}
//+------------------------------------------------------------------+
//| Obtém a direção da negociação |
//+------------------------------------------------------------------+
int GetTradeDirection()
{
return TimeCurrent() % 2 == 0 ? OP_BUY : OP_SELL;
}
//+------------------------------------------------------------------+
//| Fecha todas as ordens abertas |
//+------------------------------------------------------------------+
void CloseAllTrades()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
int type = OrderType();
double price = type == OP_BUY ? Bid : Ask;

     if (OrderClose(OrderTicket(), OrderLots(), price, Slippage, clrNONE))
       {
        Print("Ordem fechada com sucesso: ", OrderTicket());
       }
     else
       {
        Print("Erro ao fechar ordem: ", GetLastError());
       }
    }
 }

}
//+------------------------------------------------------------------+
//| Calcula o lucro atual das ordens abertas |
//+------------------------------------------------------------------+
double GetCurrentProfit()
{
double profit = 0;

for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
profit += OrderProfit();
}
}

return profit;
}
//+------------------------------------------------------------------+
//| Calcula o valor do pip |
//+------------------------------------------------------------------+
double PointValue()
{
if (ManualPipValue > 0)
{
return ManualPipValue;
}
else
{
double pipValue = MarketInfo(_Symbol, MODE_TICKVALUE);
return pipValue;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant