private bool PlaceBracketOrder(RangeBreakOutStockConfig stock, OrderMode mode, int quantity)
        {
            var stopLoss = Math.Abs(stock.SellBreakOutPrice - stock.BuyBreakOutPrice);
            Dictionary <string, dynamic> orderResponse = new Dictionary <string, dynamic>();
            var triggerPrice = mode == OrderMode.BUY ? stock.BuyBreakOutPrice : stock.SellBreakOutPrice;
            var targetPrice  = mode == OrderMode.BUY ?
                               Math.Round((stock.BuyBreakOutPrice + (stock.BuyBreakOutPrice * (stock.ProfitMargin / 100.0m))), 2).GetNextValidPrice(true) :
                               Math.Round((stock.SellBreakOutPrice - (stock.SellBreakOutPrice * (stock.ProfitMargin / 100.0m))), 2).GetNextValidPrice(true);

            var targetPoint = mode == OrderMode.BUY ?
                              (targetPrice - stock.BuyBreakOutPrice) :
                              (stock.SellBreakOutPrice - targetPrice);

            orderResponse = _kite.PlaceOrder(stock.Exchange, stock.Symbol, mode.ToString(), quantity, Product: Constants.PRODUCT_MIS, OrderType: Constants.ORDER_TYPE_LIMIT, Price: triggerPrice, Variety: Constants.VARIETY_BO, Validity: Constants.VALIDITY_DAY, SquareOffValue: targetPoint, StoplossValue: stopLoss);
            if (orderResponse.Any(s => s.Key.ToLower() == "status" && s.Value.ToLower() == "success"))
            {
                string orderId = GetOrderId(orderResponse);
                stock.AllOrderStatus[OrderType.BracketOrder]      = new KeyValuePair <string, OrderStatus>(orderId, OrderStatus.Ordered);
                stock.AllOrderTargetPrice[OrderType.BracketOrder] = new KeyValuePair <OrderMode, decimal>(mode, targetPrice);
                Events.RaiseAskForOrderSubscriptionEvent(orderId, true);
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #2
0
        public override void BuySellStock(Quote ltp)
        {
            bool      shouldPlaceOrder = false;
            OrderMode orderMode        = OrderMode.BUY;
            var       lastPrice        = ltp.LastPrice;

            if (lastPrice <= StockActionPrice[OrderMode.BUY])
            {
                //Place Buy Order
                shouldPlaceOrder = true;
                orderMode        = OrderMode.BUY;
            }
            else if (lastPrice >= StockActionPrice[OrderMode.SELL])
            {
                //Place Sell Order
                shouldPlaceOrder = true;
                orderMode        = OrderMode.SELL;
            }


            if (shouldPlaceOrder)
            {
                int quantity = (OpenPositionsCount != 0 && LastOrderMode != orderMode) ? StocksCountToBuyOrCell() : StocksBuySellQuantityStart;

                var price = lastPrice.GetNextValidPrice(orderMode == OrderMode.BUY ? false : true);
                this.PlaceOrder(orderMode.ToString(), quantity, price);
                CurrentPrice       = lastPrice;
                OpenPositionsCount = (OpenPositionsCount != 0 && LastOrderMode != orderMode) ? (OpenPositionsCount - quantity) : (OpenPositionsCount + quantity);
                SaveData(orderMode, quantity, price);
            }


            LastOrderMode = orderMode;
        }
예제 #3
0
        public override void BuySellStock(Quote ltp)
        {
            bool      shouldPlaceOrder = false;
            OrderMode orderMode        = OrderMode.BUY;
            var       lastPrice        = ltp.LastPrice;

            if (lastPrice <= StockActionPrice[OrderMode.BUY])
            {
                //Place Buy Order
                shouldPlaceOrder = true;
                orderMode        = OrderMode.BUY;
            }
            else if (lastPrice >= StockActionPrice[OrderMode.SELL])
            {
                //Place Sell Order
                shouldPlaceOrder = true;
                orderMode        = OrderMode.SELL;
            }

            if (shouldPlaceOrder)
            {
                var price = lastPrice.GetNextValidPrice(orderMode == OrderMode.BUY ? false : true);
                this.PlaceOrder(orderMode.ToString(), StocksBuySellQuantityStart, price);
                CurrentPrice = lastPrice;
                SaveData(orderMode, StocksBuySellQuantityStart, price);
            }
        }
        /// <summary>
        /// Returns true if it reaches max loss and max profit
        /// </summary>
        /// <param name="position"></param>
        /// <returns></returns>
        public bool CheckMaxProfitLossAndClosePosition(int quantity, decimal PNL)
        {
            try
            {
                _config.NetQuantity = quantity;
                _config.UpdateMax();
                if ((PNL >= _config.MaxProfit && _config.MaxProfit != 0) || (PNL <= -(_config.MaxLoss) && _config.MaxLoss != 0))
                {
                    OrderMode mode = OrderMode.BUY;
                    if (quantity > 0)
                    {
                        mode = OrderMode.SELL;
                    }
                    else
                    {
                        mode = OrderMode.BUY;
                    }
                    var status = _kite.PlaceOrder(_config.Exchange, _config.Symbol, mode.ToString(), Convert.ToInt32(Math.Abs(quantity)), Product: "MIS", OrderType: "MARKET");
                    var orderPlacedSuccessfully = status.Any(s => s.Key.ToLower() == "status" && s.Value.ToLower() == "success");
                    if (orderPlacedSuccessfully)
                    {
                        if (PNL > _config.MaxProfit)
                        {
                            Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, StrategyStockStatus.MaxProfitReached.ToString());
                        }
                        else
                        {
                            Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, StrategyStockStatus.MaxLossReached.ToString());
                        }

                        fileWather.Changed            -= FileWather_Changed;
                        fileWather.EnableRaisingEvents = false;
                        return(true);
                    }
                    return(false);
                }
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private bool PlaceCoverOrder(RangeBreakOutStockConfig stock, OrderMode mode, int quantity)
        {
            stock.StopLoss = mode == OrderMode.BUY ? stock.SellBreakOutPrice : stock.BuyBreakOutPrice;
            Dictionary <string, dynamic> orderResponse = new Dictionary <string, dynamic>();

            orderResponse = _kite.PlaceOrder(stock.Exchange, stock.Symbol, mode.ToString(), quantity, Product: Constants.PRODUCT_MIS, OrderType: Constants.ORDER_TYPE_MARKET, TriggerPrice: stock.StopLoss, Variety: stock.Variety, Validity: Constants.VALIDITY_DAY);
            if (orderResponse.Any(s => s.Key.ToLower() == "status" && s.Value.ToLower() == "success"))
            {
                stock.TargetPrice = null;
                string orderId = GetOrderId(orderResponse);
                Events.RaiseAskForOrderSubscriptionEvent(orderId, true);
                stock.ParentOrderId       = orderId;
                stock.LastOrderedQuantity = quantity;
                stock.ReversalNumber++;
                stock.OrderedQuantity = quantity;
                return(true);
            }
            else
            {
                return(true);
            }
        }
예제 #6
0
 public void SaveSettings()
 {
     GridPainterSettings.Default.PaletteOrderMode = OrderMode.ToString();
     GridPainterSettings.Default.Save();
 }
예제 #7
0
        public override void ExecutedOrder(Order order)
        {
            nextOrderMode = null;
            if (order.Status.Equals("complete", StringComparison.InvariantCultureIgnoreCase))
            {
                OrderMode mode = order.TransactionType.Equals("buy", StringComparison.InvariantCultureIgnoreCase) ? OrderMode.BUY : OrderMode.SELL;
                if (mode == OrderMode.BUY)
                {
                    OpenPositions = OpenPositions + order.Quantity;
                }
                else
                {
                    OpenPositions = OpenPositions - order.Quantity;
                }

                if (TargetStatus == null)
                {
                    var buyTargetPriceMargin = (MarginType == MarginType.Absolute) ?
                                               (Margin).GetNextValidPrice(true) :
                                               (((order.AveragePrice * Margin) / 100.0m)).GetNextValidPrice(true);

                    var sellTargetPriceMargin = (MarginType == MarginType.Absolute) ?
                                                (Margin).GetNextValidPrice(false) :
                                                (((order.AveragePrice * Margin) / 100.0m)).GetNextValidPrice(false);

                    if (mode == OrderMode.BUY)
                    {
                        TargetPrice   = order.AveragePrice + buyTargetPriceMargin;
                        StopLossPrice = order.AveragePrice - (sellTargetPriceMargin * 2);
                        lastOrder     = OrderMode.BUY;
                    }
                    else if (mode == OrderMode.SELL)
                    {
                        TargetPrice   = order.AveragePrice - sellTargetPriceMargin;
                        lastOrder     = OrderMode.SELL;
                        StopLossPrice = order.AveragePrice + (buyTargetPriceMargin * 2);
                    }
                    if (OpenPositions != 0)
                    {
                        _transactionCount++;
                    }
                }
                else
                {
                    if (TargetStatus == StockTradeConfiguration.Models.TargetStatus.TargetHit)
                    {
                        TargetStatus = null;
                        TargetHitCount++;
                        if (mode == OrderMode.BUY)
                        {
                            PlaceOrder(OrderMode.SELL.ToString(), GetQuantity(), order.AveragePrice, OrderOnPrice.MarketPrice);
                        }
                        else
                        {
                            PlaceOrder(OrderMode.BUY.ToString(), GetQuantity(), order.AveragePrice, OrderOnPrice.MarketPrice);
                        }
                    }
                    else
                    {
                        TargetStatus = null;
                        StopLossHitCount--;
                        PlaceOrder(mode.ToString(), GetQuantity(), order.AveragePrice, OrderOnPrice.MarketPrice);
                    }
                }
            }
            RaiseTargetStopLossEvent();
            RaiseTargetStopLossHitEvent();
            Events.RaiseOpenPositionsChangedEvent(Exchange, Symbol, Convert.ToInt32(OpenPositions));
        }
        private OrderMode?IsEligibleToPlaceOrder(string signal, OrderMode?oldOrderMode)
        {
            if (_signalSettingInfo != null)
            {
                string seperator  = string.IsNullOrEmpty(_signalSettingInfo.Seperator) ? _signalSettingInfo.Seperator.Trim() : ",";
                int    priceIndex = _signalSettingInfo.PriceIndex;

                decimal priceBuffer = _signalSettingInfo.PriceBufferToAcceptOrder;
                int     timeIndex   = _signalSettingInfo.TimeIndex;

                var splitData = signal.Split(new string[] { seperator }, StringSplitOptions.RemoveEmptyEntries);

                OrderMode mode = splitData[_signalSettingInfo.BuySellSignalIndex].Trim().ToLower().Equals("buy", StringComparison.InvariantCultureIgnoreCase) ? OrderMode.BUY : OrderMode.SELL;

                if (oldOrderMode.HasValue && oldOrderMode.Value == mode)
                {
                    Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, "Current generated order is same as last order : " + mode.ToString());
                    //MessageBox.Show("Current generated order is same as last order : " + mode.ToString());
                    return(null);
                }

                var price = Convert.ToDecimal(splitData[priceIndex]);

                //Check Price Buffer
                if (_config.LTP < (Math.Abs(price - priceBuffer)) || _config.LTP > (Math.Abs(price + priceBuffer)))
                {
                    Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, "Rejected because buffer price didn't match : " + "LTP:" + _config.LTP + " $ Price:" + price + " $PriceBuffer:" + priceBuffer + " $Start:" + Math.Abs(price - priceBuffer) + " $End:" + Math.Abs(price + priceBuffer));
                    //MessageBox.Show("Rejected because buffer price didn't match : " + "LTP:"+_config.LTP+" $ Price:"+price + " $PriceBuffer:"+priceBuffer+" $Start:"+ Math.Abs(price - priceBuffer)+" $End:"+ Math.Abs(price + priceBuffer));
                    return(null);
                }
                try
                {
                    DateTime dt                    = DateTime.ParseExact(splitData[timeIndex], _signalSettingInfo.TimeFormat, System.Globalization.CultureInfo.InvariantCulture);
                    var      signalTimeSpan        = dt.TimeOfDay;
                    var      signalTimeSpanMinutes = (signalTimeSpan.TotalMinutes + _signalSettingInfo.TimeDifferenceBetweenSystemAndSignal);

                    var currentTimeSpanMinutes = DateTime.Now.TimeOfDay.TotalMinutes;

                    if (signalTimeSpanMinutes < Math.Abs(currentTimeSpanMinutes - _signalSettingInfo.TimeBufferToTakeOrder) || currentTimeSpanMinutes > Math.Abs(signalTimeSpanMinutes + _signalSettingInfo.TimeBufferToTakeOrder))
                    {
                        Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, "Rejected because buffer time didn't match : " + "Current Time:" + DateTime.Now.TimeOfDay + " $ Generated Time:" + signalTimeSpan + " $ Buffer Time:" + TimeSpan.FromMinutes(signalTimeSpanMinutes));
                        // MessageBox.Show("Rejected because buffer time didn't match : " + "Current Time:" + DateTime.Now.TimeOfDay + " $ Generated Time:" + signalTimeSpan + " $ Buffer Time:" + TimeSpan.FromMinutes(signalTimeSpanMinutes));
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, ex.Message + " " + splitData[timeIndex] + _signalSettingInfo.TimeFormat);
                    return(null);
                    //MessageBox.Show(ex.Message + " " + splitData[timeIndex] + _signalSettingInfo.TimeFormat);
                }
                return(mode);
            }
            else
            {
                var       splitData = signal.Split(new string[] { ",", }, StringSplitOptions.RemoveEmptyEntries);
                OrderMode mode      = splitData[_signalSettingInfo.BuySellSignalIndex].Equals("buy", StringComparison.InvariantCultureIgnoreCase) ? OrderMode.BUY : OrderMode.SELL;

                if (oldOrderMode.HasValue && oldOrderMode.Value == mode)
                {
                    return(null);
                }
                else
                {
                    return(mode);
                }
            }
        }
        private void PlaceOrder(OrderMode orderMode, decimal price)
        {
            int quantity = _config.LotSize;

            if (_oldOrderMode.HasValue && _oldOrderMode.Value == orderMode)
            {
                return;
            }

            var reversal = _reversalMultiplier.Where(s => s.Key <= _countOfContiniousExecutionInOneDirection).OrderByDescending(s => s.Key).FirstOrDefault();

            if (reversal.Value != 0)
            {
                quantity = (_config.LotSize * reversal.Value) + Math.Abs(_currentOpenPosition);
            }
            else
            {
                quantity = _config.LotSize;
            }

            _countOfContiniousExecutionInOneDirection++;

            _oldOrderMode = orderMode;
            try
            {
                var orderResponse = _kite.PlaceOrder(_config.Exchange, _config.Symbol, orderMode.ToString(), quantity, Product: "MIS", OrderType: "MARKET");
                Events.RaiseStatusChangedEvent(_config.Exchange, _config.Symbol, orderMode + " order executed");
            }
            catch (Exception ex)
            {
            }
        }