Forum Replies Created

Check out all your contributions and responses across the community.

Viewing 15 posts - 31 through 45 (of 136 total)
  • Author
    Posts
  • Yes sir, alertcondition() is the standard way to create alert conditions in a custom TradingView indicator.

    It does not send alerts by itself. Instead, it tells TradingView which conditions should be available when you create an alert.

    For example, suppose your indicator generates Buy and Sell signals like this:

    //@version=6
    indicator("EMA Crossover", overlay=true)
    
    fastEMA = ta.ema(close, 9)
    slowEMA = ta.ema(close, 21)
    
    buySignal = ta.crossover(fastEMA, slowEMA)
    sellSignal = ta.crossunder(fastEMA, slowEMA)

    Now you can create alert conditions like this:

    alertcondition( buySignal, title="Buy Signal", message="BUY")
    
    alertcondition( sellSignal, title="Sell Signal", message="SELL")

    Now save the script and add it to your chart.

    Then follow these steps:

    -Step 1:
    Click the “Create Alert” button in TradingView.

    -Step 2:
    In the Condition dropdown, select your custom indicator.

    -Step 3:
    You will now see the alert conditions that you created using alertcondition(), such as:

    -Buy Signal

    -Sell Signal

    -Step 4:
    Select the condition you want, configure the notification settings, and click “Create”.

    That’s it.

    Whenever buySignal becomes true, the “Buy Signal” alert can be triggered.

    Whenever sellSignal becomes true, the “Sell Signal” alert can be triggered.

    One important thing to remember is that alertcondition() only defines the alert conditions. It does not send alerts automatically.

    You still need to create the alert from the TradingView interface after adding the indicator to your chart.

    This is the recommended approach when you are building custom indicators and want users to create TradingView alerts based on your Buy and Sell conditions.

    Yes sir, you can definitely use these syntaxes with TradingView, just like you use the Strategy Order syntax.

    The process is exactly the same.

    You simply generate the required JSON syntax, paste it into the TradingView alert message, configure the webhook URL, and whenever the alert is triggered, AlgoDelta will execute that JSON request.

    The main difference is how these orders are handled by the JSON Bridge.

    -Strategy Order

    If you use the Strategy Order syntax, the order is managed and monitored by the JSON Bridge itself.

    Because of this, you can see the order details, status, and other information inside the JSON Bridge section of the AlgoDelta platform.

    -Limit Order

    If you generate a Limit Order syntax, the order is sent directly to your broker as a limit order. It is not monitored by the JSON Bridge after execution.

    -Stop Order

    Similarly, a Stop Order syntax is also sent directly to the broker and is managed by the broker instead of the JSON Bridge.

    -Square Off Position

    This syntax is used to close an existing position directly at the broker. It is not tracked as a Strategy Order inside the JSON Bridge.

    -Cancel Order

    This syntax allows you to cancel a pending order that already exists at the broker. It is also executed directly at the broker level.

    So the key difference is:

    -Strategy Order
    -> Managed and monitored by the JSON Bridge. The order information is visible inside the JSON Bridge section.

    -All other syntaxes (Limit Order, Stop Order, Square Off Position, and Cancel Order)
    -> Executed directly at the broker. They are not monitored or tracked by the JSON Bridge after execution.

    So if your use case requires JSON Bridge features such as strategy order management and monitoring, use the Strategy Order syntax.

    If you simply want to place, modify, cancel, or square off orders directly at the broker, you can use the other JSON syntaxes in exactly the same way through TradingView or any platform capable of sending webhook requests.

    Yes sir, you can definitely detect this in MQL5.

    The recommended way is to check the deals generated after a position is closed. MT5 stores the reason for every completed deal in the trading history, and you can read that information programmatically.

    The most commonly used property is:

    HistoryDealGetInteger(dealTicket, DEAL_REASON);

    This returns the reason why the deal was executed.

    Some commonly used values are:

    -DEAL_REASON_SL
    -> The position was closed because the Stop Loss was hit.

    -DEAL_REASON_TP
    -> The position was closed because the Take Profit was hit.

    -DEAL_REASON_EXPERT
    -> The position was closed by an Expert Advisor (EA).

    -DEAL_REASON_CLIENT
    -> The position was closed manually by the trader.

    -DEAL_REASON_SO
    -> The position was closed due to Stop Out.

    A simple example is shown below:

    ulong dealTicket = HistoryDealGetTicket(HistoryDealsTotal() - 1);
    
    ENUM_DEAL_REASON reason = (ENUM_DEAL_REASON)HistoryDealGetInteger(dealTicket, DEAL_REASON);
    
    if(reason == DEAL_REASON_SL)
    {
       Print("Position closed by Stop Loss");
    }
    else if(reason == DEAL_REASON_TP)
    {
       Print("Position closed by Take Profit");
    }
    else if(reason == DEAL_REASON_CLIENT)
    {
       Print("Position closed manually");
    }
    else if(reason == DEAL_REASON_EXPERT)
    {
       Print("Position closed by Expert Advisor");
    }

    Before reading the deal history, make sure you’ve selected the required history range using:

    HistorySelect(fromTime, TimeCurrent());

    This ensures that the completed deals are available for reading.

    This approach is very useful when you want to:

    -Calculate separate statistics for Stop Loss and Take Profit trades.

    -Trigger different logic after a winning or losing trade.

    -Send different webhook messages depending on how the previous trade was closed.

    -Generate detailed trading reports inside your EA.

    So, instead of guessing why a position was closed, you can directly read the deal reason from the MT5 trading history and handle each case accordingly.

    Yes sir, this is a very common issue while developing TradingView strategies.

    In most cases, this doesn’t happen because of AlgoDelta. It happens because the strategy conditions remain true for multiple candles, so the strategy keeps generating new entry signals.

    To avoid this, your strategy should first check whether there is already an open position before creating a new entry.

    For example, if you’re using a Pine Script strategy, you can use strategy.position_size to determine whether a position is already open.

    -Only generate a Buy entry if there is currently no Buy position.

    -Only generate a Sell entry if there is currently no Sell position.

    -Wait until the existing position is closed before allowing a new entry.

    This ensures that your strategy enters only once for each trading opportunity instead of creating repeated entries on every candle.

    If you’re using AlgoDelta with either the JSON Bridge or the Custom Bridge, this approach is highly recommended because it prevents unnecessary duplicate trade signals from reaching the platform.

    So in simple terms:

    -Check whether a position is already open before generating a new entry.

    -Allow a new Buy or Sell signal only after the previous position has been exited.

    -This keeps your strategy clean, avoids repeated entries, and makes the automation much more reliable.

    Yes sir, this is one of the most common questions when users start automating their TradingView strategies.

    In most cases, duplicate orders are not caused by AlgoDelta. They usually happen because the TradingView alert or the strategy is configured in a way that sends multiple alerts for the same trading signal.

    To avoid this, you can follow these recommendations:

    -Step 1:

    While creating the TradingView alert, set the Trigger option to:

    -One Per Bar Close

    This ensures that TradingView sends only one alert after the candle closes instead of sending multiple alerts while the candle is still forming.

    -Step 2:

    Make sure your strategy or indicator generates only one Buy or Sell signal for a single trading opportunity.

    If your script keeps returning the same signal on every tick, TradingView may continue sending alerts.

    -Step 3:

    If you’re using a Pine Script strategy, use proper entry conditions so that a new order is generated only when a fresh signal appears instead of on every price update.

    -Step 4:

    If you’re using the Custom Bridge, make sure the Upside and Downside executions are configured correctly. If you’re using the JSON Bridge, verify that your generated syntax matches your intended trading logic.

    So, in simple terms, the best practice is:

    -Use “One Per Bar Close” while creating alerts.
    -Generate alerts only when a new trading signal occurs.
    -Avoid writing strategy logic that repeatedly sends the same signal.

    Yes sir, this is a very common question for anyone developing strategies in MT5.

    There is no built-in function in MQL5 that directly tells you a new candle has started.

    The standard and recommended approach is to compare the opening time of the latest candle with the previously stored candle time.

    Whenever the latest candle time changes, it means a new candle has been formed.

    You can do it like this:

    datetime lastBarTime = 0;
    
    bool IsNewCandle()
    {
       datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
    
       if(currentBarTime != lastBarTime)
       {
          lastBarTime = currentBarTime;
          return true;
       }
    
       return false;
    }

    Now, wherever you want your strategy to execute only once per candle, simply use the function like this:

    void OnTick()
    {
       if(IsNewCandle())
       {
          // Your strategy logic here
    
          Print("New candle detected.");
       }
    }

    This is the most commonly used approach in MQL5 because:

    -It prevents your strategy from executing on every incoming tick.

    -It ensures your trading logic runs only once for each newly formed candle.

    -It works on any timeframe since it uses the current chart timeframe (PERIOD_CURRENT).

    So, instead of looking for a dedicated “new candle” function, the recommended practice in MT5 is to compare the latest candle’s opening time with the previously stored time. This is the approach used in most professional MQL5 Expert Advisors.

    Yes, definitely.

    Instead of printing values in the Experts log, you can display them directly on the MT5 chart using the built-in Comment() function.

    The Comment() function creates a live information panel in the top-left corner of the chart and automatically updates every time your EA executes.

    You can display almost any information, such as: Trend Direction, Current Position, Entry Price, Stop Loss, Target Price, Current Profit/Loss, etc…

    A simple example is shown below:

    Comment(
       "Trend          : ", trend, "\n",
       "Entry Price    : ", entryPrice, "\n",
       "Stop Loss      : ", stopLoss, "\n",
       "Target         : ", targetPrice, "\n",
       "Current Profit : ", currentProfit, "\n",
       "ATR            : ", atrValue, "\n",
       "EMA Fast       : ", emaFast, "\n",
       "EMA Slow       : ", emaSlow
    );

    Place this code near the end of your OnTick() function (or wherever your strategy updates its values).

    Every time a new tick arrives, the displayed information will refresh automatically, giving you a live dashboard of your strategy.

    This approach is much cleaner than continuously checking the Experts log and is commonly used while developing and debugging MT5 Expert Advisors.

    Yes sir, you can easily do this using MT5 chart objects.

    The best approach is to create a reusable helper function that draws the required object whenever your strategy generates a signal.

    You only need to create this function once, and then call it wherever your Buy or Sell conditions are satisfied.

    You can place the following function anywhere above your OnTick() function.

    //+------------------------------------------------------------------+
    //| DRAW OBJECT ON CHART                                             |
    //+------------------------------------------------------------------+
    void DrawObject(string prefix, datetime time, double price, string objectType, color objColor, int width = 1, string text = "")
    {
       // Create unique name
       string name = prefix + "_" + IntegerToString((int)time) + "_" + IntegerToString(rand());
       
       // Delete existing object if any
       if(ObjectFind(0, name) >= 0)
          ObjectDelete(0, name);
       
       // Create arrow object
       if(!ObjectCreate(0, name, OBJ_ARROW, 0, time, price))
          return;
       
       //--- Set arrow code based on type
       if(objectType == "arrow_up")
          ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 233);   // Up arrow
       else if(objectType == "arrow_down")
          ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 234);   // Down arrow
       else if(objectType == "flag")
          ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 79);    // Flag
       else
          ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 234);   // Default Down arrow
       
       //--- Set properties
       ObjectSetInteger(0, name, OBJPROP_COLOR, objColor);
       ObjectSetInteger(0, name, OBJPROP_WIDTH, width);
       ObjectSetInteger(0, name, OBJPROP_BACK, false);
       ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
       ObjectSetInteger(0, name, OBJPROP_HIDDEN, false);
       
       //--- Tooltip
       ObjectSetString(0, name, OBJPROP_TOOLTIP, objectType + " at " + TimeToString(time, TIME_DATE | TIME_MINUTES | TIME_SECONDS));
    }

    Now, whenever your Buy condition is satisfied, simply call the function like this:

    double arrowPrice = breakoutLow - PipsToPoints(ArrowPips);
    DrawObject("Signal", breakoutTime, arrowPrice, "arrow_up", clrLime, 2);

    Similarly, for a Sell signal, you can draw a down arrow:

    double arrowPrice = breakoutHigh + PipsToPoints(ArrowPips);
    DrawObject("Signal", breakoutTime, arrowPrice, "arrow_down", clrRed, 2);

    That’s it.

    Whenever your strategy generates a signal, simply call DrawObject() with the appropriate parameters, and MT5 will plot the symbol on the chart automatically.

    You can also customise the symbols by changing the OBJPROP_ARROWCODE values. MT5 supports many different Wingdings symbols such as arrows, flags, stars, circles, check marks, and more.

    The DrawObject() function shown above is a reusable helper built using the official MQL object documentation. You can explore all available symbol codes here:

    https://docs.mql4.com/constants/objectconstants/wingdings

    You can replace the arrow codes with any Wingdings code you like to display different symbols on your chart. This makes it easy to visually mark breakouts, entries, exits, reversals, or any other event generated by your strategy.

    Yes sir, this is completely normal and one of the most common confusions among traders.

    The reason is that Sell positions are executed and closed based on the Ask price, not the Bid price.

    By default, MT5 charts display only the Bid price, so it may look like your Stop Loss or Target was hit early.

    To verify this, simply enable the Ask price line in MT5.

    Follow these steps:

    -Step 1:

    Right-click anywhere on the chart and select “Properties”.

    -Step 2:

    Enable the option “Show Ask Line”.

    That’s it.

    Now you will see both the Bid price and the Ask price on the chart.

    For Sell trades:

    -Stop Loss is triggered when the Ask price reaches your Stop Loss level.

    -Take Profit is triggered when the Ask price reaches your Target level.

    So even if the Bid price hasn’t touched your level yet, the Ask price may already have reached it, which is why the order gets closed.

    For Buy trades, it’s the opposite.

    -Buy positions are executed and closed based on the Bid price.

    So, in simple terms:

    -Buy Trade → Watch the Bid price.

    -Sell Trade → Watch the Ask price.

    Once you enable the Ask price line, you’ll notice that your Stop Loss and Take Profit are being executed exactly where they should.

    The main difference between an Indicator and an Expert Advisor (EA) is that an Indicator only analyzes the market, while an Expert Advisor can analyze the market and execute trades automatically.

    An Indicator is used to display trading information on the chart. It performs calculations based on price or volume and helps traders identify trends, momentum, support and resistance, or potential entry and exit points. However, an Indicator cannot place, modify, or close trades on its own.

    For example, indicators such as Moving Average, RSI, MACD, and Supertrend help you make trading decisions, but you still need to place the trade manually.

    An Expert Advisor (EA) is an automated trading program. It can analyze market conditions, generate trading signals, and automatically place, modify, and close trades based on the logic you’ve programmed into it.

    For example, you can create an EA that buys whenever the 9 EMA crosses above the 21 EMA and exits the trade when the opposite crossover occurs. Once Auto Trading is enabled, the EA can perform these actions without manual intervention.

    In short:

    -Indicator → Analyzes the market and displays information on the chart. It does not execute trades.

    -Expert Advisor (EA) → Analyzes the market and can automatically execute trades based on predefined trading rules.

    If your goal is only to study the market or generate signals, use an Indicator. If you want your trading strategy to execute orders automatically, you’ll need an Expert Advisor (EA).

    Refreshing your broker session in AlgoDelta is very simple. Depending on the type of broker you’re using, there are two ways to refresh the login token.

    1. One-click token refresh

    Some brokers support one-click token refresh.

    To refresh these accounts:

    • Open the AlgoDelta Platform.
    • Go to the Demat section.
    • Click the “Relogin All Demat” button available at the top-right corner.

    Once you click this button, all supported broker accounts will automatically refresh their login tokens without requiring any additional steps.

    2. Manual login brokers

    Some brokers require a manual login whenever the session expires.

    For these brokers:

    • First, log in to your broker account in the same browser tab where you’re logged into AlgoDelta.
    • Then go to the Demat section in AlgoDelta.
    • Click the “Relogin” button for that broker.
    • A login window will open.
    • Complete the authentication by entering the required details, such as your PIN, password, or any other credentials required by your broker.

    Once the login is successful, the broker token will be refreshed, and your account will be ready to place orders again.

    I hope this helps! If you’re still facing issues while refreshing your broker session, feel free to ask to our support team.

    Yes, there are two ways to create alerts in Pine Script: alertcondition() and alert().

    1. Using alertcondition()

    This is the most common method and is mainly used to create alert conditions that appear in TradingView’s Create Alert dialog.

    buyCondition = ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
    
    alertcondition(
        buyCondition,
        title = "Buy Signal",
        message = "EMA Crossover Buy Signal"
    )
    

    2. Using alert()

    The alert() function lets you trigger an alert directly from your code whenever a condition is met.

    if buyCondition
        alert("EMA Crossover Buy Signal")
    

    You can also control how often the alert is triggered by using the freq parameter.

    if buyCondition
        alert("EMA Crossover Buy Signal", alert.freq_once_per_bar_close)
    

    In short:

    -Use alertcondition() when you want to create alert conditions that users can select from TradingView’s Create Alert window.

    -Use alert() when you want to trigger alerts directly from your script with more control over when they are sent.

    Both methods are useful, and the one you choose depends on how you want your alerts to behave.

    Yes, request.security() is one of the most useful functions in Pine Script. It allows you to fetch data from a different symbol or timeframe while your script is running on the current chart.

    The basic syntax is:

    request.security(symbol, timeframe, expression)
    

    Where:

    symbol is the symbol you want to get data from.

    timeframe is the timeframe of that data.

    expression is the value you want to retrieve, such as close, high, low, or even another indicator.

    For example, suppose you’re on a 5-minute chart, but you want to use the 1-hour closing price in your indicator. You can do that like this:

    //@version=6
    indicator("Higher Timeframe Close", overlay = true)
    
    htfClose = request.security(syminfo.tickerid, "60", close)
    
    plot(htfClose, color = color.orange, linewidth = 2)
    

    In this example:

    syminfo.tickerid tells Pine Script to use the current chart’s symbol.

    "60" represents the 1-hour timeframe.

    close returns the closing price from that timeframe.

    The script then plots the 1-hour closing price directly on your current chart.

    You can also use request.security() to retrieve values from other timeframes, calculate indicators on higher timeframes, or even fetch data from different symbols.

    I hope this helps! If you have any questions about request.security() or want to explore more advanced use cases, feel free to ask again.

    Yes, you can create a Supertrend indicator in Pine Script very easily using the built-in ta.supertrend() function.

    The code below creates a Supertrend with an ATR Multiplier of 3 and an ATR Length of 10. It returns two values:

    supertrend – The Supertrend line.
    direction – The current trend direction.

    The plot() functions then display the Supertrend on the chart. When the trend is bullish, the line is plotted in green, and when the trend is bearish, it is plotted in red.

    The script also includes a custom function named pine_supertrend(). This function manually calculates the Supertrend using ATR, upper band, lower band, and trend direction. It produces the same result as the built-in ta.supertrend() function and is useful if you want to understand or customize the Supertrend calculation.

    You can simply copy the code below into the Pine Script Editor and click Add to Chart to see the Supertrend indicator in action.

    //@version=6
    indicator("My super trend", overlay = true)
    
    [supertrend, direction] = ta.supertrend(3, 10)
    plot(direction < 0 ? supertrend : na, "Up direction", color = color.green, style = plot.style_linebr)
    plot(direction > 0 ? supertrend : na, "Down direction", color = color.red, style = plot.style_linebr)
    
    // The same on Pine Script®
    pine_supertrend(factor, atrPeriod) =>
        src = hl2
        atr = ta.atr(atrPeriod)
        upperBand = src + factor * atr
        lowerBand = src - factor * atr
        prevLowerBand = nz(lowerBand[1])
        prevUpperBand = nz(upperBand[1])
    
        lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
        upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
    
        int _direction = na
        float superTrend = na
        prevSuperTrend = superTrend[1]
    
        if na(atr[1])
            _direction := 1
        else if prevSuperTrend == prevUpperBand
            _direction := close > upperBand ? -1 : 1
        else
            _direction := close < lowerBand ? 1 : -1
    
        superTrend := _direction == -1 ? lowerBand : upperBand
        [superTrend, _direction]
    
    [Pine_Supertrend, pineDirection] = pine_supertrend(3, 10)
    
    plot(pineDirection < 0 ? Pine_Supertrend : na, "Up direction", color = color.green, style = plot.style_linebr)
    plot(pineDirection > 0 ? Pine_Supertrend : na, "Down direction", color = color.red, style = plot.style_linebr)

    Also, if you want the code of tradingview provided for the supertrend then just visit the refrance manual and search for the supertrend in that example you will find the code of the supertrend.

    I hope this helps! If you have any questions about the code or want to customize the Supertrend settings, feel free to ask in the comments.

    Yes, this is completely possible in Pine Script.

    Normally, when you create an indicator with:

    indicator("My Indicator", overlay = false)

    the entire indicator is displayed in a separate pane below the price chart.

    However, Pine Script allows individual plots and drawings to be forced onto the main chart by using the force_overlay parameter.

    For example:

    indicator("My Indicator", overlay = false)
    plot(close, force_overlay = true)

    In this example, the indicator itself still lives in the separate pane because overlay = false, but the plot() is forced to appear on the main price chart using force_overlay = true.

    The same concept can be used with other drawing functions that support the force_overlay parameter, allowing you to keep your calculations in a separate pane while displaying important signals or visual elements directly on the chart.

    This approach is useful when you want the best of both worlds:

    Keep oscillators like RSI, MACD, or custom calculations in a separate pane.
    Display buy/sell signals, labels, or important plots on the main price chart.

    This keeps your indicator organized while still making the important trading signals easy to see.

    Below is an example showing how this works in practice.

Viewing 15 posts - 31 through 45 (of 136 total)
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

⚠️

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top