TradingView {{strategy.order.action}} Explained: Strategy Alert Placeholders, Partial Exits and Webhook JSON

TradingView strategy.order.action placeholders, partial exits and webhook JSON for AlgoWay and MT5

The most dangerous TradingView webhook mistakes begin when an alert describes the position that remains instead of the order that was just executed. A strategy can close part of a long trade, leave the rest of the long position open, and correctly report that its current market position is still long. If that value is used as the external trading command, the receiving platform can open another long position at the exact moment when the strategy intended to reduce risk.

This guide explains the problem from the beginning and follows it through every layer of real automation: the Pine Script order, the TradingView broker emulator, the strategy alert placeholder, the JSON body, AlgoWay routing, MetaTrader 5 execution, account mode, position size and broker response. It is written for traders who do not want a dictionary of placeholder names. They want to know why the chart says one thing, the webhook log says another thing, and the broker account does something that appears to contradict both.

The central lesson is simple, but its consequences reach every advanced strategy. An executed order is an event. A market position is a state. A strategy can execute a sell order and still remain long. It can execute a buy order and still remain short. It can execute 1.50 contracts and finish with a position of only 0.50. None of those results is an error. They are normal consequences of partial exits, position reduction and automatic reversal.

Last updated: 2026-07-29 • Author: AlgoWay

The Quick Answer: Why a Partial Take Profit Opened Another Long

Consider a TradingView strategy that opens one XAUUSD long position and uses three take-profit levels. The first target closes 0.20 lots. When that target fills, TradingView has processed a sell-side order for 0.20, but the strategy still owns the remaining long position. At that moment, the values can be read as follows:

{{strategy.order.action}} = sell
{{strategy.order.contracts}} = 0.20
{{strategy.market_position}} = long
{{strategy.market_position_size}} = remaining long size

Now look at a commonly used message:

{
  "platform_name": "metatrader5",
  "ticker": "{{ticker}}",
  "order_action": "{{strategy.market_position}}",
  "order_contracts": "{{strategy.order.contracts}}"
}

After substitution, TradingView does not send the history of the trade or the reason for the fill. It sends the final text:

{
  "platform_name": "metatrader5",
  "ticker": "XAUUSD",
  "order_action": "long",
  "order_contracts": "0.20"
}

That message contains no partial-close instruction. It says that the action is long and the quantity is 0.20. AlgoWay and MT5 are not able to discover the missing intention from the chart. They can only process the command they received. A new 0.20 BUY is therefore a logical result of the JSON, even though it is the opposite of what the Pine strategy author wanted.

The correct external instruction for this event must say that exposure should be closed, not that the resulting TradingView position is long. With AlgoWay, an explicit long-side partial close can be represented as:

{
  "platform_name": "metatrader5",
  "ticker": "XAUUSD",
  "order_action": "flat",
  "order_contracts": "0.20",
  "close_side": "long"
}

This is the difference between reporting state and communicating intent. The first message says what remains inside TradingView. The second says what the execution platform must do.

The Mental Model That Prevents Most Strategy Alert Errors

A strategy order alert is created when TradingView's broker emulator fills an order. That fill has a side, a quantity, a simulated fill price, an ID, a comment and an optional custom message. After the fill, the strategy also has a position state: long, short or flat, with a current size and a previous size. TradingView exposes both groups of information because both are useful. Problems begin only when a field from one group is treated as though it belonged to the other.

The order group answers: what transaction has just occurred? The position group answers: what position exists after the transaction? A full long exit creates a sell transaction and leaves a flat position. A partial long exit creates the same sell transaction but leaves a long position. A short entry from flat creates a sell transaction and leaves a short position. The word sell therefore does not identify the purpose of an order, while the word long does not prove that long exposure increased.

This distinction becomes even more important when a strategy uses pyramiding. A buy order can add to an existing long position. A sell order can reduce that same long position. Both fills can occur while {{strategy.market_position}} remains long. If the webhook uses only the resulting position direction, it cannot distinguish increasing exposure from decreasing exposure.

The same issue appears on the short side. A partial short exit is a buy transaction, but the remaining strategy position is still short. Sending short as the command can add another SELL. Sending buy without an explicit close instruction can open a hedged BUY ticket. The Pine strategy knows why the order exists. The alert message must preserve that knowledge instead of forcing the destination to guess.

TradingView Strategy Alert Placeholders in Plain Language

The following table is not merely a reference. The final column explains the interpretation mistake that causes real execution failures.

