Skip to content
Docs
Open Portal
Copy manually

Your browser did not allow direct clipboard access. Select and copy the text below.

Adapt an existing strategy

Add a complete PineConnector order-fill mapping to the practice strategy, then identify what must be reviewed in another script.

Connect the practice strategy’s simulated entry fill to a PineConnector buy message and its simulated closing fill to closelong. You will first inspect those messages with sending disabled, then use the same method to review an editable strategy of your own.

Before this lesson, complete Choose strategy alert events, Choose trade size and protective stops, and Verify your setup on demo. Keep earlier alerts for this practice workflow paused.

The example is a long-only market-entry/full-close strategy. It has one TradingView entry ID, no pyramiding, no partial exits and no pending orders. Its PineConnector size is a separate fixed-lot input.

1

Replace the strategy practice source

Click Copy below. In TradingView, open Pine and your saved My strategy practice file. Click inside its code, select all with Cmd+A / Ctrl+A, and paste.

What you should see

My strategy practice contains the complete adapted source, with no missing fragments.

Complete long-only strategy with PineConnector messagesPine v6 · Order-fill integration
TradingView → Pine Editor → My strategy practice Pine Script
//@version=6
strategy("Pine practice: connect strategy", overlay = true, initial_capital = 1000000,
default_qty_type = strategy.fixed, default_qty_value = 1, pyramiding = 0,
calc_on_every_tick = false, calc_on_order_fills = false, process_orders_on_close = false)
int length = input.int(20, "EMA length", minval = 1, group = "Strategy")
// This script can generate broker instructions when an order-fill alert is enabled.
bool enableFillAlerts = input.bool(false, "Enable order-fill alerts", group = "PineConnector")
string licenseId = input.string("", "License ID", group = "Destination", display = display.none)
string brokerSymbol = input.string("", "Exact broker symbol", group = "Destination", display = display.none)
string signalSecret = input.string("", "Signal secret (only if required)", group = "Destination", display = display.none)
float lots = input.float(0.01, "Lots per entry", minval = 0.00000001, step = 0.01, group = "Size and protection", display = display.none)
float stopPips = input.float(20, "Stop loss (PineConnector pips; 0 = omit)", minval = 0, group = "Size and protection", display = display.none)
float targetPips = input.float(40, "Take profit (PineConnector pips; 0 = omit)", minval = 0, group = "Size and protection", display = display.none)
string lotsText = str.tostring(lots, "0.########")
string stopText = str.tostring(stopPips, "0.########")
string targetText = str.tostring(targetPips, "0.########")
bool validLicense = str.length(licenseId) > 0 and str.match(licenseId, "^[0-9]+$") == licenseId
bool validSymbol = str.length(brokerSymbol) > 0 and not str.contains(brokerSymbol, ",") and not str.contains(brokerSymbol, "=") and not str.contains(brokerSymbol, " ") and not str.contains(brokerSymbol, "\n") and not str.contains(brokerSymbol, "\t")
bool validSecret = not str.contains(signalSecret, ",") and not str.contains(signalSecret, "=") and not str.contains(signalSecret, " ") and not str.contains(signalSecret, "\n") and not str.contains(signalSecret, "\t")
bool routingReady = validLicense and validSymbol and validSecret
bool sizeReady = lots > 0 and str.tonumber(lotsText) == lots and str.tonumber(stopText) == stopPips and str.tonumber(targetText) == targetPips
string entryFields = ",vol_lots=" + lotsText + (stopPips > 0 ? ",sl_pips=" + stopText : "") + (targetPips > 0 ? ",tp_pips=" + targetText : "")
string secretField = signalSecret == "" ? "" : ",secret=" + signalSecret
string buyMessage = licenseId + ",buy," + brokerSymbol + entryFields + secretField
string closeMessage = licenseId + ",closelong," + brokerSymbol + secretField
float ema = ta.ema(close, length)
bool crossedUp = ta.crossover(close, ema)
bool crossedDown = ta.crossunder(close, ema)
bool entrySignal = crossedUp and barstate.isconfirmed
bool exitSignal = crossedDown and barstate.isconfirmed
// Simulation remains active while external alert messages are disabled.
if entrySignal and strategy.position_size == 0
strategy.entry("Practice long", strategy.long, alert_message = buyMessage,
disable_alert = not (enableFillAlerts and routingReady and sizeReady))
if exitSignal and strategy.position_size > 0
strategy.close("Practice long", alert_message = closeMessage,
disable_alert = not (enableFillAlerts and routingReady))
plot(ema, title = "EMA", color = color.blue, linewidth = 2)
plotshape(entrySignal, title = "Entry condition", style = shape.triangleup,
location = location.belowbar, color = color.blue, size = size.small, text = "Entry")
plotshape(exitSignal, title = "Exit condition", style = shape.triangledown,
location = location.abovebar, color = color.orange, size = size.small, text = "Exit")
// Preview hides the secret. TradingView's simulated position is not broker feedback.
string displayLicense = licenseId == "" ? "LicenseID" : licenseId
string displaySymbol = brokerSymbol == "" ? "BrokerSymbol" : brokerSymbol
string hiddenSecret = signalSecret == "" ? "" : ",secret=[hidden]"
string buyPreview = displayLicense + ",buy," + displaySymbol + entryFields + hiddenSecret
string closePreview = displayLicense + ",closelong," + displaySymbol + hiddenSecret
string status = not enableFillAlerts ? "ORDER-FILL ALERTS OFF" : not routingReady ? "BLOCKED: check destination / secret format" : not sizeReady ? "ENTRY ALERT BLOCKED; close alerts remain enabled" : "ENABLED: future simulated fills can send broker instructions"
var preview = table.new(position.top_right, 1, 4, border_width = 1)
if barstate.islast
table.cell(preview, 0, 0, status, text_color = color.white, bgcolor = enableFillAlerts ? color.rgb(125, 45, 35) : color.rgb(30, 64, 100), text_size = size.normal)
table.cell(preview, 0, 1, "BUY MESSAGE (wrapped)\n" + str.replace_all(buyPreview, ",", ",\n"), text_color = color.black, bgcolor = color.white, text_halign = text.align_left, text_size = size.normal)
table.cell(preview, 0, 2, "CLOSE-BUY MESSAGE (wrapped)\n" + str.replace_all(closePreview, ",", ",\n"), text_color = color.black, bgcolor = color.rgb(240, 245, 250), text_halign = text.align_left, text_size = size.normal)
table.cell(preview, 0, 3, "Simulated quantity: " + str.tostring(strategy.position_size) + "\nNot the broker position. Start flat; recreate alerts after changes.", text_color = color.black, bgcolor = color.rgb(255, 246, 214), text_size = size.normal)
2

