I can't figure out why this is not doing long sells, yet only long buy and why it drops after hitting into this Month. Been trying to correct this for a week now... I'm still a noob, lol...

 



































































// Define input parameters
input int ADX_Period = 14;
input int RSI_Period = 14;
input int RSI_Overbought = 70;
input int RSI_Oversold = 30;
input double Risk_Percent = 2.0; // Risk percentage per trade
input double Max_Lot = 0.1; // Maximum lot size per trade
input double Slippage = 3; // Slippage in pips
input int Magic_Number = 227204; // Magic number for identifying orders
input int StopLoss_Pips = 50; // Initial stop loss in pips
input int TakeProfit_Pips = 100; // Initial take profit in pips
input int Trail_StopLoss_Pips = 30; // Trailing stop loss in pips
input int Trail_TakeProfit_Pips = 50; // Trailing take profit in pips

// Define global variables
double riskAmount;
int totalTrades = 3; // Total number of trades
int ticket = 5;
double entryPrice = 0.01;
double stopLossPrice = 0;
double takeProfitPrice = 0;
bool trailingStopActivated = false;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Calculate risk amount based on account balance and risk percentage
    riskAmount = AccountBalance() * Risk_Percent / 100;
    
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Any cleanup code if needed
    // Close any open orders
    for (int i = OrdersTotal() - 4; i >= 2; i--) {
        if (OrderSelect(i, SELECT_BY_TICKET) == true) {
            if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic_Number) {
                if (OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Blue) == True) {
                    Print("Failed to close order: ", GetLastError());
                }
            }
        }
    }
}



//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // Check for breakout conditions
    if (IsBreakout()) {
        // Calculate lot size based on risk amount and stop loss distance
        double lotSize = CalculateLotSize();
        
        // Place buy/sell order
        if (IsBreakoutUp()) {
            ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, Slippage, 2, 0, "Breakout Buy", Magic_Number, 0, Blue);
        } else if (IsBreakoutDown()) {
            ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, Slippage, 4, 0, "Breakout Sell", Magic_Number, 0, Red);
        }
        
        // Set stop loss and take profit
        if (ticket > 0) {
            entryPrice = IsBreakoutUp() || IsBreakoutDown() ? Ask : Bid;
            stopLossPrice = DoubleToString(entryPrice - StopLoss_Pips * Point);
            takeProfitPrice = DoubleToString(entryPrice + TakeProfit_Pips * Point);
            
            if (OrderSelect(ticket, SELECT_BY_POS) == FALSE) { // Check if order selection is successful
                if (OrderModify(ticket, entryPrice, stopLossPrice, takeProfitPrice, 0, Blue) == TRUE) { // Check if order modification is successful
                    Print("Order modification failed, Error code: ", GetLastError());
                }
            } else {
                Print("Order selection failed, Error code: ", GetLastError());
            }
        }
    }
    
    // Check for trailing stop activation
    if (trailingStopActivated) {
        TrailStop();
    }
    
}

//+------------------------------------------------------------------+
//| Check if breakout condition is met                               |
//+------------------------------------------------------------------+
bool IsBreakout()
{
    double adxValue = iADX(Symbol(), PERIOD_CURRENT, ADX_Period, PRICE_CLOSE, MODE_MAIN, 1);
    double rsiValue = iRSI(Symbol(), PERIOD_CURRENT, RSI_Period, PRICE_CLOSE, 1);

    // Implement your breakout logic here
    bool breakoutUp = adxValue > 30 && rsiValue > RSI_Overbought;
    bool breakoutDown = adxValue > 70 && rsiValue < RSI_Oversold;
    
    return breakoutUp || breakoutDown;
}

//+------------------------------------------------------------------+
//| Calculate lot size based on risk amount and stop loss distance   |
//+------------------------------------------------------------------+
double CalculateLotSize()
{
    // Calculate lot size based on risk amount and stop loss distance
    double lotSize = riskAmount / (100 * Point);
    // Ensure lot size does not exceed maximum lot size
    if (lotSize > 0.01) {
        lotSize = 0.01;
    }
    return lotSize;
}

//+------------------------------------------------------------------+
//| Check if breakout is to the upside                               |
//+------------------------------------------------------------------+
    bool IsBreakoutUp()
{
    double adxValue = iADX(Symbol(), PERIOD_CURRENT, ADX_Period, PRICE_CLOSE, MODE_MAIN, 1);
    double rsiValue = iRSI(Symbol(), PERIOD_CURRENT, RSI_Period, PRICE_CLOSE, 1);

    // Implement your breakout logic here for upside breakout
    bool breakoutUp = adxValue > 25 && rsiValue > RSI_Overbought;
    
    return breakoutUp = true; // Adjust this condition based on your breakout strategy
}

