Strategies
动态交叉移动平均线趋势捕捉策略与风险管理系统-Dynamic-Crossover-Moving-Average-Trend-Capture-Strategy-with-Risk-Management-System
ianzeng123 · PineScript · Trend Following · 2025-03-24 11:59:09
Trend Following
Mean ReversionRisk and Position Sizing
Uptrend · InferredDowntrend · InferredRange · Inferred
Filter
Sizing
—
Exit
—
Context terms
No English write-up in the source (no author description).
Source code (67 lines)
/*backtest
start: 2025-02-21 00:00:00
end: 2025-03-23 00:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=5
strategy("crypto strat", overlay=true, initial_capital=100, default_qty_type=strategy.cash, default_qty_value=100)
// Input parameters
fastSMA = input.int(10, "Fast SMA Period", minval=1)
slowSMA = input.int(25, "Slow SMA Period", minval=1)
emaLength = input.int(250, "EMA Length", minval=1)
riskAmount = input.float(7, "Risk Amount in USD", minval=1)
leverage = input.int(100, "Leverage", minval=1, maxval=125)
// Calculate indicators
fastMA = ta.sma(close, fastSMA)
slowMA = ta.sma(close, slowSMA)
longEMA = ta.ema(close, emaLength)
// Plot indicators
plot(fastMA, "Fast SMA", color=color.blue)
plot(slowMA, "Slow SMA", color=color.red)
plot(longEMA, "250 EMA", color=color.purple, linewidth=2)
// Entry conditions
longCondition = ta.crossover(fastMA, slowMA) and close > longEMA and strategy.position_size == 0
shortCondition = ta.crossunder(fastMA, slowMA) and close < longEMA and strategy.position_size == 0
// Exit conditions - close when price touches 250 EMA
exitLongCondition = low <= longEMA and strategy.position_size > 0
exitShortCondition = high >= longEMA and strategy.position_size < 0
// Position sizing based on risk
positionSize = math.max((100 * leverage) / close, 0.001) // Minimum 0.001 BTC
stopLossDistance = riskAmount / positionSize // $7 risk in price terms
// Entry logic
if (longCondition)
entryPrice = close
strategy.entry("Long", strategy.long, qty=positionSize)
strategy.exit("Long Exit", "Long",
stop=entryPrice - stopLossDistance,
trail_points=stopLossDistance * 3,
trail_offset=stopLossDistance)
if (shortCondition)
entryPrice = close
strategy.entry("Short", strategy.short, qty=positionSize)
strategy.exit("Short Exit", "Short",
stop=entryPrice + stopLossDistance,
trail_points=stopLossDistance * 3,
trail_offset=stopLossDistance)
// Exit logic - close when price touches 250 EMA
if (exitLongCondition)
strategy.close("Long", comment="EMA Exit")
if (exitShortCondition)
strategy.close("Short", comment="EMA Exit")
// Visualize entry signals
plotshape(longCondition, "Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(shortCondition, "Sell Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)