Deeper dive into Logical Operators

Knowing how to combine conditions is a key factor in programming. Here we take a deeper dive into the Logical Operators and advanced conditioning.

Advanced Conditions

Logical Operators can be used for multiple tasks in HaasScript. It is most common in any if-statements, but can also be used to assign values based on some condition.
An example of advanced conditions:

-- advanced conditions example part 1
local orderId = Load('orderId') -- default value is nil


-- we assume the orderId is usable again
-- when one of these conditions is true
if (not orderId)              -- orderId is nil
or (orderId == '')            -- or orderId is '' (empty string)
or (orderId != ''             -- or orderId contains an id...
and not IsOrderOpen(orderId)) -- ...but is not open
then
    orderId = PlaceGoLongOrder(price, amount)
end


Save('orderId', orderId)

This is probably a lot to take in, but let us take a look at another example of advanced conditioning.

-- advanced conditions example part 2
local c = ClosePrices()
local fast_sma = SMA(c, 10)
local slow_sma = SMA(c, 50)
local rsi = RSI(c, 14)
local macd = MACD(c, 12, 26, 9)


if (fast_sma > slow_sma)      -- fast sma above slow sma

and (rsi < 40)                -- and rsi below 40
and (macd.macd > macd.signal) -- and macd above its signal
and (macd.macd > 0)           -- and macd above zero
then
    DoLong()
end

Conditional assignments

HaasScript allows us to create conditional assignments with these Logical Operators and same thing can be achieved with the built-in commands like IfElse() and IfElseIf(). However, the built-in commands can only go so far; Logical Operators and be stretched virtually infinitely.

-- conditional assignment example
local c = ClosePrices()
local ma_type = 0


-- if ma_type is zero, we calculate and assign SMA values to 
-- our variable. if the value is anything else, we calculate and assign EMA 
-- values to the variable.
local ma = (ma_type == 0) and SMA(c, 20) or EMA(c, 20)


-- same achieved with a built-in command IfElse()
local ma = IfElse( ma_type == 0, SMA(c, 20), EMA(c, 20) )
Back to: HaasScript Fundamentals > Operators