0bps

Strategy vault / Arbitrage

Triple Moving Average Quantitative Trading Strategy 433095

Overview: This strategy is a typical technical analysis strategy. It uses several commonly used moving average indicators EMA and auxiliary indicators such as RSI, MACD, and PSR to form entry and stop loss rules…

Author
ChaoZhang
Complexity
Intermediate · 193 lines
Parameters
16
Backtest bar
1d · swing
Tested on
BTC/USDT · futures

IMG

Overview: This strategy is a typical technical analysis strategy. It uses several commonly used moving average indicators EMA and auxiliary indicators such as RSI, MACD, and PSR to form entry and stop loss rules through the combination of different period moving average configurations and indicator signals to find opportunities to buy low and sell high.

Strategy principle: The core of this strategy is the 5, 9, and 21-day moving averages. When the short-period moving average crosses the long-period moving average, it is bullish, and when the short-period moving average crosses below the long-period moving average, it is bearish. In addition, combine the RSI indicator to determine overbought and oversold, the MACD indicator to determine the trend, and the PSR indicator to identify support and resistance for combined trading. The background color setting shows market sentiment and helps determine the trend direction. Set parameters to combine and configure entry rules yourself.

Analysis of strategic advantages:

  1. The moving average indicator is clear and intuitive, making it easy to determine the trend direction.
  2. RSICan effectively identify overbought and oversold conditions, MACD determines long and short trends, PSR finds key price levels, and indicators complement each other.
  3. Multiple entry rules and parameter settings provide strong flexibility.
  4. Numerous combinations of indicators and parameters that can be continuously adjusted and optimized according to the market.

Risk Analysis:

  1. Short-term operations are difficult to grasp the overall trend and there is a risk of missing reversals.
  2. Improper parameter settings may result in too many false signals or missed signals.
  3. Pure technical indicators are easily exploited by arbitrage institutions, leading to losses.
  4. It is easy to stop losses during sharp market fluctuations.

Response method:

  1. Appropriately grasp mid-to-long-term trends to prevent counter-trend short-term operations.
  2. Optimize parameter combinations, set stop-loss, control risk.
  3. Pay attention to potential high-level pullbacks and low-level rebounds.

Optimization Direction:

  1. Adjust moving average parameters to test the best combination.
  2. Add other auxiliary indicators to filter signals.
  3. Add machine learning indicator probability judgment.
  4. Improve signal accuracy based on changes in trading volume.
  5. Add a stop-loss strategy to prevent further losses.

Summary: This strategy combines a variety of auxiliary indicator signals and takes advantage of the moving average indicators to explore short-term opportunities to buy low and sell high. The strategy effect can be continuously improved through parameter optimization and indicator combination, but operation frequency and risk need to be moderately controlled to prevent a single loss from being too large and affecting overall profits.

||

Overview: This strategy is a typical technical analysis strategy that utilizes several common moving average indicators like EMA and auxiliary indicators like RSI, MACD, PSR to form entry and stop loss rules for finding low buy high sell opportunities.

Principle: The core of this strategy is the 5, 9, 21 day moving averages. When the short period MA crosses over the long period one, it signals an uptrend; when the short period MA crosses below the long period one, it signals a downtrend. In addition, RSI is used to determine overbought and oversold levels, MACD to judge the trend, PSR to identify support and resistance for combo trading. The background color shows market sentiment to assist trend judgment. The parameters are customizable for configuring entry rules.

Advantages:

  1. MA indicators give clear trend direction.
  2. RSI effectively spots overbought/oversold levels, MACD judges short-long trend, PSR finds key price levels. The indicators are complementary.
  3. Flexible entry rules and parameter settings.
  4. Many optimizable indicators and parameter combinations adaptable to varying market conditions.

