using System; using System.Collections.Generic; using System.Linq; using System.Text; using StockSharp.Algo.Strategies; using StockSharp.Algo.Candles; using StockSharp.Algo.Logging; using StockSharp.BusinessEntities; using StockSharp.AlfaDirect; using Ecng.Common; namespace simple_strategy { class SimpleStrategy : Strategy { private CandleManager _candleManager; private CandleToken _candleToken; public SimpleStrategy() : base() { } protected override void OnStarting() { base.OnStarting(); _candleManager = _candleManager ?? new CandleManager(Trader); _candleToken = _candleToken ?? _candleManager.RegisterTimeFrameCandles(Security, (TimeSpan)AlfaTimeFrames.Minute1); this .When(_candleToken.CandlesFinished()) .Do(TryMakeTrade).Once(); //.Do(SetTrStop).Once(); this .When(_candleToken.CandlesFinished()) .Do(() => { this.AddInfoLog("Свеча окончена."); }); } private void TryMakeTrade() { this.AddInfoLog("Свеча завершена, начинаем проверку условий."); // проверим есть ли позиция по бумаге. if (HavePosition()) return; // если позиция нулевая, проверим есть ли не закрытые ордера на покупку. if (HaveActiveOrders()) return; // проверяем можно ли в текущей ситуации делать сделку. Проверка тренда итд. if(!CanTrade()) return; this.AddInfoLog("Проверка завершена, можно входить в позицию."); // Если сделку взять можно, то покупаем. Как только купили ставим трейлинг стоп лосс с датой истечения месяц. var order = new Order() { Direction = OrderDirections.Buy, Type = OrderTypes.Market, Volume = this.Security.MinLotSize, Security = this.Security, Portfolio = this.Portfolio, }; this.AddInfoLog("Формируем ордер. Направление: {0} Тип: {1} Объем: {2} Инструмент: {3}".Put(order.Direction, order.Type, order.Volume, order.Security.Code)); RegisterOrder(order); this .When(order.Matched()) .Do(SetStop).Once(); // Сделка висит пока не закроется по стоплоссу. } private bool CanTrade() { return true; } private bool HaveActiveOrders() { var orders = Trader.Orders.Where(o => ((o.Security == Security) && ((o.State == OrderStates.Active) || (o.State == OrderStates.None)) )); return orders.Any(); } private bool HavePosition() { var pos = Trader.Positions.FirstOrDefault(p => (p.Security == Security && p.Portfolio == Portfolio)); return (pos != null) && (pos.CurrentValue > 0); } private void SetStop(Order order) { var averPrice = order.GetAlfaAveragePrice(); var stopPersent = 0.01; var trailLevel = (double)averPrice * stopPersent; var stop = new Order() { Type = OrderTypes.Conditional, Direction = OrderDirections.Sell, Portfolio = this.Portfolio, Security = this.Security, Volume = this.Security.MinLotSize, StopCondition = new AlfaStopCondition() { Slippage = 1, //StopPrice = (double)averPrice - trailLevel, StopPrice = (double)averPrice + 0.5, TrailingLevel = trailLevel, }, }; this.AddInfoLog("Заявка исполнена, формируем стоп. Направление: {0} Тип: {1} Объем: {2} Инструмент: {3}".Put(stop.Direction, stop.Type, stop.Volume, stop.Security.Code)); RegisterOrder(stop); } private void SetTrStop() { var price = Security.BestPair.Ask.Price; var stop = new Order() { Type = OrderTypes.Conditional, Direction = OrderDirections.Buy, Portfolio = this.Portfolio, Security = this.Security, Volume = this.Security.MinLotSize, StopCondition = new AlfaStopCondition() { Slippage = 1, //StopPrice = (double)averPrice - trailLevel, StopPrice = (double)price - 1, TrailingLevel = 1, }, }; this.AddInfoLog("Заявка исполнена, формируем стоп. Направление: {0} Тип: {1} Объем: {2} Инструмент: {3}".Put(stop.Direction, stop.Type, stop.Volume, stop.Security.Code)); RegisterOrder(stop); } } }