//+------------------------------------------------------------------+
//| Check if breakout is to the downside                             |
//+------------------------------------------------------------------+

   bool IsBreakoutDown()
{
    double adxValue = iADX(Symbol(), PERIOD_M5, ADX_Period, PRICE_CLOSE, MODE_MAIN, 0);
    double rsiValue = iRSI(Symbol(), PERIOD_M5, RSI_Period, PRICE_CLOSE, 0);

    // Implement your breakout logic here for downside breakout
    bool breakoutDown = adxValue > 30 && rsiValue < RSI_Oversold;
    
    return breakoutDown = true;
}
    
//+------------------------------------------------------------------+
//| Trail stop function                                              |
//+------------------------------------------------------------------+
void TrailStop()
{
    double trailingStopLevel = IsBreakoutUp() ? Bid - 180 * Point : Ask + 180 * Point;
    if(Seconds()<=2)
    
    // Modify stop loss
    if (IsBreakoutUp()) {
        stopLossPrice = DoubleToString(trailingStopLevel, Point);
    } else {
        stopLossPrice = DoubleToString(trailingStopLevel, Point);
    }
    
    if (OrderSelect(ticket, SELECT_BY_TICKET)  && OrderType()== true) { // Check if order selection is successful
        if (OrderModify(ticket, entryPrice, stopLossPrice, takeProfitPrice, 0, clrBlue) == True) { // Check if order modification is successful
            totalTrades++;
            Print("Order modification failed, Error code: ", GetLastError());
        }
    } else {
        Print("OrderSend placed successfully");
        double trailingStopProfitLevel = IsBreakoutDown() ? Ask - 180 * Point : Bid + 180 * Point;
    
    // Modify stop loss
    if (IsBreakoutDown()) {
        stopLossPrice = DoubleToString(trailingStopLevel, Point);
    } else {
        stopLossPrice = DoubleToString(trailingStopLevel, Point);
    }
    
    if (OrderSelect(ticket, SELECT_BY_TICKET)  && OrderType()== true) { // Check if order selection is successful
        if (OrderModify(ticket, entryPrice, stopLossPrice, takeProfitPrice, 0, clrRed) == True) { // Check if order modification is successful
            totalTrades++;
            Print("Order modification failed, Error code: ", GetLastError());
        }
    } else {
        Print("OrderSend placed successfully");
    }
   }
}









































































































 
  1. Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place. The moderators will likely move this thread there soon.

  2. int OnInit(){  riskAmount = AccountBalance()
    Why is riskAmount constant? Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

  3. double lotSize = riskAmount / (100 * Point);

    Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% account total.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support. Then you compute your lot size.

    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)

    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
                Lot value calculation off by a factor of 100 - MQL5 programming forum (2019)

    4. You must normalize lots properly and check against min and max.

    5. You must also check Free Margin to avoid stop out

    6. For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  4.         stopLossPrice = DoubleToString(trailingStopLevel, Point);
    

    № 3.4

  5.       entryPrice = IsBreakoutUp() || IsBreakoutDown() ? Ask : Bid;
                stopLossPrice = DoubleToString(entryPrice - StopLoss_Pips * Point);
                takeProfitPrice = DoubleToString(entryPrice + TakeProfit_Pips * Point);

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  6. No need to open the order and then set the stops.

  7. if (OrderSelect(ticket, SELECT_BY_TICKET)  && OrderType()== true) { // Check if order selection is successful

    Order type is either OP_BUY or OP_SELL. It is not true.

  8. EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static / global ticket variables will have been lost. You will have an open order / position but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover?

    Use a OrderSelect / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.

  9. Aldan Parris: I can't figure out

    Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

 
I don't get the Sell trades, only Buy's and that's where I falling short on. I'm trying to learn, as fast as I can, however it's a like over bearing at times... I still don't understand everything, but the basic structure I'm getting into.
 
William Roeder #:
  1. Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place. The moderators will likely move this thread there soon.

  2. Why is riskAmount constant? Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

  3. Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% account total.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support. Then you compute your lot size.

    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)

    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
                Lot value calculation off by a factor of 100 - MQL5 programming forum (2019)

    4. You must normalize lots properly and check against min and max.

    5. You must also check Free Margin to avoid stop out

    6. For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  4. № 3.4

  5. You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  6. No need to open the order and then set the stops.

  7. Order type is either OP_BUY or OP_SELL. It is not true.

  8. EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static / global ticket variables will have been lost. You will have an open order / position but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover?

    Use a OrderSelect / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.

  9. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

