private void QuotingClick(object sender, RoutedEventArgs e)
        {
            var wnd = new QuotingWindow
            {
                //Security = SecurityPicker.SelectedSecurity,
            };

            if (!wnd.ShowModal(this))
            {
                return;
            }

            var quoting = new MarketQuotingStrategy(wnd.Side, wnd.Volume)
            {
                Security  = wnd.Security,
                Portfolio = wnd.Portfolio,
                Connector = MainWindow.Instance.Connector
            };

            if ((decimal?)TakeProfit.EditValue > 0 || (decimal?)StopLoss.EditValue > 0)
            {
                var tp = (decimal?)TakeProfit.EditValue;
                var sl = (decimal?)StopLoss.EditValue;

                quoting
                .WhenNewMyTrade()
                .Do(trade =>
                {
                    var tpStrategy = tp == null ? null : new TakeProfitStrategy(trade, tp.Value);
                    var slStrategy = sl == null ? null : new StopLossStrategy(trade, sl.Value);

                    if (tpStrategy != null && slStrategy != null)
                    {
                        var strategy = new TakeProfitStopLossStrategy(tpStrategy, slStrategy);
                        AddStrategy($"TPSL {trade.Trade.Price} Vol={trade.Trade.Volume}", strategy);
                    }
                    else if (tpStrategy != null)
                    {
                        AddStrategy($"TP {trade.Trade.Price} Vol={trade.Trade.Volume}", tpStrategy);
                    }
                    else if (slStrategy != null)
                    {
                        AddStrategy($"SL {trade.Trade.Price} Vol={trade.Trade.Volume}", slStrategy);
                    }
                })
                .Apply(quoting);
            }

            AddStrategy($"Quoting {quoting.Security} {wnd.Side} Vol={wnd.Volume}", quoting);
        }
        private void QuotingClick(object sender, RoutedEventArgs e)
        {
            var wnd = new StrategyAddWindow
            {
                //Security = SecurityPicker.SelectedSecurity,
            };

            if (!wnd.ShowModal(this))
            {
                return;
            }

            var security  = wnd.Security;
            var portfolio = wnd.Portfolio;

            var quoting = new MarketQuotingStrategy(wnd.Side, wnd.Volume);

            if (wnd.TakeProfit > 0 || wnd.StopLoss > 0)
            {
                var tp = wnd.TakeProfit;
                var sl = wnd.StopLoss;

                quoting
                .WhenNewMyTrade()
                .Do(trade =>
                {
                    var tpStrategy = tp == 0 ? null : new TakeProfitStrategy(trade, tp);
                    var slStrategy = sl == 0 ? null : new StopLossStrategy(trade, sl);

                    if (tpStrategy != null && slStrategy != null)
                    {
                        var strategy = new TakeProfitStopLossStrategy(tpStrategy, slStrategy);
                        AddStrategy($"TPSL {trade.Trade.Price} Vol={trade.Trade.Volume}", strategy, security, portfolio);
                    }
                    else if (tpStrategy != null)
                    {
                        AddStrategy($"TP {trade.Trade.Price} Vol={trade.Trade.Volume}", tpStrategy, security, portfolio);
                    }
                    else if (slStrategy != null)
                    {
                        AddStrategy($"SL {trade.Trade.Price} Vol={trade.Trade.Volume}", slStrategy, security, portfolio);
                    }
                })
                .Apply(quoting);
            }

            AddStrategy($"Quoting {quoting.Security} {wnd.Side} Vol={wnd.Volume}", quoting, security, portfolio);
        }
        private void QuotingClick(object sender, RoutedEventArgs e)
        {
            var quoting = new MarketQuotingStrategy();

            var wnd = new StrategyEditWindow
            {
                Strategy = quoting,
            };

            if (!wnd.ShowModal(this))
            {
                return;
            }

            //if (wnd.TakeProfit > 0 || wnd.StopLoss > 0)
            //{
            //	var tp = wnd.TakeProfit;
            //	var sl = wnd.StopLoss;

            //	quoting
            //		.WhenNewMyTrade()
            //		.Do(trade =>
            //		{
            //			var tpStrategy = tp == 0 ? null : new TakeProfitStrategy(trade, tp);
            //			var slStrategy = sl == 0 ? null : new StopLossStrategy(trade, sl);

            //			if (tpStrategy != null && slStrategy != null)
            //			{
            //				var strategy = new TakeProfitStopLossStrategy(tpStrategy, slStrategy);
            //				AddStrategy($"TPSL {trade.Trade.Price} Vol={trade.Trade.Volume}", strategy, security, portfolio);
            //			}
            //			else if (tpStrategy != null)
            //			{
            //				AddStrategy($"TP {trade.Trade.Price} Vol={trade.Trade.Volume}", tpStrategy, security, portfolio);
            //			}
            //			else if (slStrategy != null)
            //			{
            //				AddStrategy($"SL {trade.Trade.Price} Vol={trade.Trade.Volume}", slStrategy, security, portfolio);
            //			}
            //		})
            //		.Apply(quoting);
            //}

            AddStrategy($"Quoting {quoting.Security} {quoting.QuotingDirection} Vol={quoting.QuotingVolume}", quoting);

            SaveStrategy(quoting);
        }
