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

Formatting

Formatting HaasScript Code

Proper code formatting makes your HaasScript scripts easier to read, debug, and maintain. While HaasScript will execute regardless of how your code looks, consistent formatting helps you spot errors quickly and understand your logic at a glance.

Why Formatting Matters

  • Readability: Well-formatted code is easier to scan and understand
  • Debugging: Clear structure helps identify logic errors and typos
  • Maintenance: Easier to modify scripts weeks or months later
  • Sharing: Other traders can understand your scripts when you share them
  • Collaboration: Essential when working with others on complex strategies

Basic Formatting Rules

Indentation

Use consistent indentation to show code structure and nesting:

-- Good: Consistent indentation
local rsi = RSI(ClosePrices(), 14)

if rsi < 30 then
    DoLong("Oversold")
    StopLoss(2.0)
else
    DoShort("Overbought")
end

-- Bad: No indentation makes code hard to read
local rsi = RSI(ClosePrices(), 14)
if rsi < 30 then
DoLong("Oversold")
StopLoss(2.0)
else
DoShort("Overbought")
end

Standard practice: Use 4 spaces or 1 tab per indentation level.

Line Length

Keep lines at a reasonable length for readability:

-- Good: Split long lines
local rsi = RSI(
    ClosePrices(),
    Input("RSI Period", 14)
)

-- Acceptable: Shorter lines can stay on one line
local rsi = RSI(ClosePrices(), 14)

Standard practice: Limit lines to 80-100 characters when possible.

Blank Lines

Use blank lines to separate logical sections:

-- Define inputs
local rsiPeriod = Input("RSI Period", 14)
local buyLevel = Input("Buy Level", 30)

-- Calculate indicators
local rsi = RSI(ClosePrices(), rsiPeriod)
local macd = MACD(ClosePrices(), 12, 26, 9)

-- Execute trading logic
if rsi < buyLevel then
    DoLong("Entry signal")
end

Standard practice: One blank line between logical sections, no blank lines within code blocks.

Commenting for Clarity

Comments explain why your code does something, not what it does (the code itself shows what).

Good Comments

-- Use ATR for dynamic stop loss since market volatility changes
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)
local atrPercentage = (atr / ClosePrices()) * 100
StopLoss(atrPercentage * 2)

-- Wait for RSI confirmation before entering
if rsi < 30 and macdSignal == SignalLong then
    DoLong("RSI oversold + MACD confirmation")
end

Bad Comments

-- Calculate RSI
local rsi = RSI(ClosePrices(), 14)  -- This comment adds no value

-- Check if RSI is less than 30
if rsi < 30 then                    -- The code already tells us this
    DoLong()
end

Comment Styles

HaasScript supports two comment styles:

-- Single-line comment (use this most of the time)

--[[
Multi-line comment
for longer explanations
that span multiple lines
]]

Naming Conventions

Variable Names

Use descriptive names that explain the variable's purpose:

-- Good: Clear, descriptive names
local rsiPeriod = Input("RSI Period", 14)
local atrPercentage = (atr / ClosePrices()) * 100
local entrySignal = SignalLong

-- Bad: Unclear abbreviations
local rp = Input("RSI Period", 14)
local atp = (atr / ClosePrices()) * 100
local es = SignalLong

camelCase Naming

HaasScript follows Lua convention using camelCase (lowercase first letter, uppercase for subsequent words):

-- Good: camelCase
local closePrices = ClosePrices()
local rsiValue = RSI(ClosePrices(), 14)
local stopLossPercentage = 2.0

-- Avoid: snake_case (Python style)
local close_prices = ClosePrices()
local rsi_value = RSI(ClosePrices(), 14)

Structuring Your Scripts

Organize your scripts in a logical flow from top to bottom:

Recommended Structure

-- ============================================
-- Strategy Name
-- Description of what this strategy does
-- Author: Your Name
-- Date: 2024-01-15
-- ============================================

