Using Comments
Using Comments
Comments are non-executable text in your HaasScript code that explain what your code does and why it does it. While HaasScript ignores comments when executing your scripts, well-written comments are essential for creating maintainable, understandable trading strategies.
Why Comments Matter
- Documentation: Explain complex logic and trading decisions
- Memory aid: Remember why you wrote code a certain way weeks or months later
- Collaboration: Help other traders understand your strategies
- Debugging: Temporarily disable code without deleting it
- Learning: Teach yourself and others how HaasScript works
HaasScript Comment Syntax
HaasScript supports two types of comments:
Single-Line Comments
Use -- for comments that span a single line:
-- This is a single-line comment
local rsiPeriod = Input("RSI Period", 14) -- Comments can follow code
-- Blank space before comment improves readability
local rsi = RSI(ClosePrices(), rsiPeriod)
Multi-Line Comments
Use --[[ ]] for longer comments that span multiple lines:
--[[
This is a multi-line comment.
Use it for longer explanations
that don't fit on a single line.
]]
local rsi = RSI(ClosePrices(), 14)
You can also use this style to temporarily disable blocks of code:
--[[
local oldLogic = RSI(ClosePrices(), 14)
if oldLogic < 30 then
DoLong("Old strategy")
end
--]]
-- New logic goes here
local newLogic = MACD(ClosePrices(), 12, 26, 9)
What to Comment
Comment why, not what. The code itself shows the what. Comments should explain the reasoning behind it.
Good Comments
-- Use 2x ATR for stop loss to accommodate normal volatility
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)
local atrPercentage = (atr / ClosePrices()) * 100
StopLoss(atrPercentage * 2)
-- Only enter when both RSI and MACD confirm the signal
if rsi < 30 and macdSignal == SignalLong then
DoLong("Dual indicator confirmation")
end
-- Tighter stop loss for scalping strategy
StopLoss(0.5)
Bad Comments
-- Define RSI period
local rsiPeriod = Input("RSI Period", 14)
-- Calculate RSI
local rsi = RSI(ClosePrices(), rsiPeriod)
-- Check if RSI is less than 30
if rsi < 30 then
DoLong("Buy signal")
end
These comments just repeat what the code already says. They add no value.
Commenting Strategies
Script Headers
Always start your scripts with a header comment explaining the strategy:
-- ============================================
-- RSI Mean Reversion Strategy
--
-- Enters long when RSI is oversold (< 30)
-- Enters short when RSI is overbought (> 70)
-- Uses 2x ATR dynamic stop loss
--
-- Best for: Ranging markets with clear support/resistance
-- Risk: Medium
-- Timeframe: 1 hour or higher recommended
-- ============================================
local rsiPeriod = Input("RSI Period", 14)
local atrMultiplier = Input("ATR Multiplier", 2)
Section Dividers
Use comments to divide your script into logical sections:
-- ===== INPUT PARAMETERS =====
local rsiPeriod = Input("RSI Period", 14)
local buyLevel = Input("Buy Level", 30)
-- ===== INDICATOR CALCULATIONS =====
local rsi = RSI(ClosePrices(), rsiPeriod)
local macd = MACD(ClosePrices(), 12, 26, 9)
-- ===== ENTRY LOGIC =====
if rsi < buyLevel then
DoLong("Entry signal")
end
-- ===== RISK MANAGEMENT =====
StopLoss(2.0)
TakeProfit(5.0)
Pro Tip - Foldable Sections:
Indent code under your section comments to create foldable sections in the editor. When you collapse a folded section, the comment remains visible as the label:
-- INPUT PARAMETERS
local rsiPeriod = Input("RSI Period", 14)
local buyLevel = Input("Buy Level", 30)
local sellLevel = Input("Sell Level", 70)
-- INDICATOR CALCULATIONS
local rsi = RSI(ClosePrices(), rsiPeriod)
local macd = MACD(ClosePrices(), 12, 26, 9)
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)
-- ENTRY LOGIC
if rsi < buyLevel then
DoLong("Entry signal")
end
When you fold these sections, you'll just see this:
-- INPUT PARAMETERS ...
-- INDICATOR CALCULATIONS ...
-- ENTRY LOGIC ...
This makes navigating large scripts much easier.
Explaining Complex Logic
Comment code that might not be immediately obvious:
-- Calculate position size based on account balance and risk percentage
-- Risk 2% of account per trade
local accountBalance = Balance()
local riskPercentage = 2
local riskAmount = (accountBalance / 100) * riskPercentage
-- Use ATR to calculate stop loss distance in price terms
local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)
local stopDistance = atr * 2
-- Calculate position size that respects risk amount
local positionSize = riskAmount / stopDistance
Documenting Input Parameters
Explain why you chose specific default values:
-- 14-period RSI is standard, widely used by traders
local rsiPeriod = Input("RSI Period", 14)
-- 30/70 levels reduce false signals compared to 20/80
local buyLevel = Input("Buy Level", 30)
local sellLevel = Input("Sell Level", 70)
-- 2x ATR accommodates normal market volatility
local atrMultiplier = Input("ATR Stop Loss Multiplier", 2)
Recording Strategy Performance
Keep a changelog of modifications and results:
-- ============================================
-- STRATEGY CHANGE LOG
-- ============================================
-- 2024-01-15: Initial version
-- 2024-01-20: Changed RSI period from 14 to 21 (fewer false signals)
-- 2024-02-01: Added MACD confirmation (improved win rate by 15%)
-- 2024-02-15: Adjusted stop loss from 1.5x to 2x ATR (reduced early exits)
-- ============================================
When NOT to Comment
Don't comment code that is self-explanatory:
-- Bad: These comments add no value
local rsi = RSI(ClosePrices(), 14) -- Calculate RSI with period 14
local sma = SMA(ClosePrices(), 20) -- Calculate SMA with period 20
local ema = EMA(ClosePrices(), 20) -- Calculate EMA with period 20
-- Good: Code is clear without comments
local rsi = RSI(ClosePrices(), 14)
local sma = SMA(ClosePrices(), 20)
local ema = EMA(ClosePrices(), 20)
Don't comment outdated information:
-- Bad: Comment describes old code
-- Use RSI period of 21 for fewer signals
local rsi = RSI(ClosePrices(), 14) -- This is now 14, not 21
-- Good: Either update the comment or remove it
local rsi = RSI(ClosePrices(), 14)
Commenting for Debugging
Use comments to debug by temporarily disabling code:
-- Original logic
if rsi < 30 then
DoLong("RSI oversold")
end
-- Testing alternative logic
-- if rsi < 30 and macdSignal == SignalLong then
-- DoLong("RSI + MACD confirmation")
-- end
-- Keep both versions while testing, remove the old one when confirmed
Multi-Line Comment Tips
When using multi-line comments, maintain consistent formatting:
--[[
Strategy: Moving Average Crossover
Entry: When fast MA crosses above slow MA
Exit: When fast MA crosses below slow MA
Stop Loss: 2x ATR
Take Profit: 1:2 risk-reward ratio
Best for: Trending markets
Avoid: Ranging or choppy markets
]]
local fastMA = EMA(ClosePrices(), 9)
local slowMA = EMA(ClosePrices(), 21)
Comment Density
Aim for the right balance—too few comments make code hard to understand, too many make it cluttered:
-- Too few: Hard to understand
local r = RSI(ClosePrices(), 14)
local m = MACD(ClosePrices(), 12, 26, 9)
if r < 30 and m == SignalLong then DoLong() end
-- Too many: Cluttered and redundant
-- Define the RSI period
local rsiPeriod = 14
-- Calculate RSI using ClosePrices and the period
local rsi = RSI(ClosePrices(), rsiPeriod)
-- Define the RSI buy level
local buyLevel = 30
-- Check if RSI is below buy level
if rsi < buyLevel then
-- Execute a long position
DoLong("Entry signal")
end
-- Just right: Clear and helpful
local rsiPeriod = Input("RSI Period", 14)
local rsi = RSI(ClosePrices(), rsiPeriod)
local buyLevel = Input("Buy Level", 30)
-- Enter when RSI is oversold
if rsi < buyLevel then
DoLong("RSI oversold entry")
end
Commenting Best Practices
- Keep comments current: Update comments when you modify code
- Be concise: Say what you need to say, then stop
- Explain trading logic: Focus on the reasoning, not the syntax
- Document parameters: Explain why you chose specific values
- Date your changes: Add timestamps when making significant modifications
- Remove dead comments: Delete comments that no longer apply
Template Scripts
Create templates with helpful comments for reuse:
-- ============================================
-- TEMPLATE: Simple Indicator Strategy
-- ============================================
-- Strategy Name: [YOUR STRATEGY NAME]
-- Strategy Type: [Trend Following / Mean Reversion / Breakout]
-- Timeframe: [Best timeframes for this strategy]
-- Risk Level: [Low / Medium / High]
-- ============================================
-- CHANGE LOG
-- ============================================
-- YYYY-MM-DD: Initial creation
-- ============================================
-- ===== INPUT PARAMETERS =====
-- Add user-configurable parameters here
local indicatorPeriod = Input("Indicator Period", 14)
local entryLevel = Input("Entry Level", 30)
-- ===== INDICATOR CALCULATIONS =====
-- Calculate your indicators here
local indicator = RSI(ClosePrices(), indicatorPeriod)
-- ===== ENTRY LOGIC =====
-- Define your entry conditions
if indicator < entryLevel then
DoLong("Entry signal")
end
-- ===== EXIT LOGIC =====
-- Define your exit conditions
if indicator > 70 then
DoExitPosition("Exit signal")
end
-- ===== RISK MANAGEMENT =====
-- Set stop loss and take profit
StopLoss(2.0)
TakeProfit(5.0)
Review Your Comments
Before finalizing a script, review your comments:
- Are they explaining why, not what?
- Are they accurate and up to date?
- Do they add value or just repeat the code?
- Would another trader understand your strategy?
- Are there any uncommented complex sections?
Good comments are the difference between a script that only you understand and one that others can use, modify, and improve.