示例#4
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;
            }
        }
示例#5
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;
			}
		}
示例#6
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);
        }
        private void AnalyseAndTrade()
        {
            // calculate MA X-ing cases
            bool xUp = this.ShortMA.GetCurrentValue() > this.LongMA.GetCurrentValue() && this.ShortMA.GetValue(1) <= this.LongMA.GetValue(1);
            bool xDown = this.ShortMA.GetCurrentValue() < this.LongMA.GetCurrentValue() && this.ShortMA.GetValue(1) >= this.LongMA.GetValue(1);

            // calculate Filters
            bool upFilter = this.FilterMA.GetCurrentValue() > this.FilterMA.GetValue(10);
            bool downFilter = !upFilter;

            OrderDirections direction;
            decimal price;
            Order order = null;

            // calculate order direction
            if (xUp)
            {
                if (upFilter)
                {
                    direction = OrderDirections.Buy;
                    price = (this.UseQuoting) ? Security.GetMarketPrice(direction) : Security.LastTrade.Price;
                    order = this.CreateOrder(direction, price, base.Volume);

                    this.AddInfoLog("Xing Up appeared (MarketTime: {0}), and filter allowed the deal.", base.Security.GetMarketTime());
                }
                else
                {
                    this.AddInfoLog("Xing Up appeared (MarketTime: {0}), but filter blocked the deal.", base.Security.GetMarketTime());
                }
            }

            if (xDown)
            {
                if (downFilter)
                {
                    direction = OrderDirections.Sell;
                    price = (this.UseQuoting) ? Security.GetMarketPrice(direction) : Security.LastTrade.Price;
                    order = this.CreateOrder(direction, price, base.Volume);

                    this.AddInfoLog("Xing Down appeared (MarketTime: {0}), and filter allowed the deal.", base.Security.GetMarketTime());
                }
                else
                {
                    this.AddInfoLog("Xing Down appeared (MarketTime: {0}), but filter blocked the deal.", base.Security.GetMarketTime());
                }
            }

            // make order
            if (order != null)
            {
                if (this.PositionManager.Position == 0)
                {
                    if (this.UseQuoting)
                    {
                        MarketQuotingStrategy quotingStrategy = new MarketQuotingStrategy(order, this.BestPriceOffset, -3) { PriceType = MarketPriceTypes.Following };
                        base.ChildStrategies.Add(quotingStrategy);

                        this.Trader
                            .WhenNewMyTrades()
                            .Do(ProtectMyNewTrades)
                            .Once()
                            .Apply();
                    }
                    else
                    {
                        order
                            .WhenNewTrades()
                            .Do(ProtectMyNewTrades)
                            .Until(order.IsMatched)
                            .Apply();

                        RegisterOrder(order);
                    }
                }
                else
                {
                    this.AddInfoLog("PositionManager blocked the deal (MarketTime: {0}), we're already in position.", base.Security.GetMarketTime());
                }
            }
        }
示例#8
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
                {
                    // переворачиваем позицию через котирование
                    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);
        }
示例#9
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  в стопах
                }
            }
        }