Placeholder What TradingView reports What it does not prove
{{strategy.order.action}} buy or sell for the executed order It does not prove entry, exit, partial close or reversal.
{{strategy.order.contracts}} The quantity of the order that was executed It does not always equal the remaining or final position size.
{{strategy.order.price}} The order fill price simulated by TradingView It does not guarantee the final broker fill price.
{{strategy.order.id}} The ID assigned by the Pine order-generating call It does not automatically identify an MT5 ticket.
{{strategy.order.comment}} The Pine order comment, or the order ID when no comment exists It does not create broker-side linkage unless the integration uses it.
{{strategy.order.alert_message}} The custom dynamic message assigned to that Pine order It is empty unless the script supplies an alert message.
{{strategy.market_position}} The current strategy state: long, short or flat It does not say whether the latest fill increased or reduced exposure.
{{strategy.market_position_size}} The current strategy position size as an absolute value It does not identify the quantity of the latest transaction.
{{strategy.prev_market_position}} The position direction before the latest state change It does not replace an explicit command for the destination.
{{strategy.prev_market_position_size}} The previous position size as an absolute value It does not explain which Pine exit order caused the change.
{{strategy.position_size}} The current Pine strategy position size, normally signed by direction It is strategy state, not the executed order quantity.
{{ticker}} The TradingView chart symbol It does not guarantee the broker uses the same symbol name.
{{close}} The chart close value available to the alert calculation It is not necessarily the strategy fill or MT5 execution price.
{{time}} The bar time It is not always the exact moment the webhook was sent.
{{timenow}} The alert trigger time It does not represent the broker acknowledgement time.

TradingView documents these fields in its strategy alert reference. The important point for automation is not memorizing the definitions. It is choosing a field that describes the same concept expected by the receiving JSON property.

What {{strategy.order.action}} Really Means

{{strategy.order.action}} returns buy or sell for the executed TradingView order. That definition is exact, but many users silently add another meaning that TradingView never promised. They read buy as open long and sell as open short. That interpretation works for entries from a flat position, so the mistake can remain hidden for months. It fails on the first real exit.

A long position is reduced through selling. A short position is reduced through buying. The same order side is therefore used for entry in one context and exit in another context. TradingView is reporting the mechanics of the transaction, not the business intention behind it.

Imagine four order fills. Opening a long from flat returns buy. Closing a short returns buy. Adding to a long returns buy. Reversing from short to long also returns buy. All four events can share the same action, but they require different handling when the destination maintains independent tickets, applies hedge logic or expects a separate close command.

The same is true for sell. It can open a short, close a long, add to a short or reverse a long into a short. A generic webhook router cannot always determine which meaning was intended because the external account may not match the TradingView strategy state. The broker account may contain manual trades, a previous alert may have failed, the symbol may use a different lot model, or the account may permit both directions simultaneously.

This is why simply changing {{strategy.market_position}} to {{strategy.order.action}} is an incomplete repair. It fixes the false statement that a partial close is a new long state command, but it still sends only a transaction side. In a netting environment, a sell of 0.20 may reduce a long of 1.00 exactly as intended. In a hedging environment, it can create a new short ticket while the long remains open. The message must match the destination's execution model.

What {{strategy.order.contracts}} Really Means

{{strategy.order.contracts}} reports the quantity of the executed order. That sounds straightforward until a strategy reverses a position. TradingView's strategy.entry() can automatically add the size of the current opposite position to the requested new entry size. The resulting transaction is large enough to close the old position and establish the requested new position in one operation.

Suppose the strategy is long 1.00 and calls a short entry for 0.50. The sell transaction can be 1.50. One lot removes the long and the remaining 0.50 creates the short. The final position is short 0.50, but {{strategy.order.contracts}} reports the 1.50 transaction. If a webhook interprets that number as the desired final short size, the broker account can become short 1.50 instead of short 0.50.

The same placeholder behaves correctly during a partial exit, but only when the recipient understands that the quantity belongs to a close operation. A TP1 order that closes 0.20 reports 0.20. A TP2 order that closes another 0.20 reports 0.20. The number is not wrong. The surrounding command determines whether it increases or decreases exposure.

Quantity units also matter. TradingView speaks in strategy contracts, shares, lots or units according to the strategy and market. MT5 speaks in broker lot sizes. A crypto exchange can use base-asset quantity, contract quantity or quote value. Even when the number is identical, the economic exposure may not be. AlgoWay routing can transmit and normalize values, but it cannot invent the user's intended unit when the message does not state it and the destination configuration expects another model.

A Complete Event Map for Long and Short Positions

The following examples show why no single direction placeholder can describe every order. Assume that quantities are already normalized for the destination.

