I'm new to structural programming languages and I'm trying to make an indicator and a strategy based on 2 stochastic oscillators, one being faster than the other. Crossover/under value of the 2 oscillators and the values of the slower and the faster oscillator are used to determine the entry and exit conditions. Here are the conditions described in Structured English:
IF crossover is below 25 OR slow stoch oscil is below 20 THEN
Open long position
ELSE
IF fast stoch oscil is above 90 THEN
Close long position
ELSE
Do nothing
ENDIF
ENDIF
IF crossunder is above 75 OR slow stoch oscil is above 80 THEN
Open short position
ELSE
IF fast stoch oscil is below 10 THEN
Close short position
ELSE
Do nothing
ENDIF
ENDIF
EXIT
and in pseudocode:
crossover = (stoch_slow, stoch_fast)
crossunder = (stoch_slow, stoch_fast)
long
if crossover < 25 or stoch_slow < 20
close_long
if long == true and stoch_fast > 90
short
if crossunder > 75 or stoch_slow > 80
close_short
if short == true and stoch_fast < 10
I read the relevant sections of the Pine Script's User Manual, but couldn't finding a similar example, and, in the end, only managed to plot all of the instances of an crossover/under.
//@version=5
indicator(title="Stochastic oscillator-SlowFast", shorttitle="Stoch-SF", overlay=false)
// Input and calculate values
periodKs = input.int(10)
smoothKs = input.int(10)
ks = ta.sma(ta.stoch(close, high, low, periodKs), smoothKs)
periodKf = input.int(6)
smoothKf = input.int(3)
kf = ta.sma(ta.stoch(close, high, low, periodKf), smoothKf)
// Plot crossover/under circles
long = plot(ta.crossover(ks, kf) ? kf : na, color=color.teal, linewidth=3, style=plot.style_circles)
short = plot(ta.crossunder(ks, kf) ? kf : na, color=color.red, linewidth=3, style=plot.style_circles)
// Plot Stochastics lines
plot(ks, color=color.yellow)
plot(kf, color=color.white)
hline(18)
hline(36)
hline(64)
hline(82)
Later, I've found another way to accomplish the marking of crossovers/unders on TradingCode.net, replacing the "// Plot crossover/under circles" section in the above code:
co = ta.crossover(ks, kf)
cu = ta.crossunder(ks, kf)
// Colour the background when a crossover/under happens
backgroundColour = if co
color.new(color.teal, 80)
else if cu
color.new(color.orange, 80)
bgcolor(backgroundColour)
but I haven't found a way to assimilate the boolean and floating point values to 1 common type.
TLDR How to get a value of a crossover/under and plot only those who are over/under a certain fixed value.
It was fun figuring out the solution and I even figured out a solution to a secondary problem, which I didn't mention. The next code replaces the last code block of my question:
sfco = ta.crossover(kf, ks) and kf < 25 or ks < 20 //Open long position
sfcu = ta.crossunder(kf, ks) and kf > 75 or ks > 80 //Open short position
// Color the background when long conditions are met
opencolor = if sfco
color.new(color.teal, 80)
else if sfcu
color.new(color.orange, 80)
bgcolor(opencolor)