Karan spent three months building the perfect EMA crossover strategy. He fine-tuned the parameters, walked through five years of Nifty data, optimised position sizing, and finally arrived at a backtest equity curve that made him feel something most retail traders rarely feel: confident. The strategy had a Sharpe above 1.8. Maximum drawdown was manageable. Win rate sat at 54%. The logic was clean, the Pine Script code compiled without errors, and every alert condition was wired up properly in TradingView.
Then the market opened. The crossover fired at 9:47 AM — a clean signal, exactly what the backtest flagged dozens of times. Karan was in a client call. He saw the TradingView notification at 9:53 AM, opened the chart, and the entry was already six points away. He placed the order anyway, stopped out two candles later, and closed the trade for a loss. The same signal that had returned 2.3R in the backtest returned negative 1.1R in live trading. Not because the strategy was wrong. Because TradingView cannot place orders. That is what OpenAlgo is for.
TL;DR
- Pine Script v6 lets you build fully dynamic alert message strings using
str.tostring()andsyminfo.*variables, so the same code generates exchange-ready JSON for any symbol - OpenAlgo exposes an
/api/v1/placesmartorder(and/placeorder) webhook endpoint that accepts that JSON and routes it to your connected broker - The critical field to get right is
exchange—NSEfor equities,NFOfor NSE futures and options,BSEfor BSE equities,BFOfor BSE F&O - Paper trading mode in OpenAlgo lets you test the full pipeline — TradingView → webhook → order log — before a single rupee is at risk
Before we start: does your current Pine Script strategy actually fire alerts on bar close, or does it re-paint during the candle? Take 30 seconds to check that before reading further — it changes everything about how you wire up the webhook.
What You'll Build
By the end of this tutorial you will have a working end-to-end automated trading pipeline. A Pine Script v6 strategy running on TradingView fires an alert. That alert carries a JSON payload. The payload is delivered via HTTPS webhook to OpenAlgo running on your machine (or a VPS). OpenAlgo validates the payload and places a real order with your connected broker.
| Component | Tool | Role | Where It Runs |
|---|---|---|---|
| Strategy logic | Pine Script v6 on TradingView | Generates signals and builds the alert JSON | TradingView cloud |
| Alert delivery | TradingView webhook | HTTP POSTs the JSON payload to your endpoint | TradingView cloud → your server |
| Order router | OpenAlgo | Receives webhook, validates JSON, calls broker API | Your machine or VPS |
| Order execution | Broker API (Zerodha, Fyers, Shoonya, etc.) | Receives the order instruction and places it in the market | Broker cloud |
The beauty of this system is that every component is stateless with respect to the others. TradingView does not care what happens after it fires the webhook. OpenAlgo does not care what indicator produced the signal. Your broker does not care that it came from a chart. Each layer does one job cleanly.
<!-- IMAGE BRIEF 1: Diagram showing the four-layer pipeline: TradingView chart → webhook arrow → OpenAlgo server → broker API → exchange. Use a clean horizontal flow with icons for each stage. Dark background, accent colours matching the site palette. Label each arrow with what is being transmitted (JSON payload, order request, order confirmation). -->
Step 1: Install and Configure OpenAlgo
OpenAlgo is an open-source Python application. It runs a local web server that exposes REST API endpoints — including the webhook endpoint your TradingView alerts will POST to.
- Visit the official OpenAlgo documentation at openalgo.in/docs and follow the installation guide for your operating system (Windows, macOS, or Linux).
- Clone the repository and install dependencies:
pip install -r requirements.txt - Copy the
.env.examplefile to.envand fill in your configuration — specifically your broker name, API key, API secret, and the port you want OpenAlgo to listen on (default is5000). - Connect your broker. Each broker has a slightly different OAuth or token flow. The OpenAlgo docs have dedicated pages for each supported broker. Follow the one for yours.
- Start the OpenAlgo server:
python app.py - Open a browser and navigate to
http://localhost:5000. You should see the OpenAlgo dashboard. If you see it, the server is running. - If you are running OpenAlgo on a remote VPS (which is recommended for reliability), note the public IP or domain name of your server — you will need this for the TradingView webhook URL.
OpenAlgo supports a growing list of Indian brokers including Zerodha (Kite), Fyers, Angel One, Shoonya, Flattrade, Firstock, and more. Check the broker list in the docs before assuming yours is supported.
At this point, you have a running order router. Here is the question to sit with before moving on: which broker account are you going to connect — your main live account, or a separate paper/test account? The answer determines what happens in Step 5.
Step 2: Understanding the OpenAlgo Order API JSON Format
OpenAlgo's /api/v1/placeorder endpoint expects a JSON body with specific fields. Every TradingView alert message you write must produce valid JSON that matches this schema exactly. One typo, one wrong field name, one incorrect exchange code — and the order does not get placed.
Here are the required fields:
| Field | Type | Example | Description |
|---|---|---|---|
apikey | string | "abc123xyz" | Your OpenAlgo API key, generated in the OpenAlgo dashboard under Settings |
strategy | string | "EMA Crossover v1" | A label for your strategy. Used in logs. Can be any string. |
symbol | string | "NIFTY25MARFUT" | The broker-specific symbol name. Must match exactly what your broker accepts. |
action | string | "BUY" or "SELL" | Direction of the order. Must be uppercase. |
exchange | string | "NSE" | The exchange code. See the warning below. |
pricetype | string | "MARKET" | Order type. Common values: MARKET, LIMIT, SL, SL-M |
product | string | "MIS" | Product type. MIS for intraday, CNC for delivery equity, NRML for F&O overnight |
quantity | integer | 75 | Number of units. For F&O, this is number of lots × lot size, or number of lots depending on broker. |
A minimal valid JSON payload looks like this:
json{ "apikey": "your_openalgo_api_key", "strategy": "EMA Crossover v1", "symbol": "RELIANCE", "action": "BUY", "exchange": "NSE", "pricetype": "MARKET", "product": "MIS", "quantity": "1" }
Common mistake: using "exchange": "NSE" for futures and options trades.
NSE refers to the NSE cash equity segment. If you are trading Nifty futures, Bank Nifty options, or any NSE-listed derivative, the correct exchange code is "NFO" (NSE Futures and Options). Using NSE for an F&O symbol will cause the order to fail or route to the wrong segment. Similarly, for BSE derivatives use "BFO", not "BSE". For MCX commodities, use "MCX".
Step 3: Writing the Pine Script v6 Strategy with Dynamic Alert Messages
This is the core of the tutorial. Pine Script v6 introduced proper string interpolation and a cleaner alert() function signature. We will use str.tostring() to embed runtime values — the symbol name, action, and quantity — directly into the alert message JSON string.
The strategy below is a simple EMA crossover: go long when the 9 EMA crosses above the 21 EMA, exit and go short when it crosses below. The key insight is that the alert() call constructs a complete JSON string at runtime, using syminfo.ticker to automatically pick up whatever symbol the chart is showing.
pine//@version=6 strategy( title = "EMA Crossover → OpenAlgo v6", shorttitle = "EMA-OA", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1, initial_capital = 100000, currency = currency.INR ) // ── Inputs ────────────────────────────────────────────────────────────────── emaFast = input.int(9, "Fast EMA Period", minval = 1) emaSlow = input.int(21, "Slow EMA Period", minval = 1) apiKey = input.string("YOUR_OPENALGO_API_KEY", "OpenAlgo API Key") stratName = input.string("EMA Crossover v1", "Strategy Name") exchange = input.string("NSE", "Exchange", options = ["NSE", "BSE", "NFO", "BFO", "MCX", "CDS"]) product = input.string("MIS", "Product", options = ["MIS", "CNC", "NRML"]) priceType = input.string("MARKET", "Price Type", options = ["MARKET", "LIMIT", "SL", "SL-M"]) qty = input.int(1, "Quantity", minval = 1) // ── Indicators ─────────────────────────────────────────────────────────────── fastEma = ta.ema(close, emaFast) slowEma = ta.ema(close, emaSlow) plot(fastEma, color = color.new(color.blue, 0), linewidth = 1, title = "Fast EMA") plot(slowEma, color = color.new(color.orange, 0), linewidth = 1, title = "Slow EMA") // ── Signal conditions ──────────────────────────────────────────────────────── longCondition = ta.crossover(fastEma, slowEma) shortCondition = ta.crossunder(fastEma, slowEma) // ── Strategy entries/exits ─────────────────────────────────────────────────── if longCondition strategy.entry("Long", strategy.long) if shortCondition strategy.entry("Short", strategy.short) // ── Build OpenAlgo JSON alert strings ─────────────────────────────────────── // We construct the JSON manually as a string. // str.tostring() converts numeric inputs to strings for embedding. buyAlertMsg = '{' + '"apikey":"' + apiKey + '",' + '"strategy":"' + stratName + '",' + '"symbol":"' + syminfo.ticker + '",' + '"action":"BUY",' + '"exchange":"' + exchange + '",' + '"pricetype":"' + priceType + '",' + '"product":"' + product + '",' + '"quantity":"' + str.tostring(qty) + '"' + '}' sellAlertMsg = '{' + '"apikey":"' + apiKey + '",' + '"strategy":"' + stratName + '",' + '"symbol":"' + syminfo.ticker + '",' + '"action":"SELL",' + '"exchange":"' + exchange + '",' + '"pricetype":"' + priceType + '",' + '"product":"' + product + '",' + '"quantity":"' + str.tostring(qty) + '"' + '}' // ── Fire alerts ────────────────────────────────────────────────────────────── if longCondition alert(buyAlertMsg, alert.freq_once_per_bar_close) if shortCondition alert(sellAlertMsg, alert.freq_once_per_bar_close)
A few things to notice in this code:
syminfo.tickerresolves at runtime to the ticker symbol of the chart the strategy is applied to. If you put this onRELIANCEon NSE, it outputsRELIANCE. If you apply it to a Nifty futures chart, it outputs the current futures symbol. You still need to make sure theexchangeinput matches.str.tostring(qty)converts the integer input to a string for embedding in the JSON. Without this, Pine Script will throw a type error when concatenating.alert.freq_once_per_bar_closeis critically important — it ensures the alert fires only once per completed bar, not on every tick. More on this in Step 4.- The
apiKeyis entered as a script input. This is convenient but means it will appear in the alert message. Do not share screenshots of your alert messages publicly.
Here is something worth reflecting on: if you apply this script to a chart with a different symbol than you intended, the syminfo.ticker will silently change. Is that the behaviour you want — or do you need a hard-coded symbol per alert? For single-symbol strategies, consider hard-coding the symbol string to avoid accidental misfires on the wrong instrument.
Step 4: Setting Up the TradingView Webhook Alert
Once your Pine Script strategy is added to the chart and you have confirmed it compiles and shows signals, you set up the TradingView alert that will deliver the payload to OpenAlgo.
- Open TradingView and navigate to the chart where your EMA Crossover strategy is running.
- Click the Alert icon in the right toolbar (the clock/bell icon), or press
Alt + A. - In the Condition dropdown, select your strategy name:
EMA Crossover → OpenAlgo v6. - Set the condition trigger to Order fills — this fires the alert whenever the strategy fires an
entryorexit. - Scroll down to Alert actions and enable Webhook URL.
- In the Webhook URL field, enter your OpenAlgo endpoint:
https://your-ngrok-url.ngrok.io/api/v1/placeorder
- If running on a VPS with a domain: https://yourdomain.com/api/v1/placeorder
- Note: TradingView webhooks require HTTPS. Plain HTTP URLs will be rejected.
- In the Message field, paste exactly this — and nothing else:
{{strategy.order.alert_message}}
alert() message string that your Pine Script constructed, rather than the default alert message.
- Set Expiration to a date far in the future, or select Open-ended.
- Give the alert a descriptive name, e.g.,
EMA Crossover RELIANCE NSE → OpenAlgo. - Click Create.
Pro tip: always use "Once Per Bar Close" as your alert frequency for strategy-based signals. TradingView evaluates Pine Script on every price tick during a live bar, which means conditions can temporarily appear true and then become false before the bar closes. If your alert frequency is set to fire on every occurrence, you risk sending multiple order signals — and multiple broker orders — for what should be a single entry. The alert.freq_once_per_bar_close constant in Pine Script code, combined with setting the TradingView alert condition to "Once Per Bar Close", creates two layers of protection against duplicate orders.
<!-- IMAGE BRIEF 2: Screenshot mockup of the TradingView alert creation dialog. Show the Condition field with the strategy selected, the Webhook URL field filled in (use a placeholder URL), and the Message field containing {{strategy.order.alert_message}}. Annotate each field with a numbered callout matching the steps above. -->
Step 5: Testing Without Real Money
Before a single live order is placed, you need to verify that the full pipeline works. OpenAlgo supports a paper trading mode that logs incoming webhook payloads and simulates order placement without sending anything to your broker.
Enabling paper trading mode:
In your OpenAlgo .env file, set PAPER_TRADING=True. Restart the OpenAlgo server. In paper mode, all order requests are validated, logged, and returned with a simulated success response — but no real API call is made to your broker.
Verifying the webhook is received:
- With OpenAlgo running in paper mode, fire a test alert manually from TradingView. You can do this by temporarily setting the alert condition to something that is currently true on the chart, or by using TradingView's "Test alert" button if available.
- Open the OpenAlgo log file (typically
logs/openalgo.login the installation directory) or watch the terminal output. - You should see a log line showing the received JSON payload, followed by a validation result, followed by the simulated order response.
What to check in the logs:
- Does the incoming JSON match what you built in Pine Script?
- Is the
symbolfield the exact broker symbol (not a TradingView-specific format)? - Is the
exchangefield correct for the instrument? - Is the
apikeyfield matching your OpenAlgo API key?
Common log messages and what they mean:
Order received: valid— JSON was parsed and all required fields are presentSymbol not found— the symbol string does not match what your broker expectsInvalid API key— the apikey field does not match the one in OpenAlgo settingsExchange mismatch— the exchange code is wrong for the symbol type
Only move to live trading after at least one complete test cycle in paper mode — from TradingView alert firing through to a clean simulated order log in OpenAlgo.
Real Tradeoffs
No system is without compromise. Here are the three honest tradeoffs you are making with this architecture:
| Choice | Upside | Downside |
|---|---|---|
| Dynamic alert messages (Pine Script builds the JSON string) vs Static alert message (fixed JSON pasted in TradingView alert box) | Dynamic messages adapt automatically to any symbol and parameter changes in the script input | Slightly more complex Pine Script code; the API key is embedded in the alert message string |
| TradingView webhooks vs direct broker API from a custom server | Zero infrastructure required on the signal generation side; TradingView handles chart logic, backtesting, and alerting | Webhook delivery is not guaranteed; TradingView's webhook infrastructure can occasionally delay or drop alerts; you depend on TradingView's uptime |
Pine Script strategy (with strategy.entry/exit) vs Pine Script indicator (with standalone alertcondition()) | Strategy tracks position state, prevents duplicate entries, and gives you backtesting built-in | Strategy calculations can differ between backtest and live bar due to calc_on_every_tick vs calc_on_bar_close behaviour; indicators with alertcondition() are simpler but have no built-in position tracking |
Tradeoff reflection: given that TradingView webhook delivery is not guaranteed, what is your fallback if an alert is missed during a high-volatility event? Think about this before going live. Some traders run a parallel manual monitor during the first few weeks.
And the harder question: are you confident your backtest parameters — especially the EMA periods — were not curve-fitted to the historical data you tested on? If you are not sure, forward-test in paper mode for at least 20-30 signals before going live.
Choose Your Scenario
Scenario A: Simple strategy — same symbol, fixed quantity every time
This is the right starting point for most traders. You trade one symbol (say, RELIANCE on NSE), always take the same quantity (say, 5 shares), and always use market orders for intraday.
In this case, you can simplify the Pine Script code: hard-code the symbol, exchange, and quantity rather than using inputs. This reduces the risk of accidentally changing an input and firing a wrong order. Your alert JSON is small and predictable.
Use /api/v1/placeorder (the simple order endpoint) rather than /api/v1/placesmartorder. The smart order endpoint is designed for strategies that need to track net position — it is more powerful but also more complex to configure correctly.
Scenario B: Advanced — dynamic quantity based on ATR/volatility, multiple symbols
Once you are comfortable with Scenario A, you can extend the system. Dynamic position sizing based on ATR is a common technique: you calculate how many shares to buy so that a 1 ATR move equals a fixed rupee risk per trade.
In Pine Script, you calculate the quantity:
pineatrPeriod = input.int(14, "ATR Period") riskPerTrade = input.float(5000, "Risk Per Trade (₹)") atrValue = ta.atr(atrPeriod) dynamicQty = math.floor(riskPerTrade / atrValue)
Then embed str.tostring(dynamicQty) in the JSON payload instead of the fixed qty input. The quantity will now vary bar-to-bar based on market volatility. For multi-symbol strategies, use syminfo.ticker dynamically and ensure your exchange input is set correctly for each chart the strategy is applied to.
For these advanced scenarios, use /api/v1/placesmartorder and configure the position_size parameter so OpenAlgo can manage net position state correctly.
<!-- IMAGE BRIEF 3: Side-by-side comparison graphic. Left panel shows "Scenario A: Simple" with a minimal JSON block (5 fields, fixed values). Right panel shows "Scenario B: Advanced" with a JSON block including a dynamically calculated quantity. Use a light code-editor aesthetic with syntax highlighting. Label each panel clearly. -->
5-Minute Troubleshooting Framework
When something breaks, follow this flowchart before changing anything in your Pine Script or OpenAlgo configuration. Most problems are diagnosed within 3-4 decision points.
The most common failure points in order of frequency:
- Webhook URL typo or HTTP instead of HTTPS — TradingView silently rejects non-HTTPS webhook URLs
- Wrong exchange code —
NSEvsNFOis the single most common JSON error in Indian broker setups - OpenAlgo not running — if the server is not up, there is nothing to receive the webhook
- Symbol format mismatch —
NIFTY25MARFUTon TradingView may need to be formatted differently for your specific broker's API (check the OpenAlgo broker-specific docs) - Expired broker session — most broker APIs require re-authentication daily; OpenAlgo handles this for many brokers but check your broker's token expiry
Never run live alerts on a strategy that has only been backtested and never forward-tested in paper mode. Backtesting in Pine Script executes on closed historical bars. Live execution fires on real-time ticks, which means the bar you are currently in has not closed yet. Signals that look clean in a backtest can behave differently at the open of a live bar — especially intraday strategies on high-volatility instruments. The time between "backtest looks good" and "this is ready for live money" should include a minimum of 2-4 weeks of paper trading with the exact same alert setup, not just the strategy logic in the Pine Script editor's strategy tester.
Mini-Exercise: Build Your Own Alert JSON
Before you write a single line of Pine Script for your own strategy, fill in this template by hand. This forces you to think through every field before the code is written — and it becomes your reference when debugging.
My strategy name: [e.g., "RSI Reversal Scalper"]
Symbol: [e.g., BANKNIFTY25MARFUT]
Exchange: [NSE / NFO / BSE / BFO / MCX / CDS]
Action: [BUY / SELL]
Quantity: [number — if F&O, is this lots or shares?]
Product: [MIS / CNC / NRML]
Price type: [MARKET / LIMIT / SL / SL-M]
My OpenAlgo API key: [paste from OpenAlgo dashboard — keep this private]
Completed JSON payload:
{
"apikey": "[your key]",
"strategy": "[your strategy name]",
"symbol": "[your symbol]",
"action": "BUY",
"exchange": "[your exchange]",
"pricetype": "[your price type]",
"product": "[your product]",
"quantity": "[your quantity]"
}
Do this for both BUY and SELL before touching TradingView.
Here is what separates traders who get this pipeline running from those who spend two weeks debugging: the traders who succeed write the JSON template first and test it against the OpenAlgo API directly (using Postman or curl) before writing any Pine Script. Do you have Postman or a similar API testing tool installed?
And once you do have it working: what does your exit strategy look like? The Pine Script above enters on crossover and reverses on crossunder — but does your strategy require a separate exit signal, a fixed stop loss, or a trailing stop? If you need a trailing stop, that logic needs to live in Pine Script, not in OpenAlgo.
Lead Magnet: Pine Script → OpenAlgo Alert Template Pack
Five ready-to-paste Pine Script alert() message templates for common strategies. Copy the one that matches your setup, replace the placeholder values, and you are ready to connect to OpenAlgo.
Template 1: EMA Crossover (Equity Intraday)
pinealert('{"apikey":"YOUR_KEY","strategy":"EMA Cross","symbol":"' + syminfo.ticker + '","action":"BUY","exchange":"NSE","pricetype":"MARKET","product":"MIS","quantity":"' + str.tostring(qty) + '"}', alert.freq_once_per_bar_close)
Template 2: RSI Reversal (F&O)
pinealert('{"apikey":"YOUR_KEY","strategy":"RSI Reversal","symbol":"NIFTY25MARFUT","action":"BUY","exchange":"NFO","pricetype":"MARKET","product":"NRML","quantity":"75"}', alert.freq_once_per_bar_close)
Template 3: Supertrend (Equity Delivery)
pinealert('{"apikey":"YOUR_KEY","strategy":"Supertrend","symbol":"' + syminfo.ticker + '","action":"BUY","exchange":"NSE","pricetype":"MARKET","product":"CNC","quantity":"' + str.tostring(qty) + '"}', alert.freq_once_per_bar_close)
Template 4: Breakout (Dynamic Limit Order)
pinealert('{"apikey":"YOUR_KEY","strategy":"Breakout","symbol":"' + syminfo.ticker + '","action":"BUY","exchange":"NSE","pricetype":"LIMIT","price":"' + str.tostring(close) + '","product":"MIS","quantity":"' + str.tostring(qty) + '"}', alert.freq_once_per_bar_close)
Template 5: VWAP Bounce (Intraday Equity)
pinealert('{"apikey":"YOUR_KEY","strategy":"VWAP Bounce","symbol":"' + syminfo.ticker + '","action":"BUY","exchange":"NSE","pricetype":"MARKET","product":"MIS","quantity":"' + str.tostring(qty) + '"}', alert.freq_once_per_bar_close)
For each template: replace YOUR_KEY with your actual OpenAlgo API key, adjust symbol and exchange for your instrument, and set quantity to your desired position size.
Comment below: which Pine Script strategy are you connecting to OpenAlgo, and what is the one field in the JSON payload that confused you most? Drop the strategy name and the confusing field — I will add a dedicated troubleshooting section to this post based on your answers.
Keep Learning
- Next: OpenAlgo Webhooks + TradingView: Fire Real Broker Orders From Pine Script Alerts → /blog/post.php?slug=openalgo-webhook-tradingview
- Then: Pine Script v6 New Features: What Changed and Why It Matters → /blog/post.php?slug=pine-script-v6-new-features
- Also: Build a No-Code Trading Pipeline with n8n + OpenAlgo → /blog/post.php?slug=n8n-openalgo-trading-workflow
FAQ
Q1: Does OpenAlgo work with brokers outside India?
OpenAlgo is primarily designed for Indian retail brokers and the Indian exchange ecosystem (NSE, BSE, NFO, BFO, MCX, CDS). As of early 2026, the supported broker list is focused on Indian markets. If you are trading internationally, you would need to either modify OpenAlgo's broker connectors or use an alternative webhook-to-broker pipeline such as Alpaca, Interactive Brokers TWS with a webhook bridge, or a custom Flask/FastAPI server. Check the OpenAlgo GitHub repository for the current broker list before assuming your broker is supported.
Q2: Can I use this with a Pine Script indicator instead of a strategy?
Yes. Instead of using strategy.entry() and strategy.exit(), you write your conditions as booleans and use alertcondition() to register named alert conditions. Then in TradingView's alert dialog, you select the indicator and the specific condition name instead of "Order fills". The JSON message in the TradingView alert box needs to be static (or you use a fixed template), since alertcondition() does not support the {{strategy.order.alert_message}} placeholder. You can use other TradingView placeholders like {{ticker}}, {{exchange}}, and {{close}} inside the TradingView alert message box directly.
Q3: What happens if TradingView fires a duplicate alert on the same candle?
If you use alert.freq_once_per_bar_close in your Pine Script alert() call, Pine Script will only fire the alert once per completed bar — this is the first layer of protection. The second layer is setting the alert frequency to "Once Per Bar Close" in TradingView's alert creation dialog. If both are set correctly, duplicate alerts within the same bar should not occur. However, if you are using alert.freq_all or "Every time condition is met", the alert can fire multiple times per bar, and OpenAlgo will receive and act on each one. This can result in multiple orders for the same signal.
Q4: The {{strategy.order.alert_message}} placeholder is empty in my alert. Why?
This placeholder is only populated when you use alert() with a message string in your Pine Script code — as shown in Step 3. If your strategy uses strategy.entry() without a corresponding alert() call, the placeholder will be empty. Make sure you have both the strategy.entry() call and the alert(buyAlertMsg, ...) call in the same if block. Also confirm that the strategy has been re-saved and re-applied to the chart after adding the alert() calls — TradingView does not automatically update alerts based on script changes.
Q5: Can I pass a dynamic price for limit orders?
Yes. You can embed the current close price (or any calculated price level) in the JSON payload using str.tostring(close) or str.tostring(your_price_variable). Add a "price" field to your JSON string in Pine Script and include the calculated value. For example: '"price":"' + str.tostring(close) + '",'. OpenAlgo will pass this to your broker's limit order API. Make sure your broker's API supports the price field in the order payload — check the OpenAlgo documentation for your specific broker connector.
Do This Next
- Install OpenAlgo and confirm the dashboard loads at
http://localhost:5000 - Connect your broker using the broker-specific guide in the OpenAlgo docs
- Enable paper trading mode (
PAPER_TRADING=Truein.env) and restart the server - Add the EMA Crossover Pine Script v6 strategy from Step 3 to a TradingView chart
- Fill in the mini-exercise JSON template for your specific instrument before touching TradingView alerts
- Create the TradingView webhook alert pointing to your OpenAlgo endpoint, using
{{strategy.order.alert_message}}as the message - Fire a test alert (wait for a crossover signal or temporarily lower the EMA periods to trigger one) and verify the payload appears in the OpenAlgo logs
- Confirm the logged JSON matches your template exactly — check every field, especially
exchangeandsymbol - Run at least 5 paper trades end-to-end (signal → webhook → log → simulated order) before switching
PAPER_TRADINGtoFalse
This post is educational only. Nothing here is financial advice. Algorithmic trading involves significant risk. Always forward-test in paper mode before trading with real capital.
Be the first to comment