USD/JPY Automated Trading Strategy

Tarea técnica

Essa estratégia de trading automatizada foi desenvolvida para operar no par USD/JPY, utilizando médias móveis, RSI, e uma gestão de risco avançada com stop loss, take profit, trailing stop, e um sistema de análise de run-ups lucrativos. Vou explicar cada parte em detalhes:

### 1. **Identificação de Tendência:**
   - **Média Móvel Simples (SMA 200):** 
     - A estratégia usa uma média móvel simples de 200 períodos (`sma200`) para determinar a tendência do mercado.
     - **Tendência de alta:** O preço atual (`close`) está acima da SMA 200.
     - **Tendência de baixa:** O preço atual está abaixo da SMA 200.

### 2. **Sinal de Compra e Venda (RSI):**
   - **Índice de Força Relativa (RSI 14):**
     - A estratégia utiliza o RSI de 14 períodos para identificar condições de sobrecompra e sobrevenda.
     - **Compra:** O RSI precisa ter cruzado para cima o nível 70 e, em seguida, caído para 50. Quando ele cruza novamente para cima de 50 em uma tendência de alta, é gerado um sinal de compra.
     - **Venda:** O RSI precisa ter cruzado para baixo o nível 30 e, em seguida, subido para 50. Quando ele cruza novamente para baixo de 50 em uma tendência de baixa, é gerado um sinal de venda.

### 3. **Execução de Ordens:**
   - **Entrada na Operação:**
     - Quando um sinal de compra ou venda é gerado, a estratégia entra automaticamente em uma posição longa (compra) ou curta (venda).
   - **Stop Loss e Take Profit:**
     - O stop loss e o take profit são definidos com base em uma quantidade de pips configurável pelo usuário. Por exemplo, o take profit pode ser definido em 300 pips e o stop loss em 100 pips.
   - **Trailing Stop:**
     - O trailing stop também é configurável e segue a operação, movendo o stop loss conforme o preço se move a favor da posição, protegendo os lucros à medida que a operação avança.

### 4. **Gestão de Run-Ups Positivos:**
   - **Run-Up:** 
     - Refere-se ao ganho máximo que uma operação atinge antes de recuar.
   - **Média dos Últimos Run-Ups Positivos:** 
     - A estratégia calcula a média dos últimos run-ups positivos (aqueles que resultaram em lucro). Essa média é usada como uma referência adicional para fechar as operações.
   - **Fechamento Baseado na Média dos Run-Ups:**
     - Se o preço se mover a favor da posição até a média dos run-ups positivos e, em seguida, recuar, a estratégia fechará a posição para proteger os ganhos.

### 5. **Personalização:**
   - **Parâmetros Ajustáveis:**
     - O usuário pode ajustar os valores de take profit, stop loss, trailing stop, e o número de run-ups analisados.
   - **Flexibilidade:** 
     - A estratégia permite ajustes que podem adaptar-se a diferentes condições de mercado e estilos de trading.

### 6. **Plotagem:**
   - **Indicadores no Gráfico:**
     - A SMA 200 e os níveis do RSI (30, 50, 70) são plotados no gráfico para visualização das condições de mercado e sinais gerados.

### Resumo:

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)



Han respondido

1
Desarrollador 1
Evaluación
(20)
Proyectos
19
11%
Arbitraje
2
50% / 50%
Caducado
0
Trabaja
2
Desarrollador 2
Evaluación
(55)
Proyectos
64
6%
Arbitraje
24
21% / 38%
Caducado
4
6%
Trabaja
3
Desarrollador 3
Evaluación
(1)
Proyectos
3
0%
Arbitraje
0
Caducado
0
Trabaja
4
Desarrollador 4
Evaluación
(199)
Proyectos
203
28%
Arbitraje
0
Caducado
3
1%
Libre
5
Desarrollador 5
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Libre
6
Desarrollador 6
Evaluación
(195)
Proyectos
316
15%
Arbitraje
20
40% / 35%
Caducado
16
5%
Ocupado
7
Desarrollador 7
Evaluación
Proyectos
0
0%
Arbitraje
0
Caducado
0
Trabaja
8
Desarrollador 8
Evaluación
(60)
Proyectos
183
72%
Arbitraje
4
100% / 0%
Caducado
1
1%
Libre
9
Desarrollador 9
Evaluación
(255)
Proyectos
413
38%
Arbitraje
86
44% / 19%
Caducado
70
17%
Ocupado
Solicitudes similares
i want a forex robot that will read chats and enter trades on its oown. i want it to be able to use all trading strategies and partterns. good risky manegmemt, i want it to forcuse on Gold and and all major forex pairs. i want it to use stop loses and take profits as the market might change direction anytime. i want to work on both mt5 and mt4
I need a developer to create a ea. This is based on candlestick pattern identification and execution. Developers who have experience in developing candle pattern identification ea are preferred. Details will be shared on request
here are the old parameters of the robot EA based on BRILLIANT REVERSAL NON-REPAINT MT5 indicator buy when appears = slow zigzag green and fast zigzag green stop loss = 2 pip below fast zigzag green close order when it appears = fast zigzag red buy again when it appears= fast zigzag green sell when appears = slow zigzag red and fast zigzag red stop loss = 2 pip above fast zigzag red close order when it appears =
Create an EA based on the below trading algorithm. Algorithm Details: • Currency Pair: XAUUSD (Gold) • Trigger Time: New York session start time • Sell Condition: Trigger a sell order if the price is above the price at the end of the Tokyo session on the same day. • Buy Condition: Trigger a buy order if the price is below the price at the end of the Tokyo session on the same day. Settings to Include: • Lot Size • TP
Pls i have an ea login i only want a programmer that can login and monitor only how the ea martingales and its trailing stop movements then I will explain my strategy so my strategy will work with the type of the martingale and trailing stop the login ea I will show you
Hi guys I coded a pinescript strategy which I would like to translate to mql5. First of all I guess we need to create an indicator before we can create an EA out of this. The indicator should show the following drawings: Pivot highs and lows Improved pivot highs and lows with 4 indicators (RSI, MACD, Stoch, ADX) Imbalances / Fair value gaps Asia, London and NY Session Inputs for 3 timeframes: HTF (H4), MTF (H1), LTF
I need a deriv expert who can create Boom and crash indicator of this type and you must have done over 300 jobs.. I need an expert for this job who have done similar job.👉https://youtu.be/pEuzkSI-lLw?si=5IRpWcQGxigKtz58
I am looking for an EA that give above a 50% winrate using a 1:1.5 RR preferably trading in london to new york session, nothing complicated just something profitable. I would love to see a sample of the project before I purchase well thank you
Hello I need a MT4 EA which open trade according to the provided indicator 1 Master/Main indicator 1 Filter Find attached for details EA settings will send via chat or email because unable to send PDF
I need you to check an expert advisor I bought and find the best settings, parameters to get low drawdown and high performance. configuration and optimization of sets to improve management

Información sobre el proyecto

Presupuesto
30 - 100 USD

Cliente

Encargos realizados2
Número de arbitrajes0