Random Coin Toss Baseline 策略
该策略复现了经典的 GuruTrader 示例,通过掷硬币决定交易方向。 在每根完成的K线,如果没有持仓,就生成一个伪随机数作为掷硬币。 正面开多,反面开空。 每笔交易都使用固定的绝对价格距离作为止盈和止损。
参数
- Take Profit – 距离入场价的止盈距离。
- Stop Loss – 距离入场价的止损距离。
- Use Time Seed – 使用当前时间作为随机种子,每次运行结果不同;关闭后使用固定种子。
- Candle Type – 策略处理的K线类型。
交易逻辑
- 等待K线完成。
- 确认允许交易且当前没有持仓。
- 生成随机值并根据“掷硬币”结果选择方向。
- 使用预设的止盈和止损保护仓位。
警告: 本策略仅用于教育目的,禁止用于真实账户交易。
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy that tosses a virtual coin to decide trade direction.
/// A long position is opened on heads, a short position on tails.
/// Closes after N candles and re-enters.
/// </summary>
public class RandomCoinTossBaselineStrategy : Strategy
{
private readonly StrategyParam<int> _holdBars;
private readonly StrategyParam<DataType> _candleType;
private Random _random;
private int _barsInPosition;
public int HoldBars
{
get => _holdBars.Value;
set => _holdBars.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public RandomCoinTossBaselineStrategy()
{
_holdBars = Param(nameof(HoldBars), 10)
.SetGreaterThanZero()
.SetDisplay("Hold Bars", "Number of bars to hold position", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to process", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_random = null;
_barsInPosition = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_random = new Random(42);
_barsInPosition = 0;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
// Close position after holding for N bars
if (Position != 0)
{
_barsInPosition++;
if (_barsInPosition >= HoldBars)
{
if (Position > 0)
SellMarket();
else
BuyMarket();
_barsInPosition = 0;
}
return;
}
// Flip coin and enter
var coin = _random.Next(2);
if (coin == 0)
BuyMarket();
else
SellMarket();
_barsInPosition = 0;
}
}
import clr
import random as py_random
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.Strategies import Strategy
class random_coin_toss_baseline_strategy(Strategy):
def __init__(self):
super(random_coin_toss_baseline_strategy, self).__init__()
self._hold_bars = self.Param("HoldBars", 10) \
.SetDisplay("Hold Bars", "Number of bars to hold position", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to process", "General")
self._random = None
self._bars_in_position = 0
@property
def hold_bars(self):
return self._hold_bars.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(random_coin_toss_baseline_strategy, self).OnReseted()
self._random = None
self._bars_in_position = 0
def OnStarted2(self, time):
super(random_coin_toss_baseline_strategy, self).OnStarted2(time)
self._random = py_random.Random(42)
self._bars_in_position = 0
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
if self.Position != 0:
self._bars_in_position += 1
if self._bars_in_position >= int(self.hold_bars):
if self.Position > 0:
self.SellMarket()
else:
self.BuyMarket()
self._bars_in_position = 0
return
coin = self._random.randint(0, 1)
if coin == 0:
self.BuyMarket()
else:
self.SellMarket()
self._bars_in_position = 0
def CreateClone(self):
return random_coin_toss_baseline_strategy()