Grease Trap 戦略
Grease Trapはフィボナッチ長の2本の移動平均を使用し、そのクロスオーバーで利益目標と共に取引します。
詳細
- データ: 価格ローソク足.
- エントリー条件:
- ロング: 速い平均が遅い平均を上向きにクロス.
- ショート: 速い平均が遅い平均を下向きにクロス.
- エグジット条件: 利益目標または逆クロスオーバー.
- ストップ: なし.
- デフォルト値:
Length1= 9Length2= 14LongProfit= 0.02ShortProfit= 0.02
- フィルター:
- カテゴリ: トレンドフォロー
- 方向: ロング&ショート
- インジケーター: SMA
- 複雑さ: 低
- リスクレベル: 中
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>
/// Grease trap strategy.
/// The Length1 SMA crossing above the Length2 SMA goes long and crossing below goes short, reversing an opposite position. A long closes
/// when price reaches the entry plus LongProfit (a fraction of the entry price) and a short when it reaches the entry minus ShortProfit.
/// </summary>
public class GreaseTrapStrategy : Strategy
{
private readonly StrategyParam<int> _length1;
private readonly StrategyParam<int> _length2;
private readonly StrategyParam<decimal> _longProfit;
private readonly StrategyParam<decimal> _shortProfit;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevFast;
private decimal? _prevSlow;
private decimal _takePrice;
/// <summary>
/// Fast SMA length.
/// </summary>
public int Length1
{
get => _length1.Value;
set => _length1.Value = value;
}
/// <summary>
/// Slow SMA length.
/// </summary>
public int Length2
{
get => _length2.Value;
set => _length2.Value = value;
}
/// <summary>
/// Long profit target as a fraction of the entry price.
/// </summary>
public decimal LongProfit
{
get => _longProfit.Value;
set => _longProfit.Value = value;
}
/// <summary>
/// Short profit target as a fraction of the entry price.
/// </summary>
public decimal ShortProfit
{
get => _shortProfit.Value;
set => _shortProfit.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public GreaseTrapStrategy()
{
_length1 = Param(nameof(Length1), 9)
.SetGreaterThanZero()
.SetDisplay("Length 1", "Fast SMA length", "Indicators");
_length2 = Param(nameof(Length2), 14)
.SetGreaterThanZero()
.SetDisplay("Length 2", "Slow SMA length", "Indicators");
_longProfit = Param(nameof(LongProfit), 0.02m)
.SetNotNegative()
.SetDisplay("Long Profit", "Long profit target as a fraction of the entry price", "Risk");
_shortProfit = Param(nameof(ShortProfit), 0.02m)
.SetNotNegative()
.SetDisplay("Short Profit", "Short profit target as a fraction of the entry price", "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();
_prevFast = null;
_prevSlow = null;
_takePrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFast = null;
_prevSlow = null;
_takePrice = 0m;
var fast = new SimpleMovingAverage { Length = Length1 };
var slow = new SimpleMovingAverage { Length = Length2 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fast, slow, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fast);
DrawIndicator(area, slow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
var prevFast = _prevFast;
var prevSlow = _prevSlow;
_prevFast = fast;
_prevSlow = slow;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (prevFast is not decimal pf || prevSlow is not decimal ps)
return;
var close = candle.ClosePrice;
var crossUp = pf <= ps && fast > slow;
var crossDown = pf >= ps && fast < slow;
if (crossUp && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
_takePrice = LongProfit > 0 ? close * (1 + LongProfit) : 0m;
}
else if (crossDown && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
_takePrice = ShortProfit > 0 ? close * (1 - ShortProfit) : 0m;
}
else if (Position > 0 && _takePrice > 0 && candle.HighPrice >= _takePrice)
{
SellMarket(Position);
}
else if (Position < 0 && _takePrice > 0 && candle.LowPrice <= _takePrice)
{
BuyMarket(Math.Abs(Position));
}
}
}
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class grease_trap_strategy(Strategy):
"""
Grease trap strategy.
The Length1 SMA crossing above the Length2 SMA goes long and crossing below goes short, reversing an opposite position. A long closes
when price reaches the entry plus LongProfit (a fraction of the entry price) and a short when it reaches the entry minus ShortProfit.
"""
def __init__(self):
super(grease_trap_strategy, self).__init__()
self._length1 = self.Param("Length1", 9).SetGreaterThanZero().SetDisplay("Length 1", "Fast SMA length", "Indicators")
self._length2 = self.Param("Length2", 14).SetGreaterThanZero().SetDisplay("Length 2", "Slow SMA length", "Indicators")
self._long_profit = self.Param("LongProfit", 0.02).SetNotNegative().SetDisplay("Long Profit", "Long profit target as a fraction of the entry price", "Risk")
self._short_profit = self.Param("ShortProfit", 0.02).SetNotNegative().SetDisplay("Short Profit", "Short profit target as a fraction of the entry price", "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_fast = None
self._prev_slow = None
self._take_price = Decimal(0)
def OnReseted(self):
super(grease_trap_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(grease_trap_strategy, self).OnStarted2(time)
self._reset_state()
fast = SimpleMovingAverage()
fast.Length = self._length1.Value
slow = SimpleMovingAverage()
slow.Length = self._length2.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast, slow, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast)
self.DrawIndicator(area, slow)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
prev_fast = self._prev_fast
prev_slow = self._prev_slow
self._prev_fast = fast
self._prev_slow = slow
if not self.IsFormedAndOnlineAndAllowTrading():
return
if prev_fast is None or prev_slow is None:
return
close = candle.ClosePrice
long_profit = Decimal(self._long_profit.Value)
short_profit = Decimal(self._short_profit.Value)
cross_up = prev_fast <= prev_slow and fast > slow
cross_down = prev_fast >= prev_slow and fast < slow
if cross_up and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
self._take_price = close * (Decimal(1) + long_profit) if long_profit > 0 else Decimal(0)
elif cross_down and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
self._take_price = close * (Decimal(1) - short_profit) if short_profit > 0 else Decimal(0)
elif self.Position > 0 and self._take_price > 0 and candle.HighPrice >= self._take_price:
self.SellMarket(self.Position)
elif self.Position < 0 and self._take_price > 0 and candle.LowPrice <= self._take_price:
self.BuyMarket(abs(self.Position))
def CreateClone(self):
return grease_trap_strategy()