Library · Pine Script v5 · Library

WebhookMessageLibrary

by TradersPost

WebhookMessageLibrary is a helper library designed to construct structured JSON payload messages for automated trading integrations like TradersPost.

View on GitHub

GitHub stars6on the repository
Pine versionv5runs as is
Lines of code161
Settings0inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago20 Dec 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

161 lines of Pine Script v5 from libraries/WebhookMessageLibrary.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

WebhookMessageLibrary.pinescript
// 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 

// @description The webhook message library provides several functions for building JSON payloads 
library("WebhookMessageLibrary", overlay = true)

// @type Constants for payload values.
// @field <string> ACTION_BUY buy - Exit bearish position and optionally open bullish position. Used in webhookMessage.action.
// @field <string> ACTION_SELL sell - Exit bullish position and optionally open bearish position. Used in webhookMessage.action.
// @field <string> ACTION_EXIT exit - Exit open position without entering a new position on the other side. Used in webhookMessage.action.
// @field <string> ACTION_CANCEL cancel - Cancel open orders. Used in webhookMessage.action.
// @field <string> ACTION_ADD add - Add to existing open position. Used in webhookMessage.action.
// @field <string> SENTIMENT_BULLISH bullish - Open position after trade is executed should be bullish or flat. Used in webhookMessage.sentiment.
// @field <string> SENTIMENT_BEARISH bearish - Open position after trade is executed should be bearish or flat. Used in webhookMessage.sentiment.
// @field <string> SENTIMENT_FLAT flat - No position should be open after trade is executed. Used in webhookMessage.sentiment.
// @field <string> Stop loss type of market stop. Used in stopLossMessage.type.
// @field <string> Stop loss type of limit stop. Used in stopLossMessage.type.
// @field <string> Stop loss type of trailing stop. Used in stopLossMessage.type.
export type CONSTANTS
    ACTION_BUY                   = "buy"
    ACTION_SELL                  = "sell"
    ACTION_EXIT                  = "exit"
    ACTION_CANCEL                = "cancel"
    ACTION_ADD                   = "add"
    SENTIMENT_BULLISH            = "bullish"
    SENTIMENT_BEARISH            = "bearish"
    SENTIMENT_LONG               = "long"
    SENTIMENT_SHORT              = "short"
    SENTIMENT_FLAT               = "flat"
    STOP_LOSS_TYPE_STOP          = "stop"
    STOP_LOSS_TYPE_STOP_LIMIT    = "stop_limit"
    STOP_LOSS_TYPE_TRAILING_STOP = "trailing_stop"

// @type Final webhook message.
// @field <string> ticker The ticker symbol name. Example: SPY.
// @field <string> action The signal action. Supported values are buy, sell, exit, cancel or add.
// @field <string> sentiment bullish, bearish, or flat.
// @field <float> price The price of the buy or sell action. If you omit this value, the current market price will be used when the trade is executed.
// @field <int> quantity The quantity to enter. If you omit this value, the quantity will be dynamically calculated or defaulted to 1.
// @field <takeProfitMessage> takeProfit. See takeProfitMessage.
// @field <stopLossMessage> stopLoss. See stopLossMessage.
export type webhookMessage
    string ticker
    string action 
    string sentiment
    float price
    int quantity
    string takeProfit = ""
    string stopLoss = ""

// @type Take profit message.
// @field <string> limitPrice Absolute limit price calculated on the webhook sender side.
// @field <float> percent Relative percentage take profit to calculate relative to entry price. The entry price for market orders is estimated based on the mid point between the bid and ask on the most recent quote.
// @field <float> amount Relative dollar amount take profit to calculate relative to entry price. The entry price for market orders is estimated based on the mid point between the bid and ask on the most recent quote.
export type takeProfitMessage
    float limitPrice
    float percent
    float amount