Strategy event Executed action Executed quantity Resulting state External intention
Open long 1.00 from flat buy 1.00 long 1.00 Open long
Add 0.20 to long buy 0.20 long 1.20 Increase long
Close 0.20 from long sell 0.20 long 0.80 Reduce long
Close the remaining long sell 0.80 flat Close long completely
Open short 1.00 from flat sell 1.00 short 1.00 Open short
Add 0.20 to short sell 0.20 short 1.20 Increase short
Close 0.20 from short buy 0.20 short 0.80 Reduce short
Close the remaining short buy 0.80 flat Close short completely
Reverse long 1.00 into short 0.50 sell 1.50 short 0.50 Close long and open short
Reverse short 1.00 into long 0.50 buy 1.50 long 0.50 Close short and open long

The table exposes the weakness of a universal message based only on action and contracts. It can mirror raw transactions when both systems are perfectly synchronized and the destination uses compatible netting. It cannot guarantee semantic intent across a hedging MT5 account, several open tickets, manual positions, failed earlier webhooks or a connector mode that treats buy and sell as entry signals.

Why {{strategy.market_position}} Works Until the Strategy Becomes Useful

A state-based message can work very well for a simple strategy. The strategy is either flat, fully long or fully short. There is no pyramiding. Every exit closes the entire position. An opposite signal has one predictable meaning. In that narrow design, {{strategy.market_position}} appears to be the perfect command because every order fill also changes the strategy state.

The first partial exit breaks that assumption. TP1 reduces the position but leaves the direction unchanged. TP2 does the same. A trailing stop can reduce or close a remainder. An entry can add to the same direction without changing the state. The position direction has become too coarse to describe the event.

This is why users often report that entries work perfectly while take profits behave irrationally. Nothing changed in the webhook infrastructure. The strategy crossed from a state transition model into a quantity management model. The JSON remained designed for the simpler strategy.

A three-target long trade makes the failure easy to see. The initial entry sends long. TP1 sends long because the remainder is still long. TP2 sends long for the same reason. TP3 may finally send flat when the position reaches zero. From TradingView's perspective, all values are correct. From the MT5 account's perspective, the first two take profits can become two additional long entries.

The Reliable Solution: Let the Pine Order Describe Its Own Intention

The most reliable architecture uses {{strategy.order.alert_message}} in the TradingView alert dialog and assigns a dedicated dynamic message to every order-generating call inside Pine Script. The entry knows that it is an entry. TP1 knows that it is a partial long close. TP2 knows the same, with another quantity. A stop knows whether it should close the remainder. A reversal can be represented as an intentional close followed by a new entry instead of an inferred side effect.

The message field in the TradingView strategy alert should contain:

{{strategy.order.alert_message}}

The Pine script then creates complete JSON for each event. A long entry can carry:

string longEntryJson = '{"platform_name":"metatrader5","ticker":"' + syminfo.ticker + '","order_action":"buy","order_contracts":"' + str.tostring(entryQty) + '","comment":"Long Entry"}'

strategy.entry(
    "Long Entry",
    strategy.long,
    qty = entryQty,
    alert_message = longEntryJson
)

A partial long exit can carry an explicit close command:

string longTp1Json = '{"platform_name":"metatrader5","ticker":"' + syminfo.ticker + '","order_action":"flat","order_contracts":"' + str.tostring(tp1Qty) + '","close_side":"long","comment":"Long TP1"}'

strategy.exit(
    "Long TP1",
    from_entry = "Long Entry",
    limit = longTp1Price,
    qty = tp1Qty,
    alert_message = longTp1Json
)

A partial short exit uses the same close action and identifies the short side:

string shortTp1Json = '{"platform_name":"metatrader5","ticker":"' + syminfo.ticker + '","order_action":"flat","order_contracts":"' + str.tostring(tp1Qty) + '","close_side":"short","comment":"Short TP1"}'

strategy.exit(
    "Short TP1",
    from_entry = "Short Entry",
    limit = shortTp1Price,
    qty = tp1Qty,
    alert_message = shortTp1Json
)

The important change is not cosmetic JSON formatting. The intent survives the entire route. TradingView no longer sends a state and hopes the receiver reconstructs the event. AlgoWay receives a close operation, and MT5 can reduce the selected side according to the configured close-size mode.

How to Design Multi-Level Take Profits Without Reopening the Trade

A multi-level exit is not one exit split visually across the chart. TradingView creates separate orders. Each order can fill at a different time and generate its own alert. Every one of those alerts must be safe when processed independently.

Assume a long entry of 1.00 with TP1 closing 0.20, TP2 closing 0.30 and a final target closing 0.50. TP1 should not send long. It should send a flat command for 0.20 on the long side. TP2 should send a flat command for 0.30 on the long side. The final target can send flat for the remaining 0.50 or use a complete symbol-close command when that is truly the intended behavior.

Do not make the final exit depend on the original expected remainder unless earlier fills are guaranteed. A stop loss can execute before TP1. TP1 can fill while TP2 remains pending. TradingView's exit orders can reserve portions of a position, and orders created by strategy.exit() participate in reduction behavior designed to prevent the planned exits from exceeding available exposure. The external broker, however, receives only the webhook events that actually fire. It does not automatically share TradingView's internal reservation model.

