using StockSharp.Algo.Logging; using StockSharp.Quik; using StockSharp.Xaml; using System.Linq; namespace SampleSMA { using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Indicators; using StockSharp.Algo.Indicators.Trend; 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; } private LogManager _logManager; protected override void OnStarting() { _logManager = new LogManager(); _logManager.Listeners.Add(new FileLogListener("LOG/log_working.txt")); _logManager.Sources.Add(this); _series .WhenCandlesFinished() .Do(ProcessCandle) .Apply(this); // запоминаем текущее положение относительно друг друга _isShortLessThenLong = ShortSma.LastValue < LongSma.LastValue; base.OnStarting(); } private void ProcessCandle(Candle candle) { // если наша стратегия в процессе остановки if (ProcessState == ProcessStates.Stopping) { // отменяем активные заявки CancelActiveOrders(); return; } // добавляем новую свечку LongSma.Process((DecimalIndicatorValue)candle.ClosePrice); ShortSma.Process((DecimalIndicatorValue)candle.ClosePrice); // вычисляем новое положение относительно друг друга var isShortLessThenLong = ShortSma.LastValue < LongSma.LastValue; var stopOrder = CreateStopLimit(); this.AddInfoLog("ActiveOrders (Count={0}): {1}", ActiveOrders.Count(), ActiveOrders.Aggregate("", (current, o) => current + ", " + o.Id)); stopOrder.WhenRegistered().Do(oldOrder => { var newOrder = oldOrder.Clone(); newOrder.Type = OrderTypes.Limit; newOrder.Price = newOrder.Direction == OrderDirections.Buy ? Security.GetCurrentPrice().Value - 200 : Security.GetCurrentPrice().Value + 200; newOrder.WhenRegistered().Do(OrderRegistered).Apply(this); ReRegisterOrder(oldOrder, newOrder); }).Apply(this); stopOrder.WhenRegistered().Do(OrderRegistered).Apply(this); RegisterOrder(stopOrder); // если произошло пересечение /*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; }*/ } private Order CreateStopLimit() { return new Order { Type = OrderTypes.Conditional, //Type = OrderTypes.Limit, Volume = 1, Price = Security.GetCurrentPrice().Value + 100, //Price = Security.GetCurrentPrice().Value - 200, Security = Security, Direction = OrderDirections.Buy, StopCondition = new QuikStopCondition { Type = QuikStopConditionTypes.StopLimit, StopPrice = Security.GetCurrentPrice().Value - 250, }, }; } private void OrderRegistered(Order order) { this.AddInfoLog("Заявка {0} зарегистрирована Id={1}", order.Type, order.Id); } } }