
均线交叉策略是一个基于移动均线的交易策略。它使用快速移动均线和慢速移动均线的交叉作为买入和卖出信号。当快速均线从下方向上突破慢速均线时,产生买入信号;当快速均线从上方向下跌破慢速均线时,产生卖出信号。
该策略使用sma函数计算指定周期的简单移动平均线,作为快速均线和慢速均线。策略默认快速均线周期为18天,可以通过参数调整。
当快速均线从下方向上突破慢速均线时,使用crossunder函数检测到交叉信号,产生买入信号。当快速均线从上方向下跌破慢速均线时,使用crossover函数检测到交叉信号,产生卖出信号。
策略通过track信号和exit信号实现自动交易。多头入场在快速均线从下方突破慢速均线时触发;空头入场在快速均线从上方跌破慢速均线时触发。对应的exit信号也在反向交叉时产生。
均线交叉策略整体来说是一个较为经典和简单的趋势跟踪策略。它主要使用均线交叉作为交易信号,原理简单直接,容易理解实现,可通过参数调整适应市场。但也存在一些缺点,如易受震荡和趋势转向的影响, signaling频繁等。这些问题可以通过增加过滤条件、动态调整参数、引入止损等方式得到改进。该策略有着广泛的优化空间和方向,是量化交易的基础策略之一。
/*backtest
start: 2023-11-15 00:00:00
end: 2023-11-17 04:00:00
period: 30m
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=3
strategy(title = "MA Close Strategy", shorttitle = "MA Close",calc_on_order_fills=true,calc_on_every_tick =true, initial_capital=21000,commission_value=.25,overlay = true,default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
MASource = input(defval = open, title = "MA Source")
MaLength = input(defval = 18, title = "MA Period", minval = 1)
StartYear = input(2018, "Backtest Start Year")
StartMonth = input(1, "Backtest Start Month")
StartDay = input(1, "Backtest Start Day")
UseStopLoss = input(true,"UseStopLoss")
stopLoss = input(50, title = "Stop loss percentage(0.1%)")
window() => time >= timestamp(StartYear, StartMonth, StartDay,00,00) ? true : false
MA = sma(MASource,MaLength)
plot(MA, title = "Fast MA", color = green, linewidth = 2, style = line, transp = 50)
long = crossunder(MA, close)
short = crossover(MA, close)
if (long)
strategy.entry("LongId", strategy.long, when = long)
strategy.exit("ExitLong", from_entry = "LongId", when = short)
if (short)
strategy.entry("ShortId", strategy.short, when = short)
strategy.exit("ExitShort", from_entry = "ShortId", when = long)
if (UseStopLoss)
strategy.exit("StopLoss", "LongId", loss = close * stopLoss / 1000 / syminfo.mintick)
strategy.exit("StopLoss", "ShortId", loss = close * stopLoss / 1000 / syminfo.mintick)