A robust strategy therefore treats each filled exit as an independent fact. It sends the quantity that was actually intended for that exit and checks the final behavior in both the AlgoWay webhook log and MT5. For the last exit, many users prefer a complete close command because it removes small residual volume created by broker lot steps or rounding. That decision must be deliberate because closeall can close more exposure than one strategy leg when the symbol contains several managed positions.

Exact Lots and Percentage-Based Partial Closing

TradingView can size an exit with qty or qty_percent. AlgoWay's MT5 EA can also interpret a flat command's order_contracts as a fixed lot amount or as a percentage of the initial position, depending on the EA setting. These are separate layers and must agree.

In an exact-lot design, Pine calculates or specifies the quantity to close. The webhook sends that quantity, such as 0.20, and the MT5 EA uses CLOSE_LOTS. The command means close 0.20 lots. This model makes the alert log easy to read because the message contains the actual requested broker volume.

In an initial-position percentage design, the webhook can send 20 and the MT5 EA uses CLOSE_INITIAL_PERCENT. The command means close 20 percent of the initial AlgoWay-managed position. This is useful when the initial position size is determined elsewhere and the Pine strategy should express only the intended fraction.

The two messages can look valid while meaning radically different things. Sending 20 to an EA configured for lots is not a 20 percent close. Sending 0.20 to an EA configured for initial-position percent is not a 20 percent close. The receiver cannot safely infer the unit from the number because both decimals and whole numbers can be legitimate quantities.

The current AlgoWayWS-MT5 automation guide documents both close-size modes. Confirm the EA setting before publishing the TradingView alert, and test the exact partial volume on a demo account before allowing several take-profit levels to fire.

Why Reversals Are More Complicated Than Buy and Sell

TradingView's strategy.entry() can reverse an open position automatically. This feature is convenient in a backtest because one short entry call can close the current long and establish the new short. It becomes dangerous when the order transaction is copied mechanically to a separate broker account.

If the strategy is long 1.00 and requests a short entry of 0.50, TradingView can create a sell transaction of 1.50. The chart marker and {{strategy.order.contracts}} describe the transaction, while the final position is short 0.50. A destination that receives sell 1.50 without already holding the identical long 1.00 can finish with entirely different exposure.

This is one reason account synchronization matters. TradingView's broker emulator assumes its own current position. MT5 acts on its actual account. If a previous close was rejected, a manual trade was added, the EA was offline, or the symbol mapping routed to another instrument, the same reversal transaction cannot repair the divergence.

For strict automation, a reversal should be defined as an operation rather than inferred from transaction size. One design sends an explicit close for the current side and then a new entry for the required new size. Another design uses the AlgoWay execution mode that intentionally implements the desired behavior. AlgoWay distinguishes Hedge, Reverse and Opposite behavior because the phrase reverse position is used inconsistently across brokers and strategies. The AlgoWay position mode guide explains those differences.

The correct choice depends on the strategy. A signal may mean close only and wait. It may mean close and immediately flip. It may mean keep both sides in a hedging account. It may mean reduce the existing position without crossing through zero. No placeholder can make that decision for the trader.

Netting, Hedging and Why the Same Sell Command Behaves Differently

On a netting model, one symbol normally has one net position. A sell smaller than the current long can reduce it. A sell equal to the current long can flatten it. A larger sell can close the long and leave a short remainder. In that environment, mirroring {{strategy.order.action}} and {{strategy.order.contracts}} can work when TradingView and the destination remain synchronized.

On a hedging model, BUY and SELL positions can exist as separate tickets. A sell command does not inherently mean close the existing BUY. It can create a new SELL while the BUY remains open. This is exactly why a partial long take profit can become a hedged short when the message sends only sell 0.20.

AlgoWay's flat action provides a clearer instruction for close logic. The optional close_side field identifies which direction should be reduced when both sides can exist. A long-side partial close can use close_side: long, while a short-side partial close uses close_side: short. The exact destination behavior still depends on the platform and account type, which is why demo verification remains necessary.

Do not assume that the account label inside MT5 settles this question. An MT5 broker can provide hedging or netting accounts. The EA trade mode adds another layer of behavior. The Pine strategy has its own model. All three must be aligned: TradingView strategy logic, AlgoWay route mode and broker account mode.

strategy.entry, strategy.order, strategy.exit and strategy.close Are Not Interchangeable

strategy.entry() is designed for entries and can reverse an opposite position automatically. It is affected by pyramiding rules. strategy.order() creates orders without the same automatic reversal behavior and can increment or decrement the current position directly. strategy.exit() creates price-based exits such as take-profit and stop-loss orders, and multiple calls can reserve portions of a position for multi-level exits. strategy.close() and strategy.close_all() create market orders to close open exposure.

