//±-----------------------------------------------------------------+ // ZZEA.mq4 //…
- User
//±-----------------------------------------------------------------+ //| ZZ_EA.mq4 | //| Copyright © 2023, Gabriele Bassi | //| Added LotSize & Spread | //| Added MagicNumber & Custom OrdersTotal | //±-----------------------------------------------------------------+ #property copyright "Gabriele Bassi" string version = "ZZ_EA v.0.1";
// External input parameters for the EA input double LotSize = 0.1; // Fixed lot size for each trade input double TakeProfitPips = 400; // Take profit in pips input double StopLossPips = 150; // Stop loss in pips input double TrailingStopPips = 10; // Trailing stop in pips input int MagicNumber = 12345; // Magic number to identify trades by this EA input double MaximumSpread = 3; // Maximum allowed spread in pips
// External input parameters for the indicator input int CCI_Period = 12; input int Momentum_Period = 21; input int RSI_Period = 14; input double SAR_Step = 0.01; input double SAR_Maximum = 0.2;
// OnInit is called when the expert is loaded onto a chart int OnInit() { // Initialization code here return INIT_SUCCEEDED; }
int deinit() { // Deinitialization code here return(0); }
// Custom function to count only our own trades with the MagicNumber and on the current symbol int CountOrdersByMagicAndSymbol() { int count = 0; for (int i = 0; i < OrdersTotal(); i++) { if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue; if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) { count++; } } return count; }
// OnTick is called on every new tick void OnTick() { // Get the current spread in pips double spread = (Ask - Bid) / Point;
// Check the spread against the maximum allowable spread before trading if (spread > MaximumSpread) { // Spread is too high, do not place the trade // Print("Spread is too high: ", spread); // Uncomment this line to print to the log return; // Exit the OnTick function } // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // If there are no current orders with our MagicNumber, check for a buy or sell signal if (CountOrdersByMagicAndSymbol() == 0) { if (arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order double sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); double tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy order based on ZZZZZ", MagicNumber, 0, clrGreen); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } else if (arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order double sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); double tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell order based on ZZZZZ", MagicNumber, 0, clrRed); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); }}
// TrailingStopFunc adjusts the stop loss to enable a trailing stop void TrailingStopFunc() { for (int i = OrdersTotal() - 1; i >= 0; --i) { if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
// Verify that the selected order is for the current symbol with our MagicNumber if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { double newStopLoss; if (OrderType() == OP_BUY) { // Current price is far enough from the opening price to move stop loss if (Bid - OrderOpenPrice() > TrailingStopPips * Point) { newStopLoss = Bid - TrailingStopPips * Point; // Update the stop loss if it is less than the current stop loss if (newStopLoss > OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrGreen); } } } else if (OrderType() == OP_SELL) { // Current price is far enough from the opening price to move stop loss if (OrderOpenPrice() - Ask > TrailingStopPips * Point) { newStopLoss = Ask + TrailingStopPips * Point; // Update the stop loss if it is greater than the current stop loss if (newStopLoss < OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrRed); } } } } }}
//±-----------------------------------------------------------------+
ho questo errore: 'ticket' - variable already defined zzz_ea4.mq4 82 17
- Assistant
L'errore
'ticket' - variable already definedindica che all'interno dello stesso blocco di codice o nella stessa funzione, hai dichiarato la variabileticketpiù di una volta, il che non è permesso nel linguaggio di programmazione MQL4.Per correggere l'errore, devi dichiarare la variabile
ticketuna sola volta all'inizio della funzione in cui viene utilizzata e poi assegnarle dei valori senza dichiararla nuovamente. Puoi dichiarareticketall'inizio della funzioneOnTick()e poi utilizzarla per entrambe le chiamate aOrderSendsenza rideclararla.Ecco il codice corretto:
void OnTick() { // ... (codice precedente) ... int ticket; // Dichiarazione unica della variabile all'inizio della funzione // ... (eventuale codice intermedio) ... if (CountOrdersByMagicAndSymbol() == 0) { if (arrowUp != EMPTY_VALUE) { // ... (impostazioni ordine Buy) ... ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy order based on ZZZZZ", MagicNumber, 0, clrGreen); // ... (controllo errore) ... } else if (arrowDown != EMPTY_VALUE) { // ... (impostazioni ordine Sell) ... ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell order based on ZZZZZ", MagicNumber, 0, clrRed); // ... (controllo errore) ... } } else { // ... (trailing stop e altro codice) ... } } // ... (il resto del codice) ...Dopo aver fatto questa correzione, non dovresti più ricevere quel messaggio di errore di compilazione specifico. Assicurati di controllare per altri eventuali errori e testare accuratamente il tuo EA prima di utilizzarlo in un ambiente di trading live.
- User
riscrivi l'intero e completo blocco void OnTick() {
- Assistant
Ecco il codice corretto per l'intero blocco
void OnTick()della tua EA:void OnTick() { // Get the current spread in pips double spread = (Ask - Bid) / Point; // Check the spread against the maximum allowable spread before trading if (spread > MaximumSpread) { // Spread is too high, do not place the trade return; // Exit the OnTick function } // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // Declare `ticket` variable at the beginning of the function int ticket; // If there are no current orders with our MagicNumber, check for a buy or sell signal if (CountOrdersByMagicAndSymbol() == 0) { if (arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order double sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); double tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy order based on ZZZZZ", MagicNumber, 0, clrGreen); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } else if (arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order double sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); double tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell order based on ZZZZZ", MagicNumber, 0, clrRed); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); } } // ... (rest of the EA code) ...Con queste modifiche, il problema di dichiarazione multipla di
ticketdovrebbe essere risolto. Ricorda che ho rimosso la parte di codice che commenta l'eccessiva ampiezza dello spread per ridurre la lunghezza dell'esempio e ho mantenuto solo l'essenziale. Se hai bisogno di quel log di errore, puoi semplicemente decommentare quella riga nel tuo codice. - User
'tp' - variable already defined zzz_ea4.mq4 83 20
- Assistant
L'errore
'tp' - variable already definedindica che, come nel caso diticket, stai definendo la variabiletp(che immagino rappresenti il "take profit") più di una volta all'interno dello stesso blocco di codice. Per risolvere questo errore, dovresti dichiarare la variabiletpuna volta all'inizio della funzione e poi assegnarle valori nelle varie parti del codice senza ridefinirla.Ecco come dovrebbe apparire il blocco
OnTickcorretto, con una singola dichiarazione sia perticketche pertp:void OnTick() { // Get the current spread in pips double spread = (Ask - Bid) / Point; // Check the spread against the maximum allowable spread before trading if (spread > MaximumSpread) { // Spread is too high, do not place the trade return; // Exit the OnTick function } // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // Declare `ticket` and `tp` variables at the beginning of the function int ticket; double tp; // If there are no current orders with our MagicNumber, check for a buy or sell signal if (CountOrdersByMagicAndSymbol() == 0) { if (arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order double sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy order based on ZZZZZ", MagicNumber, 0, clrGreen); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } else if (arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order double sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell order based on ZZZZZ", MagicNumber, 0, clrRed); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); } } // ... (rest of the EA code) ...Assicurati che la variabile
sl(stop loss) non sia soggetta allo stesso problema. Se viene utilizzata più volte nel metodoOnTicke definita in più punti, dovrebbe anche essere dichiarata all'inizio del metodo una sola volta. - User
anche sl ha lo stesso problema
- Assistant
Capisco, correggeremo anche la variabile
sl(stop loss) nello stesso modo. Dichiareremoticket,tp(take profit) esl(stop loss) una sola volta all'inizio del metodoOnTick, eliminando così i problemi di variabili ridefinite:void OnTick() { // Get the current spread in pips double spread = (Ask - Bid) / Point; // Check the spread against the maximum allowable spread before trading if (spread > MaximumSpread) { // Spread is too high, do not place the trade return; // Exit the OnTick function } // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // Declare `ticket`, `tp`, and `sl` variables at the beginning of the function int ticket; double tp, sl; // If there are no current orders with our MagicNumber, check for a buy or sell signal if (CountOrdersByMagicAndSymbol() == 0) { if (arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy order based on ZZZZZ", MagicNumber, 0, clrGreen); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } else if (arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell order based on ZZZZZ", MagicNumber, 0, clrRed); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); } } // ... (rest of the EA code) ...Con questa correzione, tutti e tre i problemi di variabili ridefinite (
ticket,tp,sl) sono risolti e il metodoOnTickdovrebbe compilarsi correttamente senza generare errori dovuti a dichiarazioni multiple delle stesse variabili.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.