This mistake has become much more prevalent with AI-generated scripts.
It seems AI bots skipped 8th-grade algebra!
De Morgan’s Laws are essential rules in logic, set theory, and Boolean algebra that explain how negation interacts with AND and OR operations. Simply put, when you negate a combined statement, De Morgan warns us that the negation applies to each individual component, converting ANDs to ORs:
In Thinkscript, using the ToS not operation ! on a multi-condition statement flips the operations underneath in a way you might not intend.
The Problem
Consider this example:
# bear = Current candle is red AND current close is lower than previous close.
You might think !bear means "find bars where NEITHER condition is true" (a green candle that closed higher).
But because of De Morgan's Law, !(A and B) actually evaluates as (NOT A) OR (NOT B).
As a result, !bear triggers if either single condition fails:
The Solutions
To negate a compound statement correctly in Thinkscript, you have two options:
1. Do not use ! operation. Create a 2nd def statement with explicit conditions or
2. Evaluate the combined condition first using a binary signal which will force Thinkscript to evaluate both conditions together before applying your filter:
Clear as mud?
It seems AI bots skipped 8th-grade algebra!
De Morgan’s Laws are essential rules in logic, set theory, and Boolean algebra that explain how negation interacts with AND and OR operations. Simply put, when you negate a combined statement, De Morgan warns us that the negation applies to each individual component, converting ANDs to ORs:
In Thinkscript, using the ToS not operation ! on a multi-condition statement flips the operations underneath in a way you might not intend.
The Problem
Consider this example:
# bear = Current candle is red AND current close is lower than previous close.
def bear = close < open and close < close[1];
plot scan = !bear;
You might think !bear means "find bars where NEITHER condition is true" (a green candle that closed higher).
But because of De Morgan's Law, !(A and B) actually evaluates as (NOT A) OR (NOT B).
As a result, !bear triggers if either single condition fails:
▸ Red candle, but higher than previous close → Triggers scan
▸ Green candle, but lower than previous close → Triggers scan
▸ Green candle and higher than previous close Both are False → Triggers scan
Because it uses OR, it matches almost every bar on your chart!The Solutions
To negate a compound statement correctly in Thinkscript, you have two options:
1. Do not use ! operation. Create a 2nd def statement with explicit conditions or
2. Evaluate the combined condition first using a binary signal which will force Thinkscript to evaluate both conditions together before applying your filter:
def bear = if close < open and close < close[1] then 1 else -1;
plot scan = bear == -1;
Clear as mud?
Last edited: