//--- Variáveis globais
double lotSize = 0.1; // Tamanho do lote inicial
double takeProfitPoints = 10; // Meta de lucro em pontos
int maxMartingaleLevels = 3; // Máximo de níveis de martingale
int martingaleMultiplier = 2; // Fator multiplicador do martingale
int martingaleLevel = 0; // Contador do nível de martingale
bool tradeOpened = false; // Se existe uma operação aberta
int currentDirection = 0; // Direção da operação atual (1 = compra, -1 = venda)
// Função principal
void OnTick()
{
if (!tradeOpened) {
// Analisar a vela atual e tomar uma decisão de compra ou venda
int direction = AnalyzeCandle();
code
if (direction != 0) {
// Se houver uma direção (1 = alta, -1 = baixa), abrir operação
double price = (direction == 1) ? Ask : Bid;
OpenTrade(direction, lotSize, price);
}
} else {
// Verificar se atingiu o take profit ou stop loss
ManageTrade();
}
}
// Análise da vela atual para prever a próxima vela
int AnalyzeCandle() {
// Supondo que a análise seja feita com base no fechamento da última vela
double openPrice = iOpen(Symbol(), PERIOD_CURRENT, 1);
double closePrice = iClose(Symbol(), PERIOD_CURRENT, 1);
code
if (closePrice > openPrice) {
// Vela de alta, tendência de alta
return 1;
} else if (closePrice < openPrice) {
// Vela de baixa, tendência de baixa
return -1;
}
return 0; // Neutro, sem ação
// Função para gerenciar a operação aberta
void ManageTrade() {
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
double openPrice = OrderOpenPrice();
double currentPrice = (OrderType() == OP_BUY) ? Bid : Ask;
double profit = (currentPrice - openPrice) * ((OrderType() == OP_BUY) ? 1 : -1) / Point;
code
// Se atingir o take profit, fecha a operação
if (profit >= takeProfitPoints) {
OrderClose(OrderTicket(), OrderLots(), currentPrice, 3, clrGreen);
tradeOpened = false;
martingaleLevel = 0; // Resetar o nível de martingale
}
// Se saldo ficar negativo, realizar martingale
else if (profit < 0) {
if (martingaleLevel < maxMartingaleLevels) {
// Fechar a operação com prejuízo e abrir a próxima com lote aumentado
OrderClose(OrderTicket(), OrderLots(), currentPrice, 3, clrRed);
martingaleLevel++;
OpenTrade(currentDirection, lotSize * MathPow(martingaleMultiplier, martingaleLevel), currentPrice);
} else {
// Se atingir o limite de martingale, fechar a operação e resetar
OrderClose(OrderTicket(), OrderLots(), currentPrice, 3, clrRed);
tradeOpened = false;
martingaleLevel = 0;
}
}
}
}
}
The code you have shared seems to be an attempt to create an MQL5 trading algorithm for MetaTrader. It appears there are multiple compilation errors related to undeclared identifiers and syntax issues. Let's address these issues one by one:
Use of Ask and Bid:
Ask and Bid are predefined variables in MQL4 but you need to use functions in MQL5.
Replace Ask with SymbolInfoDouble(Symbol(), SYMBOL_ASK);
Replace Bid with SymbolInfoDouble(Symbol(), SYMBOL_BID);
Global vs Local Variable Name Conflict:
The variable name lotSize is being declared both globally and locally in your OpenTrade function.
To avoid this conflict, you can either rename the local variable or avoid re-declaring it.
OrderSend and OrderClose functions:
In MQL5, trading operations require MqlTradeRequest and MqlTradeResult structures.
Replace old style OrderSend and OrderClose with new style trading functions like OrderSend() using these structures.
Undeclared Identifiers like OP_BUY, OP_SELL:
In MQL5, instead of constants like OP_BUY, use enumerations like ORDER_TYPE_BUY and ORDER_TYPE_SELL.
The Use of MODE_TRADES, SELECT_BY_POS:
These are MQL4 style identifiers. In MQL5, order selection and counting should be done using order tickets, accessed via functions like HistoryDealGetTicket().
General Syntax Corrections:
Ensure that all function calls are properly parenthesized and have all necessary arguments. Follow the MQL5 documentation for proper syntax.
Here's a corrected version of your code snippet addressing these issues:
cpp
User
double lotSize = 0.1;
double takeProfitPoints = 10;
int maxMartingaleLevels = 3;
int martingaleMultiplier = 2;
int martingaleLevel = 0;
bool tradeOpened = false;
int currentDirection = 0;
void OnTick()
{
if (!tradeOpened) {
int direction = AnalyzeCandle();
The compilation errors you're encountering are due to misuses of functions and identifiers that need to be corrected for MQL5. Let's address these:
Order Management in MQL5:
In MQL5, the order management is done through positions, deals, and orders, and it requires a different approach than in MQL4.
OrderSelect, OrderType, OrderOpenPrice, OrderTicket, OrderLots in MQL4 need to be updated in MQL5 with position and order management functions and properties like PositionGetDouble, PositionGetInteger, HistoryOrderGetDouble etc.
Use ENUMS instead of constants:
MQL5 uses enumerations like ORDER_TYPE_BUY, ORDER_TYPE_SELL, and for selecting positions you use PositionSelect.
Correct the Use of Functions:
Replace the MQL4 specific functions with MQL5 specific functions.
Here is a corrected version of your code using MQL5 functions and structures:
cpp
User
double lotSize = 0.1;
double takeProfitPoints = 10;
int maxMartingaleLevels = 3;
int martingaleMultiplier = 2;
int martingaleLevel = 0;
bool tradeOpened = false;
int currentDirection = 0;
void OnTick()
{
if (!tradeOpened) {
int direction = AnalyzeCandle();
The issue you're experiencing, where the order closes immediately with a loss, might be due to multiple reasons in the code. Let's improve and debug the situation with a few key strategies:
Take Profit and Stop Loss Mismanagement:
Ensure that the takeProfitPoints calculation and application logic is correct.
Ensure that the trade is not closing prematurely due to misconfiguration in take profit levels.
Check for Point and Digits:
Ensure that the Point and price levels used in calculations are correctly applied with the appropriate conversion for different symbols (e.g., currency, indices).
Martingale Logic and Initialization:
Ensure that tradeOpened flags and martingale logic does not immediately cause execution of OpenTrade after ClosePosition.
Manage Slippage:
Consider slippage and ensure deviation is appropriately set.
Given these considerations, let's check the code:
cpp
User
ainda esta abrindo e fechando as ordens muito rapido causando percas a todo momento
a ordem apos aberta deve ser fechada somente quando ja tiver pelo menos algum lucro ficar positivo! caso contrario nao pode ser fechada!
só pode fechar a orden se a ela no qual foi aberta a ordem terminar no negativo assim que fechar por exemplo uma vela de m1 fechar e o saldo estiver negativo nesta caso pode fechar a ordem e abrir uma nova ordem nas proximas velas que estiverem dentro da regra de negociação da estrategia candle a candle
double lotSize = 0.1;
double takeProfitPoints = 10; // Make sure this aligns with your symbol's point size
int maxMartingaleLevels = 3;
int martingaleMultiplier = 2;
int martingaleLevel = 0;
bool tradeOpened = false;
int currentDirection = 0;
void OnTick()
{
if (!tradeOpened) {
int direction = AnalyzeCandle();
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3; // Ensure this value is appropriate for your broker
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.tp = price + takeProfitPoints * _Point;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.tp = price - takeProfitPoints * _Point;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true; // Mark as trade opened only if order is successful
currentDirection = direction;
} else {
Print("OrderSend failed: ", result.retcode);
}
Assistant
To adjust the strategy so that trades are closed only if they end a candle in negative and to ensure that you manage positions appropriately with the Martingale strategy logic, you need to first identify the point where a trade should be closed. This involves checking the candle close condition and ensuring that Doji or similar moves do not trigger unwanted close activities. Here’s an enhanced version of your code with considerations for your new strategy constraints:
cpp
User
inves de usar o candle a candle voce conhece a estrategia usada em opções binaria cahmada 3 m1 melhor de 1 minuto?
se sim implemente isso no meu robo
Assistant
The "3 m1" strategy in binary options typically involves making decisions based on the results of three consecutive 1-minute (M1) candles. It is a common approach to attempt to predict the movement of the market in a very short time frame, often entering a trade and closing it within a single minute.
I will provide a general implementation idea for this strategy using MQL5, based on a simplified interpretation of the "3 m1" strategy. The basic premise could be to trade in the opposite direction after observing three consecutive candles in the same direction (e.g., three green or red candles in a row).
Key Points:
Trend Detection: Identify whether the last three one-minute candles are in the same direction.
Entry Logic: Enter a trade in the opposite direction of the observed trend if conditions are met.
Exit Logic: Close trades either after achieving a pre-defined take profit or stop loss.
Here's a possible implementation:
cpp
User
me responda em portugues!
me diga oique o codigo faz
Assistant
Claro! Vou explicar o que o código faz:
Tamanho do Lote e Pontos de Take Profit:
Define o tamanho do lote como 0.1 e a meta de lucro (takeProfitPoints) como 10 pontos. Estes valores podem ser ajustados de acordo com a estratégia desejada e o ativo negociado.
Controle de Trading Aberto e Tempo:
Uma variável tradeOpened indica se uma negociação está aberta.
Usa lastTradeTime para garantir que somente uma negociação ocorra por vela de 1 minuto, evitando múltiplas operações no mesmo período.
Análise de Velas:
A função AnalyzeThreeCandles() verifica as últimas três velas de um minuto (M1) para determinar se todas estão em alta ou em baixa.
Se três velas consecutivas forem de alta, a função retorna 1; se forem de baixa, retorna -1; caso contrário, retorna 0.
Abertura de Negociações:
Abre operações no sentido oposto à tendência das três últimas velas (compra após três velas de baixa, venda após três velas de alta).
Utiliza a função OpenTrade() para enviar ordens de compra ou venda com um take profit e stop loss.
Gerenciamento de Negociações:
A função ManageTrade() monitora as negociações abertas, fechando-as se atingirem o take profit ou stop loss.
Gerencia a posição atual baseando-se no lucro ou prejuízo e ajusta as negociações conforme atingem esses limites.
Fechamento de Negociações:
A função ClosePosition() envia uma ordem para fechar a posição atual quando as condições de take profit ou stop loss forem atendidas.
Em resumo, este script é um robô de trading automatizado que observa a direção das três últimas velas M1 e tenta lucrar abrindo uma posição na direção oposta, fechando a ordem quando atinge um lucro pré-determinado ou um limite de perda. Esta estratégia é uma tentativa de explorar retornos após movimentos de preços contínuos em uma direção.
User
double lotSize = 0.1;
double takeProfitPoints = 10; // Adjust to your strategy
double stopLossPoints = 10; // Specify stop loss if needed
bool tradeOpened = false;
datetime lastTradeTime = 0;
// Avoid trading more than once within the same minute candle
if (currentTime == lastTradeTime) return;
// Ensure we're analyzing the latest finished candle
if (Minute() % 1 == 0 && !tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Enter in the opposite direction
}
}
if (tradeOpened) {
ManageTrade(); // Manage trade if open
}
lastTradeTime = currentTime;
}
// Function to analyze the direction of the last three candles
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
O erro 'Minute' - undeclared identifier ocorre porque Minute() não é uma função válida em MQL5. A função tentar verificar a passagem do tempo (minuto) pode ser feita usando TimeMinute() para obter o minuto atual.
Aqui está o que você pode fazer para corrigir o erro e fazer com que o código funcione:
Substitua Minute() por TimeMinute(currentTime) ou outra maneira de verificar se entramos em um novo minuto.
Garanta que a verificação do novo minuto esteja antes de abrir novas trades. Isso garante que você só execute a lógica para abrir trades uma vez por minuto.
Aqui está o trecho corrigido que lida com a avaliação do tempo:
cpp
void OnTick()
{
datetime currentTime = TimeCurrent();
int currentMinute = TimeMinute(currentTime); // Obtendo o minuto atual
// Evita negociar mais de uma vez dentro do mesmo minuto
if (currentTime == lastTradeTime) return;
// Verifica se estamos analisando a última vela concluída
if (currentMinute != TimeMinute(lastTradeTime) && !tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Entra na direção oposta
}
}
if (tradeOpened) {
ManageTrade(); // Gerencia a negociação, se aberta
}
lastTradeTime = currentTime;
}
Explicações:
TimeCurrent() e TimeMinute(currentTime):
TimeCurrent() é usado para obter o tempo atual do servidor, enquanto TimeMinute(currentTime) ajuda a desmembrar o minuto corrente. Isso é mais seguro e seguro do que tentar operações de tempo direto.
Controle de Abertura de Trade por Minuto:
O código só verifica se deve abrir uma nova operação quando o minuto registrado for diferente do minuto da última trade (lastTradeTime). Isso garante que você não entre em trades múltiplas no mesmo minuto.
Usar esse padrão garante que a sua estratégia só execute a lógica importante uma vez por minuto, economizando CPU e garantindo estabilidade no seu robô de trading.
User
entregue o codigo completo corrigido
Assistant
Claro, vou fornecer o código completo corrigido com a implementação adequada para o controle de tempo em MQL5, garantindo que as trades sejam abertas apenas uma vez por minuto:
Os erros que você está enfrentando se devem ao uso incorreto da função TimeMinute. A função TimeMinute() deve ser usada com o tempo obtido especificamente, e não diretamente como você faria com outras funções embutidas. No MQL5, a maneira correta de pegar partes específicas do tempo é usar TimeToStruct() para desmembrar datetime num tipo de dados MqlDateTime.
Vamos corrigir isso para utilizar a estrutura MqlDateTime de forma adequada.
Aqui está o código corrigido:
cpp
User
como funciona o take e o stop loss abertura e fechamento da ordem?
Assistant
No MQL5, as ordens de take profit e stop loss são mecanismos de gerenciamento de risco usados para definir automaticamente os pontos de fechamento de uma posição para garantir lucros ou limitar perdas. Vamos detalhar como eles funcionam no código e na prática:
Take Profit
Função: Fecha a posição automaticamente assim que o preço atinge um determinado nível desejado de lucro.
Configuração: No momento da abertura da ordem, você estabelece um preço acima (para ordens de compra) ou abaixo (para ordens de venda) do preço de abertura que, quando atingido, automaticamente fechará a posição.
No Código:
cpp
request.tp = price + takeProfitPoints * _Point; // Para uma compra
request.tp = price - takeProfitPoints * _Point; // Para uma venda
Stop Loss
Função: Fecha a posição automaticamente assim que o preço atinge um limite definido de perdas.
Configuração: Durante a abertura da ordem, define-se um preço abaixo (para ordens de compra) ou acima (para ordens de venda) do preço de abertura para minimizar perdas.
No Código:
cpp
request.sl = price - stopLossPoints * _Point; // Para uma compra
request.sl = price + stopLossPoints * _Point; // Para uma venda
Exemplos de Funcionamento:
Abertura com Take Profit e Stop Loss:
Compra: Você compra uma moeda a 1.2000.
Take Profit: Configura-se para 1.2010 (10 pontos acima).
Stop Loss: Configura-se para 1.1990 (10 pontos abaixo).
Isso significa que se o preço subir para 1.2010, a posição será fechada automaticamente para garantir o lucro, e se cair para 1.1990, será fechada para limitar as perdas.
Fechamento Automático:
Assim que o preço do mercado atinge qualquer uma dessas duas configurações, o servidor de negociação executa automaticamente uma ordem oposta para fechar a posição (sem intervenção manual).
Ordem de Fechamento no Código:
A lógica de fechamento no código acontece na função , que monitora constantemente a posição aberta em cada tick:
User
precisa sempre fechar de 10 20 a 30 pontos quando ja tem lucratividade
Assistant
Para criar uma estratégia em que a posição seja fechada automaticamente quando já houver uma lucratividade de 10, 20 ou 30 pontos, precisamos implementar uma lógica no código que monitore os lucros e feche a negociação quando o lucro atingir qualquer um desses valores. Aqui está uma abordagem sobre como você pode ajustar seu script MQL5 para implementar isso:
Implementação
A estratégia será configurada para verificar se o lucro da posição atingiu um dos três níveis de lucro predefinidos e fechará a ordem automaticamente quando isso ocorrer:
Definir Níveis de Lucro:
Configurar níveis de 10, 20 e 30 pontos para os quais a posição deve ser fechada caso o lucro atinja um destes.
Monitorar o Lucro Atual:
Verifique a cada tick se o lucro da posição aberta atinge ou supera um dos níveis definidos.
Fechar a Posição no Primeiro Nível Alcançado:
Ao detectar que um dos níveis de lucro foi alcançado, a posição será fechada automaticamente.
Aqui está como pode ser implementado no seu código:
cpp
User
e quando ele fecha a orden para proteger caso nao va para lado que deveria ir?
Assistant
Para implementar um mecanismo de proteção que fecha uma ordem quando o mercado não se move na direção esperada, podemos utilizar o conceito de Stop Loss. O Stop Loss é uma ferramenta que ajuda a limitar as perdas fechando automaticamente a ordem quando o preço atinge um determinado nível desfavorável. Vou explicar como você pode implementar isso junto com a lógica de Take Profit baseada em metas de lucro como discutido antes.
Implementando Stop Loss
Defina uma estratégia de Stop Loss:
Escolha um nível de stop loss adequado, por exemplo, uma certa quantidade de pontos distante do preço de abertura para limitar perdas.
Adicione a lógica de Stop Loss ao código:
Ao abrir uma ordem, defina um nível de stop loss além dos níveis de take profit.
Monitore as posições abertas:
Use a função ManageTrade() para verificar regularmente se o preço atingiu o nível de stop loss e, se sim, feche a posição.
Código Corrigido e Completo
Aqui está o código implementando tanto os níveis de lucro (10, 20, 30 pontos) quanto o stop loss:
cpp
User
pode ser fechada a ordem caso a vela de M1 termine negativa
Assistant
Para implementar o fechamento de uma posição caso a última vela de 1 minuto (M1) termine negativa, você pode adicionar uma verificação à lógica de gerenciamento de trades. Esta lógica irá inspecionar a direção da última vela sempre que uma nova vela se abrir. Se a vela terminar negativa (ou seja, fechar abaixo do preço de abertura), a posição será fechada.
Aqui está como você pode modificar o código para incluir essa funcionalidade:
Replaced OrderSelect, OrderType, etc., with position-related functions like PositionSelect, PositionGetInteger, PositionGetDouble.
Replaced OrderClose logic to use OrderSend structures tailored for order closing.
Check for TRADE_RETCODE_DONE after OrderSend to ensure the trade was successful.
Make sure you thoroughly test this revised code in a demo environment to verify that it meets your trading requirements without introducing unintended behavior.
a orden esta sendo fechada sempre dando prejuizo!
abre e ja fecha a ordem
double lotSize = 0.1;
double takeProfitPoints = 10; // Make sure this aligns with your symbol's point size
int maxMartingaleLevels = 3;
int martingaleMultiplier = 2;
int martingaleLevel = 0;
bool tradeOpened = false;
int currentDirection = 0;
void OnTick()
{
if (!tradeOpened) {
int direction = AnalyzeCandle();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(direction, lotSize, price);
}
} else {
ManageTrade();
}
}
// Candle analysis function
int AnalyzeCandle() {
double openPrice = iOpen(Symbol(), PERIOD_CURRENT, 1);
double closePrice = iClose(Symbol(), PERIOD_CURRENT, 1);
if (closePrice > openPrice) {
return 1;
} else if (closePrice < openPrice) {
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3; // Ensure this value is appropriate for your broker
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.tp = price + takeProfitPoints * _Point;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.tp = price - takeProfitPoints * _Point;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true; // Mark as trade opened only if order is successful
currentDirection = direction;
} else {
Print("OrderSend failed: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
long type = PositionGetInteger(POSITION_TYPE);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(Symbol(), SYMBOL_BID) : SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double profit = (currentPrice - openPrice) * ((type == POSITION_TYPE_BUY) ? 1 : -1) / _Point;
if (profit >= takeProfitPoints) {
ClosePosition();
martingaleLevel = 0;
} else if (profit < 0) {
if (martingaleLevel < maxMartingaleLevels) {
ClosePosition();
martingaleLevel++;
OpenTrade(currentDirection, lotSize * MathPow(martingaleMultiplier, martingaleLevel), currentPrice);
} else {
ClosePosition();
martingaleLevel = 0;
tradeOpened = false;
}
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
double currentPrice;
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
request.type = ORDER_TYPE_SELL;
} else {
currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
request.type = ORDER_TYPE_BUY;
}
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.price = currentPrice;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
Print("Order closed successfully: ", result.retcode);
} else {
Print("OrderClose failed: ", result.retcode);
}
tradeOpened = false; // Ensure trade opened status is correctly reset
}
}
Key Changes:
Ensure Successful Order Opening:
Only mark tradeOpened = true if the OrderSend operation is successful.
Check Pip and Point Conversion:
Ensure the value of takeProfitPoints is calibrated with _Point and matches your symbol.
Logging and Verification:
Print statements for debugging order close failures and order sending results.
Position Management:
Accurate tracking of trade usage to confirm when and why trades are opening and closing.
These changes are aimed at preventing trades from closing prematurely by ensuring correct initializations, trade flags, and analyzing working assumptions. Test with historical data to audit performance and logic flow.
double lotSize = 0.1;
double takeProfitPoints = 10; // Adjust this for the point size of your symbol
int maxMartingaleLevels = 3;
int martingaleMultiplier = 2;
int martingaleLevel = 0;
bool tradeOpened = false;
bool canCloseOnNegative = false;
int currentDirection = 0;
void OnTick()
{
static datetime lastTime = 0;
datetime currentTime = TimeCurrent();
if (lastTime != iTime(Symbol(), PERIOD_M1, 0)) {
lastTime = iTime(Symbol(), PERIOD_M1, 0); // Update to the latest candle time
canCloseOnNegative = true;
}
if (!tradeOpened) {
int direction = AnalyzeCandle();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(direction, lotSize, price);
}
} else {
ManageTrade();
}
}
// Analyzes the previous candle to determine trade direction
int AnalyzeCandle() {
double openPrice = iOpen(Symbol(), PERIOD_CURRENT, 1);
double closePrice = iClose(Symbol(), PERIOD_CURRENT, 1);
if (closePrice > openPrice) {
return 1;
} else if (closePrice < openPrice) {
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3; // Adjust for your broker
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
currentDirection = direction;
} else {
Print("OrderSend failed: ", result.retcode);
}
}
void ManageTrade() {
if (!tradeOpened || !PositionSelect(Symbol())) return;
long type = PositionGetInteger(POSITION_TYPE);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(Symbol(), SYMBOL_BID) : SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double profit = (currentPrice - openPrice) * ((type == POSITION_TYPE_BUY) ? 1 : -1) / _Point;
// Ensure trade is only closed with profit or at candle close with loss
if (profit >= takeProfitPoints) {
ClosePosition();
martingaleLevel = 0;
tradeOpened = false;
} else if (profit < 0 && canCloseOnNegative) {
canCloseOnNegative = false; // Only try to close on the new candle
if (martingaleLevel < maxMartingaleLevels) {
ClosePosition();
martingaleLevel++;
OpenTrade(currentDirection, lotSize * MathPow(martingaleMultiplier, martingaleLevel), currentPrice);
} else {
ClosePosition();
martingaleLevel = 0;
tradeOpened = false;
}
}
}
void ClosePosition() {
if (!PositionSelect(Symbol())) return;
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
double currentPrice;
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
request.type = ORDER_TYPE_SELL;
} else {
currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
request.type = ORDER_TYPE_BUY;
}
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.price = currentPrice;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
Print("Order closed successfully: ", result.retcode);
} else {
Print("OrderClose failed: ", result.retcode);
}
tradeOpened = false; // Reset trade status after closing
}
Key Changes:
Candle Close Logic:
Introduced canCloseOnNegative and lastTime to track candle endings and make closure decisions only at candle transitions.
Logical Conditions:
Checks ensure orders only close at strategic points, either when achieving the profit target or when a new candle opens with negative profit.
Conditional Trade Logic:
Fixed logic for opening and managing trades (after specific conditions like profit/loss on candle close, bias, etc.).
This setup helps mitigate premature trade closures by making conditions for closing clear and aligned with temporal conditions, thus better adhering to your trading strategy.
double lotSize = 0.1;
double takeProfitPoints = 10; // Adjust to your strategy
double stopLossPoints = 10; // Specify stop loss if needed
bool tradeOpened = false;
datetime lastTradeTime = 0;
void OnTick()
{
datetime currentTime = TimeCurrent();
// Avoid trading more than once within the same minute candle
if (currentTime == lastTradeTime) return;
// Ensure we're analyzing the latest finished candle
if (Minute() % 1 == 0 && !tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Enter in the opposite direction
}
}
if (tradeOpened) {
ManageTrade(); // Manage trade if open
}
lastTradeTime = currentTime;
}
// Function to analyze the direction of the last three candles
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
if (close1 > open1 && close2 > open2 && close3 > open3) {
// Three consecutive bullish candles
return 1;
} else if (close1 < open1 && close2 < open2 && close3 < open3) {
// Three consecutive bearish candles
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3; // Adjust as necessary
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.tp = price + takeProfitPoints * _Point;
request.sl = price - stopLossPoints * _Point;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.tp = price - takeProfitPoints * _Point;
request.sl = price + stopLossPoints * _Point;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
} else {
Print("OrderSend failed: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
double profit = (currentPrice - openPrice) * direction / _Point;
// Decide whether to hold or close based on strategy criteria
if (profit >= takeProfitPoints || profit <= -stopLossPoints) {
ClosePosition();
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
request.price = PositionGetDouble(POSITION_PRICE_CURRENT);
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = false; // Reset trade status
Print("Order closed successfully: ", result.retcode);
} else {
Print("OrderClose failed: ", result.retcode);
}
}
}
Key Implementation Notes:
Strategy Logic: The strategy looks for three consecutive candles in the same direction, then enters a trade in the opposite direction.
Exit Conditions: Trades are managed with take profit and stop loss to ensure they are closed correctly according to the strategy.
Temporal Management: Ensures that trades are not opened more than once per candle.
Remember, backtest this strategy properly with historical data and test in a demo account to fine-tune parameters like takeProfitPoints and stopLossPoints before deploying in a live trading environment. Adjust the logic further as necessary to closely align with any specific nuances or additional criteria of the "3 m1" approach that you are implementing.
double lotSize = 0.1;
double takeProfitPoints = 10; // Ajuste conforme sua estratégia
double stopLossPoints = 10; // Especificar stop loss, se necessário
bool tradeOpened = false;
datetime lastTradeTime = 0;
void OnTick() {
datetime currentTime = TimeCurrent();
int currentMinute = TimeMinute(currentTime); // Obtendo o minuto atual
// Evita negociar mais de uma vez dentro do mesmo minuto
if (currentMinute == TimeMinute(lastTradeTime)) return;
// Verifica se estamos analisando a última vela concluída
if (!tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Entra na direção oposta
}
}
if (tradeOpened) {
ManageTrade(); // Gerencia a negociação, se aberta
}
lastTradeTime = currentTime;
}
// Função para analisar a direção das últimas três velas
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
if (close1 > open1 && close2 > open2 && close3 > open3) {
// Três velas de alta consecutivas
return 1;
} else if (close1 < open1 && close2 < open2 && close3 < open3) {
// Três velas de baixa consecutivas
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3; // Ajuste conforme necessário
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.tp = price + takeProfitPoints * _Point;
request.sl = price - stopLossPoints * _Point;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.tp = price - takeProfitPoints * _Point;
request.sl = price + stopLossPoints * _Point;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
} else {
Print("OrderSend falhou: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
double profit = (currentPrice - openPrice) * direction / _Point;
// Decide se mantém ou fecha baseado nos critérios da estratégia
if (profit >= takeProfitPoints || profit <= -stopLossPoints) {
ClosePosition();
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
request.price = PositionGetDouble(POSITION_PRICE_CURRENT);
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = false; // Redefine o estado da negociação
Print("Ordem fechada com sucesso: ", result.retcode);
} else {
Print("Fechamento da ordem falhou: ", result.retcode);
}
}
}
Explicações:
Controle de Minutos: Use TimeMinute() para garantir que a lógica executada de operações seja feita apenas uma vez por cada novo minuto.
Abertura e Fechamento de Operações: As operações são abertas ao detectar três velas consecutivas na mesma direção e sempre fechadas com base em um take profit ou stop loss.
Averiguação de Condições de Trade: Verifica múltiplas condições antes de abrir ou fechar trades para evitar operações desnecessárias ou mal posicionadas.
Você deve testar este código em um ambiente de simulação antes de usá-lo em negociação real para verificar se as regras da sua estratégia são bem aplicadas.
double lotSize = 0.1;
double takeProfitPoints = 10; // Ajuste conforme sua estratégia
double stopLossPoints = 10; // Especifique o stop loss, se necessário
bool tradeOpened = false;
datetime lastTradeTime = 0;
void OnTick() {
datetime currentTime = TimeCurrent();
MqlDateTime currentTimeStruct;
TimeToStruct(currentTime, currentTimeStruct);
int currentMinute = currentTimeStruct.min; // Obtendo o minuto atual
MqlDateTime lastTradeTimeStruct;
TimeToStruct(lastTradeTime, lastTradeTimeStruct);
int lastTradeMinute = lastTradeTimeStruct.min;
// Evita negociar mais de uma vez dentro do mesmo minuto
if (currentMinute == lastTradeMinute) return;
// Verifica se estamos analisando a última vela concluída
if (!tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Entra na direção oposta
}
}
if (tradeOpened) {
ManageTrade(); // Gerencia a negociação, se aberta
}
lastTradeTime = currentTime;
}
// Função para analisar a direção das últimas três velas
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
if (close1 > open1 && close2 > open2 && close3 > open3) {
// Três velas de alta consecutivas
return 1;
} else if (close1 < open1 && close2 < open2 && close3 < open3) {
// Três velas de baixa consecutivas
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3; // Ajuste conforme necessário
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.tp = price + takeProfitPoints * _Point;
request.sl = price - stopLossPoints * _Point;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.tp = price - takeProfitPoints * _Point;
request.sl = price + stopLossPoints * _Point;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
} else {
Print("OrderSend falhou: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
double profit = (currentPrice - openPrice) * direction / _Point;
// Decide se mantém ou fecha baseado nos critérios da estratégia
if (profit >= takeProfitPoints || profit <= -stopLossPoints) {
ClosePosition();
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
request.price = PositionGetDouble(POSITION_PRICE_CURRENT);
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = false; // Redefine o estado da negociação
Print("Ordem fechada com sucesso: ", result.retcode);
} else {
Print("Fechamento da ordem falhou: ", result.retcode);
}
}
}
Correções e Melhorias:
Desmembramento de Tempo:
Usamos a estrutura MqlDateTime para dividir e comparar os minutos atuais, evitando comparar datetime diretamente.
Controle Rigoroso de Tempo:
A comparação de minutos (currentMinute e lastTradeMinute) agora funciona corretamente para garantir suficiente liberação entre negociações.
Atribuição de lastTradeTime:
Atribuído corretamente no final de OnTick para assegurar que o tempo é definido após uma análise e possível abertura de trade.
Utilize este código em um ambiente de teste e ajuste os parâmetros conforme a resposta da estratégia ao mercado. Isso irá assegurar que o script funcione conforme o esperado.
Função ClosePosition(): Envia uma requisição para fechar a posição atual com base nas regras definidas.
Resumo:
Utilizar stop loss e take profit é uma prática essencial de gerenciamento de risco, permitindo que traders protejam seu capital e automatizem o processo de fechamento das operações, evitando a necessidade de monitoramento constante das posições abertas.
double lotSize = 0.1;
bool tradeOpened = false;
datetime lastTradeTime = 0;
// Níveis de lucro para fechamento
double profitsTarget[] = {10, 20, 30}; // Repare que isso é em pontos, não em preço direto
void OnTick() {
datetime currentTime = TimeCurrent();
MqlDateTime currentTimeStruct;
TimeToStruct(currentTime, currentTimeStruct);
int currentMinute = currentTimeStruct.min;
MqlDateTime lastTradeTimeStruct;
TimeToStruct(lastTradeTime, lastTradeTimeStruct);
int lastTradeMinute = lastTradeTimeStruct.min;
if (currentMinute == lastTradeMinute) return; // Evita repetição de negociações no mesmo minuto
if (!tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Entra na direção oposta
}
}
if (tradeOpened) {
ManageTrade(); // Gerencia a negociação, se aberta
}
lastTradeTime = currentTime;
}
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
if (close1 > open1 && close2 > open2 && close3 > open3) {
return 1;
} else if (close1 < open1 && close2 < open2 && close3 < open3) {
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
} else {
Print("OrderSend falhou: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
double profitInPoints = (currentPrice - openPrice) * direction / _Point;
// Checar se atingiu qualquer nível de lucro predefinido
for (int i = 0; i < ArraySize(profitsTarget); i++) {
if (profitInPoints >= profitsTarget[i]) {
ClosePosition();
break;
}
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
request.price = PositionGetDouble(POSITION_PRICE_CURRENT);
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = false;
Print("Ordem fechada com sucesso: ", result.retcode);
} else {
Print("Fechamento da ordem falhou: ", result.retcode);
}
}
}
Explicação:
Níveis de Lucro (profitsTarget): Definimos um array profitsTarget[] contendo os valores de lucro de 10, 20 e 30 pontos. Esses valores são comparados com o lucro corrente em pontos (profitInPoints).
Verificação de Lucro: Durante a execução de ManageTrade(), o lucro atual é verificado contra os níveis predefinidos. Se o lucro atingir ou exceder qualquer um desses níveis, a posição é fechada.
Fechamento: A função ClosePosition() é invocada para fechar a posição assim que os critérios de lucro forem satisfeitos.
Teste:
É crucial testar as condições com dados históricos e em uma conta demo antes de executar em um ambiente real para garantir que o comportamento da estratégia seja conforme o esperado. Ajustes podem ser necessários com base nas condições de mercado e características específicas do ativo negociado.
double lotSize = 0.1;
bool tradeOpened = false;
datetime lastTradeTime = 0;
// Níveis de lucro e stop loss
double profitsTarget[] = {10, 20, 30}; // Metas de lucro em pontos
double stopLossPoints = 10; // Stop loss em pontos
void OnTick() {
datetime currentTime = TimeCurrent();
MqlDateTime currentTimeStruct;
TimeToStruct(currentTime, currentTimeStruct);
int currentMinute = currentTimeStruct.min;
MqlDateTime lastTradeTimeStruct;
TimeToStruct(lastTradeTime, lastTradeTimeStruct);
int lastTradeMinute = lastTradeTimeStruct.min;
if (currentMinute == lastTradeMinute) return; // Evita repetição de trades no mesmo minuto
if (!tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Entra na direção oposta
}
}
if (tradeOpened) {
ManageTrade(); // Gerencia a negociação, se aberta
}
lastTradeTime = currentTime;
}
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
if (close1 > open1 && close2 > open2 && close3 > open3) {
return 1;
} else if (close1 < open1 && close2 < open2 && close3 < open3) {
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.sl = price - stopLossPoints * _Point; // Stop loss para compra
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.sl = price + stopLossPoints * _Point; // Stop loss para venda
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
} else {
Print("Falha ao enviar ordem: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
double profitInPoints = (currentPrice - openPrice) * direction / _Point;
// Checar se atingiu qualquer nível de lucro ou se atingiu o stop loss
if (profitInPoints <= -stopLossPoints) {
ClosePosition();
} else {
for (int i = 0; i < ArraySize(profitsTarget); i++) {
if (profitInPoints >= profitsTarget[i]) {
ClosePosition();
break;
}
}
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
request.price = PositionGetDouble(POSITION_PRICE_CURRENT);
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = false;
Print("Ordem fechada com sucesso: ", result.retcode);
} else {
Print("Falha ao fechar ordem: ", result.retcode);
}
}
}
Resumo de Funcionalidades:
Níveis de Stop Loss: Implementa proteção contra perdas ao automaticamente fechar a posição quando o preço se mover contra você um número específico de pontos.
Níveis de Lucro Dinâmico: Fecha as posições se atingir pelo menos 10, 20, ou 30 pontos de lucro.
Gestão Dinâmica do Trade:ManageTrade() verifica ambos os critérios de lucro e de stop loss a cada atualização de tick para fechar a posição conforme necessário.
Nota: É importante ajustar o nível de stopLossPoints e profitsTarget com base em testes históricos e condições de mercado para garantir que a estratégia seja eficaz e alinhada com suas metas de risco e lucro. Também é essencial simular este comportamento em uma conta demo antes de negociar com dinheiro real.
double lotSize = 0.1;
bool tradeOpened = false;
datetime lastTradeTime = 0;
// Níveis de lucro e stop loss
double profitsTarget[] = {10, 20, 30}; // Metas de lucro em pontos
double stopLossPoints = 10; // Stop loss em pontos
void OnTick() {
datetime currentTime = TimeCurrent();
MqlDateTime currentTimeStruct;
TimeToStruct(currentTime, currentTimeStruct);
int currentMinute = currentTimeStruct.min;
MqlDateTime lastTradeTimeStruct;
TimeToStruct(lastTradeTime, lastTradeTimeStruct);
int lastTradeMinute = lastTradeTimeStruct.min;
// Verifica a transição de um minuto
if (currentMinute != lastTradeMinute) {
// No início de uma nova vela
if (tradeOpened) {
// Fecha a posição se a última vela de M1 foi negativa
if (WasLastM1CandleNegative()) {
ClosePosition();
}
}
if (!tradeOpened) {
int direction = AnalyzeThreeCandles();
if (direction != 0) {
double price = (direction == 1) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
OpenTrade(-direction, lotSize, price); // Entra na direção oposta
}
}
lastTradeTime = currentTime;
}
if (tradeOpened) {
ManageTrade(); // Gerencia a negociação, se aberta
}
}
// Função para analisar se a última vela de M1 foi negativa
bool WasLastM1CandleNegative() {
double open = iOpen(Symbol(), PERIOD_M1, 1);
double close = iClose(Symbol(), PERIOD_M1, 1);
return close < open; // Retorna verdadeiro se a vela fechou abaixo do preço de abertura
}
// Função para analisar a direção das últimas três velas
int AnalyzeThreeCandles() {
double open1 = iOpen(Symbol(), PERIOD_M1, 1);
double close1 = iClose(Symbol(), PERIOD_M1, 1);
double open2 = iOpen(Symbol(), PERIOD_M1, 2);
double close2 = iClose(Symbol(), PERIOD_M1, 2);
double open3 = iOpen(Symbol(), PERIOD_M1, 3);
double close3 = iClose(Symbol(), PERIOD_M1, 3);
if (close1 > open1 && close2 > open2 && close3 > open3) {
return 1;
} else if (close1 < open1 && close2 < open2 && close3 < open3) {
return -1;
}
return 0;
}
void OpenTrade(int direction, double lots, double price) {
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.magic = 0;
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
if (direction == 1) {
request.type = ORDER_TYPE_BUY;
request.price = price;
request.volume = lots;
request.sl = price - stopLossPoints * _Point; // Stop loss para compra
} else if (direction == -1) {
request.type = ORDER_TYPE_SELL;
request.price = price;
request.volume = lots;
request.sl = price + stopLossPoints * _Point; // Stop loss para venda
}
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = true;
} else {
Print("Falha ao enviar ordem: ", result.retcode);
}
}
void ManageTrade() {
if (PositionSelect(Symbol())) {
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
int direction = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
double profitInPoints = (currentPrice - openPrice) * direction / _Point;
// Checa se atingiu qualquer nível de lucro ou se atingiu o stop loss
if (profitInPoints <= -stopLossPoints) {
ClosePosition();
} else {
for (int i = 0; i < ArraySize(profitsTarget); i++) {
if (profitInPoints >= profitsTarget[i]) {
ClosePosition();
break;
}
}
}
}
}
void ClosePosition() {
if (PositionSelect(Symbol())) {
ulong ticket = PositionGetInteger(POSITION_TICKET);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.symbol = Symbol();
request.deviation = 3;
request.type_filling = ORDER_FILLING_IOC;
request.price = PositionGetDouble(POSITION_PRICE_CURRENT);
if (OrderSend(request, result) && result.retcode == TRADE_RETCODE_DONE) {
tradeOpened = false;
Print("Ordem fechada com sucesso: ", result.retcode);
} else {
Print("Falha ao fechar ordem: ", result.retcode);
}
}
}
Resumo das Alterações:
Fechamento Baseado na Vela M1: A função WasLastM1CandleNegative() determina se a última vela fechou negativa. Essa função é chamada no início de cada nova vela, dentro de OnTick, para decidir fechar a posição se a última vela foi negativa.
Lógica de Fechamento: Fechar a posição imediatamente ao início de um novo minuto se a última vela era desfavorável, garantindo que as operações são protegidas contra continuar em uma direção não desejada.
Essas alterações adicionam um componente extra de proteção, que pode ser útil dependendo da sua estratégia de mercado e abordagem de risco.