Double Trading Strategy
Pairs trading strategy that opens opposite positions on two correlated instruments and closes them when combined profit reaches a target.
Details
- Entry Criteria: simultaneously open first security and second security in opposite directions
- Long/Short: Long & Short
- Exit Criteria: combined profit >= ProfitTarget
- Stops: No
- Default Values:
Volume1= 1Volume2= 1.3ProfitTarget= 20SecondSecurity= required
- Filters:
- Category: Pair Trading
- Direction: Hedged
- Indicators: None
- Stops: No
- Complexity: Basic
- Timeframe: Intraday
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Simple double-leg trading strategy.
/// Enters both legs at the start, then monitors combined hypothetical PnL
/// to exit and re-enter in cycles.
/// </summary>
public class DoubleTradingStrategy : Strategy
{
public enum TradeDirections { Auto, Buy, Sell }
private readonly StrategyParam<decimal> _profitTarget;
private readonly StrategyParam<TradeDirections> _direction1;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _maxRoundTrips;
private bool _inPosition;
private Sides _side1;
private decimal _entryPrice;
private decimal _lastPrice;
private int _roundTrips;
public decimal ProfitTarget { get => _profitTarget.Value; set => _profitTarget.Value = value; }
public TradeDirections Direction1 { get => _direction1.Value; set => _direction1.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int MaxRoundTrips { get => _maxRoundTrips.Value; set => _maxRoundTrips.Value = value; }
public DoubleTradingStrategy()
{
_profitTarget = Param(nameof(ProfitTarget), 500m)
.SetDisplay("Profit Target", "Exit profit per round trip", "Risk");
_direction1 = Param(nameof(Direction1), TradeDirections.Auto)
.SetDisplay("Direction1", "Initial side", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Candles", "Data");
_maxRoundTrips = Param(nameof(MaxRoundTrips), 20)
.SetDisplay("Max Round Trips", "Max number of entry/exit cycles", "Risk");
}
protected override void OnReseted()
{
base.OnReseted();
_inPosition = false;
_side1 = default;
_entryPrice = 0m;
_lastPrice = 0m;
_roundTrips = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_side1 = Direction1 == TradeDirections.Sell ? Sides.Sell : Sides.Buy;
_inPosition = false;
_roundTrips = 0;
SubscribeCandles(CandleType).Bind(ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
_lastPrice = candle.ClosePrice;
if (!_inPosition)
{
if (_roundTrips >= MaxRoundTrips)
return;
// Enter position
_entryPrice = candle.ClosePrice;
if (_side1 == Sides.Buy)
BuyMarket();
else
SellMarket();
_inPosition = true;
return;
}
// Check profit target
var pnl = _side1 == Sides.Buy
? _lastPrice - _entryPrice
: _entryPrice - _lastPrice;
if (pnl >= ProfitTarget)
{
// Exit position
if (_side1 == Sides.Buy)
SellMarket();
else
BuyMarket();
_inPosition = false;
_roundTrips++;
// Alternate direction for next round
_side1 = _side1 == Sides.Buy ? Sides.Sell : Sides.Buy;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates, Sides
from StockSharp.Algo.Strategies import Strategy
class double_trading_strategy(Strategy):
# TradeDirections: 0=Auto, 1=Buy, 2=Sell
def __init__(self):
super(double_trading_strategy, self).__init__()
self._profit_target = self.Param("ProfitTarget", 500.0) \
.SetDisplay("Profit Target", "Exit profit per round trip", "Risk")
self._direction1 = self.Param("Direction1", 0) \
.SetDisplay("Direction1", "Initial side", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Candles", "Data")
self._max_round_trips = self.Param("MaxRoundTrips", 20) \
.SetDisplay("Max Round Trips", "Max number of entry/exit cycles", "Risk")
self._in_position = False
self._side1 = Sides.Buy
self._entry_price = 0.0
self._last_price = 0.0
self._round_trips = 0
def OnReseted(self):
super(double_trading_strategy, self).OnReseted()
self._in_position = False
self._side1 = Sides.Buy
self._entry_price = 0.0
self._last_price = 0.0
self._round_trips = 0
def OnStarted2(self, time):
super(double_trading_strategy, self).OnStarted2(time)
# 2=Sell maps to Sides.Sell, otherwise Sides.Buy
self._side1 = Sides.Sell if self._direction1.Value == 2 else Sides.Buy
self._in_position = False
self._round_trips = 0
sub = self.SubscribeCandles(self._candle_type.Value)
sub.Bind(self.process_candle).Start()
def process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
self._last_price = float(candle.ClosePrice)
if not self._in_position:
if self._round_trips >= self._max_round_trips.Value:
return
# Enter position
self._entry_price = float(candle.ClosePrice)
if self._side1 == Sides.Buy:
self.BuyMarket()
else:
self.SellMarket()
self._in_position = True
return
# Check profit target
if self._side1 == Sides.Buy:
pnl = self._last_price - self._entry_price
else:
pnl = self._entry_price - self._last_price
if pnl >= float(self._profit_target.Value):
# Exit position
if self._side1 == Sides.Buy:
self.SellMarket()
else:
self.BuyMarket()
self._in_position = False
self._round_trips += 1
# Alternate direction for next round
if self._side1 == Sides.Buy:
self._side1 = Sides.Sell
else:
self._side1 = Sides.Buy
def CreateClone(self):
return double_trading_strategy()