Risks:

  1. Short-term operations may fail to capture major trend and miss reversals.
  2. Improper parameter configuration can lead to too many false signals or missing good signals.
  3. Pure technical indicators are susceptible to manipulation by arbitrageurs causing losses.
  4. Prone to being stopped out in high volatile markets.

Solutions:

  1. Capture mid-long term trend appropriately to avoid trading against major trend.
  2. Optimize parameters, use stop loss to control risks.
  3. Watch out the possibilities of pullback from highs and bounce from lows.

Optimization:

  1. Fine tune MA parameters for best combo.
  2. Add more indicators to filter signals.
  3. Increase machine learning metrics for probability estimate.
  4. Combine volume changes to enhance signal accuracy.
  5. Add stop loss to restrict loss expansion.

Summary: This strategy integrates multiple auxiliary signals, leverages the strength of MA indicators to identify short-term low buy high sell chances. Parameters and indicators combinations may be optimized continuously to improve strategy efficacy, but operation frequency and risks should be moderated to prevent oversized single trade loss from eroding overall profitability.

Parameters

NameDefaultWhat it controls
v_input_10Strategy: rsi | ema | macd | psr | off | BB | ema5
v_input_20background color: rsi | ema | macd | psr | off | exchange | BB | ema5
v_input_3falseShow ema5?
v_input_4trueShow ema9?
v_input_5trueShow ema21?
v_input_6falseShow ema50?
v_input_7falseShow ema100?
v_input_8trueShow ema200
v_input_9trueColor oversold and overbought bars?
v_input_10trueShow Parabolic Sar
v_input_11trueShow Bollinger Bands?
v_input_12falseShow Daily Pivots?
v_input_13truelinewidth
v_input_14truesar points width
v_input_1540oversold rsi
v_input_1665overbought rsi

Source Pine Script