These differences matter because the placeholder output reflects the filled order produced by the function, not the name a trader gives the condition. A function called when the code variable is named takeProfit still produces buy or sell according to the side of the actual order. TradingView does not convert the developer's intention into words such as partial_close_long.

The strategy author should use the function that matches the trade logic and attach an alert message that matches the external execution logic. A strategy.exit() TP for a long can send an AlgoWay flat command. A strategy.entry() long can send buy. A market close can also send flat. The external message does not have to repeat TradingView's internal order vocabulary when a clearer destination command exists.

Order IDs, Comments and Stable Trade References

{{strategy.order.id}} reports the ID used in the Pine order call. {{strategy.order.comment}} reports the order comment and falls back to the order ID when no comment is defined. These fields are useful for logs and for identifying which strategy event fired, especially when several take-profit orders share the same symbol and direction.

An ID does not automatically become an MT5 ticket. TradingView and MT5 are separate systems with separate order identifiers. If a connector supports a stable external reference such as tv_order_id, the Pine strategy can send a deliberate value that the execution route uses for matching, duplicate detection or position management. The identifier should be stable for the intended trade leg and unique when separate legs must remain distinguishable.

Human-readable comments are also valuable during development. A webhook log entry that says Long TP2 is easier to diagnose than an anonymous sell of 0.20. Comments should describe the event, not pretend to be proof of execution. The broker response and MT5 ticket remain the final evidence that the requested operation was accepted.

Order Fill Alerts, alert() Calls and Duplicate Commands

A TradingView strategy alert can be configured for order fills, alert() function calls, or both. Order-fill alerts fire when the broker emulator fills a strategy order. An alert() call fires when the Pine script executes that function under its frequency rules. Those are different event sources.

A strategy can accidentally send two trade commands for one logical signal when the Pine code calls alert() and the TradingView alert is also configured to include order fills. The first message can be generated when the condition appears. The second arrives when the simulated order fills. If both messages contain an entry command, MT5 can receive two entries.

Choose one authoritative execution event. For strategies that must mirror simulated order fills, use order fills and assign alert_message to the order calls. For custom signal automation that does not depend on the broker emulator, use alert() calls and build the dynamic JSON directly. Enabling both is valid only when the messages serve different purposes and the destination can distinguish them.

The official TradingView alerts documentation explains that order fill alerts and alert() calls are separate trigger types. When diagnosing duplicate entries, check the Condition selection in the active TradingView alert instead of examining only the Pine code.

Why Editing the Strategy Does Not Update an Existing Alert

When a TradingView strategy alert is created, TradingView creates a server-side copy of the strategy and its settings. That copy continues to run independently from the chart in the browser. Editing the Pine code, changing an input, adjusting quantity, replacing the JSON or switching the chart timeframe does not rewrite the already running alert.

This produces one of the most confusing support cases. The user opens the chart, sees the corrected code and proves that the message now contains flat. The webhook log continues to receive long. Both observations can be true because the chart and the alert are running different versions.

After any material strategy change, stop or delete the old alert and create a new one. Confirm the strategy name, symbol, interval, condition type and message in the new alert dialog. Then inspect the first received payload in AlgoWay Webhook Logs. Do not assume the visible chart code is the code executing on TradingView's alert servers.

Historical Strategy Trades Do Not Become Webhooks

A strategy can display hundreds of trades in Strategy Tester immediately after it is added to a chart. Those historical trades are calculations, not realtime alert deliveries. TradingView strategy alerts trigger for order fills that occur in realtime after the alert exists.

This explains why a performance dashboard can show 411 trades while AlgoWay contains only a few webhook events. TradingView does not replay the historical trade list into the webhook URL. The trader must wait for the strategy to generate a new realtime fill or use a controlled realtime test condition.

Historical and realtime behavior can also diverge because a completed historical candle contains final OHLC data, while a live candle changes tick by tick. Settings such as recalculation after order fills, calculation on every tick, bar magnifier behavior and order processing timing can affect when fills appear. A backtest marker is not proof that the live alert sent the same sequence at the same moment.

Several Fills on One Candle and the Order of Webhooks

A strategy can generate more than one order fill on a single bar. A take profit may close a position, a reversal condition may create a new entry, or recalculation after a fill may trigger another order. TradingView can send a separate notification for each fill.

The receiving system processes actual webhook requests in the order they arrive. That order matters. A new entry arriving before the intended close can create temporary or permanent exposure that differs from the strategy. The problem is especially visible when a Pine strategy emits a sell entry and then a flat event several seconds later, even though the developer expected close first and open second.

