double lowlevel, highlevel; bool inaccumulationphase = false; void OnTick() { //…
- User
double low_level, high_level; bool in_accumulation_phase = false;
void OnTick() { // Detectar o intervalo de negociação (Acumulação) if (!in_accumulation_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Diferença percentual pequena, indicando lateralização { in_accumulation_phase = true; }}
// Detecção de Spring double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual
if (in_accumulation_phase && close_price < low_level) { // Detectou um Spring if (close_price > low_level) // Retorno para dentro da faixa { // Sinal de compra Buy(); } } }
// Função simples para abrir uma ordem de compra void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point; // Stop Loss abaixo do Spring double tp = high_level + 100 * Point; // Take Profit após rompimento da resistência
// Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result);
request.action = TRADE_ACTION_DEAL; // Ação de envio da ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_BUY; // Tipo de ordem: Compra request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Preço de compra (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio de preço máximo request.magic = 123456; // Número mágico para identificar a ordem request.comment = "Wyckoff Spring Buy"; // Comentário da ordem
// Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de compra: ", GetLastError()); } else { Print("Ordem de compra enviada com sucesso!"); } }
erro:
';' - open parenthesis expected teste_Wyckoff_001.mq5 36 38 ';' - open parenthesis expected teste_Wyckoff_001.mq5 37 40
- Assistant
The error messages you're encountering suggest that there is a missing opening parenthesis before the statements on lines 36 and 37 of your MQL5 script. Let's review the configuration of the
OrderSend()function call where the error is likely occurring.The
OrderSend()function is part of the MQL5 standard library used to place trade orders. The syntax ofOrderSend()is generally:bool OrderSend(const MqlTradeRequest& request, MqlTradeResult& result);In your case, you should ensure that the
OrderSend()function is properly declared and all the necessary header files are included. Here's the revised section of the code including a complete function:#include <Trade\Trade.mqh> void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Corrected to _Point for MQL5 double tp = high_level + 100 * _Point; // Corrected to _Point for MQL5 // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Volume of the lot request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Ask price for buying request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum deviation request.magic = 123456; // Magic number for identifying the order request.comment = "Wyckoff Spring Buy"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de compra: ", GetLastError()); } else { Print("Ordem de compra enviada com sucesso!"); } }Key Revisions:
-
Include the Trade Library: At the top of your code, include the
Trade.mqhfile which contains the necessary objects and functions for trading operations (#include <Trade\Trade.mqh>). -
Use of
_Pointinstead ofPoint: MQL5 uses_Pointto determine the point calculation, which might be more compatible based on the referenced environment or the kind of broker settings you have. -
Correct
OrderSendSyntax: Make sure you've correctly structured theOrderSend()function without any missing parentheses. If there is still an issue, check for typos or line continuation errors related to parentheses.
This corrected usage should resolve the specified errors assuming your environment is configured correctly for MQL5. If you still encounter issues, verify that no other parts of your codebase are incorrect or conflict with
OrderSend(). -
- User
double low_level, high_level; bool in_accumulation_phase = false;
void OnTick() { // Detectar o intervalo de negociação (Acumulação) if (!in_accumulation_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Diferença percentual pequena, indicando lateralização { in_accumulation_phase = true; }}
// Detecção de Spring double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual
if (in_accumulation_phase && close_price < low_level) { // Detectou um Spring if (close_price > low_level) // Retorno para dentro da faixa { // Sinal de compra Buy(); } } }
// Função simples para abrir uma ordem de compra void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point; // Stop Loss abaixo do Spring double tp = high_level + 100 * Point; // Take Profit após rompimento da resistência
// Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result);
request.action = TRADE_ACTION_DEAL; // Ação de envio da ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_BUY; // Tipo de ordem: Compra request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Preço de compra (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio de preço máximo request.magic = 123456; // Número mágico para identificar a ordem request.comment = "Wyckoff Spring Buy"; // Comentário da ordem
// Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de compra: ", GetLastError()); } else { Print("Ordem de compra enviada com sucesso!"); } }
esse robo só tem sinal de compra?
- Assistant
Yes, the provided Expert Advisor (EA) code only includes logic for generating buy signals. It is designed to detect a trading range (accumulation phase) and a "spring" event within the Wyckoff method. When a spring is detected—meaning the price temporarily falls below a defined low level and then reverses—the EA attempts to open a buy order.
If you want to extend the EA to also include sell signals (potentially for distribution phases or breakdowns), you'll need to incorporate additional logic to identify those scenarios. Here's a basic outline of how you might add a simple sell signal logic:
-
Define a Distribution Phase: Similar to the accumulation logic, you could define criteria for a distribution phase.
-
Detecting Breakdowns: Add logic to detect when the price breaks below the specified range, indicating a potential move downward.
Here's a skeleton of how you might expand the EA to include sell signals:
double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; void OnTick() { // Detectar o intervalo de negociação (Acumulação) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); if ((high_level - low_level) / low_level < 0.02) // Faixa lateral { in_accumulation_phase = true; } // Alternativamente, você pode definir regras para detectar distribuição if ((high_level - low_level) / high_level < 0.02) // Faixa lateral para distribuição, ou alguma outra lógica { in_distribution_phase = true; } } // Detecção de Spring (para compra) double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual if (in_accumulation_phase && close_price < low_level) { if (close_price > low_level) { // Sinal de compra Buy(); } } // Detecção de um "Upthrust" ou quebra para downside (para venda) if (in_distribution_phase && close_price > high_level) { if (close_price < high_level) { // Sinal de venda Sell(); } } } // Função simples para abrir uma ordem de venda void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point; // Stop Loss acima do Upthrust double tp = low_level - 100 * Point; // Take Profit abaixo do suporte // Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; // Ação de envio da ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_SELL; // Tipo de ordem: Venda request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Preço de venda (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio de preço máximo request.magic = 654321; // Número mágico diferente para identificar a ordem de venda request.comment = "Wyckoff Upthrust Sell"; // Comentário da ordem // Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de venda: ", GetLastError()); } else { Print("Ordem de venda enviada com sucesso!"); } }Key Points:
-
Distribution Phase: This example introduces a potential detection mechanism based on a similar low volatility condition, but targeting distribution. You should adjust the logic based on what you consider a signal for selling within Wyckoff logic (often called "upthrust" or other distribution phase events).
-
Sell Orders: The
Sell()function mirrors the structure of theBuy()function but sets appropriate stop-loss and take-profit levels for selling. -
Magic Number: Different magic numbers are used to distinguish between buy and sell orders, which can help in identifying and managing open trades.
Remember to test and modify the strategy extensively in a demo environment to suit your own criteria or chosen methodologies within the Wyckoff trading strategy.
-
- User
double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
void OnTick() { // Detectar o intervalo de negociação (Acumulação) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Faixa lateral { in_accumulation_phase = true; } // Alternativamente, você pode definir regras para detectar distribuição if ((high_level - low_level) / high_level < 0.02) // Faixa lateral para distribuição, ou alguma outra lógica { in_distribution_phase = true; }}
// Detecção de Spring (para compra) double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual
if (in_accumulation_phase && close_price < low_level) { if (close_price > low_level) { // Sinal de compra Buy(); } }
// Detecção de um "Upthrust" ou quebra para downside (para venda) if (in_distribution_phase && close_price > high_level) { if (close_price < high_level) { // Sinal de venda Sell(); } } }
// Função simples para abrir uma ordem de venda void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point; // Stop Loss acima do Upthrust double tp = low_level - 100 * Point; // Take Profit abaixo do suporte
// Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result);
request.action = TRADE_ACTION_DEAL; // Ação de envio da ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_SELL; // Tipo de ordem: Venda request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Preço de venda (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio de preço máximo request.magic = 654321; // Número mágico diferente para identificar a ordem de venda request.comment = "Wyckoff Upthrust Sell"; // Comentário da ordem
// Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de venda: ", GetLastError()); } else { Print("Ordem de venda enviada com sucesso!"); } }
erro:
'Buy' - undeclared identifier teste_Wyckoff_001.mq5 33 10 ')' - expression expected teste_Wyckoff_001.mq5 33 14 ';' - open parenthesis expected teste_Wyckoff_001.mq5 52 39 ';' - open parenthesis expected teste_Wyckoff_001.mq5 53 39
- Assistant
The error messages you're encountering indicate there are issues with how the
Buy()function is invoked and implemented in your MQL5 script. Let's address and correct each problem:-
Undeclared Identifier for
Buy: This error suggests that theBuy()function is either missing or not declared correctly. You need to ensure theBuy()function is properly defined in your code, in a similar manner as theSell()function. -
Expression Expected Error: This usually occurs when the syntax for invoking or defining a function is incorrect. Ensure that your function calls are correctly structured.
-
Open Parenthesis Expected Error: This indicates a syntax error, often due to a missing parenthesis or other structural issue, usually in the section where function parameters or calculations occur.
Here's a revised version that includes a correct implementation of both
Buy()andSell()functions:// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; // Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; } } // Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle if (in_accumulation_phase && close_price < low_level) { if (close_price > low_level) { // Buy signal Buy(); } } // Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { if (close_price < high_level) { // Sell signal Sell(); } } } // Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point; // Stop Loss below the Spring double tp = high_level + 100 * Point; // Take Profit after resistance break // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { Print("Buy order sent successfully!"); } } // Function to place a sell order (already provided, no changes) void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point; // Stop Loss above the Upthrust double tp = low_level - 100 * Point; // Take Profit below the support // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { Print("Sell order sent successfully!"); } }Key Corrections:
-
Declared the
Buy()Function: Ensure that theBuy()function is declared and defined just like theSell()function. This prevents the "undeclared identifier" error. -
Corrected Order Structure: Validate that both
OrderSend()calls are correctly structured in both theBuy()andSell()functions.
Make sure your trading logic accurately reflects your intent and test this EA on a demo account thoroughly before using it in a live trading environment. Also, review and adjust the
Pointvalue usage to adapt it to the asset specifics (price format, broker settings). -
- User
// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
// Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; }}
// Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle
if (in_accumulation_phase && close_price < low_level) { if (close_price > low_level) { // Buy signal Buy(); } }
// Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { if (close_price < high_level) { // Sell signal Sell(); } } }
// Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point; // Stop Loss below the Spring double tp = high_level + 100 * Point; // Take Profit after resistance break
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result);
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { Print("Buy order sent successfully!"); } }
// Function to place a sell order (already provided, no changes) void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point; // Stop Loss above the Upthrust double tp = low_level - 100 * Point; // Take Profit below the support
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result);
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { Print("Sell order sent successfully!"); } }
erro:
';' - open parenthesis expected teste_Wyckoff_001.mq5 54 38 ';' - open parenthesis expected teste_Wyckoff_001.mq5 55 40 ';' - open parenthesis expected teste_Wyckoff_001.mq5 89 39 ';' - open parenthesis expected teste_Wyckoff_001.mq5 90 39
- Assistant
The errors you're encountering seem to refer to a syntax issue, specifically related to parentheses or semicolon placement for some expressions or statements in your MQL5 script. In your case, these errors might be related to the call to
ZeroMemory()or formatting of theOrderSend()function.Steps to Resolve:
-
ZeroMemory() Syntax: Ensure that
ZeroMemoryfunction calls use the correct syntax with parentheses encompassing the structure to be initialized. -
OrderSend() Syntax: Ensure that all function calls, particularly
OrderSend, are correctly formed with proper use of parentheses, and that you're handling results correctly.
Here is a refined version of your code with comments indicating the corrections.
// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; // Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; } } // Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle if (in_accumulation_phase && close_price < low_level) { if (close_price > low_level) { // Buy signal Buy(); } } // Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { if (close_price < high_level) { // Sell signal Sell(); } } } // Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point; // Stop Loss below the Spring double tp = high_level + 100 * Point; // Take Profit after resistance break // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Correctly using ZeroMemory with parentheses ZeroMemory(result); // Correctly using ZeroMemory with parentheses request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { Print("Buy order sent successfully!"); } } // Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point; // Stop Loss above the Upthrust double tp = low_level - 100 * Point; // Take Profit below the support // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Correctly using ZeroMemory with parentheses ZeroMemory(result); // Correctly using ZeroMemory with parentheses request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { Print("Sell order sent successfully!"); } }Key Changes:
-
ZeroMemory Usage: Ensure you use
ZeroMemoryfunctions correctly, with parentheses enclosing the structure to be zeroed. -
Function Syntax: Make sure all functions (like
OrderSend) are properly invoked with parentheses and arguments.
By resolving these, your code should compile without the previously mentioned syntax errors. Be sure to test thoroughly in a demo environment to verify the behavior matches your expectations, especially after these changes.
-
- User
// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
// Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; }}
// Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle
if (in_accumulation_phase && close_price < low_level) { // Buy signal Buy(); }
// Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { // Sell signal Sell(); } }
// Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point(); // Stop Loss below the Spring double tp = high_level + 100 * Point(); // Take Profit after resistance break
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { Print("Buy order sent successfully!"); } }
// Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point(); // Stop Loss above the Upthrust double tp = low_level - 100 * Point(); // Take Profit below the support
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { Print("Sell order sent successfully!"); } }
tem algo errado no codigo?
- Assistant
Your code is mostly correct, but there are a few issues and clarifications that can be made, specifically regarding the usage of
Pointand possibly overlooked MQL5 specifics. Here’s a review and fixes:-
Use of
Point(): In MQL,Pointis a built-in constant and should not be used as a function call (i.e.,Point()is incorrect). It should be used without parentheses. In some circumstances, MQL5 uses_Point, but typicallyPointwill work correctly unless otherwise specified by your broker or system configuration. -
Include the Trade Library: You should include the necessary trading library at the beginning of your script to ensure full access to trading functions, especially in MQL5 environments.
-
OrderSend Function: The call to
OrderSendshould be corrected as per MQL5 standards. It's worth noting in MQL5 and above, you might need specific handling or compatibility checks if dealing with accounts/orders.
Here is the corrected script:
#include <Trade\Trade.mqh> // Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; // Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; } } // Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle if (in_accumulation_phase && close_price < low_level) { // Buy signal Buy(); } // Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { // Sell signal Sell(); } } // Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * Point; // Stop Loss below the Spring double tp = high_level + 100 * Point; // Take Profit after resistance break // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { Print("Buy order sent successfully!"); } } // Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * Point; // Stop Loss above the Upthrust double tp = low_level - 100 * Point; // Take Profit below the support // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { Print("Sell order sent successfully!"); } }Key Corrections:
- Point Usage: Removed parentheses from
Pointwhich should bePointinstead ofPoint(). - Include the Trade Library: Ensured that the script includes the trade library for using MQL5 trading functions (only if necessary).
- Code Structure: Validated the usage of
ZeroMemorysyntax, ensuring the structures are zeroed properly.
You're encouraged to thoroughly test this code in a simulated environment before attempting to use it for live trading to confirm every part behaves as expected and aligns with your trading principles.
-
- User
e agora?
// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
// Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; }}
// Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle
if (in_accumulation_phase && close_price < low_level) { // Buy signal Buy(); }
// Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { // Sell signal Sell(); } }
// Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss below the Spring double tp = high_level + 100 * _Point; // Take Profit after resistance break
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { Print("Buy order sent successfully!"); } }
// Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss above the Upthrust double tp = low_level - 100 * _Point; // Take Profit below the support
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { Print("Sell order sent successfully!"); } }
- Assistant
Your script looks mostly correct, with the appropriate use of
_Pointinstead ofPointif your MQL5 environment requires it. However, let's review a few potential areas where further improvements or clarifications might be necessary to ensure everything works smoothly:-
Include Necessary Headers: Make sure you are including the necessary headers, particularly if you're using MQL5 and want access to the Trading functions.
-
OrderSend Logic in MQL5: Since MQL5's
OrderSend()procedure can sometimes require specific checks and error handling, ensure your trading environment and account type (e.g., netting vs. hedging) are correctly set up to handle the trade requests you're sending. -
Error Handling: Consider including detailed error handling to catch specific error codes and provide useful debug information. This could greatly assist during testing and when running in a live environment.
Here's an improved version incorporating these suggestions:
#include <Trade\Trade.mqh> // Include trade functions library // Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; // Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; } } // Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle if (in_accumulation_phase && close_price < low_level) { // Buy signal Buy(); } // Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { // Sell signal Sell(); } } // Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss below the Spring double tp = high_level + 100 * _Point; // Take Profit after resistance break // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { if(result.retcode == 10009) // Check for successful execution code Print("Buy order sent successfully!"); else Print("Buy order failed: ", result.retcode); // Output specific error code } } // Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss above the Upthrust double tp = low_level - 100 * _Point; // Take Profit below the support // Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment // Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { if(result.retcode == 10009) // Check for successful execution code Print("Sell order sent successfully!"); else Print("Sell order failed: ", result.retcode); // Output specific error code } }Key Points:
-
Include the Library: The trade library is included for trade functions to ensure full function access and compatibility with MQL5 systems.
-
Enhanced Error Handling: Improved error handling with additional checks on
result.retcode, a standard approach to verify the success or failure of orders. -
Use of
_Point: Correct usage of_Point, which is appropriate for price calculation adjustments in MQL5.
Ensure you validate this code in a robust testing environment, such as a demo account, to ensure it functions as intended without causing unintended trades in live settings. Adjust parameters for lot sizes, stop losses, and take profits according to your specific trading strategy and risk management approach.
-
- User
#include <Trade\Trade.mqh> // Include trade functions library
// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
// Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; }}
// Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle
if (in_accumulation_phase && close_price < low_level) { // Buy signal Buy(); }
// Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { // Sell signal Sell(); } }
// Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss below the Spring double tp = high_level + 100 * _Point; // Take Profit after resistance break
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { if(result.retcode == 10009) // Check for successful execution code Print("Buy order sent successfully!"); else Print("Buy order failed: ", result.retcode); // Output specific error code } }
// Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss above the Upthrust double tp = low_level - 100 * _Point; // Take Profit below the support
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { if(result.retcode == 10009) // Check for successful execution code Print("Sell order sent successfully!"); else Print("Sell order failed: ", result.retcode); // Output specific error code } }
me responda em portugues, nao aparece mensagem nenhuma nem ordem de compra nem de venda!
- Assistant
Se o seu código MQL5 não está mostrando mensagens ou realizando ordens de compra e venda, pode ser necessário verificar alguns pontos para identificar o problema:
-
Condições de Acumulação ou Distribuição: As condições para entrar em fase de acumulação ou distribuição podem não estar sendo atendidas. Verifique se a lógica para definir
in_accumulation_phaseein_distribution_phaseestá correta e se realmente há condições no mercado para que isso aconteça. Ajuste a condição percentual se necessário. -
Verificação de Fechamento: Certifique-se de que a variável
close_priceseja calculada corretamente e que esteja de fato abaixolow_levelpara compras ou acima dehigh_levelpara vendas, conforme esperado. -
Execução de Ordem: Verifique os logs do terminal Metatrader para ver potencialmente outras mensagens de erro ou informações que não estão aparecendo diretamente, como por exemplo mensagens relacionadas a problemas no envio da ordem (por exemplo, se o volume não é aceito pelo seu corretor, ou se há algum erro de execução).
-
Configuração do Desvio: O valor do
deviationtalvez esteja muito baixo para permitir que a ordem seja executada dentro dos limites de variação de preço aceitáveis. -
Configurações da Conta: Certifique-se de que a conta do Metatrader está conectada e que possui permissões adequadas para trading. Além disso, certifique-se de que haja saldo suficiente na conta para executar as ordens conforme o tamanho de lote especificado.
-
Teste do Código: Execute o código em modo de depuração (debug mode) ou coloque mensagens adicionais de depuração (
Print) para acompanhar o fluxo lógico e certificar-se de que as condições estão sendo atendidas como esperado. Isso pode incluir imprimir valores delow_level,high_level, eclose_priceantes de cada checagem lógica.
Aqui está uma abordagem para adicionar algumas mensagens de depuração:
void OnTick() { // Detectar o intervalo de negociação (Acumulação) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); Print("Low Level: ", low_level, " High Level: ", high_level); if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; Print("Entrou em fase de acumulação"); } else if ((high_level - low_level) / high_level < 0.02) // Lateral para distribuição { in_distribution_phase = true; Print("Entrou em fase de distribuição"); } } // Detecção de Spring (para compra) double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual Print("Close Price: ", close_price); if (in_accumulation_phase && close_price < low_level) { Print("Condicional de Buy atingida"); Buy(); } // Detecção de um "Upthrust" ou quebra (para venda) if (in_distribution_phase && close_price > high_level) { Print("Condicional de Sell atingida"); Sell(); } }Use as mensagens acima apenas para fins de teste durante o desenvolvimento e reveja os logs com atenção para descobrir mais sobre o comportamento do script.
-
- User
verifique meu codigo e melhore ele para que funcione:
#include <Trade\Trade.mqh> // Include trade functions library
// Global variables double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
// Main function that runs on every tick void OnTick() { // Detect the trading range (Accumulation) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Lateral range { in_accumulation_phase = true; } // Alternative rules to detect distribution if ((high_level - low_level) / high_level < 0.02) // Lateral range for distribution, or some other logic { in_distribution_phase = true; }}
// Detection of Spring (for buy) double close_price = iClose(NULL, PERIOD_H1, 0); // Closing price of the current candle
if (in_accumulation_phase && close_price < low_level) { // Buy signal Buy(); }
// Detection of an "Upthrust" or breakdown (for sell) if (in_distribution_phase && close_price > high_level) { // Sell signal Sell(); } }
// Function to place a buy order void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss below the Spring double tp = high_level + 100 * _Point; // Take Profit after resistance break
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_BUY; // Type of order: Buy request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Buy price (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 123456; // Magic number to identify order request.comment = "Wyckoff Spring Buy"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending buy order: ", GetLastError()); } else { if(result.retcode == 10009) // Check for successful execution code Print("Buy order sent successfully!"); else Print("Buy order failed: ", result.retcode); // Output specific error code } }
// Function to place a sell order void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss above the Upthrust double tp = low_level - 100 * _Point; // Take Profit below the support
// Configure the structure for sending the order MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Clear the structure ZeroMemory(result); // Clear the result structure
request.action = TRADE_ACTION_DEAL; // Action to send order request.symbol = Symbol(); // Symbol of the asset request.volume = lot_size; // Lot size request.type = ORDER_TYPE_SELL; // Type of order: Sell request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Sell price (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Maximum price deviation request.magic = 654321; // Magic number for sell order request.comment = "Wyckoff Upthrust Sell"; // Order comment
// Send the order if(!OrderSend(request, result)) { Print("Error sending sell order: ", GetLastError()); } else { if(result.retcode == 10009) // Check for successful execution code Print("Sell order sent successfully!"); else Print("Sell order failed: ", result.retcode); // Output specific error code } }
- Assistant
Para melhorar o funcionamento do seu código e garantir que ele execute ordens de compra e venda corretamente, algumas considerações adicionais podem ajudar a resolver problemas de desempenho e lógica. O código atual parece correto na sua estrutura básica, mas existem algumas áreas em que melhorias podem ser feitas, especialmente em termos de confiabilidade e debug.
Melhorias Sugeridas e Ajustes:
-
Verificação da Sessão de Negociação: Certifique-se de que as ações só ocorrem quando o mercado está aberto. Você pode querer adicionar verificações de tempo para evitar operações fora do horário de mercado, o que pode causar falhas silenciosas.
-
Verificações de Lote e Conta: Confirme se o lote e outras configurações são válidos para a conta que você está utilizando. O tamanho do lote deve ser compatível com a sua conta e com as margens exigidas pelo corretor.
-
Errore de Identificação Retcode: Assegure-se de usar o retcode apropriado para verificar a execução bem-sucedida de ordens. Use
ORDER_REQUEST_SUCCEEDEDem vez do número literal10009, uma vez que nomes simbólicos são mais claros e propensos a se adaptar a mudanças futuras na API. -
Uso Correto de Funções e Objetos: Embora você já tenha bons padrões, considere checar sempre a integridade das funções externas como
iLowest()eiHighest(). -
Melhor Controle do Estado de Fase: Pode ser benéfico adicionar uma lógica que redefine
in_accumulation_phaseein_distribution_phasepara garantir que essas fases podem se desativar corretamente.
Alterando o trecho que detecta o sucesso do envio de ordens:
if(result.retcode == TRADE_RETCODE_DONE) // Use symbolic constant for successCódigo Melhorado
#include <Trade\Trade.mqh> // Biblioteca de funções de trade // Variáveis globais double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; // Função principal executada a cada tick void OnTick() { // Detecção do intervalo de negociação (Acumulação) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); if ((high_level - low_level) / low_level < 0.02) // Faixa lateral { in_accumulation_phase = true; in_distribution_phase = false; // Resetar distribuição se for acumulando Print("Iniciando fase de acumulação"); } // Regras alternativas para detectar distribuição if ((high_level - low_level) / high_level < 0.02) { in_distribution_phase = true; in_accumulation_phase = false; // Resetar acumulação se for distribuindo Print("Iniciando fase de distribuição"); } } // Detecção de um Spring (para compra) double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual if (in_accumulation_phase && close_price < low_level) { Print("Spring detectado. Enviando ordem de compra."); Buy(); } // Detecção de um "Upthrust" ou quebra (para venda) if (in_distribution_phase && close_price > high_level) { Print("Upthrust detectado. Enviando ordem de venda."); Sell(); } } // Função para enviar uma ordem de compra void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss abaixo do Spring double tp = high_level + 100 * _Point; // Take Profit após rompimento da resistência // Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Limpar a estrutura ZeroMemory(result); // Limpar a estrutura do resultado request.action = TRADE_ACTION_DEAL; // Ação de enviar ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_BUY; // Tipo de ordem: Compra request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Preço de aquisição (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio máximo de preço request.magic = 123456; // Número mágico para identificar ordem request.comment = "Wyckoff Spring Buy"; // Comentário da ordem // Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de compra: ", GetLastError()); } else { if(result.retcode == TRADE_RETCODE_DONE) // Constante simbólica para sucesso Print("Ordem de compra enviada com sucesso!"); else Print("Falha ao enviar ordem de compra: ", result.retcode); // Código de erro específico } } // Função para enviar uma ordem de venda void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss acima da resistência double tp = low_level - 100 * _Point; // Take Profit abaixo do suporte // Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Limpar a estrutura ZeroMemory(result); // Limpar a estrutura do resultado request.action = TRADE_ACTION_DEAL; // Ação de enviar ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_SELL; // Tipo de ordem: Venda request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Preço de venda (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio máximo de preço request.magic = 654321; // Número mágico para identificar ordem request.comment = "Wyckoff Upthrust Sell"; // Comentário da ordem // Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de venda: ", GetLastError()); } else { if(result.retcode == TRADE_RETCODE_DONE) // Constante simbólica para sucesso Print("Ordem de venda enviada com sucesso!"); else Print("Falha ao enviar ordem de venda: ", result.retcode); // Código de erro específico } }Revisão das Melhorias:
- Mensagens de Depuração: Adicionados prints para ajudar a acompanhar quando as fases são iniciadas e quando as condições de ordens são atingidas.
- Verificação de Retorno de Ordem: Uso de constantes simbólicas para verificar o sucesso da execução da ordem.
- Controle de Estado: Garantiu que ao entrar em uma fase, a outra fase é desativada.
Teste este script em um ambiente de conta demo para garantir que está em funcionamento correto e revise los logs para entender qualquer comportamento inesperado ou mensagens de erro.
-
- User
#include <Trade\Trade.mqh> // Biblioteca de funções de trade
// Variáveis globais double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false;
// Função principal executada a cada tick void OnTick() { // Detecção do intervalo de negociação (Acumulação) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0));
if ((high_level - low_level) / low_level < 0.02) // Faixa lateral { in_accumulation_phase = true; in_distribution_phase = false; // Resetar distribuição se for acumulando Print("Iniciando fase de acumulação"); } // Regras alternativas para detectar distribuição if ((high_level - low_level) / high_level < 0.02) { in_distribution_phase = true; in_accumulation_phase = false; // Resetar acumulação se for distribuindo Print("Iniciando fase de distribuição"); }}
// Detecção de um Spring (para compra) double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual
if (in_accumulation_phase && close_price < low_level) { Print("Spring detectado. Enviando ordem de compra."); Buy(); }
// Detecção de um "Upthrust" ou quebra (para venda) if (in_distribution_phase && close_price > high_level) { Print("Upthrust detectado. Enviando ordem de venda."); Sell(); } }
// Função para enviar uma ordem de compra void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss abaixo do Spring double tp = high_level + 100 * _Point; // Take Profit após rompimento da resistência
// Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Limpar a estrutura ZeroMemory(result); // Limpar a estrutura do resultado
request.action = TRADE_ACTION_DEAL; // Ação de enviar ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_BUY; // Tipo de ordem: Compra request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Preço de aquisição (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio máximo de preço request.magic = 123456; // Número mágico para identificar ordem request.comment = "Wyckoff Spring Buy"; // Comentário da ordem
// Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de compra: ", GetLastError()); } else { if(result.retcode == TRADE_RETCODE_DONE) // Constante simbólica para sucesso Print("Ordem de compra enviada com sucesso!"); else Print("Falha ao enviar ordem de compra: ", result.retcode); // Código de erro específico } }
// Função para enviar uma ordem de venda void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss acima da resistência double tp = low_level - 100 * _Point; // Take Profit abaixo do suporte
// Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Limpar a estrutura ZeroMemory(result); // Limpar a estrutura do resultado
request.action = TRADE_ACTION_DEAL; // Ação de enviar ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_SELL; // Tipo de ordem: Venda request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Preço de venda (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio máximo de preço request.magic = 654321; // Número mágico para identificar ordem request.comment = "Wyckoff Upthrust Sell"; // Comentário da ordem
// Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de venda: ", GetLastError()); } else { if(result.retcode == TRADE_RETCODE_DONE) // Constante simbólica para sucesso Print("Ordem de venda enviada com sucesso!"); else Print("Falha ao enviar ordem de venda: ", result.retcode); // Código de erro específico } }
nada de ordem nem mensagem
- Assistant
Se você não está recebendo mensagens nem está observando ordens sendo enviadas, há algumas áreas a serem verificadas para garantir que o script funcione conforme esperado. Vou sugerir algumas melhorias e verificações para ajudar a identificar e resolver o problema.
Sugestões de Verificação e Melhorias:
-
Impressão de Log: Certifique-se de que a função
Printestá ativada no seu ambiente do MetaTrader para verificar mensagens no diário (journal) ou no registro de log. Isso é essencial para depurar e entender em que parte do fluxo de execução o código está. -
Condições de Acumulação e Distribuição:
- Verifique se as condições de acumulação e distribuição estão corretas. É possível que os níveis de baixa e alta (
low_levelehigh_level) não sejam adequados para detectar as fases esperadas. - Experimente ajustar o percentual de detecção de fase (por exemplo, trocando para
< 0.03ou outro valor razoável) para verificar se as condições estão sendo realmente atingidas.
- Verifique se as condições de acumulação e distribuição estão corretas. É possível que os níveis de baixa e alta (
-
Tempo Gráfico e Disponibilidade de Dados:
- Confirme se o gráfico de 1 hora (H1) está ativo e que há dados suficientes nesse tempo gráfico.
- Às vezes, dados históricos podem estar faltando, o que pode causar falhas silenciosas ao calcular mínimos e máximos.
-
Verifique Permissões e Conexão da Conta:
- Assegure-se de que a conta está conectada e que possui permissões para realizar transações.
- Verifique se a configuração do corretor permite negociação automatizada.
-
Testes com Debug Prints:
- Adicione declarações
Printadicionais em locais críticos do código, para verificar se os cálculos e condições estão sendo produzidos conforme esperado.
- Adicione declarações
Aqui está uma versão com mensagens de debug ampliadas:
#include <Trade\Trade.mqh> // Biblioteca de funções de trade // Variáveis globais double low_level, high_level; bool in_accumulation_phase = false; bool in_distribution_phase = false; // Função principal executada a cada tick void OnTick() { // Detecção do intervalo de negociação (Acumulação) if (!in_accumulation_phase && !in_distribution_phase) { low_level = iLow(NULL, PERIOD_H1, iLowest(NULL, PERIOD_H1, MODE_LOW, 20, 0)); high_level = iHigh(NULL, PERIOD_H1, iHighest(NULL, PERIOD_H1, MODE_HIGH, 20, 0)); Print("Low Level: ", low_level); Print("High Level: ", high_level); if ((high_level - low_level) / low_level < 0.02) // Faixa lateral { in_accumulation_phase = true; in_distribution_phase = false; // Resetar distribuição se for acumulando Print("Iniciando fase de acumulação"); } else if ((high_level - low_level) / high_level < 0.02) // Lateral para distribuição { in_distribution_phase = true; in_accumulation_phase = false; // Resetar acumulação se for distribuindo Print("Iniciando fase de distribuição"); } } // Detecção de um Spring (para compra) double close_price = iClose(NULL, PERIOD_H1, 0); // Preço de fechamento da vela atual Print("Close Price: ", close_price); if (in_accumulation_phase && close_price < low_level) { Print("Spring detectado. Enviando ordem de compra."); Buy(); } // Detecção de um "Upthrust" ou quebra (para venda) if (in_distribution_phase && close_price > high_level) { Print("Upthrust detectado. Enviando ordem de venda."); Sell(); } } // Função para enviar uma ordem de compra void Buy() { double lot_size = 0.1; double sl = low_level - 50 * _Point; // Stop Loss abaixo do Spring double tp = high_level + 100 * _Point; // Take Profit após rompimento da resistência // Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Limpar a estrutura ZeroMemory(result); // Limpar a estrutura do resultado request.action = TRADE_ACTION_DEAL; // Ação de enviar ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_BUY; // Tipo de ordem: Compra request.price = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Preço de aquisição (Ask) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio máximo de preço request.magic = 123456; // Número mágico para identificar ordem request.comment = "Wyckoff Spring Buy"; // Comentário da ordem // Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de compra: ", GetLastError()); } else { if(result.retcode == TRADE_RETCODE_DONE) // Constante simbólica para sucesso Print("Ordem de compra enviada com sucesso!"); else Print("Falha ao enviar ordem de compra: ", result.retcode); // Código de erro específico } } // Função para enviar uma ordem de venda void Sell() { double lot_size = 0.1; double sl = high_level + 50 * _Point; // Stop Loss acima da resistência double tp = low_level - 100 * _Point; // Take Profit abaixo do suporte // Configurar a estrutura para envio da ordem MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); // Limpar a estrutura ZeroMemory(result); // Limpar a estrutura do resultado request.action = TRADE_ACTION_DEAL; // Ação de enviar ordem request.symbol = Symbol(); // Símbolo do ativo request.volume = lot_size; // Tamanho do lote request.type = ORDER_TYPE_SELL; // Tipo de ordem: Venda request.price = SymbolInfoDouble(Symbol(), SYMBOL_BID); // Preço de venda (Bid) request.sl = sl; // Stop Loss request.tp = tp; // Take Profit request.deviation = 2; // Desvio máximo de preço request.magic = 654321; // Número mágico para identificar ordem request.comment = "Wyckoff Upthrust Sell"; // Comentário da ordem // Enviar a ordem if(!OrderSend(request, result)) { Print("Erro ao enviar ordem de venda: ", GetLastError()); } else { if(result.retcode == TRADE_RETCODE_DONE) // Constante simbólica para sucesso Print("Ordem de venda enviada com sucesso!"); else Print("Falha ao enviar ordem de venda: ", result.retcode); // Código de erro específico } }Análise de Saída:
- Diagnóstico Inicial: As mensagens no log devem dar uma ideia se as condições de acumulação, distribuição, e envio de ordem estão sendo atingidas.
- Avaliação de Resposta: Veja quais mensagens são exibidas e se alguma não corresponde ao que você espera. Isso pode significar onde a lógica precisa de ajustes.
Esperamos que essas melhorias ajudem a resolver o problema. Continue monitorando os logs para obter mais informações se algo não estiver funcionando conforme o esperado.
-