Save and inspect the chart

Save with Cmd+S / Ctrl+S or the cloud-shaped Save control. Use Update on chart if shown. If the strategy is not already on the chart, click Add to chart.

What you should see

The chart lists Pine practice: connect strategy and its message preview says ORDER-FILL ALERTS OFF.

The strategy can still draw simulated trades while its external messages are off. That is expected. The preview does not send a test order.

Connected strategy preview shows ORDER-FILL ALERTS OFF, placeholder messages and simulated quantity zero.
Enlarge screenshot
Check ORDER-FILL ALERTS OFF before activation. Simulated quantity is TradingView state; even when it reads 0, you must check the receiving broker account separately.

Check ORDER-FILL ALERTS OFF before activation. Simulated quantity is TradingView state; even when it reads 0, you must check the receiving broker account separately.

Connected strategy preview shows ORDER-FILL ALERTS OFF, placeholder messages and simulated quantity zero.

Hover over Pine practice: connect strategy in the chart’s indicator list, click its Settings gear, and open Inputs. Keep the enable switch unchecked while filling in the other fields.

Connected strategy Inputs show order-fill alerts unchecked and blank License ID, broker symbol and secret.
Enlarge screenshot
Keep order-fill alerts off while preparing the connection (1). Enter and review your own destination privately in these fields (2).

Keep order-fill alerts off while preparing the connection (1). Enter and review your own destination privately in these fields (2).