Use explicit messages, stable order IDs where required, and Pine logic that intentionally sequences the operations. Do not rely on the visual order of markers alone. The TradingView alert log and the AlgoWay webhook timestamps show the real emitted sequence. When two operations belong to one reversal, design them as a known close-and-open workflow instead of hoping that a generic state placeholder makes them self-correcting.

{{close}} Is Chart Data, Not Guaranteed Execution

{{close}} reports the chart's close value available to the alert event. {{strategy.order.price}} reports the fill price simulated by TradingView's broker emulator. The broker that executes the AlgoWay command has its own bid, ask, spread, liquidity, tick size and fill rules. These three prices can differ without any component being defective.

Use {{strategy.order.price}} when the log should record the TradingView simulated fill. Use {{close}} when the message needs chart context. Do not use either as proof of the MT5 fill. The MT5 position or deal record is the execution source of truth for the broker account.

The same distinction applies to stop and target values. A chart plot can show a calculated target price, but a webhook field named take_profit may represent a distance rather than an absolute price. The key name and the configured SL/TP model determine how AlgoWay interprets the number.

Absolute SL/TP Prices, Distances and Percentages

A valid JSON body can still communicate the wrong unit. If XAUUSD has an intended stop at 4033.480, placing that number in a field configured as a pip or point distance does not mean stop at 4033.480. It can request an enormous distance.

AlgoWay uses sl_price and tp_price for absolute price levels. Distance-oriented values use stop_loss and take_profit under the selected calculation model. Percentage-based values require the percentage model. The AlgoWay JSON schema guide documents these fields and their intended roles.

An absolute-price example is:

{
  "platform_name": "metatrader5",
  "ticker": "XAUUSD",
  "order_action": "buy",
  "order_contracts": "0.20",
  "sl_price": "4033.480",
  "tp_price": "4052.470"
}

A distance example uses different values and should declare the correct model when needed:

{
  "platform_name": "metatrader5",
  "ticker": "XAUUSD",
  "order_action": "buy",
  "order_contracts": "0.20",
  "stop_loss": "100",
  "take_profit": "200",
  "sltp_type": "pips"
}

Do not infer the unit from the number's appearance. A decimal can be a price, a percentage or a quantity. The field name and configuration must make the meaning explicit.

Symbol Names: XAUUSD in TradingView May Not Be XAUUSD in MT5

TradingView can send XAUUSD while the MT5 broker exposes XAUUSD.a, XAUUSDm, GOLD or another broker-specific name. A correct alert can reach AlgoWay and the EA but still fail because the destination symbol does not exist or is not selected.

Use AlgoWay MT5 symbol mapping when the names differ. Check the exact ticker received in the webhook log, the configured TradingView-to-broker mapping, and the symbol visible in MT5 Market Watch. Do not modify a mapping until the actual names have been verified.

Symbol specifications also affect quantity. XAUUSD contract size, minimum lot and lot step can differ between brokers. A strategy quantity that worked on one account can be invalid on another. The broker can reject the order even though the webhook JSON is structurally correct.

Valid JSON Is Necessary, but It Is Not Proof of a Valid Trade

TradingView must send one complete JSON object when the AlgoWay route expects JSON. Keys and string values use double quotes. There must be no trailing comma, explanatory sentence outside the object or second object pasted below the first. A placeholder must resolve to a value that preserves valid JSON.

This is valid:

{"platform_name":"metatrader5","ticker":"{{ticker}}","order_action":"buy","order_contracts":"0.20"}

This is not valid JSON:

Open this trade now
{'platform_name':'metatrader5','ticker':'XAUUSD','order_action':'buy',}

After syntax validation, the trade can still fail for semantic reasons: wrong platform name, unsupported symbol, invalid quantity, wrong account mode, market closure, disabled Algo Trading, invalid stops, broker filling restrictions or an offline EA. Webhook success and trade success are separate stages.

What TradingView “Successfully Delivered” Actually Proves

The TradingView delivery status proves that the webhook request was sent and that the endpoint returned a response TradingView accepted. It does not prove that MetaTrader opened, reduced or closed a position.

AlgoWay first receives and validates the payload. It then applies routing and mode logic. For MT5, the EA receives the command and asks the terminal to execute it. The broker performs the final checks. A failure can occur after successful HTTP delivery at every one of those stages.

The correct investigation uses evidence from the entire route. The TradingView alert panel confirms trigger time and active message configuration. AlgoWay Webhook Logs show the final substituted payload and processing result. MT5 Experts and Journal logs show whether the EA received the command and what the broker returned. The open position and deal history confirm final execution.

A Practical Debugging Method for Any Strategy Alert Problem

Begin with the exact received JSON, not the Pine template and not the user's memory of the alert. Placeholders disappear before AlgoWay receives the request. The final payload reveals whether TradingView sent long, sell, flat, an unexpected quantity or a stale message.

