ゴールド・スキャルピング戦略(精密エントリー)
EMAトレンドフィルター、RSIレンジ、エングルフィングパターンを使用したゴールド向けスキャルピング戦略。
詳細
- エントリー条件: EMAトレンドフィルターでRSIが45から55の間、かつEMA50付近で強気/弱気のエングルフィングパターン。
- ロング/ショート: 両方向。
- エグジット条件: テイクプロフィットまたはストップロス。
- ストップ: ATRベースのストップロスと固定Pipターゲット。
- デフォルト値:
EmaFastPeriod= 50EmaSlowPeriod= 200RsiPeriod= 14AtrPeriod= 14RsiLower= 45RsiUpper= 55PipTarget= 2CandleType= TimeSpan.FromMinutes(1)
- フィルター:
- カテゴリ: スキャルピング
- 方向: 両方
- インジケーター: EMA, RSI, ATR
- ストップ: はい
- 複雑さ: 基本
- 時間軸: イントラデイ (1m)
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Gold scalping strategy with precise entries.
/// The trend is up when the EmaFastPeriod EMA is above the EmaSlowPeriod EMA. With RSI between RsiLower and RsiUpper, a bullish
/// engulfing candle that touches the fast EMA in an uptrend goes long and a bearish engulfing candle touching it in a downtrend goes
/// short. The stop is one ATR from the entry and the target PipTarget price steps away.
/// </summary>
public class GoldScalpingWithPreciseEntriesStrategy : Strategy
{
private readonly StrategyParam<int> _emaFastPeriod;
private readonly StrategyParam<int> _emaSlowPeriod;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _rsiLower;
private readonly StrategyParam<decimal> _rsiUpper;
private readonly StrategyParam<decimal> _pipTarget;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevOpen;
private decimal? _prevClose;
private decimal _stopPrice;
private decimal _takePrice;
/// <summary>
/// Fast EMA period.
/// </summary>
public int EmaFastPeriod
{
get => _emaFastPeriod.Value;
set => _emaFastPeriod.Value = value;
}
/// <summary>
/// Slow EMA period.
/// </summary>
public int EmaSlowPeriod
{
get => _emaSlowPeriod.Value;
set => _emaSlowPeriod.Value = value;
}
/// <summary>
/// RSI period.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// ATR period for the stop.
/// </summary>
public int AtrPeriod
{
get => _atrPeriod.Value;
set => _atrPeriod.Value = value;
}
/// <summary>
/// Lower bound of the RSI range.
/// </summary>
public decimal RsiLower
{
get => _rsiLower.Value;
set => _rsiLower.Value = value;
}
/// <summary>
/// Upper bound of the RSI range.
/// </summary>
public decimal RsiUpper
{
get => _rsiUpper.Value;
set => _rsiUpper.Value = value;
}
/// <summary>
/// Take profit distance in price steps.
/// </summary>
public decimal PipTarget
{
get => _pipTarget.Value;
set => _pipTarget.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public GoldScalpingWithPreciseEntriesStrategy()
{
_emaFastPeriod = Param(nameof(EmaFastPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Fast Period", "Fast EMA period", "Indicators");
_emaSlowPeriod = Param(nameof(EmaSlowPeriod), 200)
.SetGreaterThanZero()
.SetDisplay("EMA Slow Period", "Slow EMA period", "Indicators");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI period", "Indicators");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Period", "ATR period for the stop", "Risk");
_rsiLower = Param(nameof(RsiLower), 45m)
.SetDisplay("RSI Lower", "Lower bound of the RSI range", "Indicators");
_rsiUpper = Param(nameof(RsiUpper), 55m)
.SetDisplay("RSI Upper", "Upper bound of the RSI range", "Indicators");
_pipTarget = Param(nameof(PipTarget), 2m)
.SetNotNegative()
.SetDisplay("Pip Target", "Take profit distance in price steps", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
ResetState();
}
private void ResetState()
{
_prevOpen = null;
_prevClose = null;
_stopPrice = 0m;
_takePrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ResetState();
var emaFast = new ExponentialMovingAverage { Length = EmaFastPeriod };
var emaSlow = new ExponentialMovingAverage { Length = EmaSlowPeriod };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(emaFast, emaSlow, rsi, atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, emaFast);
DrawIndicator(area, emaSlow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal emaFast, decimal emaSlow, decimal rsi, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
var prevOpen = _prevOpen;
var prevClose = _prevClose;
_prevOpen = candle.OpenPrice;
_prevClose = candle.ClosePrice;
if (ManagePosition(candle))
return;
if (prevOpen is not decimal po || prevClose is not decimal pc)
return;
if (!IsFormedAndOnlineAndAllowTrading() || Position != 0)
return;
var open = candle.OpenPrice;
var close = candle.ClosePrice;
var rsiInRange = rsi >= RsiLower && rsi <= RsiUpper;
var touchesEma = candle.LowPrice <= emaFast && candle.HighPrice >= emaFast;
var bullishEngulfing = pc < po && close > open && open <= pc && close >= po;
var bearishEngulfing = pc > po && close < open && open >= pc && close <= po;
var target = PipTarget * (Security?.PriceStep ?? 1m);
if (emaFast > emaSlow && rsiInRange && touchesEma && bullishEngulfing)
{
BuyMarket(Volume);
_stopPrice = close - atr;
_takePrice = close + target;
}
else if (emaFast < emaSlow && rsiInRange && touchesEma && bearishEngulfing)
{
SellMarket(Volume);
_stopPrice = close + atr;
_takePrice = close - target;
}
}
// Returns true when the position was closed on this candle.
private bool ManagePosition(ICandleMessage candle)
{
if (Position > 0 && _stopPrice > 0)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takePrice)
{
SellMarket(Position);
return true;
}
}
else if (Position < 0 && _stopPrice > 0)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takePrice)
{
BuyMarket(Math.Abs(Position));
return true;
}
}
return false;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage, RelativeStrengthIndex, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class gold_scalping_with_precise_entries_strategy(Strategy):
"""
Gold scalping strategy with precise entries.
The trend is up when the EmaFastPeriod EMA is above the EmaSlowPeriod EMA. With RSI between RsiLower and RsiUpper, a bullish
engulfing candle that touches the fast EMA in an uptrend goes long and a bearish engulfing candle touching it in a downtrend goes
short. The stop is one ATR from the entry and the target PipTarget price steps away.
"""
def __init__(self):
super(gold_scalping_with_precise_entries_strategy, self).__init__()
self._ema_fast_period = self.Param("EmaFastPeriod", 50).SetGreaterThanZero().SetDisplay("EMA Fast Period", "Fast EMA period", "Indicators")
self._ema_slow_period = self.Param("EmaSlowPeriod", 200).SetGreaterThanZero().SetDisplay("EMA Slow Period", "Slow EMA period", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 14).SetGreaterThanZero().SetDisplay("RSI Period", "RSI period", "Indicators")
self._atr_period = self.Param("AtrPeriod", 14).SetGreaterThanZero().SetDisplay("ATR Period", "ATR period for the stop", "Risk")
self._rsi_lower = self.Param("RsiLower", 45.0).SetDisplay("RSI Lower", "Lower bound of the RSI range", "Indicators")
self._rsi_upper = self.Param("RsiUpper", 55.0).SetDisplay("RSI Upper", "Upper bound of the RSI range", "Indicators")
self._pip_target = self.Param("PipTarget", 2.0).SetNotNegative().SetDisplay("Pip Target", "Take profit distance in price steps", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_open = None
self._prev_close = None
self._stop_price = Decimal(0)
self._take_price = Decimal(0)
def OnReseted(self):
super(gold_scalping_with_precise_entries_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(gold_scalping_with_precise_entries_strategy, self).OnStarted2(time)
self._reset_state()
ema_fast = ExponentialMovingAverage()
ema_fast.Length = self._ema_fast_period.Value
ema_slow = ExponentialMovingAverage()
ema_slow.Length = self._ema_slow_period.Value
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_period.Value
atr = AverageTrueRange()
atr.Length = self._atr_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema_fast, ema_slow, rsi, atr, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema_fast)
self.DrawIndicator(area, ema_slow)
self.DrawOwnTrades(area)
def _process_candle(self, candle, ema_fast, ema_slow, rsi, atr):
if candle.State != CandleStates.Finished:
return
prev_open = self._prev_open
prev_close = self._prev_close
self._prev_open = candle.OpenPrice
self._prev_close = candle.ClosePrice
if self._manage_position(candle):
return
if prev_open is None or prev_close is None:
return
if not self.IsFormedAndOnlineAndAllowTrading() or self.Position != 0:
return
open_price = candle.OpenPrice
close = candle.ClosePrice
rsi_in_range = Decimal(self._rsi_lower.Value) <= rsi <= Decimal(self._rsi_upper.Value)
touches_ema = candle.LowPrice <= ema_fast and candle.HighPrice >= ema_fast
bullish_engulfing = prev_close < prev_open and close > open_price and open_price <= prev_close and close >= prev_open
bearish_engulfing = prev_close > prev_open and close < open_price and open_price >= prev_close and close <= prev_open
step = self.Security.PriceStep if self.Security is not None and self.Security.PriceStep is not None else Decimal(1)
target = Decimal(self._pip_target.Value) * step
if ema_fast > ema_slow and rsi_in_range and touches_ema and bullish_engulfing:
self.BuyMarket(self.Volume)
self._stop_price = close - atr
self._take_price = close + target
elif ema_fast < ema_slow and rsi_in_range and touches_ema and bearish_engulfing:
self.SellMarket(self.Volume)
self._stop_price = close + atr
self._take_price = close - target
def _manage_position(self, candle):
if self.Position > 0 and self._stop_price > 0:
if candle.LowPrice <= self._stop_price or candle.HighPrice >= self._take_price:
self.SellMarket(self.Position)
return True
elif self.Position < 0 and self._stop_price > 0:
if candle.HighPrice >= self._stop_price or candle.LowPrice <= self._take_price:
self.BuyMarket(abs(self.Position))
return True
return False
def CreateClone(self):
return gold_scalping_with_precise_entries_strategy()