[pshaiCmd] Trailing Arm Stop-Loss (TASL)

stable
By pshai in Safeties Published November 2021 👁 2,351 views 💬 0 comments

Description

A custom command implementation of the built-in TrailingArmStopLoss command for educational purposes.
HaasScript
-- [pshaiCmd] Trailing Arm Stop-Loss (TASL)
-- Author: pshai

DefineCommand('TrailingArmStopLoss', 'Educational TASL')

local percentage = DefineParameter(NumberType, 'percentage', 'Trailing distance in percentage', true, 1)
local arm = DefineParameter(NumberType, 'arm', 'Activation distance in percentage', true, 0.2)
local positionId = DefineParameter(StringType, 'positionId', 'Optional position ID', false, '')
local direction = DefineParameter(EnumType, 'direction', 'Optional direction enum', false, NoPosition)

local pos = PositionContainer(positionId)
if positionId == '' then positionId = pos.positionId end

local isTrailing = Load('tasl:it'..positionId, false)
local price = Load('tasl:p'..positionId, pos.enterPrice)

local cp = CurrentPrice(pos.market)
local result = false


if pos.isLong and not pos.isShort then
    if direction != PositionShort then
        if not isTrailing then
            local armTarget = AddPerc(pos.enterPrice, arm)
            if cp.high > armTarget then
                isTrailing = true
            end

            Plot(0, 'Arm Target '..arm..'%', armTarget, {color = Green, id = positionId})
        else
            price = ArrayGet(Max(price, cp.high), 1)

            local stop = SubPerc(price, percentage)

            result = stop > cp.bid

            Plot(0, 'Trailing Stop '..percentage..'%', stop, {color = Red, id = positionId})
        end
    end
elseif pos.isShort and not pos.isLong then
    if direction != PositionLong then
        if not isTrailing then
            local armTarget = SubPerc(pos.enterPrice, arm)
            if cp.low < armTarget then
                isTrailing = true
            end

            Plot(0, 'Arm Target '..arm..'%', armTarget, {color = Green, id = positionId})
        else
            price = ArrayGet(Min(price, cp.low), 1)

            local stop = AddPerc(price, percentage)

            result = stop < cp.ask

            Plot(0, 'Trailing Stop '..percentage..'%', stop, {color = Red, id = positionId})
        end
    end
end

Save('tasl:it'..positionId, isTrailing)
Save('tasl:p'..positionId, price)

DefineOutput(BooleanType, result, '')

0 Comments

Sign in to leave a comment.

No comments yet. Be the first!