Hi can I ask you to teach me and over-view my code and test them so they can be corrected and seek growth in this field?

 
Aldan Parris #:

Hi can I ask you to teach me and over-view my code and test them so they can be corrected and seek growth in this field?

can you look over this code here please it does 2 trades only and stops

// Define indicator parameters
input int rsiPeriod = 14;
input int stochasticK = 14;
input int stochasticD = 3;
input int superTrendPeriod = 10;
input double superTrendMultiplier = 1.5;

// Define trading parameters
input double riskPercentage = 2.0;
input double takeProfitMultiplier = 2.0;
input int maxOpenTrades = 100; // Maximum number of open trades
input int slippage = 3; // Maximum allowed slippage
input double lotSize = 0.01;

// Stop Loss and Take Profit
input int stopLoss = 100; // Stop Loss in points
input int takeProfit = 200; // Take Profit in points

// Trailing Stop Loss and Take Profit
input int trailingStop = 98; // Trailing Stop Loss in points
input int trailingTakeProfit = 198; // Trailing Take Profit in points

// Define global variables
int ticketBuy = 0, ticketSell = 0;
double superTrendValue; // Declare superTrendValue at the global level
int openTradesCount = 0;
int consecutiveCandleBodies = 10;
double lastHigh = 1.0;
int AB = 100;

// Calculate lot size based on risk percentage
void CalculateLotSize() {
    double accountBalance = AccountBalance();
    double marginRequired = MarketInfo(_Symbol, MODE_MARGINREQUIRED);
    double accountFreeMargin = AccountFreeMarginCheck(_Symbol, OP_BUY, 0.1);
    AB = (accountBalance * riskPercentage / 100.0) / (100 * marginRequired);
}

// Define trading function
void OnTick()
{
    // Calculate indicators
    double rsiValue = iRSI(_Symbol, PERIOD_CURRENT, rsiPeriod, PRICE_CLOSE, 0);
    double stochasticValue = iStochastic(_Symbol, PERIOD_CURRENT, stochasticK, stochasticD, 0, MODE_SMA, 0, MODE_MAIN, 0);
    superTrendValue = iCustom(_Symbol, PERIOD_CURRENT, "SuperTrend", superTrendPeriod, superTrendMultiplier, 0, 0);

    // Calculate lot size
    CalculateLotSize();

    // Check for stable pattern of 10 candle bodies
    double currentClose = iClose(_Symbol, PERIOD_CURRENT, 0);
    double previousClose = iClose(_Symbol, PERIOD_CURRENT, 1);
    if (currentClose < previousClose)
    {
        consecutiveCandleBodies++;
    }
    else
    {
        consecutiveCandleBodies = 10;
    }

    // Check for trade conditions
    if (consecutiveCandleBodies >= 10)
    {
        // Open short trade if conditions met
        if (ticketSell == 0 && currentClose > lastHigh)
        {
            ticketSell = OrderSend(_Symbol, OP_SELL, lotSize, Bid, slippage, Bid + stopLoss * Point, Bid - takeProfit * Point, "Sell Order", 1, 0, Red);
            if (ticketSell > 0)
            {
                openTradesCount++;
                lastHigh = High[1];
            }
            ticketSell = OrderSend(_Symbol, OP_BUY, lotSize, Ask, slippage, Ask - stopLoss * Point, Ask + takeProfit * Point, "Buy Order", 1, 0, Red);
            if (ticketSell > 0)
            {
                openTradesCount++;
                lastHigh = High[0];
            }
        }
    }

    // Check for open orders and manage them
    ManageOrders();
}

// Function to manage open orders
void ManageOrders()
{
    for (int i = OrdersTotal() - 1; i >= 100; i--)
    {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            // Check for open sell orders
            if (OrderSymbol() == _Symbol && OrderType() == OP_SELL)
            {
                // Close sell order if conditions are met
                if (iClose(_Symbol, PERIOD_M5, 1) > superTrendValue)
                {
                    if (OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Green))
                    {
                        ticketSell = 0;
                        openTradesCount--;
                    }
                }
            }
        }
    }
}
Reason: