Cookies are used for the best experience on my website.

Accept Cookie Policy

No internet detected

Check your connection and try again.

Logo Image

No match found

Buy a coffee

I launched this blog in 1995. Since then, we have published 1603 articles. It's all free and means a lot of work in my spare time. I enjoy sharing knowledge and experiences with you.

Your support

Have you learned something new by reading, listening, or watching my content? With your help, I can spend enough time to keep publishing great content in the future.

Or, select an option below:

A small slice of my data processing time each month

It's ongoing work running this site and what's really great is ongoing support. Here's a sense of what goes into this site: research topics for discussion. Manage the Tech stuff: website, SEO, graphics, email, back-end servers, DNS routing, edge servers. Create advertisements and load the campaigns in Google Ads. Manage the social media forums (Facebook, Reddit, Twitter). Write updates to the blog. Keep GitHub up-to-date.

$4.50 — A large cappuccino at my local

Things just work better with coffee! I like to take the kids to school then grab a cappuccino from my local on the way home before beginning the things that take mental energy.

$8.99 — A month of Netflix for some quiet nights in

A lot of the work on this happens after hours when I should be relaxing on the couch. Help me make it so and I promise to keep off the devices for a bit!

$11.50 — Fund a month of email delivery

This site sends out thousands of emails every month. For that volume and to ensure deliverability, I need to pay MailChimp.

$20 — Pay for one month of AWS storage fees

Websites are not free. The storage alone takes some cash. If you are willing to lighten the burden, we can keep this site up online.

$30 — One hour's pay for a graphics artist

Art doesn't create itself without a hand to guide it. I can't draw, so I need to pay others to help.

$45 — Pay a full-stack web developer for one hour

Much of the work on this site happens on weekends which means giving up time with the kids. Help me pay the developers so I can give my kids more time.

Coding a Simple Trading Strategy in TradingView Step-by-Step

Contribute to the world of objective technical analysis ⋯

Author

Marie RIVIERE


  • 1079

  • 6871

  • 3

  • 0

  • 9

Without a doubt the Stochastic Oscillator is a universally used indicator. It uses such a simple yet powerful formula in order to detect rapid oversold and overbought conditions. This article discusses a certain strategy based on this indicator.

Coding the Stochastic Oscillator in Pine Script 🔗

The stochastic oscillator is a bounded technical indicator seeks to find oversold and overbought zones by incorporating the highs and lows using the normalization formula as shown below:

Stochastic Oscillatori=(PriceiLowest Lowi:nHighest Highi:nLowest Lowi:n)×100\text{Stochastic Oscillator}_i = \left ( \frac {\text {Price}_i - \text{Lowest Low}_\text{i:n}} {\text{Highest High}_\text{i:n} - \text{Lowest Low}_\text{i:n} } \right ) \times 100



This means that at any time, it must be bounded between 0 and 100 as dictated by the mathematical formula above. We generally use the oscillator in a contrarian way where we use the concepts of oversold and overbought to describe certain extreme events.

An overbought level is an area where the market is perceived to be extremely bullish and is bound to consolidate, therefore giving us a bearish bias. An oversold level is an area where market is perceived to be extremely bearish and is bound to bounce, therefore giving us a bullish bias. Hence, the stochastic oscillator is a contrarian indicator that seeks to signal the expected reactions of extreme movements.

Why is this section called “Creating the Stochastic Oscillator in Pine Script” when it is already a built-in script in TradingView and does not require coding?

The answer to that is because we want to learn how to code all types of indicators from scratch in Pine Script so that we become fluent and comfortable back-testing and tweaking any strategy. By understanding how to code it, we are also able to code variations on the indicator such as the stochastic smoothing oscillator, an indicator discussed in previous articles.

Hourly USDJPY values with the 13-period stochastic oscillator

Generally, we smooth the oscillator with a 3-period moving average applied onto it. This can be seen in the above chart with the orange line following the stochastic in blue.

To code the oscillator, we first start by choosing the version of Pine Script, the official language of TradingView. In our case, we will choose the latest version. Then as we will create an indicator, we have to tell the program that we will do that by using the indicator() function. We will put two arguments inside, the title which we will call “Our Stochastic Oscillator” and the Boolean argument overlay. By putting false, we are telling the script that the oscillator will be in a different panel. If we were to create a moving average, we must put true.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sofien-Kaabar
// @version = 5
indicator("Our Stochastic Oscillator", overlay = false)

Next, we define the input values such as the lookback period, the oversold level, and the overbought level. We use the input() function to give us the opportunity to tweak these parameters on the settings directly from the chart. In other words, we do not have to code new parameters if we want to change them. The title is the name of the variable and the defval is the default value. In our case, it is 13, 20, and 80 as discussed previously.

lookback = input(title = 'Period', defval = 13)
oversold_level = input(title = 'Oversold', defval = 20)
overbought_level = input(title = 'Overbought', defval = 80)

Now, we will calculate the highest highs and the lowest lows in the lookback period so that we construct the stochastic formula. This is done by using the ta.highest() and ta.lowest() functions. Each require a lookback which in our case is the defined variable with a default value of 13.

// highest high
highest = ta.highest(high, lookback)// lowest low
lowest = ta.lowest(low, lookback)

The last step is applying the formula. This is simply done below where we define the stochastic_k (%K) followed by the stochastic_D (%D) which is the 3-period simple moving average of stochastic_k. The simple moving average is calculated using the ta.sma() function.

// stochastic oscillator
stochastic_K = ((close - lowest) / (highest - lowest)) * 100
stochastic_D = ta.sma(stochastic_K, 3)

Let us plot what we have so far and compare it to the built-in stochastic oscillator script.

plot(stochastic_K)
plot(stochastic_D, color = color.orange)
hline(oversold_level)
hline(overbought_level)

Hourly USDJPY values with the 13-period built-in stochastic oscillator and the 13-period coded stochastic oscillator

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sofien-Kaabar
// @version = 5
indicator("Our Stochastic Oscillator", overlay = false)lookback = input(title = 'Period', defval = 13)
oversold_level = input(title = 'Oversold', defval = 20)
overbought_level = input(title = 'Overbought', defval = 80)// highest high
highest = ta.highest(high, lookback)// lowest low
lowest = ta.lowest(low, lookback)// stochastic oscillator
stochastic_K = ((close - lowest) / (highest - lowest)) * 100
stochastic_D = ta.sma(stochastic_K, 3)plot(stochastic_K)
plot(stochastic_D, color = color.orange)
hline(oversold_level)
hline(overbought_level)

Coding and Analyzing the Strategy in Pine Script 🔗

The strategy is pretty clear, we will initiate position based on the exit of extremes. Therefore, the trading conditions are:

  • A buy (Long) signal is generated whenever the current 13-period stochastic oscillator is above 20 while the previous reading is below 20.
  • A sell (Short) signal is generated whenever the current 13-period stochastic oscillator is below 80 while the previous reading is above 80.

Let us code the conditions of the signals first. When we use the stochastic_K[1] statement, it refers to the previous value of wherever we are now.

buy_signal  = stochastic_K > oversold_level and stochastic_K[1] < oversold_level
sell_signal = stochastic_K < overbought_level and stochastic_K[1] > overbought_level

Now, to simulate the orders, we use strategy.entry() built-in function which allows us to either go long or short whenever the signal is generated. The position is initiated at the opening price after the signal. (Which itself is generated at the close).

strategy.entry('Buy',  strategy.long,  when = buy_signal)
strategy.entry('Sell', strategy.short, when = sell_signal)

Signal chart following the strategy

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sofien-Kaabar
// @version=5

strategy("Our Stochastic Oscillator", overlay = false)lookback = input(title = 'Period', defval = 13)

oversold_level = input(title = 'Oversold', defval = 20)
overbought_level = input(title = 'Overbought', defval = 80)// highest high
highest = ta.highest(high, lookback)// lowest low
lowest = ta.lowest(low, lookback)// stochastic oscillator
stochastic_K = ((close - lowest) / (highest - lowest)) * 100
stochastic_D = ta.sma(stochastic_K, 3)plot(stochastic_K)

plot(stochastic_D, color = color.orange)
hline(oversold_level)
hline(overbought_level)buy_signal  = stochastic_K > oversold_level and stochastic_K[1] < oversold_level

sell_signal = stochastic_K < overbought_level and stochastic_K[1] > overbought_levelstrategy.entry('Buy',  strategy.long,  when = buy_signal)
strategy.entry('Sell', strategy.short, when = sell_signal)

Summary 🔗

To sum up, what I am trying to do is to simply contribute to the world of objective technical analysis which is promoting more transparent techniques and strategies that need to be back-tested before being implemented. This way, technical analysis will get rid of the bad reputation of being subjective and scientifically unfounded.

This license allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, so long as attribution is given to the creator. The license allows for commercial use. If you remix, adapt, or build upon the material, you must license the modified material under identical terms.