Then compare the payload with the intended strategy event. If TP1 should close 0.20 long but the payload says long 0.20, the problem is already proven. There is no reason to investigate broker slippage or MT5 permissions before fixing the message. If the payload correctly says flat 0.20 long, continue to AlgoWay processing and the MT5 logs.

Check the route mode and account mode only after verifying the command. A correct sell transaction can behave differently in netting and hedging. A correct flat command can still select the wrong side if the message omits close_side in a two-sided workflow. A correct quantity can still be wrong if the EA interprets it as percentage instead of lots.

Finally, confirm broker execution. MT5 error codes, symbol availability, volume steps, stop distances, market session and Algo Trading permissions belong to this stage. Do not diagnose the entire system from one screenshot of the chart. Each layer has its own evidence.

Safe JSON Patterns for AlgoWay and MT5

A simple long entry can be explicit:

{
  "platform_name": "metatrader5",
  "ticker": "{{ticker}}",
  "order_action": "buy",
  "order_contracts": "{{strategy.order.contracts}}",
  "price": "{{strategy.order.price}}",
  "comment": "Long Entry"
}

A simple short entry can be explicit:

{
  "platform_name": "metatrader5",
  "ticker": "{{ticker}}",
  "order_action": "sell",
  "order_contracts": "{{strategy.order.contracts}}",
  "price": "{{strategy.order.price}}",
  "comment": "Short Entry"
}

A partial long exit should describe a close:

{
  "platform_name": "metatrader5",
  "ticker": "{{ticker}}",
  "order_action": "flat",
  "order_contracts": "0.20",
  "close_side": "long",
  "comment": "Long TP1"
}

A partial short exit should also describe a close:

{
  "platform_name": "metatrader5",
  "ticker": "{{ticker}}",
  "order_action": "flat",
  "order_contracts": "0.20",
  "close_side": "short",
  "comment": "Short TP1"
}

A complete symbol close can omit quantity when the route and EA version support the intended complete-close action:

{
  "platform_name": "metatrader5",
  "ticker": "{{ticker}}",
  "order_action": "closeall",
  "comment": "Emergency or Final Close"
}

Use closeall only when all matching AlgoWay-managed exposure for the symbol should close. A strategy that manages several independent legs may require more selective flat commands instead.

When a Generic Placeholder Template Is Acceptable

A generic template based on {{strategy.market_position}} can be acceptable when the strategy always moves between flat and one complete directional position. There are no partial exits, no pyramiding, no scale-in, no separate entry IDs, no manual positions and no same-bar close-and-open workflow. The destination mode must also match the strategy's interpretation of an opposite state.

A transaction-mirroring template based on {{strategy.order.action}} and {{strategy.order.contracts}} can be acceptable when the destination is a compatible netting system and account state is continuously synchronized with TradingView. The moment independent hedged tickets, manual changes or failed prior executions become possible, the same template loses certainty.

Advanced strategies should not depend on generic templates merely because they are easy to paste into the alert dialog. The extra work belongs in Pine Script, where the reason for every order is already known. Explicit event messages make the live system easier to audit and support.

The Production Rule: Send Intention, Then Verify Reality

A strategy should send buy when it intentionally opens or increases long exposure. It should send sell when it intentionally opens or increases short exposure. It should send flat when it intentionally closes exposure. It should include quantity when the close is partial and identify the side when both directions can exist. A reversal should be designed according to the chosen AlgoWay mode or expressed as an explicit close and new entry.

After the message is correct, the live account still requires verification. TradingView simulates strategy orders. AlgoWay routes commands. MT5 and the broker execute them under real account rules. The systems are connected, but they are not one shared position database.

This is why a reliable automation workflow tests the entry, each take-profit level, the stop loss, the complete close and the reversal separately with small demo size. It then checks both AlgoWay Webhook Logs and MT5 execution logs. A single successful entry does not validate the exit architecture.

Questions and Answers

What does {{strategy.order.action}} return in a TradingView strategy alert?

It returns buy or sell for the order that the TradingView broker emulator has just executed. It describes the transaction side. It does not directly say whether that transaction opened a position, reduced a position, closed it completely, or reversed it.

Why does a partial close of a long position produce sell?

A long position is reduced through a sell-side transaction. TradingView therefore reports sell in {{strategy.order.action}}, even when the purpose of the order is only to close part of an existing long position.

Why does {{strategy.market_position}} remain long after a take profit?

Because a partial take profit leaves some long exposure open. The placeholder reports the position state after the fill, so it remains long until the entire strategy position has been closed.

Why can a partial take profit open another long position in MT5?

This happens when the webhook uses {{strategy.market_position}} as the order command. After a partial long exit, that placeholder still returns long. The receiving platform therefore sees a new long command instead of an instruction to close part of the existing long position.

