Skip to main content

How to create a custom indicator

In this tutorial we will create a custom indicator that displays a Simple Moving Average (SMA) and a Smoothing Line. The line represents either SMA, Exponential Moving Average (EMA), or Weighted Moving Average (WMA) calculated based on the existing SMA.

After completing the tutorial, you will learn how to add a custom indicator to the library, specify the indicator look and feel, and implement data calculations.

Before you start

Consider taking the following steps before proceeding with the tutorial:

  1. Set up the Widget Constructor and run the library. Refer to the First run tutorial for more information.
  2. Connect data to the library. Refer to the Connecting data tutorial for more information.

Tutorial structure

The tutorial is divided into three parts:

  1. Add a custom indicator to the library
  2. Implement metainfo
  3. Implement constructor
Tips
  • At the end of each part, you will find the complete code blocks related to a specific step.
  • Refer to the CodePen example above to see the complete tutorial code right away.

Add a custom indicator to the library

To add a custom indicator to the library, specify a function that returns a Promise object and assign this function to the custom_indicators_getter property in the Widget Constructor. The Promise object should be resolved with an array of CustomIndicator instances. In this tutorial, only one custom indicator will be created, therefore, the array contains one element.

CustomIndicator is an interface that you should implement to provide information on the indicator. The interface contains the following required fields:

  • name: an indicator's internal name that is not visible in the UI. This name should be unique.
  • metainfo: the field that describes how the indicator looks like.
  • constructor: the field that contains data calculations.

At this stage of the tutorial, you should adjust the name filed only.

var widget = window.tvWidget = new TradingView.widget({
// ...
custom_indicators_getter: function(PineJS) {
return Promise.resolve([
// Indicator object
{
name: 'Custom Moving Average',
metainfo: {
// ...
},
constructor: function() {
// ...
}
}
]);
},
});

In the next steps, you will specify the metainfo and constructor fields.