Esempio n. 1
0
        private void ProcessCandle(Candle candle)
        {
            // strategy are stopping
            if (ProcessState == ProcessStates.Stopping)
            {
                CancelActiveOrders();
                return;
            }

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

            // process new candle
            var longValue  = LongSma.Process(candle);
            var shortValue = ShortSma.Process(candle);

            // calc new values for short and long
            var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();

            // crossing happened
            if (_isShortLessThenLong != isShortLessThenLong)
            {
                // if short less than long, the sale, otherwise buy
                var direction = isShortLessThenLong ? Sides.Sell : Sides.Buy;

                // calc size for open position or revert
                var volume = Position == 0 ? Volume : Position.Abs().Min(Volume) * 2;

                // calc order price as a close price + offset
                var price = candle.ClosePrice + ((direction == Sides.Buy ? Security.PriceStep : -Security.PriceStep) ?? 1);

                RegisterOrder(this.CreateOrder(direction, price, volume));

                // or revert position via market quoting
                //var strategy = new MarketQuotingStrategy(direction, volume);
                //ChildStrategies.Add(strategy);

                // store current values for short and long
                _isShortLessThenLong = isShortLessThenLong;
            }

            var trade = _myTrades.FirstOrDefault();

            _myTrades.Clear();

            var data = new ChartDrawData();

            data
            .Group(candle.OpenTime)
            .Add(_candlesElem, candle)
            .Add(_shortElem, shortValue)
            .Add(_longElem, longValue)
            .Add(_tradesElem, trade);

            _chart.Draw(data);
        }
Esempio n. 2
0
        public void OperatorNotEqual_SameValues_IsFalse()
        {
            // Arrange
            var value1 = Position.Abs(100, 100);
            var value2 = Position.Abs(100, 100);

            // Act
            var result = value1 != value2;

            // Assert
            result.Should().BeFalse();
        }
Esempio n. 3
0
        public void OperatorEquals_SameValues_IsTrue()
        {
            // Arrange
            var value1 = Position.Abs(100, 100);
            var value2 = Position.Abs(100, 100);

            // Act
            var result = value1 == value2;

            // Assert
            result.Should().BeTrue();
        }
Esempio n. 4
0
        /// <summary>
        /// Calculates the gravitational force that exists between this body and another gravitational body.
        /// </summary>
        /// <returns>Force (Vector) directed toward this body, i.e. if the other body has higher gravitational strength,
        /// the force will be negative (directed away from this body)</returns>
        public Vector GravitationalForceToward(GravitationalBody b)
        {
            double distance = Math.Abs(Position.Abs() - b.Position.Abs());

            if (distance < Radius || distance < b.Radius)
            {
                throw new OverLappingRadiusException("Bodies must not be connected!");
            }

            Vector direction = b.Position - Position;

            double r_squared = direction.Abs() * direction.Abs();

            return(direction.Normalised() * Constants.Common.G * Mass * b.Mass / r_squared);
        }
Esempio n. 5
0
        private void Process(Candle candle)
        {
            //this.AddInfoLog("Свеча {0}: {1};{2};{3};{4}; объем {5}", candle.OpenTime, candle.OpenPrice, candle.HighPrice, candle.LowPrice, candle.ClosePrice, candle.TotalVolume);

            var isShortWasFormed = _shortSma.IsFormed;
            var isLongWasFormed  = _longSma.IsFormed;

            var currentShort = _shortSma.Process(candle);
            var currentLong  = _longSma.Process(candle);

            if (candle.State == CandleStates.Finished && isShortWasFormed && isLongWasFormed &&
                _longSma.Length > 1 && _shortSma.Length > 1 && candle.OpenTime > StartedTime)
            {
                Order order = null;

                var prevShort = _shortSma.GetValue(1);
                var prevLong  = _longSma.GetValue(1);

                if (prevShort < prevLong && currentShort.GetValue <decimal>() > currentLong.GetValue <decimal>() && Position <= 0)
                {
                    this.AddInfoLog(LocalizedStrings.Str3297);
                    order = this.BuyAtMarket(Position == 0 ? Volume : Position.Abs() * 2);
                }
                else if (prevShort > prevLong && currentShort.GetValue <decimal>() < currentLong.GetValue <decimal>() && Position >= 0)
                {
                    this.AddInfoLog(LocalizedStrings.Str3298);
                    order = this.SellAtMarket(Position == 0 ? Volume : Position.Abs() * 2);
                }

                if (order != null)
                {
                    RegisterOrder(order);
                }
            }

            new ChartDrawCommand(candle.OpenTime, new Dictionary <IChartElement, object>
            {
                { _area.Elements[0], candle },
                { _area.Elements[1], currentLong },
                { _area.Elements[2], currentShort },
            }).Process(this);
        }