// @type Stop loss message.
// @field <string> type Type of stop loss. If a value is provided, it overrides the stop loss type configured in strategy subscription settings. Allowed values are: stop, stop_limit, trailing_stop.
// @field <float> percent Relative percentage stop loss to calculate relative to entry price.
// @field <float> amount Relative dollar amount stop loss to calculate relative to entry price.
// @field <float> stopPrice Absolute stop price calculated on the webhook sender side.
// @field <float> limitPrice Absolute limit price calculated on the webhook sender side. type must be set to stop_limit to use this field.
// @field <float> trailPrice A dollar value away from the highest water mark. If you set this to 2.00 for a sell trailing stop, the stop price is always hwm - 2.00. type must be set to trailing_stop to use this field.
// @field <float> trailPercent A percent value away from the highest water mark. If you set this to 1.0 for a sell trailing stop, the stop price is always hwm * 0.99. type must be set to trailing_stop to use this field.
export type stopLossMessage
    string type
    float percent
    float amount
    float stopPrice
    float limitPrice
    float trailPrice
    float trailPercent

// @function Builds the final JSON payload from a webhookMessage type.
// @param msg (webhookMessage) A prepared webhookMessage.
// @returns <string> A JSON Payload.
export method buildWebhookJson(webhookMessage msg, CONSTANTS constants = na) =>
    cnst = na(constants) ? CONSTANTS.new() : constants

    json = "{"
    json += '"library": "WebhookMessage"'
    json += ',"timestamp": "' + str.tostring(time) + '"'
    //ticker
    json += ',"ticker": "' + (msg.ticker == "" ? syminfo.ticker : msg.ticker) + '"'
    // action
    json += ',"action": "' + msg.action + '"'
    // sentiment
    if (msg.sentiment == cnst.SENTIMENT_BULLISH or msg.sentiment == cnst.SENTIMENT_BEARISH or msg.sentiment == cnst.SENTIMENT_LONG or msg.sentiment == cnst.SENTIMENT_SHORT or msg.sentiment == cnst.SENTIMENT_FLAT)
        json += ',"sentiment": "' + msg.sentiment + '"'
    // price
    json += msg.price > 0 ? ',"price": ' + str.tostring(msg.price) : ""
    // quantity
    json += msg.quantity > 0 ? ',"quantity": ' + str.tostring(msg.quantity) : ""
    // takeProfit
    if (msg.takeProfit != "")
        json += ',"takeProfit":' + msg.takeProfit
    // stopLoss
    if (msg.stopLoss != "")
        json += ',"stopLoss":' + msg.stopLoss
    json += "}"
    json

// @function Builds the takeProfit JSON message to be used in a webhook message.
// @param msg (takeProfitMessage)
// @returns <string> A JSON takeProfit payload.
export method buildTakeProfitJson(takeProfitMessage msg) =>
    json = '{'
    json += na(msg.limitPrice) ? "" : '"limitPrice": ' + str.tostring(msg.limitPrice)
    json += na(msg.percent) ? "" : '"percent": ' + str.tostring(msg.percent)
    json += na(msg.amount) ? "" : '"amount": ' + str.tostring(msg.amount)
    json += "}"
    json

