Skip to content

Commit dbfd205

Browse files
authored
Update README.md
1 parent 57c18b7 commit dbfd205

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

faq_and_code/README.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -635,7 +635,7 @@ plot(initOnEachBar2, "initOnEachBar2", color.orange, 3, transp = 0)
635635
See [here](https://www.tradingview.com/pine-script-docs/en/v4/language/Expressions_declarations_and_statements.html#variable-declaration) for more information. This is another example by vitvlkv: [Holding a state in a variable](https://www.tradingview.com/script/llcoIPKG-Pine-Example-Holding-a-state-in-a-variable/).
636636

637637
### How do I calculate averages?
638-
1. If you just want the average between two values, you can use `avg(val1, val2)` or `(val1 + val2)/2`. Note that the [`avg()`](https://www.tradingview.com/pine-script-reference/v4/#fun_avg) accepts up to 6 values.
638+
1. If you just want the average between two values, you can use `avg(val1, val2)` or `(val1 + val2)/2`. Note that [`avg()`](https://www.tradingview.com/pine-script-reference/v4/#fun_avg) accepts up to 6 values.
639639
1. To average the last x values in a series, you can use `sma(series, x)`.
640640

641641
### How can I calculate an average only when a certain condition is true?
@@ -818,6 +818,24 @@ plot(v3, "3. f_verboseAndINEFFICIENT_TimesInLast")
818818
bgcolor(v1 != v2 or v2 != v3 ? color.red : na, transp = 80)
819819
```
820820

821+
### How can implement and On/Off switch?
822+
```js
823+
//@version=4
824+
study("On/Off condition", "", true)
825+
upBar = close > open
826+
// On/off conditions.
827+
triggerOn = upBar and upBar[1] and upBar[2]
828+
triggerOff = not upBar and not upBar[1]
829+
// Switch state is implicitly saved across bars thanks to initialize-only-once keyword "var".
830+
var onOffSwitch = false
831+
// Turn the switch on when triggerOn is true. If it is already on,
832+
// keep it on unless triggerOff occurs.
833+
onOffSwitch := triggerOn or (onOffSwitch and not triggerOff)
834+
bgcolor(onOffSwitch ? color.green : na)
835+
plotchar(triggerOn, "triggerOn", "", location.belowbar, color.lime, 0, size = size.tiny, text = "On")
836+
plotchar(triggerOff, "triggerOff", "", location.abovebar, color.red, 0, size = size.tiny, text = "Off")
837+
```
838+
821839
**[Back to top](#table-of-contents)**
822840

823841

0 commit comments

Comments
 (0)