Esempio n. 6
0
        private void ProcessCandle(Candle candle)
        {
            // если наша стратегия в процессе остановки
            if (ProcessState == ProcessStates.Stopping)
            {
                // отменяем активные заявки
                CancelActiveOrders();
                return;
            }

            // добавляем новую свечу
            LongSma.Process(candle);
            ShortSma.Process(candle);

            // вычисляем новое положение относительно друг друга
            var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();

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

                // вычисляем размер для открытия или переворота позы
                var volume = Position == 0 ? Volume : Position.Abs() * 2;

                // регистрируем заявку (обычным способом - лимитированной заявкой)
                //RegisterOrder(this.CreateOrder(direction, (decimal)Security.GetCurrentPrice(direction), volume));

                // переворачиваем позицию через котирование
                var strategy = new MarketQuotingStrategy(direction, volume);
                ChildStrategies.Add(strategy);

                // запоминаем текущее положение относительно друг друга
                _isShortLessThenLong = isShortLessThenLong;
            }
        }
Esempio n. 7
0
        private void ProcessCandle(Candle candle)
        {
            // strategy are stopping
            if (ProcessState == ProcessStates.Stopping)
            {
                CancelActiveOrders();
                return;
            }

            // process new candle
            LongSma.Process(candle);
            ShortSma.Process(candle);

            // calc new values for short and long
            var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();

            // crossing happened
            if (_isShortLessThenLong != isShortLessThenLong)
            {
                // if short less than long, the sale, otherwise buy
                var direction = isShortLessThenLong ? Sides.Sell : Sides.Buy;

                // calc size for open position or revert
                var volume = Position == 0 ? Volume : Position.Abs() * 2;

                // register order (limit order)
                RegisterOrder(this.CreateOrder(direction, (decimal)(Security.GetCurrentPrice(this, direction) ?? 0), volume));

                // or revert position via market quoting
                //var strategy = new MarketQuotingStrategy(direction, volume);
                //ChildStrategies.Add(strategy);

                // store current values for short and long
                _isShortLessThenLong = isShortLessThenLong;
            }
        }
Esempio n. 8
0
        private void ProcessCandle(Candle candle)
        {
            // strategy are stopping
            if (ProcessState == ProcessStates.Stopping)
            {
                CancelActiveOrders();
                return;
            }

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

            // process new candle
            var longValue  = LongSma.Process(candle);
            var shortValue = ShortSma.Process(candle);

            // calc new values for short and long
            var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();

            // crossing happened
            if (_isShortLessThenLong != isShortLessThenLong)
            {
                // if short less than long, the sale, otherwise buy
                var direction = isShortLessThenLong ? Sides.Sell : Sides.Buy;

                // calc size for open position or revert
                var volume = Position == 0 ? Volume : Position.Abs().Min(Volume) * 2;

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

                    // register "market" order (limit order with guaranteed execution price)
                    if (price != null)
                    {
                        RegisterOrder(this.CreateOrder(direction, price.Value, volume));
                    }
                }
                else
                {
                    // register order (limit order)
                    RegisterOrder(this.CreateOrder(direction, (decimal)(Security.GetCurrentPrice(this, direction) ?? 0), volume));

                    // or revert position via market quoting
                    //var strategy = new MarketQuotingStrategy(direction, volume)
                    //{
                    //	WaitAllTrades = true,
                    //};
                    //ChildStrategies.Add(strategy);
                }

                // store current values for short and long
                _isShortLessThenLong = isShortLessThenLong;
            }

            var trade = _myTrades.FirstOrDefault();

            _myTrades.Clear();

            var dict = new Dictionary <IChartElement, object>
            {
                { _candlesElem, candle },
                { _shortElem, shortValue },
                { _longElem, longValue },
                { _tradesElem, trade }
            };

            _chart.Draw(candle.OpenTime, dict);
        }
Esempio n. 9
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  = LongSma.Process(candle);
            var shortValue = ShortSma.Process(candle);

            // вычисляем новое положение относительно друг друга
            var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();

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

                // вычисляем размер для открытия или переворота позы
                var volume = Position == 0 ? Volume : Position.Abs().Min(Volume) * 2;

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

                    // регистрируем псевдо-маркетную заявку - лимитная заявка с ценой гарантирующей немедленное исполнение.
                    if (price != null)
                    {
                        RegisterOrder(this.CreateOrder(direction, price.Value, volume));
                    }
                }
                else
                {
                    // регистрируем заявку (обычным способом - лимитированной заявкой)
                    RegisterOrder(this.CreateOrder(direction, (decimal)(Security.GetCurrentPrice(this, direction) ?? 0), volume));

                    // переворачиваем позицию через котирование
                    //var strategy = new MarketQuotingStrategy(direction, volume)
                    //{
                    //	WaitAllTrades = true,
                    //};
                    //ChildStrategies.Add(strategy);
                }

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

            var trade = _myTrades.FirstOrDefault();

            _myTrades.Clear();

            var dict = new Dictionary <IChartElement, object>
            {
                { _candlesElem, candle },
                { _shortElem, shortValue },
                { _longElem, longValue },
                { _tradesElem, trade }
            };

            _chart.Draw(candle.OpenTime, dict);
        }