Ejemplo n.º 1
0
        private void ProcessCandle(Candle candle)
        {
            // если наша стратегия в процессе остановки
            if (ProcessState == ProcessStates.Stopping)
            {
                // отменяем активные заявки
                CancelActiveOrders();
                return;
            }

            this.AddInfoLog(LocalizedStrings.Str2177Params.Put(candle.OpenTime, candle.OpenPrice, candle.HighPrice, candle.LowPrice, candle.ClosePrice, candle.TotalVolume));

            // добавляем новую свечу
            var longValue  = LongATR.Process(candle);
            var shortValue = ShortATR.Process(candle);

            if (Position < 0)
            {
                if (maxPrice > candle.ClosePrice)
                {
                    maxPrice = candle.ClosePrice;
                }
            }
            // вычисляем новое положение относительно друг друга
            // var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();
            if (-maxPrice + candle.ClosePrice > protectLevel && needProtect)
            {
                var price = Security.GetMarketPrice(Connector, Sides.Buy);

                // регистрируем псевдо-маркетную заявку - лимитная заявка с ценой гарантирующей немедленное исполнение.
                if (price != null)
                {
                    RegisterOrder(this.CreateOrder(Sides.Buy, price.Value, Volume));
                    needProtect = false;
                }
            }
            // если индикаторы заполнились
            if (LongATR.Container.Count >= LongATR.Length)
            {
                if (LongATR.GetCurrentValue <int>() > ShortATR.GetCurrentValue <int>() && Position == 0)
                {
                    // если короткая меньше чем длинная, то продажа, иначе, покупка.
                    var direction = Sides.Sell;

                    // вычисляем размер для открытия или переворота позы
                    var volume = Volume;

                    if (!SafeGetConnector().RegisteredMarketDepths.Contains(Security))
                    {
                        var price = Security.GetMarketPrice(Connector, direction);

                        // регистрируем псевдо-маркетную заявку - лимитная заявка с ценой гарантирующей немедленное исполнение.
                        if (price != null)
                        {
                            RegisterOrder(this.CreateOrder(direction, price.Value, volume));
                            needProtect  = true;
                            protectLevel = LongATR.GetCurrentValue <int>() * 3;
                        }
                    }
                    else
                    {
                        // переворачиваем позицию через котирование
                        var strategy = new MarketQuotingStrategy(direction, volume)
                        {
                            WaitAllTrades = true,
                        };
                        ChildStrategies.Add(strategy);
                    }
                }
            }


            _myTrades.Clear();

            var dict = new Dictionary <IChartElement, object>
            {
                { _candlesElem, candle },
            };

            _chart.Draw(candle.OpenTime, dict);
        }
Ejemplo n.º 2
0
        protected void ProcessFinCandle(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));

            // добавляем новую свечку
            LongATR.Process(candle);
            ShortATR.Process(candle);
            PLB.Process(candle);
            int tt = PLB.GetCurrentValue <int>();

            if ((double)candle.ClosePrice < buyprice - deflevel && buyprice > 0)
            {
            }
            //+! костыльная проверка что индикатор заполнен.
            // нужно всегда заполнять перед торговлей
            if (LongATR.Container.Count >= LongATR.Length)
            {
                if (LongATR.GetCurrentValue <int>() > ShortATR.GetCurrentValue <int>() && this.Position == 0)
                {
                    var direction = OrderDirections.Buy;
                    buyprice = (double)candle.ClosePrice;
                    //спизжено из стоп лос стретеджи
                    //var longPos = this.BuyAtMarket();

                    //// регистрируем правило, отслеживающее появление новых сделок по заявке
                    //longPos
                    //    .WhenNewTrades()
                    //    .Do(OnNewOrderTrades)
                    //    .Apply(this);

                    //// отправляем заявку на регистрацию
                    //RegisterOrder(longPos);

                    double dl = 2.5 * ShortATR.GetCurrentValue <int>();
                    deflevel = (int)(dl + 0.5);
                    Order longPos;
                    if (!((EmulationTrader)Trader).MarketEmulator.Settings.UseMarketDepth)
                    {
                        // регистрируем псевдо-маркетную заявку - лимитная заявка с ценой гарантирующей немедленное исполнение.
                        longPos = this.CreateOrder(direction, Security.GetMarketPrice(direction), Volume);
                        RegisterOrder(longPos);
                    }
                    else
                    {
                        // переворачиваем позицию через котирование
                        var strategy = new MarketQuotingStrategy(direction, Volume)
                        {
                            WaitAllTrades = true,
                        };
                        ChildStrategies.Add(strategy);
                    }

                    // если произошло пересечение
                    //if (_isShortLessThenLong != isShortLessThenLong)
                    //{
                    //     если короткая меньше чем длинная, то продажа, иначе, покупка.
                    //    var direction = isShortLessThenLong ? OrderDirections.Sell : OrderDirections.Buy;

                    //    if (!((EmulationTrader)Trader).MarketEmulator.Settings.UseMarketDepth)
                    //    {
                    //         регистрируем псевдо-маркетную заявку - лимитная заявка с ценой гарантирующей немедленное исполнение.
                    //        RegisterOrder(this.CreateOrder(direction, Security.GetMarketPrice(direction), Volume));
                    //    }
                    //    else
                    //    {
                    //         переворачиваем позицию через котирование
                    //        var strategy = new MarketQuotingStrategy(direction, Volume)
                    //        {
                    //            WaitAllTrades = true,
                    //        };
                    //        ChildStrategies.Add(strategy);
                    //    }

                    //     запоминаем текущее положение относительно друг друга
                    //    _isShortLessThenLong = isShortLessThenLong;
                    //}

                    //+! щас будет костыльный параметр 2.5 на ATR  в стопах
                }
            }
        }