/// @function Builds the stopLoss JSON message to be used in a webhook message.
// @param msg (stopLossMessage)
// @returns <string> A JSON stopLoss payload.
export method buildStopLossJson(stopLossMessage msg, CONSTANTS constants = na) =>
    cnst = na(constants) ? CONSTANTS.new() : constants

    //overload type message if not configured properly
    if (not na(msg.limitPrice) and msg.type != cnst.STOP_LOSS_TYPE_STOP_LIMIT)
        msg.type := cnst.STOP_LOSS_TYPE_STOP_LIMIT
    if (not na(msg.trailPrice) or not na(msg.trailPercent) and msg.type != cnst.STOP_LOSS_TYPE_TRAILING_STOP)
        msg.type := cnst.STOP_LOSS_TYPE_TRAILING_STOP

    json = '{'
    messages = array.new_string(0)
    if (na(msg.type) == false)
        array.push(messages, '"type": "' + msg.type + '"')
    if (na(msg.percent) == false)
        array.push(messages, '"percent": ' + str.tostring(msg.percent))
    if (na(msg.amount) == false)
        array.push(messages, '"amount": ' + str.tostring(msg.amount))
    if (na(msg.stopPrice) == false)
        array.push(messages, '"stopPrice": ' + str.tostring(msg.stopPrice))
    if (na(msg.limitPrice) == false)
        array.push(messages, '"limitPrice": ' + str.tostring(msg.limitPrice))
    if (na(msg.trailPrice) == false)
        array.push(messages, '"trailPrice": ' + str.tostring(msg.trailPrice))
    if (na(msg.trailPercent) == false)
        array.push(messages, '"trailPercent": ' + str.tostring(msg.trailPercent))
    json += array.join(messages, ",")
    json += "}"
    json

// tp = takeProfitMessage.new(percent = 2).buildTakeProfitJson()
// sl = stopLossMessage.new(type = STOP_LOSS_TYPE_TRAILING_STOP, percent = 0.75).buildStopLossJson()
// msg = webhookMessage.new(ticker = syminfo.ticker, action = ACTION_BUY, sentiment = SENTIMENT_BULLISH, quantity = 1, takeProfit = tp, stopLoss = sl)

// msg2 = webhookMessage.new(
//   ticker = syminfo.ticker,
//   action = ACTION_SELL,
//   sentiment = SENTIMENT_BEARISH,
//   quantity = 1,
//   stopLoss = stopLossMessage.new(type = STOP_LOSS_TYPE_TRAILING_STOP, percent = 0.75).buildStopLossJson()
//   )

Overview

WebhookMessageLibrary defines custom exported types and constants for trade actions, market sentiments, quantities, limit prices, take profits, and stop loss configurations. Traders can import this library into custom Pine Script strategies or indicators to format automated webhook alerts consistently. As a developer utility, it does not plot visual indicators or generate trade signals on its own.

Details

Published by

TradersPost on GitHub

Type

Library, Pine Script v5

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

FunctionLinearRegression

by ricardosantos79
261 stars

This Pine Script v5 library provides functions to calculate and plot linear regression channels using sample point arrays. It evaluates paired X and Y arrays to calculate the regression slope, intercept, fitted values, maximum deviation, minimum deviation, and

Library v5 Trend
Updated 4 years ago · None stated GitHub repository of FunctionLinearRegression

PositionSizing

by iamrichardD
57 stars

This Pine Script v6 library calculates trade position sizes and provides risk management functions for external scripts. It computes position sizes from account equity, percentage risk, and stop-loss distance, and offers dynamic sizing adjustments based on vol

Library v6
Updated 1 year ago · Apache-2.0 GitHub repository of PositionSizing

Chart Patterns

by deepentropy
13 stars

Chart Patterns is a Pine Script v6 library designed to scan for and render technical chart patterns directly on the price chart. It defines custom user-defined types to configure scanning parameters, such as Zigzag pivot offsets, error ratios, flat ratios, and

Library v6 Repaints
Updated 6 months ago · MIT GitHub repository of Chart Patterns

Standard Lib

by vitahoang
5 stars

Standard Lib is a utility Pine Script library designed to assist developers with chart debugging and dynamic text display. It exports a print function that creates and updates a single text label on the price chart. The label automatically positions itself at

Library v5
Updated 3 years ago · None stated GitHub repository of Standard Lib

TheStratGrammar

by 345-strategies
5 stars

This library calculates TheStrat price action states, classifying candles by directional break structure, close relative to open, and rejected break conditions. It draws demo bar labels directly on the price chart using standard or glyph notation. User inputs

Library v6 Repaints
Updated 2 days ago · MPL-2.0 GitHub repository of TheStratGrammar

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers