
Esta estrategia es una estrategia de comercio cuantitativa que combina un índice relativamente débil (RSI) y un indicador de tendencia / dispersión de medias móviles (MACD). El núcleo de la estrategia consiste en determinar la dirección de la tendencia del mercado mediante la observación de las zonas de sobreventa / sobreventa en el RSI, en combinación con las señales cruzadas del indicador MACD en casi 5 ciclos de negociación, y establecer paradas de pérdida para controlar el riesgo. Este método no solo puede proporcionar señales de comercio más precisas, sino que también puede reducir eficazmente el riesgo de señales falsas.
La estrategia se basa en los siguientes componentes centrales:
La estrategia combina los indicadores RSI y MACD, junto con condiciones de entrada flexibles y mecanismos de control de riesgo, para construir un sistema de negociación relativamente completo. Si bien hay algunos lugares que necesitan ser optimizados, el marco básico tiene una buena escalabilidad y, con mayor optimización y perfección, se espera que se convierta en una estrategia de negociación más sólida.
/*backtest
start: 2024-11-12 00:00:00
end: 2024-12-12 00:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=5
strategy("MACD & RSI Strategy with SL/TP and Flexible Entry (5 bars)", overlay=true)
// Параметры для RSI и MACD
rsiLength = 14
overbought = 70
oversold = 30
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)
// Рассчитаем RSI
rsi = ta.rsi(close, rsiLength)
// Проверка пересечения MACD
macdCrossOver = ta.crossover(macdLine, signalLine)
macdCrossUnder = ta.crossunder(macdLine, signalLine)
// Логика для проверки пересечения MACD за последние 5 баров
var bool macdCrossOverRecent = false
var bool macdCrossUnderRecent = false
// Проверяем пересечения за последние 5 баров
for i = 0 to 4
if macdCrossOver[i]
macdCrossOverRecent := true
if macdCrossUnder[i]
macdCrossUnderRecent := true
// Условия для шортовой сделки: RSI выше 70 (перекупленность) + пересечение MACD за последние 5 баров
shortCondition = ta.highest(rsi, 5) > overbought and macdCrossOverRecent
// Условия для лонговой сделки: RSI ниже 30 (перепроданность) + пересечение MACD за последние 5 баров
longCondition = ta.lowest(rsi, 5) < oversold and macdCrossUnderRecent
// Процент для стоп-лосса и тейк-профита
takeProfitPercent = 0.02
stopLossPercent = 0.02
// Открытие шортовой позиции
if (shortCondition)
strategy.entry("Short", strategy.short)
// Открытие лонговой позиции
if (longCondition)
strategy.entry("Long", strategy.long)
// Рассчитываем стоп-лосс и тейк-профит для шорта
shortStopLoss = strategy.position_avg_price * (1 + stopLossPercent)
shortTakeProfit = strategy.position_avg_price * (1 - takeProfitPercent)
// Рассчитываем стоп-лосс и тейк-профит для лонга
longStopLoss = strategy.position_avg_price * (1 - stopLossPercent)
longTakeProfit = strategy.position_avg_price * (1 + takeProfitPercent)
// Устанавливаем выход по стоп-лоссу и тейк-профиту для шортов
if (strategy.position_size < 0) // Проверяем, что открыта шортовая позиция
strategy.exit("Take Profit/Stop Loss Short", "Short", stop=shortStopLoss, limit=shortTakeProfit)
// Устанавливаем выход по стоп-лоссу и тейк-профиту для лонгов
if (strategy.position_size > 0) // Проверяем, что открыта лонговая позиция
strategy.exit("Take Profit/Stop Loss Long", "Long", stop=longStopLoss, limit=longTakeProfit)
// Графики для отображения RSI и MACD
plot(rsi, "RSI", color=color.purple)
hline(overbought, "Overbought", color=color.red)
hline(oversold, "Oversold", color=color.green)
plot(macdLine, "MACD Line", color=color.blue)
plot(signalLine, "Signal Line", color=color.orange)