Connected strategy Inputs show order-fill alerts unchecked and blank License ID, broker symbol and secret.

The captured destination fields are blank deliberately. Enter your own values privately; neither the screenshot nor a placeholder identifies a valid receiving account.

Input What to enter or check
EMA length Start at 20 to match the practice rules.
License ID The ID for the intended demo connection. The source leaves this blank.
Exact broker symbol The receiving broker’s exact symbol, including suffix and case. This also starts blank.
Signal secret (only if required) Your configured Signal Authentication key when required. It is added to both entry and close messages.
Lots per entry Your chosen demo size in MetaTrader lots. 0.01 is an example default, not a universal broker minimum.
Stop loss (PineConnector pips; 0 = omit) A broker-valid protective distance. The example starts at 20; 0 omits the stop parameter.
Take profit (PineConnector pips; 0 = omit) A broker-valid target distance. The example starts at 40; 0 omits that parameter.
The connected strategy has a separate Lots per entry value of 0.01 and explicit stop/target inputs.
Enlarge screenshot
Lots per entry controls the message sent to MetaTrader (1). Review protection and its units separately (2). The displayed values are examples, not a broker-size recommendation.

Lots per entry controls the message sent to MetaTrader (1). Review protection and its units separately (2). The displayed values are examples, not a broker-size recommendation.

The connected strategy has a separate Lots per entry value of 0.01 and explicit stop/target inputs.

Click Ok and read the two preview rows on the chart. Check the action, destination symbol, lot size and protective distances. A supplied secret appears as [hidden] in the preview; the actual message uses the value you entered. Keep the saved script and its inputs private.

Zero means this script sends no corresponding field. It does not guarantee an unprotected new broker position: the receiving EA’s input-source settings may supply their own stop or target. Check Signal or EA inputs and the actual broker outcome. Omitting a field also does not remove protection from an existing position.

Match the market as well as the spelling. If the chart is BTCUSD, choose the corresponding broker market. Typing an unrelated symbol changes the request’s destination; it does not turn a Bitcoin condition into a signal calculated from that other market. If your broker has no suitable market, use a chart and broker symbol that correspond before continuing.

The format guards catch missing or malformed fields and numbers that would be rounded when converted to message text. They do not verify your License ID, authentication key, broker symbol, minimum lot size or stop distance. Review the actual Syntax reference and the account you are using.

TradingView event Attached message
The Practice long entry fills buy, the exact broker symbol, vol_lots=, any positive sl_pips= / tp_pips=, and the optional secret.
The matching simulated full close fills closelong, the exact broker symbol, and the optional secret.

alert_message is attached to both order calls. Their disable_alert arguments keep messages off until enabled and correctly formatted. An invalid entry size blocks entry messages; it does not suppress a close message whose destination is valid.

The TradingView ID Practice long links the simulated entry and close. PineConnector’s closelong command instead acts on matching broker buys within the receiving EA’s scope. It does not search MetaTrader for that Pine order ID. Review Magic Restriction and strategy separation before sharing a destination with other trading activity.

First inspect the behaviour checks in the next lesson. Keep the integration disabled until you can explain its entries, full closes, size and protective-stop behaviour.

3

Start with the intended scope flat

Read the preview’s Simulated quantity. If it is not 0, keep sending off while waiting for the strategy’s closing event. Separately inspect the actual demo account. The preview is not broker-position feedback.

What you should see

The strategy's simulated quantity is 0, and the receiving demo scope has no existing position to confuse with the test.

Use a dedicated empty demo scope. Do not assume an old or unrelated position belongs to this strategy.

4

Enable the reviewed message route

Return to Settings → Inputs, turn on Enable order-fill alerts, and click Ok. If the preview reports a blocked field, correct it before creating the alert.

What you should see

The preview says that future simulated fills can send broker instructions.

5

Select fills and the attached message

Open Create alert. Select Pine practice: connect strategy and Order fills only if an event selector is shown. A strategy with no alert() calls may omit that selector.

Open Message, replace its contents with the placeholder below, give the alert a recognisable demo name, then click Apply.

