Strategies KB.ZH
Strategies

50周期指数移动平均线交叉结合月度定投的双重优化趋势跟踪策略-50-Period-EMA-Crossover-with-Monthly-Dollar-Cost-Averaging-Dual-Optimization-Trend-Following-Strategy

ianzeng123 · PineScript · Trend Following · 2025-04-07 11:51:14

All strategies →

No English write-up in the source (no author description).

Read the Chinese version →

Source code (62 lines)
/*backtest
start: 2024-10-23 00:00:00
end: 2024-12-23 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5 

//CELIA IS EEN KLEINE VIS

strategy("50 EMA Crossover With Monthly DCA", overlay=true, initial_capital=100000, slippage=1, default_qty_type=strategy.cash, process_orders_on_close=true)

// === Parameters ===
dca_amount = input.int(100000, title="DCA Investment Amount ($)", minval=1)  // Monthly DCA amount
//ema_length = input.int(50, title="EMA Length", minval=1)  // EMA length
emaValue = ta.ema(close, 50)
plot(emaValue, color=color.blue, title="50W EMA")

// === Tracking Variables ===
var float cash_reserve = 0  // To track the accumulated cash
var float total_invested = 0  // To track the total amount invested (cash + DCA)
var float last_investment_time = na
month_seconds = 30 * 24 * 60 * 60  // Approx 1 month in seconds


// === Time Check: Has 1 Month Passed? ===
time_since_last_investment = na(last_investment_time) ? month_seconds : (time - last_investment_time) / 1000

// === Strategy Conditions ===
longCondition = close > emaValue   // Buy when close is above the 50-week EMA
if longCondition 
    if strategy.opentrades == 0  // No open positions
        // Invest full capital (equity + cash), including DCA saved
        strategy.order("Open Order", strategy.long, qty = (strategy.equity+cash_reserve) / close)  
        cash_reserve := 0  // Reset cash reserve after full reinvestment
    
    if time_since_last_investment >= month_seconds
        // Accumulate DCA buy orders
        strategy.order("DCA Buy", strategy.long, qty = dca_amount / close)  
        last_investment_time := time  // Update the time of the last investment

// Accumulate DCA amount into cash reserve every month, regardless of long condition
if time_since_last_investment >= month_seconds 
    last_investment_time := time  

// === Exit Strategy ===
exitCondition = close < emaValue  // Exit if the price crosses below the 50-week EMA
if exitCondition
    strategy.close_all()  // Close the position when price crosses below the EMA

//plot(strategy.equity, style = plot.style_line, title = "Equity")
//plot(cash_reserve, style = plot.style_line, title = "DCA")

// Place the text below the current bar
var label myLabel = na
if (na(myLabel))
    myLabel := label.new(bar_index, low - 0.02, "Celia is een kleine vis", color=color.white, textcolor=color.black, style=label.style_label_up, size=size.normal)

// Update the position of the label each bar
label.set_xy(myLabel, bar_index, low - 200)