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

Handling leverage

Handling Leverage

Leveraged markets allows you to trade larger positions with less capital, but it also increases risk. Understanding how to calculate and manage leverage is essential for margin and futures trading in HaasScript.

What is Leverage?

Leverage multiplies your trading power by allowing you to control a larger position with less collateral.

Example:

  • No leverage (1x): $1,000 capital = $1,000 position
  • 10x leverage: $1,000 capital = $10,000 position
  • 20x leverage: $1,000 capital = $20,000 position
  • 100x leverage: $1,000 capital = $100,000 position

Risk: Leverage amplifies both gains AND losses. A 1% price move with 10x leverage = 10% gain or loss on your capital.

Leverage in HaasScript

Calculate Required Margin

local market = PriceMarket()
local price = CurrentPrice().close
local amount = 0.1
local margin = 1000
local leverage = 10

-- Required margin for 0.1 contracts
local requiredMargin = UsedMargin(market, price, amount, leverage)

-- Contracts with 1000 margin
local positionSize = MarginToTradeAmount(price, margin, leverage, market)

Log("Required margin: " .. requiredMargin)
Log("Position size: " .. positionSize)

Margin Calculation

UsedMargin() Command

Calculates the margin required for a position:

UsedMargin(market, price, amount, leverage)

Basic Example

local market = CreateMarket("", "BTC", "USDT", "")
local price = 45000
local amount = 0.1
local leverage = 10

local margin = UsedMargin(market, price, amount, leverage)

Log("Position value: $" .. (price * amount))  -- $4,500
Log("Leverage: " .. leverage .. "x")
Log("Required margin: $" .. margin)            -- $450

Cross-Margin vs Isolated Margin

-- Isolated margin (specific leverage)
local isolatedMargin = UsedMargin(market, price, amount, 10)

-- Cross-margin (0 = use account-wide margin)
local crossMargin = UsedMargin(market, price, amount, 0)

MarginToTradeAmount() Command

MarginToTradeAmount(price, margin, leverage, market)
local market = CreateMarket("", "BTC", "USDT", "")
local price = 45000
local margin = 1000
local leverage = 10

local amount = MarginToTradeAmount(price, margin, leverage, market)

Log("Position value: $" .. margin)  -- $1,000
Log("Leverage: " .. leverage .. "x")
Log("Contracts: " .. amount .. " BTC")  -- 0.222 BTC

Leverage Examples

Example 1: Long Position with Leverage

local price = 45000
local amount = 0.5
local leverage = 10
local market = PriceMarket()

-- Position value
local positionValue = price * amount  -- $22,500

-- Required margin
local requiredMargin = UsedMargin(market, price, amount, leverage)  -- $2,250

Log("Position: " .. amount .. " BTC @ $" .. price)
Log("Position value: $" .. positionValue)
Log("Leverage: " .. leverage .. "x")
Log("Required margin: $" .. requiredMargin)

-- Check if sufficient margin
local availableMargin = Balance(QuoteCurrency()).Available
if availableMargin >= requiredMargin then
    DoLong("Sufficient margin for long position")
end

Example 2: Short Position with Leverage

local price = 45000
local amount = 0.3
local leverage = 5

-- Calculate required margin (optional - exchange will reject if insufficient)
local requiredMargin = UsedMargin(PriceMarket(), price, amount, leverage)

Log("Short position margin: $" .. requiredMargin)

-- Check if we have enough margin (optional)
if Balance(QuoteCurrency()).Available >= requiredMargin then
    local position = GetPositionDirection()
    if position == PositionShort then
        Log("Already in short position")
    else
        DoShort("Open short position")
    end
else
    Log("Insufficient margin for short position")
end

Example 3: Dynamic Leverage Selection

local rsi = RSI(ClosePrices(), 14)
local price = CurrentPrice().close
local amount = 0.1

-- Choose leverage based on RSI
local leverage
if rsi < 20 then
    leverage = 20  -- Higher leverage for extreme oversold
    SetLeverage(leverage)
elseif rsi < 30 then
    leverage = 10  -- Moderate leverage for oversold
    SetLeverage(leverage)
else
    leverage = 5   -- Lower leverage for normal conditions
    SetLeverage(leverage)
end

