Types
Data Types
HaasScript uses various data types to store and manipulate different kinds of information. Understanding these types is essential for writing correct and efficient trading strategies.
Overview of HaasScript Data Types
HaasScript automatically determines variable types based on the assigned value. The main types you'll work with are:
- Numbers - Numeric values (integers and decimals)
- Strings - Text values
- Booleans - true/false values
- Collections - Arrays of numeric data
- Signals - Trading signal constants
- Enums - Predefined constant values
Numbers
Numbers represent numeric values and can be integers or decimals.
Integers
Whole numbers without decimal points:
local rsiPeriod = 14
local quantity = 100
local count = 0
Decimals
Numbers with decimal points for precise calculations:
local price = 45000.50
local stopLossPercent = 2.5
local leverage = 5.0
Scientific Notation
For very large or small numbers:
local veryLarge = 1.5e10 -- 15,000,000,000
local verySmall = 1.5e-10 -- 0.00000000015
Number Operations
local a = 10
local b = 3
-- Basic arithmetic
local sum = a + b -- 13
local difference = a - b -- 7
local product = a * b -- 30
local quotient = a / b -- 3.333...
local remainder = a % b -- 1 (modulus)
local power = a ^ b -- 1000 (10 to the power of 3)
Using Numbers in Trading
-- Indicator parameters
local rsiPeriod = 14
local macdFast = 12
local macdSlow = 26
-- Risk management percentages
local stopLossPercent = 2.0
local takeProfitPercent = 5.0
-- Price calculations
local currentPrice = ClosePrices() -- Uses latest price
local targetPrice = currentPrice * 1.05 -- 5% above
local stopPrice = currentPrice * 0.98 -- 2% below
Strings
Strings represent text data enclosed in quotes.
String Declaration
-- Single quotes
local text1 = 'Hello'
-- Double quotes
local text2 = "World"
-- Empty string
local empty = ""
String Concatenation
Combine strings using the .. operator:
local greeting = "Hello, " .. "World!"
local market = "BTC_USDT"
local message = "Trading " .. market
-- Concatenating strings with numbers
local rsi = 25.5
local logMessage = "RSI value: " .. rsi -- "RSI value: 25.5"
Using Strings in Trading
-- Trading reasons
local entryReason = "RSI oversold signal"
local exitReason = "Take profit reached"
-- Log messages
local message = "Entering long position at RSI: " .. rsiValue
Log(message)
-- Market identification
local market = BaseCurrency() .. "_" .. QuoteCurrency()
Booleans
Booleans represent logical values: either true or false.
Boolean Declaration
local inPosition = true
local useStopLoss = false
local isMarketOpen = true
Boolean Operations
local a = true
local b = false
-- AND (both must be true)
local andResult = a and b -- false
-- OR (at least one must be true)
local orResult = a or b -- true
-- NOT (reverses the value)
local notResult = not a -- false
Comparison Operators
Comparisons return boolean values:
local price = 45000
local target = 46000
local isAbove = price > target -- false
local isBelow = price < target -- true
local isEqual = price == target -- false
local notEqual = price ~= target -- true
local greaterOrEqual = price >= target -- false
local lessOrEqual = price <= target -- true
Using Booleans in Trading
-- Position state
local hasLongPosition = HasLongPosition()
local hasShortPosition = HasShortPosition()
-- Strategy conditions
local isOversold = rsi < 30
local isOverbought = rsi > 70
local trendIsUp = fastMA > slowMA
-- Combine conditions
local buySignal = isOversold and trendIsUp
local sellSignal = isOverbought or (rsi > 60 and trendIsDown)
if buySignal then
DoLong("Multiple indicators confirm buy")
end
Collections (HaasNumberCollection)
Collections are arrays of numeric data that store historical values. They are the most common data type you'll work with in HaasScript.
What are Collections?
Collections store multiple numeric values in sequence, typically representing time-series data like prices, volumes, or indicator values.
local closePrices = ClosePrices() -- Collection of closing prices
local highPrices = HighPrices() -- Collection of high prices
local lowPrices = LowPrices() -- Collection of low prices
local volume = Volume() -- Collection of volume data
Accessing Collection Values
HaasScript collections use 1-based indexing where:
- Index 1 = Latest value (most recent candle)
- Index N = Oldest value (N candles ago)
local closePrices = ClosePrices()
-- Access specific values
local latestClose = closePrices[1] -- Most recent closing price
local previousClose = closePrices[2] -- Previous candle closing price
local tenCandlesAgo = closePrices[10] -- Price 10 candles ago
Important: Never use index 0 - it does not exist in HaasScript's 1-based indexing.
Automatic Value Usage
When you use a collection in a number context, HaasScript automatically uses the latest value (index 1):
local closePrices = ClosePrices()
-- These are equivalent:
local currentPrice = closePrices -- Uses latest value
local currentPrice2 = closePrices[1] -- Explicitly uses latest value
-- Works in calculations
local avgPrice = (closePrices + highPrices + lowPrices) / 3
Collection Operations
Many HaasScript functions work directly with collections:
-- Indicators accept collections
local rsi = RSI(ClosePrices(), 14) -- Uses closePrices collection
local sma = SMA(HighPrices(), 20) -- Uses highPrices collection
local macd = MACD(ClosePrices(), 12, 26, 9) -- Uses closePrices collection
-- Math operations
local avgPrice = (ClosePrices() + HighPrices()) / 2
-- Length of collection
local candleCount = Count(ClosePrices()) -- Number of candles in data
Collections in Custom Commands
When defining parameters for custom commands, use ListNumberType for collections:
DefineCommand("MyIndicator", "Custom indicator")
local prices = DefineParameter(ListNumberType, 'prices', 'Price data', true, ClosePrices())
local period = DefineParameter(NumberType, 'period', 'Period', true, 14)
-- Your logic here
Common Collection Mistakes
local closePrices = ClosePrices()
-- Wrong: Trying to access index 0 (doesn't exist)
local value = closePrices[0] -- Error!
-- Wrong: Using .Value property (doesn't exist)
local value = closePrices.Value -- Error!
-- Correct: Use index 1 for latest value
local latest = closePrices[1]
-- Correct: Use collection directly (auto-uses latest)
local latest = closePrices
Signals
Signals are special constants used for trading decisions.
Signal Types
-- Entry signals
SignalLong -- Enter long position
SignalShort -- Enter short position
SignalNone -- No signal
-- Exit signals
SignalExitLong -- Exit long position
SignalExitShort -- Exit short position
SignalExitPosition -- Exit any position
Using Signals in Trading
local rsi = RSI(ClosePrices(), 14)
local signal = SignalNone
-- Determine signal based on conditions
if rsi < 30 then
signal = SignalLong
elseif rsi > 70 then
signal = SignalShort
else
signal = SignalNone
end
-- Execute the signal
DoSignal(signal)
Signal Functions
-- Direct signal execution
DoLong("Entry reason")
DoShort("Entry reason")
DoExitPosition("Exit reason")
-- Signal-based execution
if condition then
DoSignal(SignalLong)
end
Enums
Enums (enumerations) are predefined constant values used throughout HaasScript.
Common Enums
HaasScript uses enums for various settings:
-- Time intervals
Minute1, Minute5, Minute15, Minute30, Hour1, Hour4, Hour12, Day1, Week1
-- Order types
Limit, Market
-- Position sides
Long, Short
-- And many more defined in HaasScript
Using Enums
-- Set chart interval
SetCurrentInterval(Minute15)
-- Order type selection
local orderType = Market -- or Limit
-- Position side checks
if HasLongPosition() then
-- Long position logic
end
Type Conversions
HaasScript automatically handles many type conversions, but understanding them helps avoid errors.
Number to String
local rsi = 25.5
local message = "RSI: " .. rsi -- Automatically converts to string
String to Number
local text = "14.5"
local number = tonumber(text) -- Converts to number: 14.5
local invalid = "abc"
local result = tonumber(invalid) -- Returns nil (not a number)
Boolean to Number
local flag = true
local numberValue = flag and 1 or 0 -- true = 1, false = 0
Collection to Number
local closePrices = ClosePrices()
-- When used in number context, uses latest value
local currentPrice = closePrices -- Same as closePrices[1]
Type Checking
Check variable types when needed:
local value = 100
-- Check if number
if type(value) == "number" then
Log("Value is a number")
end
-- Check if string
if type(value) == "string" then
Log("Value is a string")
end
-- Check if nil
if value == nil then
Log("Value is nil")
end
Common Type Mistakes
Type Mismatch in Operations
-- Error: Can't concatenate boolean directly
local isActive = true
local message = "Status: " .. isActive -- Error!
-- Correct: Convert to string or use text
local isActive = true
local message = "Status: " .. tostring(isActive) -- "Status: true"
Incorrect Collection Access
local closePrices = ClosePrices()
-- Error: Index 0 doesn't exist
local value = closePrices[0]
-- Error: .Value property doesn't exist
local value = closePrices.Value
-- Correct: Use index 1 or collection directly
local latest = closePrices[1]
local latest2 = closePrices
Mixing Types in Comparisons
local number = 100
local text = "100"
-- These are NOT equal
if number == text then -- This is false!
Log("They are equal")
end
-- Correct: Convert to same type first
if tostring(number) == text then
Log("They are equal")
end
Best Practices
- Use appropriate types for the data you're storing
- Let HaasScript infer types rather than declaring them explicitly
- Be careful with collections - remember 1-based indexing
- Check for nil before using variables that might be empty
- Use proper string concatenation when combining text and numbers
- Understand auto-conversion - collections automatically use latest value in number contexts
- Use signal constants rather than string values for trading signals
Summary
- Numbers: Integers and decimals for calculations
- Strings: Text data enclosed in quotes
- Booleans: true/false for logical conditions
- Collections: Arrays of data with 1-based indexing, auto-use latest value
- Signals: Predefined constants for trading decisions
- Enums: Predefined constants for configuration
- Type conversions: Automatic in many cases, manual when needed
- Collections are special: 1-based indexing, index 1 = latest, no .Value property
Understanding data types helps you write correct HaasScript code and avoid common errors related to type mismatches and incorrect data access.