TradingView
TradingView is a social network of 30 million traders and investors using the world's best charts and tools to spot trading opportunities across global markets.
How To Build A Trading Bot From Any TradingView Strategy In Your Broker Using TradersPost
The TradersPost webhook system lets you easily integrate alerts from platforms like TradingView with TradersPost. Webhooks can receive JSON like the following.
{
"ticker": "TSLA",
"action": "buy",
"price": "420.69"
}
This JSON data structure is very important and it must be 100% correct otherwise TradersPost will not be able to parse the data out of the JSON in order to use the information correctly.
You can dynamically send the values in the above JSON using TradingView variables. You can read more about TradingView variables here.
Using Pine Script strategies as opposed to indicators or studies is the best way to build automated trading strategies that work well with systems like TradersPost.
The Pine Script code of a strategy will have a line at the top of the code which calls the function
strategy()
strategy("My TradersPost Strategy", overlay=true)
If you build your Pine Script as a strategy, you only need one alert per ticker, and you can use the following JSON for the alert.
{
"ticker": "{{ticker}}",
"action": "{{strategy.order.action}}",
"sentiment": "{{strategy.market_position}}",
"quantity": "{{strategy.order.contracts}}",
"price": "{{close}}"
}
TradingView will replace the
{{...}}
values dynamically with a real value when the alert gets sent to TradersPost.- {{ticker}} - the ticker the alert is setup on
- {{strategy.order.action}} - buy or sell
- {{strategy.market_position}} - long, short or flat. This value tells TradersPost what the state of the position should be after executing the
- {{strategy.order.contracts}} - the quantity of the order executed
- {{close}} - the current price at the time the alert was triggered
You can alternatively use a Pine Script indicator instead of a strategy to send signals to TradersPost.
The Pine Script of an indicator will have a line at the top of the code which calls the function
indicator()
indicator("My TradersPost Indicator", overlay=true)
With an indicator, you have to setup separate buy and sell alerts per ticker. Your code should have multiple calls to the
alertcondition()
function.alertcondition(tradersPostBuy, title="TradersPost Buy")
alertcondition(tradersPostSell, title="TradersPost Sell")
Then you can copy and paste the following JSON snippets in to the alert message in TradingView.
{
"ticker": "{{ticker}}",
"action": "buy",
"price": "{{close}}"
}
{
"ticker": "{{ticker}}",
"action": "exit",
"price": "{{close}}"
}
You can also use the sentiment field to exit a bullish position without entering a bearish position on the other side. When you send sentiment=flat, it will always exit the full quantity of the open position.
{
"ticker": "{{ticker}}",
"action": "sell",
"sentiment": "flat",
"price": "{{close}}"
}
{
"ticker": "{{ticker}}",
"action": "sell",
"price": "{{close}}"
}
{
"ticker": "{{ticker}}",
"action": "exit",
"price": "{{close}}"
}
You can also use the sentiment field to exit a bearish position without entering a bullish position on the other side.
When you send sentiment=flat, it will always exit the full quantity of the open position.
{
"ticker": "{{ticker}}",
"action": "buy",
"sentiment": "flat",
"price": "{{close}}"
}
The values inside of the {{ and }} will be dynamically replaced by TradingView when the alert triggers.
When you create an alert in TradingView, you only need to enter the above JSON in the Message field and the URL of your webhook in the Webhook URL field. Here is a screenshot of a simple example that would send a signal to buy SQ when the price crosses above 241.94.

TradingView plain manually configured alert webhook.
This is a simple example to demonstrate the basics of how you can integrate TradingView alerts with TradersPost but the same principals apply if you are doing something more advanced with a Pine Script indicator. Continue reading to learn how you can integrate your Pine Script indicators and alerts with TradersPost.

TradersPost WebhookMessage Library - Automatically Build JSON by TradersPostInc
TradingView
View the WebhookMessage Library
To make it easier to write strategies with the alert messages automatically constructed in valid JSON, we have written the WebhookMessage Library that allows you to pass along your parameters and it will build the JSON for you.
You can add the library to your favorites and then import the library into your Pine Script strategies and indicators.
There are several different ways that you can build strategies in TradingView from studies that are purely visual indicators to strategies that can be backtested.
Sometimes you may want to hook up a strategy to TradersPost that was built by someone else and you do not have the ability to modify the Pine Script. You can easily send alerts from existing strategies and send the alerts as webhooks to TradersPost.
Just send the following JSON in the alert message to TradersPost.
{
"ticker": "{{ticker}}",
"action": "{{strategy.order.action}}",
"sentiment": "{{strategy.market_position}}",
"quantity": "{{strategy.order.contracts}}",
"price": "{{close}}"
}
Here is an example where the JSON for the alert message is defined in the Pine Script strategy itself and passed to the
alert_message
parameter in functions like strategy.entry()
.// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradersPostInc
//@version=5
strategy('TradersPost Example MOMO Strategy', overlay=true)
ema8 = ta.ema(close, 8)
ema21 = ta.ema(close, 21)
isUptrend = ema8 >= ema21
isDowntrend = ema8 <= ema21
trendChanging = ta.cross(ema8, ema21)
tradersPostBuy = trendChanging and isUptrend
tradersPostSell = trendChanging and isDowntrend
buyAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "buy", "price": ' + str.tostring(close) + '}'
sellAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "sell", "price": ' + str.tostring(close) + '}'
if tradersPostBuy
strategy.entry("Long", strategy.long, alert_message = buyAlertMessage)
if tradersPostSell
strategy.close("Long", when = open[0], alert_message = sellAlertMessage)
Then when you are setting up the alert for your strategy you can put the following code in the
Alert Message
text area in TradingView.{{strategy.order.alert_message}}
Here is a much more complex version of the above strategy with many more features implemented. It has the following additional features implemented.
- Both long and short trades
- Long and short take profit and stop losses
- Configure EMA length
- Configure backtest time window
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradersPostInc
//@version=5
strategy('TradersPost Example MOMO Strategy', overlay=true, default_qty_value=100, initial_capital=100000, default_qty_type=strategy.percent_of_equity, pyramiding=0)
startTime = input.time(defval = timestamp('01 Jan 2021 00:00 +0000'), title = 'Start Time', group = 'Date Range')
endTime = input.time(defval = timestamp('31 Dec 2023 23:59 +0000'), title = 'End Time', group = 'Date Range')
timeCondition = time >= startTime and time < endTime
timeConditionEnd = timeCondition[1] and not timeCondition
fastEmaLength = input.int(defval = 8, title = 'Fast EMA Length')
slowEmaLength = input.int(defval = 21, title = 'Slow EMA Length')
sides = input.string(defval = 'Both', title = 'Sides', options = ['Long', 'Short', 'Both', 'None'])
fastEma = ta.ema(close, fastEmaLength)
slowEma = ta.ema(close, slowEmaLength)
isUptrend = fastEma >= slowEma
isDowntrend = fastEma <= slowEma
trendChanging = ta.cross(fastEma, slowEma)
ema105 = request.security(syminfo.tickerid, '30', ta.ema(close, 105)[1], barmerge.gaps_off, barmerge.lookahead_on)
ema205 = request.security(syminfo.tickerid, '30', ta.ema(close, 20)[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(ema105, linewidth=4, color=color.new(color.purple, 0), editable=true)
plot(ema205, linewidth=2, color=color.new(color.purple, 0), editable=true)
aa = plot(fastEma, linewidth=3, color=color.new(color.green, 0), editable=true)
bb = plot(slowEma, linewidth=3, color=color.new(color.red, 0), editable=true)
fill(aa, bb, color=isUptrend ? color.green : color.red, transp=90)
tradersPostBuy = trendChanging and isUptrend and timeCondition
tradersPostSell = trendChanging and isDowntrend and timeCondition
pips = syminfo.pointvalue / syminfo.mintick
percentOrPipsInput = input.string('Percent', title='Percent or Pips', options=['Percent', 'Pips'])
stopLossLongInput = input.float(defval=0, step=0.01, title='Stop Loss Long', minval=0)
stopLossShortInput = input.float(defval=0, step=0.01, title='Stop Loss Short', minval=0)
takeProfitLongInput = input.float(defval=0, step=0.01, title='Target Profit Long', minval=0)
takeProfitShortInput = input.float(defval=0, step=0.01, title='Target Profit Short', minval=0)
stopLossPriceLong = ta.valuewhen(tradersPostBuy, close, 0) * (stopLossLongInput / 100) * pips
stopLossPriceShort = ta.valuewhen(tradersPostSell, close, 0) * (stopLossShortInput / 100) * pips
takeProfitPriceLong = ta.valuewhen(tradersPostBuy, close, 0) * (takeProfitLongInput / 100) * pips
takeProfitPriceShort = ta.valuewhen(tradersPostSell, close, 0) * (takeProfitShortInput / 100) * pips
takeProfitALong = takeProfitLongInput > 0 ? takeProfitLongInput : na
takeProfitBLong = takeProfitPriceLong > 0 ? takeProfitPriceLong : na
takeProfitAShort = takeProfitShortInput > 0 ? takeProfitShortInput : na
takeProfitBShort = takeProfitPriceShort > 0 ? takeProfitPriceShort : na
stopLossALong = stopLossLongInput > 0 ? stopLossLongInput : na
stopLossBLong = stopLossPriceLong > 0 ? stopLossPriceLong : na
stopLossAShort = stopLossShortInput > 0 ? stopLossShortInput : na
stopLossBShort = stopLossPriceShort > 0 ? stopLossPriceShort : na
takeProfitLong = percentOrPipsInput == 'Pips' ? takeProfitALong : takeProfitBLong
stopLossLong = percentOrPipsInput == 'Pips' ? stopLossALong : stopLossBLong
takeProfitShort = percentOrPipsInput == 'Pips' ? takeProfitAShort : takeProfitBShort
stopLossShort = percentOrPipsInput == 'Pips' ? stopLossAShort : stopLossBShort
buyAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "buy", "price": ' + str.tostring(close) + '}'
sellAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "sell", "price": ' + str.tostring(close) + '}'
exitLongAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "price": ' + str.tostring(close) + '}'
exitShortAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "price": ' + str.tostring(close) + '}'