Can I fix partial exits by replacing {{strategy.market_position}} with {{strategy.order.action}}?

That replacement exposes the real buy or sell side of the fill, but it is not always a complete solution. On a hedging account, sell can open a new short instead of reducing a long. The safest design is an explicit close command created for the exit order.

What does {{strategy.order.contracts}} mean?

It is the quantity of the executed order. It is not always the remaining position size or the desired final position size. During a reversal, the executed quantity can include both the amount needed to close the old position and the amount needed to open the new one.

Which TradingView placeholder should I use for partial exits?

Use {{strategy.order.alert_message}} and assign a dedicated JSON message to each strategy.exit, strategy.close, or other exit order in Pine Script. The message should explicitly describe a close operation and its quantity.

Should an AlgoWay partial exit use sell or flat?

Use flat when the intention is to close exposure rather than open a new position. Add order_contracts for the quantity and close_side when the long or short side must be selected explicitly.

What is the difference between {{strategy.position_size}} and {{strategy.market_position_size}}?

{{strategy.position_size}} represents the current Pine strategy position size and normally carries direction through its sign. {{strategy.market_position_size}} reports the current position size as an absolute non-negative number.

Why is the reversal order quantity larger than the new position?

strategy.entry can reverse a position automatically. TradingView adds the size of the open opposite position to the requested new entry size, so the transaction closes the old position and opens the new one in a single fill.

Why did three take-profit levels create three new positions?

Each partial take-profit fill left the strategy in the same long or short state. A webhook based on {{strategy.market_position}} repeated that state as a new entry command after every fill. Each take-profit order needs its own explicit partial-close message.

Does TradingView send historical strategy orders to a webhook?

No. Strategy alerts are triggered by realtime order fills after the alert is created. Historical Strategy Tester trades are calculated for the backtest but are not replayed as webhook notifications.

Why does my alert still send the old JSON after I changed Pine Script?

TradingView runs a server-side copy of the strategy and its settings from the moment the alert was created. Delete or stop the old alert and create a new one after changing code, inputs, symbol, timeframe, or the alert message.

Can one TradingView strategy alert fire more than once on the same bar?

Yes. Several order fills can occur on one bar, and each fill can create its own notification. This is common with multiple exits, recalculation after fills, intrabar logic, or a close followed by a new entry.

What is the difference between {{close}} and {{strategy.order.price}}?

{{close}} is chart data for the bar or realtime calculation that triggered the alert. {{strategy.order.price}} is the fill price simulated by the TradingView broker emulator for that strategy order. Neither guarantees the final broker fill in MT5.

Why did TradingView report successful delivery while MT5 showed no trade?

Successful delivery only confirms that TradingView sent the HTTP request and received an acceptable response. The payload can still fail validation, routing, symbol mapping, EA execution, broker volume rules, market permissions, or broker-side order checks.

How should Stop Loss and Take Profit prices be sent to AlgoWay?

Use sl_price and tp_price for absolute price levels. Use stop_loss and take_profit only for the configured distance or percentage model, together with the correct sltp_type where required.

What is the safest general architecture for TradingView strategy automation?

Let every Pine order create a message that explicitly states its intent. Entry orders should send buy or sell, partial exits should send flat with quantity and side, complete exits should send flat or closeall as appropriate, and reversals should be designed deliberately rather than inferred from one placeholder.

Final Answer

{{strategy.order.action}} is the side of the executed TradingView order. {{strategy.market_position}} is the position state that remains after the order. {{strategy.order.contracts}} is the size of the executed transaction. Those values are accurate, but they answer different questions.

A partial long take profit executes a sell order while the strategy remains long. A partial short take profit executes a buy order while the strategy remains short. Therefore a webhook that uses the remaining market position as its order command can reopen the same direction instead of closing it. Replacing the field with the order action reveals the transaction side, but it can still open a hedge when the destination needs an explicit close.

The production solution is to use {{strategy.order.alert_message}} and attach a complete JSON command to every Pine order. Entries send entry commands. Partial exits send flat with quantity and side. Final exits send the appropriate complete-close instruction. Reversals follow an intentional close-and-open or configured AlgoWay mode. No layer is forced to guess what the strategy meant.

When the webhook describes the operation explicitly, AlgoWay can route it correctly, MT5 can apply the configured close logic, and the webhook log becomes a readable record of the strategy's actual decisions instead of a stream of ambiguous long, short, buy and sell words.

Related AlgoWay Guides

Continue with the AlgoWay JSON schema guide for every supported field, the AlgoWayWS-MT5 automation guide for partial-close modes and close_side, the Hedge, Reverse and Opposite mode guide for opposite-signal behavior, and the TradingView to MT5 setup guide for the full connection and logging workflow.