π Definition
The CountIf() function in NinjaScript is a formidable tool that allows traders and programmers to determine how often a certain condition holds true over a defined look-back period in bars. Imagine asking, “Over the past ‘Y’ bars, how many times did ‘X’ happen?” That’s exactly what this function helps discern.
Important: Always remember that this tool is not tailored for multi-series strategies and indicators.
β©οΈ Method Return Value
Expect an integer (int) when you use the CountIf() function. This integer showcases the number of times the specified condition was met over the period you’ve defined.
π§ Syntax
CountIf(Func condition, int period)
- condition: Think of this as the rule you’re keen on checking. It boils down to either a ‘true’ or ‘false’.
- period: This is the span, in bars, during which you’re probing the condition.
Pro Tip: If lambda expressions, like the one in “condition”, seem foreign, simply visualize them as concise, bite-sized functions. They make it a breeze to detail a slice of logic directly.
π Examples
1. Counting Up Bars:
// Among the last 10 bars, if 8 were up bars, then we can enter a long position.
if (CountIf(() => Close[0] > Open[0], 10) > 8)
EnterLong();
Here, the check is for bars where the closing is higher than the opening price. A long position is initiated if over 8 such bars surface in the last 10.
2. Bars Above a Moving Average:
// If a 20-period SMA is surpassed by the closing of 7 out of the last 10 bars, take a specific action.
if (CountIf(() => Close[0] > SMA(20)[0], 10) == 7)
// Implement your desired action here.
This instance observes how often the last 10 bars ended above a 20-period simple moving average.
3. Tracing Oversold Conditions:
// Over the last 14 bars, let’s pinpoint how many times the RSI dipped below 30, hinting at a potentially oversold market.
if (CountIf(() => RSI(14)[0] < 30, 14) > 3)
// Here’s a potential buying cue. Tailor your strategy accordingly.
In this illustration, the RSI (Relative Strength Index) aids in detecting potential “oversold” scenarios.
4. Tallying Consecutive Down Bars:
// If a decline is witnessed in all the last 5 bars, perhaps a reversal is on the cards.
if (CountIf(() => Close[0] < Open[0], 5) == 5)
// A bounce back might be imminent. Consider going long.
The above example demonstrates the prowess of CountIf() in counting consecutive occurrences.
π Conclusion
NinjaScript’s CountIf() function stands as a powerful asset for traders aiming to embed more dynamism and condition-centric strategies in their trading algorithms. Knowledge is potent, but applying this knowledge by rigorously back-testing strategies before live trading ensures safety and efficiency.