local margin = UsedMargin(PriceMarket(), price, amount, leverage)
Log("RSI: " .. rsi .. ", Leverage: " .. leverage .. "x, Margin: $" .. margin)

Position Size with Leverage

Position Size Calculator

local availableMargin = 1000 -- Investment size
local price = 45000
local leverage = 10

-- Calculate position size
local positionValue = availableMargin * leverage  -- $10,000
local amount = positionValue / price  -- 0.222 BTC

Log("With $" .. availableMargin .. " and " .. leverage .. "x leverage:")
Log("Position size: " .. amount .. " BTC")
Log("Position value: $" .. positionValue)

Risk Management with Leverage

Liquidation Risk

local price = 45000
local entryPrice = price
local leverage = 10

-- Approximate liquidation price
local liquidationPrice = entryPrice * (1 - (1 / leverage))

Log("Entry price: $" .. entryPrice) -- $45,000
Log("Leverage: " .. leverage .. "x") -- 10x
Log("Liquidation price: $" .. liquidationPrice) -- $40,500
Log("Price drop to liquidation: " .. ((entryPrice - liquidationPrice) / entryPrice * 100) .. "%") -- 10%

Safe Leverage Calculation

local maxRiskPercent = 2  -- Max 2% of capital risk
local accountBalance = 10000
local stopLossPercent = 5  -- 5% stop loss

local maxRiskAmount = accountBalance * (maxRiskPercent / 100)
local positionValue = maxRiskAmount / (stopLossPercent / 100)
local requiredLeverage = positionValue / accountBalance

Log("Account balance: $" .. accountBalance) -- $10,000
Log("Max risk: " .. maxRiskPercent .. "% = $" .. maxRiskAmount) -- 2% = $200
Log("Safe leverage: " .. requiredLeverage .. "x") -- 0.4x

Leverage Based on Volatility

local atr = ATR(HighPrices(), LowPrices(), ClosePrices(), 14)
local price = CurrentPrice().close
local atrPercent = (atr / price) * 100

-- Adjust leverage based on volatility
local leverage
if atrPercent < 1 then
    leverage = 10  -- High leverage for low volatility
elseif atrPercent < 2 then
    leverage = 5   -- Moderate leverage for moderate volatility
else
    leverage = 2   -- Low leverage for high volatility
end

Log("ATR: " .. atrPercent .. "%, Using leverage: " .. leverage .. "x")

Leverage with Stop Loss

local price = CurrentPrice().close
local amount = 0.1
local leverage = 10
local capital = 10000

local entryPrice = price
local stopLossPercent = 3  -- 3% stop loss

local stopLossPrice = entryPrice * (1 - (stopLossPercent / 100))
local stopLossAmount = (entryPrice - stopLossPrice) * amount

Log("Entry: $" .. entryPrice)
Log("Stop loss: $" .. stopLossPrice)
Log("Loss amount: $" .. stopLossAmount)

-- Check if loss is acceptable
local maxAcceptableLoss = capital * 0.05  -- 5% of capital

if stopLossAmount <= maxAcceptableLoss then
    DoLong("Leverage: " .. leverage .. "x, Risk acceptable")
    StopLoss(stopLossPercent)
end

Best Practices

  1. Start conservative - Use low leverage (2-5x) when starting
  2. Calculate margin - Always check UsedMargin() before opening positions
  3. Adjust for volatility - Reduce leverage during high volatility
  4. Set stop losses - Essential when using leverage
  5. Monitor liquidation price - Know when you'll be liquidated
  6. Scale appropriately - Match leverage to account size and experience
  7. Consider risk/reward - Higher leverage = higher risk
  8. Test thoroughly - Backtest with leverage to understand risks

Summary

  • Leverage multiplies your position size but also your risk
  • UsedMargin() calculates required margin for a position
  • Cross-margin (leverage = 0) uses account-wide margin
  • Isolated margin (leverage > 0) uses specific margin for position
  • Liquidation risk increases with leverage
  • Conservative leverage (2-5x) is safer than high leverage (20-100x)
  • Adjust leverage based on volatility, account size, and market conditions
  • Always calculate margin requirements before opening positions

Understanding leverage helps you trade larger positions while managing risk effectively. Always use leverage responsibly and calculate potential liquidation scenarios.