-- ===== INPUT PARAMETERS =====
-- Define all user-configurable settings at the top
local rsiPeriod = Input("RSI Period", 14)
local buyLevel = Input("Buy Level", 30)
local sellLevel = Input("Sell Level", 70)

-- ===== INDICATOR CALCULATIONS =====
-- Calculate all indicators together
local rsi = RSI(ClosePrices(), rsiPeriod)
local macd = MACD(ClosePrices(), 12, 26, 9)

-- ===== TRADING LOGIC =====
-- Define entry conditions
local shouldBuy = rsi < buyLevel
local shouldSell = rsi > sellLevel

-- Execute trades based on conditions
if shouldBuy then
    DoLong("RSI oversold")
elseif shouldSell then
    DoShort("RSI overbought")
end

-- ===== RISK MANAGEMENT =====
-- Apply stop loss and take profit
StopLoss(2.0)
TakeProfit(5.0)

This structure makes it easy to:

  • Find and modify input parameters
  • Understand what indicators are being used
  • Follow the trading logic
  • Adjust risk management settings

Conditionals and Flow Control

Format conditional statements for maximum readability:

-- Good: Clear structure
if rsi < 30 then
    DoLong("Oversold")
elseif rsi > 70 then
    DoShort("Overbought")
else
    DoExitPosition("Exit position")
end

-- Good: Complex conditions on multiple lines
if rsi < buyLevel and
   macdSignal == SignalLong and
   volume > AverageVolume()
then
    DoLong("Multiple indicators confirm entry")
end

Function Calls

Format function calls consistently:

-- Good: Simple calls on one line
local rsi = RSI(ClosePrices(), 14)

-- Good: Multi-line for complex calls
local macd = MACD(
    ClosePrices(),
    12,    -- Fast period
    26,    -- Slow period
    9      -- Signal period
)

-- Good: Align parameters for readability
local sma = SMA(ClosePrices(), 20)
local ema = EMA(ClosePrices(), 20)
local rsi = RSI(ClosePrices(), 14)

Common Formatting Mistakes

Inconsistent Indentation

-- Bad: Mixed indentation
if rsi < 30 then
  DoLong()
elseif rsi > 70 then
    DoShort()
end

-- Good: Consistent indentation
if rsi < 30 then
    DoLong()
elseif rsi > 70 then
    DoShort()
end

Magic Numbers

-- Bad: Unclear numbers in code
if rsi < 30 then
    DoLong()
end

-- Good: Named constants explain the meaning
local oversoldLevel = 30
if rsi < oversoldLevel then
    DoLong()
end

Excessive Comments

-- Bad: Over-commenting obvious code
-- Define RSI period
local rsiPeriod = Input("RSI Period", 14)  -- Set RSI period to 14
-- Calculate RSI
local rsi = RSI(ClosePrices(), rsiPeriod)  -- Calculate RSI using ClosePrices and rsiPeriod
-- Check if RSI is less than 30
if rsi < 30 then  -- If RSI is oversold
    DoLong()  -- Enter long position
end

-- Good: Comments only explain why
local rsiPeriod = Input("RSI Period", 14)
local rsi = RSI(ClosePrices(), rsiPeriod)

-- RSI oversold indicates potential buying opportunity
if rsi < 30 then
    DoLong()
end

Formatting Tools

The HaasOnline code editor includes:

  • Auto-indentation: Automatically indents lines as you type
  • Syntax highlighting: Color-codes different elements of your code
  • Line numbers: Helps when debugging and discussing code
  • Code folding: Collapse sections to focus on specific parts

Use these features to maintain consistent formatting throughout your scripts.

Review Your Formatting

Before deploying or sharing a script, ask yourself:

  • Can I understand the logic at a glance?
  • Would another trader be able to read this?
  • Are my variable names clear and descriptive?
  • Have I removed unnecessary comments?
  • Is the indentation consistent throughout?

If you can answer yes to these questions, your code is well-formatted.