0bps

Strategy vault / Trend following

Trend Following Strategy Based on MA Lines

This strategy calculates moving averages (MA) of different periods to determine the market trend direction. It goes long when the trend is up and goes short when the trend is down to follow the trend.

Author
ChaoZhang
Complexity
Starter · 56 lines
Parameters
0
Backtest bar
1d · swing
Tested on
BTC/USDT · futures

IMG

Overview

This strategy calculates moving averages (MA) of different periods to determine the market trend direction. It goes long when the trend is up and goes short when the trend is down to follow the trend.

Strategy Principle

  1. Calculate 20-period, 60-period and 120-period MAs
  2. Compare the magnitude relationship among MA20, MA60 and MA120 to determine the current trend direction
    • If MA20>MA60>MA120, judge the trend to be upward
    • If MA20<MA60<MA120, judge the trend to be downward
  3. Go long when MA20 crosses over MA60, and go short when MA20 crosses below MA60
  4. Use MA60 as the reference line for take profit and stop loss
    • Take profit line for long position is 3 times of MA60
    • Take profit line for short position is 0.9 times of MA60

Advantage Analysis

  1. Use MA combos of different periods to determine trend to avoid whipsaws
  2. Only enter at trend reversal points to increase winning rate
  3. Have clear rules for take profit and stop loss to reduce risks

Risk Analysis

  1. In range-bound markets, MA crossovers may happen frequently, causing too frequent trading
  2. Parameters for take profit and stop loss need to be optimized, otherwise position may be stopped out prematurely or take profit is not enough

Optimization Directions

  1. Add indicators to identify range-bound markets to avoid overtrading
  2. Optimize MA period combinations to find the best parameters
  3. Test and optimize take profit and stop loss coefficients to balance maximizing returns and minimizing risks

Summary

The strategy has a clear logic of using MAs to determine trends. After parameter optimization and indicator optimization, it can become a very practical trend following strategy.

Source Pine Script

/*backtest
start: 2023-02-15 00:00:00
end: 2024-02-21 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("MA60Long on the top and short on the bottom", overlay=true)

// CalculationMA20/60/120
ma20 = ta.sma(close, 20)
ma60 = ta.sma(close, 60)
ma120 = ta.sma(close, 120)

// JudgmentMATrends
maUpTrend = ma20 > ma60 and ma60 > ma120
maDownTrend = ma20 < ma60 and ma60 < ma120

// Draw vertical line markMATrend turning point
plotshape(maUpTrend and ta.crossover(ma20, ma60), style=shape.triangledown, location=location.abovebar, color=color.green, size=size.small)
plotshape(maDownTrend and ta.crossunder(ma20, ma60), style=shape.triangleup, location=location.belowbar, color=color.red, size=size.small)

// Draw background markerMAtrend
bgcolor(maUpTrend ? color.new(color.green, 90) : na)
bgcolor(maDownTrend ? color.new(color.red, 90) : na)

// Conditions for Opening Long Positions
longCondition = ta.crossover(close, ma60)

// Conditions for Opening Short Positions
shortCondition = ta.crossunder(close, ma60)

// is passing throughMA60According to conditions, establish corresponding long or short positions
if (longCondition)
    strategy.entry("Long", strategy.long)

if (shortCondition)
    strategy.entry("Short", strategy.short)

// Take profit and stop loss rules
calculateReturns() =>
    close / strategy.position_avg_price - 1

takeProfitCondition = calculateReturns() >= 3  // Position profit reached300%
stopLossCondition = calculateReturns() <= -0.1  // Position loss reaches10%

if (takeProfitCondition)
    strategy.close("Long", comment="Take Profit")
    strategy.close("Short", comment="Take Profit")

if (stopLossCondition)
    strategy.close("Long", comment="Stop Loss")
    strategy.close("Short", comment="Stop Loss")

Published by ChaoZhang on the FMZ strategy square · last modified 2024-02-22. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/Trend-Following-Strategy-Based-on-MA-Lines.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open