If Statements in Pine Script - The Thing That Actually Makes Your Code Work
okay so here's the deal with if statements in pine script. they're like... the thing that stops your code from being completely useless. without them, your script just does the same thing over and over like a robot having a stroke.
so what the hell is an if statement anyway?
think of it like this: you're staring at a chart and you're like "if price goes above this level, i wanna know about it" - that's basically what if statements do. they check if something is true, and if it is, they do stuff. if not, they either do nothing or do something else.
the actual syntax (it's not that scary)
if close > open
color = color.green
else
color = color.red
see? not rocket science. if today's close is higher than open, make it green. otherwise make it red. boom. done.
oh and yeah you need pine script v2 or whatever. probably not an issue unless you're living in 2018.
real talk about returning values
you can actually make if statements give you values back. like:
var result = if close > open
1
else
0
this is actually pretty handy when you want to keep track of stuff. just remember both sides gotta return the same type of thing or pine gets cranky.
some random tips i learned the hard way
- indent with 4 spaces or a tab. yeah i know it's annoying but pine is picky about this
- you can nest these things but honestly it gets messy real fast. try not to go too crazy
- else if works too if you need multiple conditions. just don't make it like 20 levels deep or you'll hate yourself later
why should you even care?
because without if statements, your indicators are basically just... static lines on a chart. with them, you can:
- make colors change when conditions flip (way more satisfying than it should be)
- turn indicators on/off based on market conditions
- build actual strategies instead of just pretty pictures
seriously, start with something simple like changing colors based on whether you're above or below a moving average. once you get that working, you'll figure out the rest.
anyway, that's pretty much it. go mess around with some code and break stuff. that's how you actually learn this stuff.
