명시
Essa estratégia combina análise técnica com uma gestão de risco sofisticada para operar de forma automatizada no par USD/JPY. Utiliza a tendência do mercado para filtrar operações, o RSI para gerar sinais de entrada, e mecanismos de stop loss, take profit e trailing stop para proteger os lucros. A análise dos run-ups positivos permite que as operações sejam fechadas de forma eficiente, garantindo que os ganhos sejam capturados antes de qualquer reversão significativa.
CODIGO EM PINE SCRIPT:
Quero ele na versão do MQL5/MT5
//@version=5
strategy("USD/JPY Automated Trading Strategy", overlay=true)
// Inputs configuráveis
takeProfitPips = input.float(300.0, title="Take Profit (pips)")
stopLossPips = input.float(100.0, title="Stop Loss (pips)")
trailingStopPips = input.float(100.0, title="Trailing Stop (pips)")
runUpLength = input.int(10, title="Quantidade de Run-Ups Analisados")
// Converter pips para o valor apropriado para o par USD/JPY (1 pip = 0.01)
takeProfit = takeProfitPips * 0.01
stopLoss = stopLossPips * 0.01
trailingStop = trailingStopPips * 0.01
// Configuração das médias móveis e RSI
sma200 = ta.sma(close, 200)
rsi = ta.rsi(close, 14)
// Variáveis de tendência
isUptrend = close > sma200
isDowntrend = close < sma200
// Variáveis de compra e venda
var buySignal = false
var sellSignal = false
// Extração da chamada `ta.valuewhen` para fora do bloco condicional
rsi70crossed = ta.valuewhen(rsi > 70, rsi, 0)
rsi30crossed = ta.valuewhen(rsi < 30, rsi, 0)
// Verifica se o RSI atinge 70 e depois volta para 50 para compra
if (isUptrend and ta.crossover(rsi, 50))
if (rsi70crossed > 70)
buySignal := true
// Verifica se o RSI atinge 30 e depois volta para 50 para venda
if (isDowntrend and ta.crossunder(rsi, 50))
if (rsi30crossed < 30)
sellSignal := true
// Arrays para armazenar os run-ups positivos
var float[] runUps = array.new_float(0)
// Função para calcular o run-up atual
calcRunUp(entryPrice) =>
var float runUp = na
if (strategy.opentrades > 0)
runUp := high - entryPrice
runUp
// Função para calcular a média dos últimos N run-ups
calcAverageRunUp(length) =>
var float sumRunUp = 0.0
count = math.min(length, array.size(runUps))
if (count > 0) // Verifica se o array tem elementos antes de calcular
for i = 0 to count - 1
sumRunUp := sumRunUp + array.get(runUps, i)
sumRunUp / count
// Atualiza o array de run-ups apenas se o run-up for positivo (lucrativo)
if (strategy.closedtrades > 0)
lastTrade = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
lastRunUp = calcRunUp(lastTrade)
if (lastRunUp > 0)
array.unshift(runUps, lastRunUp)
if (array.size(runUps) > runUpLength)
array.pop(runUps)
// Ações de compra
if (buySignal)
strategy.entry("Buy", strategy.long)
// Stop Loss e Take Profit
strategy.exit("Take Profit/Stop Loss", "Buy", limit=close + takeProfit, stop=close - stopLoss)
// Trailing Stop
strategy.exit("Trailing Stop", "Buy", trail_offset=trailingStop, trail_points=trailingStop)
buySignal := false
if (rsi <= 30)
strategy.entry("Add Buy", strategy.long)
// Stop Loss e Take Profit para a segunda entrada
strategy.exit("Add Take Profit/Stop Loss", "Add Buy", limit=close + takeProfit, stop=close - stopLoss)
// Trailing Stop para a segunda entrada
strategy.exit("Add Trailing Stop", "Add Buy", trail_offset=trailingStop, trail_points=trailingStop)
// Ações de venda
if (sellSignal)
strategy.entry("Sell", strategy.short)
// Stop Loss e Take Profit
strategy.exit("Take Profit/Stop Loss", "Sell", limit=close - takeProfit, stop=close + stopLoss)
// Trailing Stop
strategy.exit("Trailing Stop", "Sell", trail_offset=trailingStop, trail_points=trailingStop)
sellSignal := false
if (rsi >= 70)
strategy.entry("Add Sell", strategy.short)
// Stop Loss e Take Profit para a segunda entrada
strategy.exit("Add Take Profit/Stop Loss", "Add Sell", limit=close - takeProfit, stop=close + stopLoss)
// Trailing Stop para a segunda entrada
strategy.exit("Add Trailing Stop", "Add Sell", trail_offset=trailingStop, trail_points=trailingStop)
// Fechar posições baseadas na média dos últimos N run-ups positivos
averageRunUp = calcAverageRunUp(runUpLength)
if averageRunUp and close >= strategy.position_avg_price + averageRunUp
strategy.close("Buy")
if averageRunUp and close <= strategy.position_avg_price - averageRunUp
strategy.close("Sell")
// Plotar indicadores no gráfico
plot(sma200, color=color.blue, title="SMA 200")
hline(50, "RSI 50", color=color.gray)
hline(70, "RSI 70", color=color.red)
hline(30, "RSI 30", color=color.green)
plot(rsi, title="RSI", color=color.purple)