📰 Latest: HaasOnline Academy Is Back — Structured Education for Smarter Trade Bots
Account
Variables

Using variables

Using Variables

Variables are containers for storing data values in your HaasScript scripts. They allow you to reference and manipulate data throughout your trading strategies.

What is a Variable?

A variable is a named location in memory that holds a value. Think of it as a labeled box where you can store information and retrieve it later.

-- Declare a variable and assign a value
local rsiPeriod = 14

-- Use the variable in calculations
local rsi = RSI(ClosePrices(), rsiPeriod)

-- The variable can be reused
local sma = SMA(ClosePrices(), rsiPeriod)

Declaring Variables

In HaasScript, you declare variables using the local keyword:

local variableName = value

Basic Variable Declaration

-- Numbers
local rsiPeriod = 14
local stopLossPercentage = 2.5
local price = 45000.50

-- Strings
local market = "BTC_USDT"
local entryReason = "RSI oversold signal"

-- Booleans
local isLongPosition = true
local useTrailingStop = false

-- Collections (data series)
local closePrices = ClosePrices()
local volume = GetVolume()

Variable Naming Rules

HaasScript variable names must follow these rules:

  • Must start with a letter (a-z, A-Z)
  • Can contain letters, numbers, and underscores
  • Cannot contain spaces or special characters
  • Are case-sensitive (myVariable != myvariable)
  • Cannot be a reserved keyword (local, end, if, then, etc.)
-- Valid variable names
local rsiPeriod = 14
local my_variable = 100
local price1 = 50000
local MarketData = "BTC_USDT"

-- Invalid variable names (will cause errors)
local 1stPrice = 50000      -- Cannot start with a number
local my-variable = 100     -- Cannot contain hyphens
local market data = "BTC"   -- Cannot contain spaces
local local = 10            -- Cannot be a reserved keyword

Variable Types

HaasScript automatically determines variable types based on the assigned value.

Numbers

Numbers can be integers or decimals:

local integer = 14
local decimal = 2.5
local negative = -10
local scientific = 1.5e10  -- Scientific notation

Strings

Strings are text enclosed in quotes:

local text1 = "Hello"
local text2 = 'World'  -- Single quotes also work
local empty = ""

-- String concatenation
local message = "Entry: " .. "Long position"
local logMessage = "RSI: " .. rsiValue

Booleans

Booleans represent true or false:

local inLongPosition = true
local useStopLoss = false
local isMarketOpen = true

Collections (Arrays)

Collections store multiple values:

-- HaasNumberCollection - array of numbers
local closePrices = ClosePrices()  -- All closing prices
local highPrices = HighPrices()    -- All high prices
local lowPrices = LowPrices()      -- All low prices

Signals

Special signal types for trading:

local entrySignal = SignalLong
local exitSignal = SignalExitLong
local noSignal = SignalNone

Variable Scope

The local keyword determines where a variable can be used.

Local Variables

Variables declared with local are only accessible within their code block:

function MyStrategy()
    local rsiPeriod = 14  -- Only accessible within this function

    if rsi < 30 then
        local entryReason = "Oversold"  -- Only accessible within this if block
        DoLong(entryReason)
    end

    -- entryReason is not accessible here
end

-- rsiPeriod is not accessible here

Global Variables

Variables declared without local are global (accessible everywhere):

-- Global variable (accessible anywhere)
globalRsiPeriod = 14

function MyStrategy()
    local rsi = RSI(ClosePrices(), globalRsiPeriod)  -- Can access global
end

Best Practice: Always use local variables unless you have a specific reason to use global variables.

Using Variables in Trading Strategies

Storing Indicator Values

-- Calculate and store indicator values
local rsi = RSI(ClosePrices(), 14)
local macd = MACD(ClosePrices(), 12, 26, 9)
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)

-- Use stored values in logic
if rsi < 30 then
    DoLong("RSI oversold: " .. rsi)
end

Input Parameters as Variables

-- Input parameters create variables
local rsiPeriod = Input("RSI Period", 14)
local buyLevel = Input("Buy Level", 30)
local stopLossPercent = Input("Stop Loss %", 2.0)

-- Use these variables throughout your script
local rsi = RSI(ClosePrices(), rsiPeriod)

if rsi < buyLevel then
    DoLong("Entry signal")
    StopLoss(stopLossPercent)
end

Reusing Calculated Values

-- Calculate once, use multiple times
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)
local atrPercentage = (atr / ClosePrices()) * 100

-- Use in multiple places
StopLoss(atrPercentage * 2)
TakeProfit(atrPercentage * 4)
Log("ATR Percentage: " .. atrPercentage)

Conditional Variable Assignment

-- Variables can change based on conditions
local signal = SignalNone

if rsi < 30 then
    signal = SignalLong
elseif rsi > 70 then
    signal = SignalShort
end

-- Use the signal variable
DoSignal(signal)

Variable Assignment

You can change a variable's value at any time:

local rsiPeriod = 14  -- Initial value

-- Later in the script
rsiPeriod = 21  -- Changed to 21

-- You can also assign based on calculations
local price = ClosePrices()
local targetPrice = price * 1.05  -- 5% above current price
local stopPrice = price * 0.98    -- 2% below current price

Multiple Variable Declaration

You can declare multiple variables in one line:

local rsiPeriod, macdFast, macdSlow = 14, 12, 26

-- Is equivalent to:
local rsiPeriod = 14
local macdFast = 12
local macdSlow = 26

Default Values and nil

Variables are nil (empty) until assigned a value:

local myVariable  -- This variable is nil

-- Check if a variable has a value
if myVariable == nil then
    Log("Variable is empty")
end

-- Assign a value
myVariable = 100

-- Now it has a value
if myVariable ~= nil then
    Log("Variable contains: " .. myVariable)
end

Variable Naming Conventions

Use descriptive names that explain the variable's purpose:

-- Good: Descriptive names
local rsiPeriod = 14
local stopLossPercentage = 2.0
local entrySignal = SignalLong
local atrValue = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)

-- Bad: Unclear abbreviations
local rp = 14
local slp = 2.0
local es = SignalLong
local av = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)

camelCase Convention

HaasScript typically uses camelCase for variables:

-- Recommended: camelCase
local closePrices = ClosePrices()
local rsiValue = RSI(ClosePrices(), 14)
local stopLossPercent = 2.0

-- Avoid: Other styles
local ClosePrices = ClosePrices()  -- Confusing
local RSI_Value = RSI(ClosePrices(), 14)  -- Unconventional
local stop_loss_percent = 2.0  -- Python style

Common Mistakes

Using Variables Before Declaration

-- Error: Using variable before declaring it
local rsi = RSI(ClosePrices(), rsiPeriod)  -- rsiPeriod doesn't exist yet
local rsiPeriod = 14  -- Declared after use

-- Correct: Declare before using
local rsiPeriod = 14
local rsi = RSI(ClosePrices(), rsiPeriod)

Case Sensitivity Errors

local rsiValue = RSI(ClosePrices(), 14)

-- Error: Variable name case mismatch
Log(rsivalue)  -- Error: rsivalue is not defined

-- Correct: Use exact case
Log(rsiValue)

Using Reserved Keywords

-- Error: 'local' is a reserved keyword
local local = 10

-- Error: 'end' is a reserved keyword
local end = 100

-- Correct: Use different names
local localValue = 10
local endValue = 100

Practical Examples

Example 1: Simple RSI Strategy

-- Define variables
local rsiPeriod = Input("RSI Period", 14)
local buyLevel = Input("Buy Level", 30)
local sellLevel = Input("Sell Level", 70)

-- Calculate indicators
local rsi = RSI(ClosePrices(), rsiPeriod)

-- Trading logic using variables
if rsi < buyLevel then
    DoLong("RSI oversold: " .. rsi)
elseif rsi > sellLevel then
    DoShort("RSI overbought: " .. rsi)
end

Example 2: Dynamic Stop Loss with ATR

-- Variables for ATR calculation
local atrPeriod = 14
local atrMultiplier = 2

-- Calculate ATR
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), atrPeriod)

-- Convert ATR price to percentage
local atrPercentage = (atr / ClosePrices()) * 100

-- Use variables in risk management
local stopLossValue = atrPercentage * atrMultiplier
StopLoss(stopLossValue)

Log("ATR-based stop loss: " .. stopLossValue .. "%")

Example 3: Multi-Indicator Strategy

-- Define indicator parameters
local fastMA = 9
local slowMA = 21
local rsiPeriod = 14

-- Calculate and store indicator values
local fastEMA = EMA(ClosePrices(), fastMA)
local slowEMA = EMA(ClosePrices(), slowMA)
local rsi = RSI(ClosePrices(), rsiPeriod)

-- Create signal variable
local entrySignal = SignalNone

-- Determine signal based on multiple indicators
if fastEMA > slowEMA and rsi < 70 then
    entrySignal = SignalLong
elseif fastEMA < slowEMA and rsi > 30 then
    entrySignal = SignalShort
end

-- Execute trade based on signal variable
DoSignal(entrySignal)

Best Practices

  1. Always use local variables unless you need global scope
  2. Use descriptive names that explain the variable's purpose
  3. Declare variables before using them
  4. Follow camelCase convention for consistency
  5. Group related variables together at the top of your script
  6. Reuse calculated values instead of recalculating
  7. Initialize variables to avoid nil errors

Summary

  • Variables store data values for use throughout your script
  • Declare with local for proper scope
  • Use descriptive names following camelCase convention
  • HaasScript determines type automatically from the assigned value
  • Variables can be reassigned new values at any time
  • Organize variables logically at the top of your scripts

Understanding variables is essential for writing functional HaasScript strategies. They allow you to store indicator values, configure parameters, and create flexible, reusable trading logic.