using System; using Ecng.Serialization; namespace SampleHistoryTesting { using Ecng.Common; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Indicators; using StockSharp.Algo.Indicators.Trend; using StockSharp.Algo.Logging; using StockSharp.Algo.Strategies; using StockSharp.BusinessEntities; class SmaStrategy : Strategy { private readonly CandleSeries _series; private bool _isShortLessThenLong; public SmaStrategy(CandleSeries series, SimpleMovingAverage longSma, SimpleMovingAverage shortSma) { _series = series; LongSma = longSma; ShortSma = shortSma; } public SimpleMovingAverage LongSma { get; private set; } public SimpleMovingAverage ShortSma { get; private set; } protected override void OnStarted() { _series .WhenCandlesFinished() .Do(ProcessCandle) .Apply(this); // запоминаем текущее положение относительно друг друга _isShortLessThenLong = ShortSma.LastValue < LongSma.LastValue; Trader.WhenIntervalElapsed(TimeSpan.FromSeconds(20)).Do(Check).Once().Apply(); Save(new SettingsStorage()); base.OnStarted(); } private void Check() { } private void ProcessCandle(Candle candle) { // если наша стратегия в процессе остановки if (ProcessState == ProcessStates.Stopping) { // отменяем активные заявки CancelActiveOrders(); return; } this.AddInfoLog("Новая свеча {0}: {1};{2};{3};{4}; объем {5}".Put(candle.OpenTime, candle.OpenPrice, candle.HighPrice, candle.LowPrice, candle.ClosePrice, candle.TotalVolume)); // добавляем новую свечку LongSma.Process((DecimalIndicatorValue)candle.ClosePrice); ShortSma.Process((DecimalIndicatorValue)candle.ClosePrice); // вычисляем новое положение относительно друг друга var isShortLessThenLong = ShortSma.LastValue < LongSma.LastValue; // если произошло пересечение if (_isShortLessThenLong != isShortLessThenLong) { // если короткая меньше чем длинная, то продажа, иначе, покупка. var direction = isShortLessThenLong ? OrderDirections.Sell : OrderDirections.Buy; // регистрируем заявку (обычным способом - лимитированной заявкой) // RegisterOrder(this.CreateOrder(direction, (decimal)Security.GetCurrentPrice(direction), Volume)); // переворачиваем позицию через котирование var strategy = new MarketQuotingStrategy(direction, Volume); ChildStrategies.Add(strategy); // запоминаем текущее положение относительно друг друга _isShortLessThenLong = isShortLessThenLong; } } public override void Save(SettingsStorage settings) { settings.SetValue("Volume", Volume); var delta = new Unit(10, UnitTypes.Limit); settings.SetValue("Delta", delta); base.Save(settings); //Сохраняем настройки в файл new XmlSerializer().Serialize(settings, "settings_t.xml"); } } }