Two X SPY TIPS
Strategy allocates capital into the traded asset when both S&P 500 and TIPS prices are above their 200-period moving averages at the turn of a new month.
Details
- Entry Criteria: S&P 500 and TIPS above their SMA at a new month.
- Long/Short: Long only.
- Exit Criteria: No exits.
- Stops: No.
- Default Values:
SmaLength= 200Leverage= 2CandleType= TimeSpan.FromDays(1)
- Filters:
- Category: Trend
- Direction: Long only
- Indicators: SMA
- Stops: No
- Complexity: Basic
- Timeframe: Daily
- Seasonality: Yes
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// 2X SPY TIPS Strategy (single-security adaptation).
/// Uses dual SMA to detect strong uptrend, then buys.
/// Original requires SPY+TIPS, adapted to single security with fast/slow SMA.
/// </summary>
public class TwoXSpyTipsStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastSmaLength;
private readonly StrategyParam<int> _slowSmaLength;
private readonly StrategyParam<int> _cooldownBars;
private SimpleMovingAverage _fastSma;
private SimpleMovingAverage _slowSma;
private int _cooldownRemaining;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int FastSmaLength
{
get => _fastSmaLength.Value;
set => _fastSmaLength.Value = value;
}
public int SlowSmaLength
{
get => _slowSmaLength.Value;
set => _slowSmaLength.Value = value;
}
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
public TwoXSpyTipsStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_fastSmaLength = Param(nameof(FastSmaLength), 50)
.SetGreaterThanZero()
.SetDisplay("Fast SMA", "Fast SMA period", "Indicators");
_slowSmaLength = Param(nameof(SlowSmaLength), 200)
.SetGreaterThanZero()
.SetDisplay("Slow SMA", "Slow SMA period", "Indicators");
_cooldownBars = Param(nameof(CooldownBars), 15)
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fastSma = null;
_slowSma = null;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fastSma = new SimpleMovingAverage { Length = FastSmaLength };
_slowSma = new SimpleMovingAverage { Length = SlowSmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_fastSma, _slowSma, OnProcess)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _fastSma);
DrawIndicator(area, _slowSma);
DrawOwnTrades(area);
}
}
private void OnProcess(ICandleMessage candle, decimal fastVal, decimal slowVal)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fastSma.IsFormed || !_slowSma.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
return;
}
var price = candle.ClosePrice;
// Strong uptrend: price above both SMAs + fast > slow
if (price > fastVal && price > slowVal && fastVal > slowVal && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_cooldownRemaining = CooldownBars;
}
// Strong downtrend: price below both SMAs + fast < slow
else if (price < fastVal && price < slowVal && fastVal < slowVal && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_cooldownRemaining = CooldownBars;
}
// Exit long: price drops below fast SMA
else if (Position > 0 && price < fastVal)
{
SellMarket(Math.Abs(Position));
_cooldownRemaining = CooldownBars;
}
// Exit short: price rises above fast SMA
else if (Position < 0 && price > fastVal)
{
BuyMarket(Math.Abs(Position));
_cooldownRemaining = CooldownBars;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class two_x_spy_tips_strategy(Strategy):
"""2X SPY TIPS Strategy."""
def __init__(self):
super(two_x_spy_tips_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._fast_sma_length = self.Param("FastSmaLength", 50) \
.SetDisplay("Fast SMA", "Fast SMA period", "Indicators")
self._slow_sma_length = self.Param("SlowSmaLength", 200) \
.SetDisplay("Slow SMA", "Slow SMA period", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 15) \
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk")
self._fast_sma = None
self._slow_sma = None
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(two_x_spy_tips_strategy, self).OnReseted()
self._fast_sma = None
self._slow_sma = None
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(two_x_spy_tips_strategy, self).OnStarted2(time)
self._fast_sma = SimpleMovingAverage()
self._fast_sma.Length = int(self._fast_sma_length.Value)
self._slow_sma = SimpleMovingAverage()
self._slow_sma.Length = int(self._slow_sma_length.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_sma, self._slow_sma, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._fast_sma)
self.DrawIndicator(area, self._slow_sma)
self.DrawOwnTrades(area)
def _on_process(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
if not self._fast_sma.IsFormed or not self._slow_sma.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
return
price = float(candle.ClosePrice)
fast_v = float(fast_val)
slow_v = float(slow_val)
cooldown = int(self._cooldown_bars.Value)
if price > fast_v and price > slow_v and fast_v > slow_v and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._cooldown_remaining = cooldown
elif price < fast_v and price < slow_v and fast_v < slow_v and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._cooldown_remaining = cooldown
elif self.Position > 0 and price < fast_v:
self.SellMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
elif self.Position < 0 and price > fast_v:
self.BuyMarket(Math.Abs(self.Position))
self._cooldown_remaining = cooldown
def CreateClone(self):
return two_x_spy_tips_strategy()