首页
/
策略示例
在 GitHub 上查看
FT CCI MA(StockSharp 版本)
概述
本策略是 MetaTrader 专家顾问“FT CCI MA”的直接移植。每当一根 K 线收盘时都会评估信号:策略把线性加权移动平均线(LWMA)与 CCI 指标阈值和可选的交易时段过滤器结合使用。StockSharp 实现保留了原始输入名称和默认值,同时利用高级 API(K 线订阅、指标绑定、仓位保护)。
主要实现要点:
LWMA 使用加权价 (High + Low + 2 * Close) / 4,完全对应 MetaTrader 的 PRICE_WEIGHTED 选项。
CCI 使用典型价 (High + Low + Close) / 3,与 PRICE_TYPICAL 相同。
所有逻辑都基于刚刚收盘的 K 线,这与原始 EA 在下一根 K 线的第一笔报价上执行上一根 K 线信号的做法一致。
StartProtection 设置的止盈止损距离以“点(pip)”计量,与 MQL 版本保持一致。
交易规则
做多条件
收盘价高于 LWMA 且 CCI 小于 CciLevelBuy(默认 -100),或
收盘价低于 LWMA 且 CCI 小于 CciLevelDown(默认 -200)。
只有当当前净头寸为空或为空头时才会触发买入。
做空条件
收盘价低于 LWMA 且 CCI 大于 CciLevelSell(默认 100),或
收盘价高于 LWMA 且 CCI 大于 CciLevelUp(默认 200)。
只有当当前净头寸为空或为多头时才会触发卖出。
时间过滤
UseTimeFilter 启用后,策略读取 candle.CloseTime 的小时部分。
如果当前时间不在交易窗口内,会立即取消所有挂单并平掉持仓。
风险控制
通过 StartProtection 把 StopLossPips、TakeProfitPips 换算成绝对价格距离,换算基于 Security.PriceStep(对 3 或 5 位小数的外汇报价额外乘以 10,使 0.00001 转换为 0.0001 pip)。
下单数量会考虑当前净头寸,因此反向开仓将自动平掉原有头寸。
参数
名称
说明
默认值
OrderVolume
下单手数(lots)。
1
StopLossPips
止损距离(pip),0 表示禁用。
150
TakeProfitPips
止盈距离(pip),0 表示禁用。
150
UseTimeFilter
是否启用交易时段过滤。
true
StartHour
开始交易的小时(0–23)。
10
EndHour
结束交易的小时(0–23)。若小于 StartHour,窗口跨越午夜。
5
CciPeriod
CCI 指标周期。
14
CciLevelUp
激进做空阈值(+200)。
200
CciLevelDown
激进做多阈值(-200)。
-200
CciLevelBuy
当价格在均线上方时的温和买入阈值(-100)。
-100
CciLevelSell
当价格在均线下方时的温和卖出阈值(+100)。
100
MaPeriod
LWMA 周期。
200
MaShift
LWMA 水平偏移(单位:K 线)。信号使用 MaShift 根之前的均线值。
0
CandleType
计算使用的 K 线类型/时间框架。
1 小时
实现细节
pip 换算 :优先使用 Security.PriceStep。若品种报价保留 3 或 5 位小数,则乘以 10 以匹配 MetaTrader 的 pip 定义。
时段过滤 :支持日内窗口(StartHour < EndHour)与跨夜窗口(StartHour > EndHour)。当二者相等时,策略被禁用,与原版逻辑一致。
指标绑定 :通过 SubscribeCandles().Bind(...) 获取指标值,无需手工复制缓冲区,仅在内部保存少量 LWMA 历史以处理 MaShift。
订单管理 :每次下市场单前都会执行 CancelActiveOrders(),保证订单簿整洁。
无 Python 版本 :按要求仅提供 C# 实现。
使用步骤
将策略绑定到目标证券,并设置合适的 CandleType(时间框架)。
根据品种规格调整手数和止盈止损的 pip 距离。
按需要开启或关闭交易时段过滤。
启动策略,它会自动订阅 K 线、执行信号并维护保护性订单。
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// FT CCI MA strategy using EMA crossover with trend filter.
/// Buys when fast EMA crosses above slow EMA and price above trend EMA.
/// </summary>
public class FtCciMaStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }
public FtCciMaStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
protected override void OnReseted()
{
base.OnReseted();
_fast = null; _slow = null;
_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new ExponentialMovingAverage { Length = FastPeriod };
_slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished) return;
if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }
_prevFast = fastValue; _prevSlow = slowValue;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ft_cci_ma_strategy(Strategy):
def __init__(self):
super(ft_cci_ma_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 14) \
.SetDisplay("Fast Period", "Fast MA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow MA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(ft_cci_ma_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(ft_cci_ma_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 100
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return ft_cci_ma_strategy()