/*backtest
start: 2022-11-17 00:00:00
end: 2023-08-08 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=3
strategy("f.society v7", title="f.society v7", overlay=true)
//@Author: rick#1414
// -----------------------------------------------------
// f.society : Pone 3EMA: 5, 9, 21, 50, 100, 200, SAR, 
// velas azules en sobreventa y velas moradas sobre compra 
// SAR 0.02, 0.02, 0.2 , Bandas de Bollinger
// estrategia de compra y venta con rsi, macd o psr
// color de fondo: ema, rsi (color azul sobreventa 35, 25 (mas intenso))
// -----------------------------------------------------
// Como agregar a Trading view:
// 1 Cerrar todos los otros indicadores antes de añadirlo
// 2. Ir a la página de inicio TradingView.com
// 3. En la parte inferior, haga clic en Editor Pine // ver imagen: // https://cdn.discordapp.com/attachments/407267549047422976/407393815112974336/unknown.png
// 4. borrar todo el texo y reemplazar con todo el contenido de este archivo
// 5. Pulse el botón "Añadir a trazar" (Add to graph)
// -----------------------------------------------------
// revisar opciones de on y off segun indicadores deseados
// https://cdn.discordapp.com/attachments/405885820114042883/412115277883506700/unknown.png
// se puede cambiar la estrategia desde este menu desplegable para señales buy/sell

// Options
estrategia = input(defval="rsi", title = "Strategy", options=["ema","rsi","macd","psr","off","BB","ema5"])
in_bkcolor = input(defval="rsi", title = "background color", options=["ema","rsi","macd","psr","off","exchange","BB","ema5"])
e5 = input(title="Show ema5?", type=bool, defval=false)
e9 = input(title="Show ema9?", type=bool, defval=true)
e21 = input(title="Show ema21?", type=bool, defval=true)
e50 = input(title="Show ema50?", type=bool, defval=false)
e100 = input(title="Show ema100?", type=bool, defval=false)
e200 = input(title="Show ema200", type=bool, defval=true)
in_rsi = input(title="Color oversold and overbought bars?", type=bool, defval=true)
in_sar = input(title="Show Parabolic Sar", type=bool, defval=true)
in_bb = input(title="Show Bollinger Bands?", type=bool, defval=true)
sd = input(false, title="Show Daily Pivots?")
linew = input(1, title="linewidth", minval=0)
sarw = input(1, title="sar points width", minval=0)
ovs = input(40, title="oversold rsi", minval=0)
ovb = input(65, title="overbought rsi", minval=0)



//pf = input(false,title="Show Filtered Pivots")
pf=false

// 3 ema
src = close // input(close, title="Source")
//len9 = input(9, minval=1, title="ema9 Length")
//len21 = input(21, minval=1, title="ema21 Length")
//len200 = input(200, minval=1, title="ema200 Length")
len5=5
len9=9
len21=21
len50=50
len100=100
len200=200
ema5 = ema(src, len5)
ema9 = ema(src, len9)
ema21 = ema(src, len21)
ema50= ema(src, len50)
ema100 = ema(src, len100)
ema200 = ema(src, len200)
plot(e5? ema5 : na, title="EMA5", linewidth=linew, color=purple)
plot(e9? ema9 : na, title="EMA9", linewidth=linew, color=blue)
plot(e21? ema21 : na, title="EMA21", linewidth=linew, color=red)
plot(e50? ema50 : na, title="EMA50", linewidth=linew, color=green)
plot(e100? ema100 : na, title="EMA100", linewidth=linew, color=lime)
plot(e200? ema200 : na, title="EMA200", linewidth=linew, color=yellow)

// RSI Color
//lenR = input(14, minval=1, title="RSI Length")
lenR=14
//up = rma(max(change(src), 0), lenR)
//down = rma(-min(change(src), 0), lenR)
//vrsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
vrsi=rsi(close,lenR)
//plot(vrsi,title="vrsi")
oversold = vrsi < ovs
overbought = vrsi > ovb
barcolor(in_rsi? oversold? #0000FF : overbought? #ff00ff:na : na)

// SAR
plot(in_sar? sar(0.02, 0.02, 0.2): na, style=cross, linewidth=sarw, color=blue, title="sar")

// BB
//length = input(20, title="Bollinger length", minval=1)
length=20
//mult = input(2.0, title="Bollinger stdDev", minval=0.001, maxval=50)
mult=2.0
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
plot(in_bb? basis :na, color=red, linewidth=linew, title="BB basis")
p1 = plot(in_bb? upper :na, color=blue, linewidth=linew, title="BB upper")
p2 = plot(in_bb? lower :na, color=blue, linewidth=linew, title="BB lower")
fill(p1, p2)

//background
bgcolor(in_bkcolor=="exchange"? #0000FF40 : in_bkcolor=="rsi"? vrsi < (ovs-15) ? #0000FF50  : vrsi < ovs ? #0000FF30 :( vrsi < ovb ? #ff00ff10 : #ff00ff20): in_bkcolor=="ema"?(ema9>ema21?#ff00ff10  : #0000FF20):in_bkcolor=="BB"?(lower>close?#ff00ff10 : close>upper?#0000FF20:#ff00ff10): in_bkcolor=="ema5"?(ema5>ema21?#ff00ff10  : #0000FF20):na)


// Strategy
if estrategia == "ema"
    strategy.entry("buy", true, 1, when= crossover(ema9,ema21) ),
    strategy.entry("sell", false, 1, when = crossover(ema21,ema9)) 
else
    if estrategia =="rsi"
        strategy.entry("buy", true, 1, when= vrsi <ovs),
        strategy.entry("sell", false, 1, when = vrsi > ovb or crossover(close,upper)) 
    else 
        if estrategia =="macd"    
            [macdLine, signalLine, histLine] = macd(close, 12, 26, 9),
            //bgcolor(macdLine > signalLine ? #98c8ff : #ff8b94),
            strategy.entry("buy", true, 1, when= macdLine>=signalLine ),
            strategy.entry("sell", false, 1, when = macdLine<signalLine) 
        else 
            if estrategia=="psr"
                leftBars = 4 //input(4)
                rightBars = 2 //input(2)
                swh = pivothigh(leftBars, rightBars)
                swl = pivotlow(leftBars, rightBars)
                swh_cond = not na(swh)
                hprice = 0.0
                hprice := swh_cond ? swh : hprice[1]
                le = false
                le := swh_cond ? true : (le[1] and high > hprice ? false : le[1])
                if (le)
                    strategy.entry("buy", strategy.long, comment="buy", stop=hprice + syminfo.mintick)
                swl_cond = not na(swl)
                lprice = 0.0
                lprice := swl_cond ? swl : lprice[1]
                se = false
                se := swl_cond ? true : (se[1] and low < lprice ? false : se[1])
                if (se)
                    strategy.entry("sell", strategy.short, comment="sell", stop=lprice - syminfo.mintick)
            else
                if estrategia=="BB"
                    strategy.entry("buy", true, 1, when= crossover(lower,close) ),
                    strategy.entry("sell", false, 1, when = crossover(close,upper)) 
                else
                    if estrategia=="ema5"
                        strategy.entry("buy", true, 1, when= crossover(ema5,ema21) ),
                        strategy.entry("sell", false, 1, when = crossover(ema21,ema5)) 



// pivots

// Classic Pivot
pivot = (high + low + close ) / 3.0
// Filter Cr
bull= pivot > (pivot + pivot[1]) / 2 + .0025
bear= pivot < (pivot + pivot[1]) / 2 - .0025
// Classic Pivots
r1 = pf and bear ? pivot + (pivot - low) : pf and bull ? pivot + (high - low) : pivot + (pivot - low)
s1 = pf and bull ? pivot - (high - pivot) : pf and bear ? pivot - (high - low) : pivot - (high - pivot)
r2 = pf ? na : pivot + (high - low)
s2 = pf ? na : pivot - (high - low)
//Pivot Average Calculation
smaP = sma(pivot, 3)
//Daily Pivots 
dtime_pivot = request.security(syminfo.tickerid, 'D', pivot[1])
dtime_pivotAvg = request.security(syminfo.tickerid, 'D', smaP[1])
dtime_r1 = request.security(syminfo.tickerid, 'D', r1[1]) 
dtime_s1 = request.security(syminfo.tickerid, 'D', s1[1]) 
dtime_r2 = request.security(syminfo.tickerid, 'D', r2[1]) 
dtime_s2 = request.security(syminfo.tickerid, 'D', s2[1])
offs_daily = 0
plot(sd and dtime_pivot ? dtime_pivot : na, title="Daily Pivot",style=line, color=fuchsia,linewidth=linew) 
plot(sd and dtime_r1 ? dtime_r1 : na, title="Daily R1",style=line, color=#DC143C,linewidth=linew) 
plot(sd and dtime_s1 ? dtime_s1 : na, title="Daily S1",style=line, color=lime,linewidth=linew) 
plot(sd and dtime_r2 ? dtime_r2 : na, title="Daily R2",style=line, color=maroon,linewidth=linew) 
plot(sd and dtime_s2 ? dtime_s2 : na, title="Daily S2",style=line, color=#228B22,linewidth=linew) 


// References:
// get number of bars since last green bar
//plot(barssince(close >= open), linewidth=3, color=blue)
//bgcolor(close < open ? #ff8b94   : #98c8ff , transp=10)
//http://www.color-hex.com/
//   #98c8ff    light blue
//    #ff8b94   red   #b21c0e
//       #7d1d90    purple
//    #0029ff blue
//    #fffa86   yellow

Published by ChaoZhang on the FMZ strategy square · last modified 2023-11-24. 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 spread arbitrage engine with WebSocket order routing and leg-risk controls from strategies/Triple-Moving-Average-Quantitative-Trading-Strategy-433095.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