Get started with kScript in 5 minutes. Build your first EMA Difference indicator step by step.
Beginner5 min read
This guide walks you through creating your very first indicator in kScript. We’ll build an off-chart indicator that plots the difference between two EMAs as bars.
We’ll build an off-chart indicator that plots the difference between two EMAs as bars. Every kScript v2 starts with a compiler annotation //@version=2 followed by a define() function that tells the platform what your script does and where to display it.
To plot anything, we first need data. In kScript, that starts with subscribing to a data source. The ohlcv() function gives us OHLCV (trade data). For this example, we’ll focus on close prices.
Now let’s calculate our EMAs. The standard library includes an ema() function. We’ll calculate a fast EMA (7 periods) and slow EMA (14 periods), then find their difference.
//@version=2// definitiondefine(title="EMA Difference", position="offchart", axis=true, customTitle="($fastPeriod, $slowPeriod)");// logictimeseries ohlcvDataSet = ohlcv(symbol=currentSymbol, exchange=currentExchange);var fastEma = ema(source=ohlcvDataSet, period=7, priceIndex=4); // dataset, period, close column (4)var slowEma = ema(source=ohlcvDataSet, period=14, priceIndex=4); // dataset, period, close column (4)// Alternatively, you can use the .close property for cleaner syntax// var fastEma = ema(source=ohlcvDataSet.close, period=7);// var slowEma = ema(source=ohlcvDataSet.close, period=14);var difference = fastEma - slowEma;// plot
EMA calculations:
ema(ohlcvDataSet, 7, 4) - Fast EMA with 7 periods using close price (column 4)
ema(ohlcvDataSet, 14, 4) - Slow EMA with 14 periods using close price (column 4)
fastEma - slowEma - Calculate the difference between the two EMAs
You can inspect the difference dataset to confirm calculations by using the Data inspection feature.
Hardcoding values isn’t very flexible. Instead, let’s allow users to set the periods via inputs using the input() function. This makes your indicator customizable.
We use var instead of timeseries because user inputs are scalar values, not time series.
If you want to include the user settings in the indicator title, you can change the definition like this:
define("EMA Difference", "offchart", true, "($fastPeriod, $slowPeriod)");
The title will then read as “EMA Difference (7, 14)”.