Ricardo Marinho
Ricardo Marinho

Reputation: 1

Pine Script V5, how to I set SL/TP pre inputing a range?

I tried to use the word range, but it didn´t work, what I want is to position the SL/TP orders together with the order based on a pre set range of $ or %. Sample: order long price $1000, pre set range of $100 or 10%, send take profit to close at $100 and Stop loss at $900 I really apreciate if someone can show me or indicate any place where I can find a help for it. Best regards Ricardo Marinho

//@version=5
strategy("Cruzamento de Médias com Range Personalizável", overlay=true)

// Input para o período das médias móveis
fast_length = input.int(9, title="Período da Média Rápida")
slow_length = input.int(21, title="Período da Média Lenta")

// Input para o range
range_type = input.string("USDT", title="Tipo de Range", options=["USDT", "Percentual"])
range_value = input.float(100, title="Valor do Range (em USDT ou %)")
is_percentage = range_type == "Percentual"

// Cálculo das médias móveis
fast_ma = ta.sma(close, fast_length)
slow_ma = ta.sma(close, slow_length)

// Condições de cruzamento
longCondition = ta.crossover(fast_ma, slow_ma)
shortCondition = ta.crossunder(fast_ma, slow_ma)

// Função para calcular stop loss e take profit
var float stopLoss = na
var float takeProfit = na

if (longCondition or shortCondition)
price = close
if is_percentage
    priceRange = price * (range_value / 100)
else
    priceRange = range_value

if (longCondition)
    stopLoss := price - priceRange
    takeProfit := price + priceRange
else
    stopLoss := price + priceRange
    takeProfit := price - priceRange

// Execução das ordens
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)

// Configuração de stop loss e take profit
strategy.exit("Exit Long", from_entry="Long", stop=stopLoss, limit=takeProfit)
strategy.exit("Exit Short", from_entry="Short", stop=stopLoss, limit=takeProfit)

// Entrada manual
manualLong = input.bool(false, title="Entrar Manualmente em Long", inline="Manual")
manualShort = input.bool(false, title="Entrar Manualmente em Short", inline="Manual")
if (manualLong)
strategy.entry("Manual Long", strategy.long)
if (manualShort)
strategy.entry("Manual Short", strategy.short)

// Plotando as médias móveis para visualização
plot(fast_ma, title="Média Rápida", color=color.blue)
plot(slow_ma, title="Média Lenta", color=color.red)

Upvotes: 0

Views: 36

Answers (0)

Related Questions