What you should see

The alert uses the strategy's order-fill messages rather than a generic description.

The complete order-fill message field
TradingView → Create alert → Message Text
{{strategy.order.alert_message}}
Strategy practice fills uses exactly the strategy.order.alert_message placeholder in its Message field.
Enlarge screenshot
Name the practice alert (1), replace the entire Message with {{strategy.order.alert_message}} (2), then Apply (3). Keep both opening and closing brace pairs.

Name the practice alert (1), replace the entire Message with {{strategy.order.alert_message}} (2), then Apply (3). Keep both opening and closing brace pairs.

Strategy practice fills uses exactly the strategy.order.alert_message placeholder in its Message field.

This picture is from the informational Strategy practice fills exercise. Use the same Message field and exact placeholder here, but choose the appropriate new name below for this connection test. The pictured name does not select an account or make an alert a demo alert.

Choose the same symbol and interval as the reviewed chart. For an initial message-only check, keep Webhook URL off, name the alert Strategy message review, and inspect a future entry and close in TradingView’s log. No broker outcome is established by that check.

For the connected demo test, pause the message-only alert first. Confirm the simulator and intended broker scope are flat, then create a fresh alert named PC strategy demo with the same reviewed inputs and order-fill placeholder. In Notifications, enable Webhook URL and use the destination from Verify your setup on demo. Follow that lesson’s account, symbol, size, protective-order and duplicate checks. Keep entry and automated-exit evidence separate; pausing after an entry stops later alert messages, so it does not also verify the strategy’s exit path. TradingView requires two-factor authentication for webhook alerts.

If an outcome differs, pause the alert and inspect the existing position and logs before repeating anything. Changing an input or switching the chart’s enable setting off does not update the already-running alert; use Update automation without duplicate alerts.

  1. In Alerts, pause Strategy message review, PC strategy demo, and any replacement you created for this exercise. Verify Stopped manually for each one. Leave unrelated alerts alone.
  2. Inspect the intended demo scope’s positions and history. Record whether the strategy’s close, a protective order or another action closed the test position. A paused alert cannot be relied on to send a later exit.
  3. If a course test position remains open, close that position through the broker interface as described in the demo cleanup, then confirm the result. Keep an unobserved automated exit recorded as pending; a manual cleanup is a different action.
  4. Open Pine practice: connect strategy → Settings → Inputs, uncheck Enable order-fill alerts, and click Ok. Check the saved-alert list again; the chart switch alone does not stop an older snapshot.

Start with a separate editable copy of the original, saved under a new name. For an open-source chart script, its Source code control opens the source; use Create a working copy when TradingView presents it. A protected script needs an author-provided alert route or no-code setup. TradingView’s source-access guide

Before adding messages, locate every order-producing call and write down the intended broker action. Only apply this example’s mapping directly when the original has the same simple market-entry/full-close behaviour. Keep the strategy’s conditions and calculations intact while adding its alert-message layer.

If the original uses… Resolve this before connecting it
Partial exits Map the requested partial quantity explicitly. A closelong message requests a full close of matching buys.
Limit/stop entries or cancellations Decide whether to mirror a simulated fill or place and manage a broker pending order. Those are different workflows.
Several entry IDs or pyramiding Identify which broker positions each entry and exit may affect. A Pine ID alone does not isolate a broker position.
Short entries or reversals Define the close/open sequence and size for each direction; this long-only source does not implement them.
Several License IDs Review every receiving account and duplicate route. Repeating a message creates another request.

If the code needs a language upgrade, do that separately. For a compiling v5 script, TradingView documents Manage script → Convert code to v6. Compare its behaviour after conversion; changing //@version alone is not a migration. For older versions, follow Convert Pine Script versions and the official v6 migration guide.

Your broker stop closes the demo buy, but TradingView still shows a simulated long position. Has strategy.position_size failed to update a live broker position?

Show the answer

No. It reports TradingView’s simulated position. The broker-side stop is separate from this strategy’s simulated exit rule. Pause and inspect the mismatch; the code has no broker feedback that can resynchronise the two positions.