Library · Pine Script v5 · Library

PineTradingbotWebhook

by PlusGenie· code credited to AlphaCentauri66367

This Pine library provides a single exported function, makeWebhookJson, that builds a JSON string for sending TradingView alerts to a Tbot server which places Interactive Brokers orders.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code76
Settings0inputs
LicenceMPL-2.0
Last update2 years ago24 Dec 2023

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

76 lines of Pine Script v5 from src/library/PineTradingbotWebhook.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

PineTradingbotWebhook.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlphaCentauri66367
//
// Credits:
//  JSON functions taken from © beskrovnykh: https://www.tradingview.com/script/HFGmR9ST-market-monitor/

//@version=5
// @description Provides Webhook JSON strings for Tbot on Tradingboat

library("PineTradingbotWebhook")

// Converts a metric name and value to a JSON formatted string.
// @param name The name of the metric.
// @param value The value of the metric.
// @returns A string representing the metric in JSON format.
_metricToJson(name, value) =>
  str.format("'{'\"name\": \"{0}\", \"value\": {1}'}'", str.tostring(name), str.tostring(value))

// @function Creates a Webhook message for Tbot on Tradingboat
// @param webhookKey the unique key to the Flask (TVWB) server -  // Use format like WebhookReceived:123456
// @param orderRef this will be used to create the order reference ID, together with timeframe and clientID 
// @param direction the same as the strategy's direction -  strategy.entrylong, strategy.entryshort, strategy.exitlong, strategy.exitshort, strategy.close, strategy.close_all
// @param qty default value is -1e10 indicating all contracts/units
// @param entryLimit this is same to strategy.entry()'s limit parameter
// @param entryStop this is same to strategy.entry()'s  stop parameter
// @param exitLimit this is the same to strategy.exit()'s limit parameter
// @param exitStop this is the same to strategy.exit()'s stop parameter
// @param contract this will be translated to secType in ib_insync. stock, forex, crypto and future(s)
// @param ticker The TradingView ticker symbol for the asset; defaults to the current chart's ticker if not specified.
// @param lastTradeDateOrContractMonth The contract's last trading day or contract month for ib_insync, mainly for futures. Should be in the format YYYYMM or YYYYMMDD.
// @param exchange Destination exchange for ib_insync, primarily for futures.
// @param multiplier The futures contract multiplier is the amount multiplying the price per point to determine total value.
// @param clientId this is for IB Gateway/TWS's clientID which should start with 1
// @returns JSON as a series string
export makeWebhookJson(
     simple string webhookKey,
     simple string orderRef = 'defOrderId',
     simple string direction,
     float qty = -1e10,
     float entryLimit = 0.0,
     float entryStop = 0.0,
     float exitLimit = 0.0,
     float exitStop = 0.0,
     simple string contract = '',
     simple string ticker = '',
     simple string lastTradeDateOrContractMonth = '',
     simple string exchange = '',
     simple string multiplier = '',
     int clientId = 1
     ) =>
    modifiedTicker = ticker == '' ? syminfo.ticker : ticker
    modifiedContract = contract == '' ? syminfo.type : contract
    metrics = array.new_string()
    array.push(metrics, _metricToJson("entry.limit", math.round_to_mintick(entryLimit)))
    array.push(metrics, _metricToJson("entry.stop", math.round_to_mintick(entryStop)))
    array.push(metrics, _metricToJson("exit.limit", math.round_to_mintick(exitLimit)))
    array.push(metrics, _metricToJson("exit.stop", math.round_to_mintick(exitStop)))
    array.push(metrics, _metricToJson("qty", math.round_to_mintick(qty)))
    array.push(metrics, _metricToJson("price", close))
    metricsJson = str.format("[{0}]", array.join(metrics,', '))

    messageContent = array.new_string()
    array.push(messageContent, str.format("\"timestamp\": {0,number,#}", timenow))
    array.push(messageContent, str.format("\"ticker\": \"{0}\"",modifiedTicker))
    array.push(messageContent, str.format("\"currency\": \"{0}\"",syminfo.currency))
    array.push(messageContent, str.format("\"timeframe\": \"{0}\"",timeframe.period))
    array.push(messageContent, str.format("\"clientId\": {0}",clientId))
    array.push(messageContent, str.format("\"key\": \"{0}\"",webhookKey))
    array.push(messageContent, str.format("\"contract\": \"{0}\"",modifiedContract))
    array.push(messageContent, str.format("\"orderRef\": \"{0}\"",orderRef))
    array.push(messageContent, str.format("\"direction\": \"{0}\"",direction))
    array.push(messageContent, str.format("\"exchange\": \"{0}\"",exchange))
    array.push(messageContent, str.format("\"lastTradeDateOrContractMonth\": \"{0}\"",lastTradeDateOrContractMonth))
    array.push(messageContent, str.format("\"multiplier\": \"{0}\"",multiplier))
    array.push(messageContent, str.format("\"metrics\": {0}",metricsJson))
    messageJson = str.format("'{'{0}'}'",array.join(messageContent, ', '))

Overview

The caller passes a webhook key, an order reference, a direction matching a strategy function such as entry long, exit short or close all, a quantity, optional limit and stop prices, and contract details such as type, ticker, exchange, expiry and multiplier. It draws nothing and does not place orders by itself.

Details

Published by

PlusGenie on GitHub

Code credit

AlphaCentauri66367, as written in the script's header

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.

Topics

ib-insyncinteractive-brokers-apitradingview

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

261 stars

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 3 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

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

More libraries

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers