コード例 #1
0
		public UpdateMarketDepthCommand(MarketDepth depth)
		{
			if (depth == null)
				throw new ArgumentNullException(nameof(depth));

			Depth = depth;
		}
コード例 #2
0
ファイル: Volume Log v1.01.cs プロジェクト: Mikai47/cAlgoBot
//--------------------------------------        
        protected override void Initialize()
        {
            _marketDepth = MarketData.GetMarketDepth(Symbol);
            _marketDepth.Updated += MarketDepthUpdated;

            foreach (var entry in _marketDepth.BidEntries)
            {
                PreviousBidList.Add(new Previouslist 
                {
                    Preis = entry.Price,
                    Volumen = entry.Volume
                });
            }

            foreach (var entry in _marketDepth.AskEntries)
            {
                PreviousAskList.Add(new Previouslist 
                {
                    Preis = entry.Price,
                    Volumen = entry.Volume
                });
            }

            FilterM = Filter * 1000000;

            var Table = new StringBuilder();
            Table.AppendLine("Bid\tTime\tMillion\t\tAsk\tTime\tMillion");
            Table.AppendLine("(Buys)\tago\tUnits\t\t(Sells)\tago\tUnits");
            Table.AppendLine("----------------------------------------------------------------------------------");
            ChartObjects.DrawText("Header", Table.ToString(), StaticPosition.TopLeft, (Colors)Enum.Parse(typeof(Colors), TextColor, true));
            Timer.Start(UpdateFrequency);
        }
コード例 #3
0
        private static void CalculateArbitrageResult(VoSExchange vaultOfSatoshi, MarketDepth bestDogeBtcAsk,
            string currencyCode)
        {
            Task<MarketDepth> bestDogeFiatBidTask = GetBestBid(vaultOfSatoshi, new VoSMarketId("DOGE", currencyCode));
            Task<MarketDepth> bestBtcFiatAskTask = GetBestAsk(vaultOfSatoshi, new VoSMarketId("BTC", currencyCode));

            MarketDepth bestDogeFiatBid = bestDogeFiatBidTask.Result;
            MarketDepth bestBtcFiatAsk = bestBtcFiatAskTask.Result;

            if (bestDogeFiatBid == null
                || bestDogeFiatBid.Price == 0.0m)
            {
                Console.WriteLine("No valid DOGE/"
                    + currencyCode + " price available.");
                return;
            }
            if (bestBtcFiatAsk == null
                || bestBtcFiatAsk.Price == 0.0m)
            {
                Console.WriteLine("No valid BTC/"
                    + currencyCode + " price available.");
                return;
            }

            CalculateArbitrageResult(bestDogeFiatBid, bestDogeBtcAsk, bestBtcFiatAsk, currencyCode);
        }
コード例 #4
0
ファイル: Mijo Volume.cs プロジェクト: Mikai47/cAlgoBot
        protected override void Initialize()
        {
            old_index = MarketSeries.Close.Count - 1;
            Symbol_PointSize = Symbol.PointSize;
            _MarketDepth = MarketData.GetMarketDepth(Symbol);

            _MarketDepth.Updated += OnUpdated;
        }
コード例 #5
0
        public UpdateMarketDepthCommand(MarketDepth depth)
        {
            if (depth == null)
            {
                throw new ArgumentNullException("depth");
            }

            Depth = depth;
        }
コード例 #6
0
ファイル: OandaServer.cs プロジェクト: zilveer/OsEngine
        // parsing incoming data
        // разбор входящих данных

        private void ClientOnMarketDepthChangeEvent(MarketDepth marketDepth)
        {
            if (MarketDepthEvent != null)
            {
                MarketDepthEvent(marketDepth);
            }

            _depthsDontGo = false;
        }
コード例 #7
0
        private void TryUpdateDepth(Subscription subscription, MarketDepth depth)
        {
            if (!_quotesWindows.TryGetValue(depth.Security, out var wnd))
            {
                return;
            }

            wnd.Update(depth.ImpliedVolatility(Connector, Connector, _model.ExchangeInfoProvider, depth.LastChangeTime));
        }
コード例 #8
0
        private void PlazaControllerOnMarketDepthChangeEvent(MarketDepth depth)
        {
            depth.Time = DateTime.Now;

            if (MarketDepthEvent != null)
            {
                MarketDepthEvent(depth);
            }
        }
コード例 #9
0
        private void TraderOnMarketDepthChanged(MarketDepth depth)
        {
            var wnd = _quotesWindows.TryGetValue(depth.Security);

            if (wnd != null)
            {
                wnd.DepthCtrl.UpdateDepth(depth);
            }
        }
コード例 #10
0
        private void TraderOnMarketDepthReceived(Subscription subscription, MarketDepth depth)
        {
            var wnd = _quotesWindows.TryGetValue(depth.Security);

            if (wnd != null)
            {
                wnd.DepthCtrl.UpdateDepth(depth);
            }
        }
コード例 #11
0
        private void OnDepth(MarketDepth depth)
        {
            if (depth.Security != _security)
            {
                return;
            }

            DepthControl.UpdateDepth(depth);
        }
コード例 #12
0
 public static MarketDepthUpdate Generate(MarketDepth depth, string channelName)
 {
     if (depth == null)
     {
         return(null);
     }
     return(new MarketDepthUpdate {
         MarketDepth = depth, UpdateDate = depth.UpdatedAt, ChannelName = channelName
     });
 }
コード例 #13
0
 protected override void OnNewMarketDepth(Instrument instrument, MarketDepth marketDepth)
 {
     this.A6MpF2380O.OnMarketDepth(instrument, marketDepth);
     this.HeHpDewVKD.OnMarketDepth(instrument, marketDepth);
     this.marketManager.OnMarketDepth(instrument, marketDepth);
     this.exits[instrument].OnMarketDepth(marketDepth);
     this.entries[instrument].OnMarketDepth(marketDepth);
     this.moneyManagers[instrument].OnMarketDepth(marketDepth);
     this.riskManagers[instrument].OnMarketDepth(marketDepth);
 }
コード例 #14
0
        public void TestParseCryptsyMarketOrders()
        {
            JObject jsonObj      = LoadTestData("getmarketorders.json");
            Book    marketOrders = CryptsyParsers.ParseMarketOrders(jsonObj.Value <JObject>("return"));

            MarketDepth lowestSellOrder = marketOrders.Asks[0];

            Assert.AreEqual((decimal)0.00001118, lowestSellOrder.Price);
            Assert.AreEqual((decimal)119.40714285, lowestSellOrder.Quantity);
        }
コード例 #15
0
ファイル: FQProvider.cs プロジェクト: zhuzhenping/FreeOQ
        public void EmitMarketDepth(Instrument instrument, DateTime time, BidAsk side, OrderBookAction action, double price, int size, int position)
        {
            MarketDepth marketDepth = new MarketDepth(time, string.Empty, position, EnumConverter.Convert(action), EnumConverter.Convert(side), price, size);

            if (this.NewMarketDepth == null)
            {
                return;
            }
            this.NewMarketDepth((object)this, new MarketDepthEventArgs(marketDepth, (IFIXInstrument)instrument.instrument, (IMarketDataProvider)this));
        }
コード例 #16
0
        /// <summary>
        /// To create a rule for the event of order book spread size decrease on a specific value.
        /// </summary>
        /// <param name="depth">The order book to be traced for the spread change event.</param>
        /// <param name="price">The shift value.</param>
        /// <param name="provider">The market data provider.</param>
        /// <returns>Rule.</returns>
        public static MarketRule <MarketDepth, MarketDepth> WhenSpreadLess(this MarketDepth depth, Unit price, IMarketDataProvider provider = null)
        {
            var pair       = depth.BestPair;
            var firstPrice = pair?.SpreadPrice ?? 0;

            return(new MarketDepthChangedRule(depth, provider, d => d.BestPair != null && d.BestPair.SpreadPrice < (firstPrice - price))
            {
                Name = LocalizedStrings.Str1058Params.Put(depth.Security, price)
            });
        }
コード例 #17
0
ファイル: SmartComServer.cs プロジェクト: w1r2p1/OsEngineMono
        private void SmartServerOnUpdateBidAsk(string symbol, int row, int nrows, double bid, double bidsize, double ask, double asksize)
        {
            MarketDepthLevel askOs = new MarketDepthLevel();

            askOs.Bid   = Convert.ToDecimal(bidsize);
            askOs.Ask   = 0;
            askOs.Price = Convert.ToDecimal(bid);

            MarketDepthLevel bidOs = new MarketDepthLevel();

            bidOs.Ask   = Convert.ToDecimal(asksize);
            bidOs.Bid   = 0;
            bidOs.Price = Convert.ToDecimal(ask);

            MarketDepth myDepth = _depths.Find(depth => depth.SecurityNameCode == symbol);

            if (myDepth == null)
            {
                myDepth = new MarketDepth();
                myDepth.SecurityNameCode = symbol;
                _depths.Add(myDepth);
            }

            myDepth.Time = ServerTime;

            List <MarketDepthLevel> asks = myDepth.Bids;
            List <MarketDepthLevel> bids = myDepth.Asks;

            if (asks == null || asks.Count != nrows)
            {
                asks = new List <MarketDepthLevel>();
                bids = new List <MarketDepthLevel>();
                for (int i = 0; i < nrows; i++)
                {
                    asks.Add(new MarketDepthLevel());
                    bids.Add(new MarketDepthLevel());
                }
                myDepth.Bids = asks;
                myDepth.Asks = bids;
            }

            asks[row] = askOs;
            bids[row] = bidOs;

            if (row != nrows - 1)
            {
                return;
            }

            if (MarketDepthEvent != null)
            {
                MarketDepthEvent(myDepth.GetCopy());
            }
        }
コード例 #18
0
ファイル: autofollowing.cs プロジェクト: iwm4892/OsEngine
        // incoming data processing
        // обработка входящих данных

        /// <summary>
        /// new MarketDepth /
        /// пришёл новый стакан
        /// </summary>
        void _connector_GlassChangeEvent(MarketDepth marketDepth)
        {
            MarketDepth = marketDepth;

            _marketDepthPainter.ProcessMarketDepth(marketDepth);

            if (MarketDepthUpdateEvent != null)
            {
                MarketDepthUpdateEvent(marketDepth);
            }
        }
コード例 #19
0
 internal void SetNewMarketDepth(Instrument instrument, MarketDepth marketDepth)
 {
     if (!this.isActive)
     {
         return;
     }
     if (Trace.IsLevelEnabled(TraceLevel.Verbose))
     {
         Trace.WriteLine(string.Format("<Strategy.SetNewMarketDepth> {0} {1} {2}", this.Name, instrument.Symbol, marketDepth));
     }
     this.OnNewMarketDepth(instrument, marketDepth);
 }
コード例 #20
0
        /// <summary>
        /// To create a Reactive Extension for the event of order book spread size decrease on a specific value.
        /// </summary>
        /// <param name="marketDepth">The order book to be traced for the spread change event.</param>
        /// <param name="price">The shift value.</param>
        /// <returns>Reactive Extension.</returns>
        public static IObservable <MarketDepth> RxWhenSpreadLess(this MarketDepth marketDepth, Unit price)
        {
            if (marketDepth == null)
            {
                throw new ArgumentNullException(nameof(marketDepth));
            }
            var pair       = marketDepth.BestPair;
            var firstPrice = pair?.SpreadPrice ?? 0;

            return(marketDepth.RxQuotesChanged().Where(_ =>
                                                       marketDepth.BestPair != null && marketDepth.BestPair.SpreadPrice < (firstPrice - price)));
        }
コード例 #21
0
ファイル: StrategyBase.cs プロジェクト: zhuzhenping/FreeOQ
 internal void NEl89GHdA(Instrument obj0, MarketDepth obj1)
 {
     if (!this.isActive)
     {
         return;
     }
     if (Trace.IsLevelEnabled(TraceLevel.Verbose))
     {
         Trace.WriteLine(string.Format("fds", (object)this.Name, (object)obj0.Symbol, (object)obj1));
     }
     this.OnNewMarketDepth(obj0, obj1);
 }
コード例 #22
0
ファイル: OandaClient.cs プロジェクト: w1r2p1/OsEngine-1
        void _marketDepthStream_DataReceived(OkonkwoOandaV20.TradeLibrary.DataTypes.Stream.PricingStreamResponse data)
        {
            if (_isDisposed)
            {
                return;
            }

            Trade newTrade  = new Trade();
            Trade newTrade2 = new Trade();

            newTrade.Price             = Convert.ToDecimal(data.price.closeoutAsk);
            newTrade2.Price            = Convert.ToDecimal(data.price.closeoutAsk);
            newTrade.SecurityNameCode  = data.price.instrument;
            newTrade2.SecurityNameCode = data.price.instrument;
            newTrade.Time          = DateTime.Parse(data.price.time);
            newTrade2.Time         = DateTime.Parse(data.price.time);
            newTrade.MicroSeconds  = newTrade.Time.Millisecond * 1000;
            newTrade2.MicroSeconds = newTrade.Time.Millisecond * 1000;

            if (NewTradeEvent != null)
            {
                NewTradeEvent(newTrade);
                NewTradeEvent(newTrade2);
            }

            MarketDepth depth = new MarketDepth();

            depth.Time = newTrade.Time;

            depth.SecurityNameCode = data.price.instrument;

            for (int i = 0; i < data.price.asks.Count; i++)
            {
                depth.Asks.Add(new MarketDepthLevel()
                {
                    Ask = data.price.asks[i].liquidity, Price = Convert.ToDecimal(data.price.asks[i].price)
                });
            }

            for (int i = 0; i < data.price.bids.Count; i++)
            {
                depth.Bids.Add(new MarketDepthLevel()
                {
                    Bid = data.price.bids[i].liquidity, Price = Convert.ToDecimal(data.price.bids[i].price)
                });
            }


            if (MarketDepthChangeEvent != null)
            {
                MarketDepthChangeEvent(depth);
            }
        }
コード例 #23
0
            private void OnMarketDepthChanged(MarketDepth depth)
            {
                if (depth.Security != Order.Security)
                {
                    return;
                }

                _bestBidPrice = depth.BestBid2?.Price;
                _bestAskPrice = depth.BestAsk2?.Price;

                TryActivate();
            }
コード例 #24
0
        /// <summary>
        /// To create the volatility order book from usual order book.
        /// </summary>
        /// <param name="depth">The order book quotes of which will be changed to volatility quotes.</param>
        /// <param name="securityProvider">The provider of information about instruments.</param>
        /// <param name="dataProvider">The market data provider.</param>
        /// <param name="currentTime">The current time.</param>
        /// <param name="riskFree">The risk free interest rate.</param>
        /// <param name="dividend">The dividend amount on shares.</param>
        /// <returns>The order book volatility.</returns>
        public static MarketDepth ImpliedVolatility(this MarketDepth depth, ISecurityProvider securityProvider, IMarketDataProvider dataProvider, DateTimeOffset currentTime, decimal riskFree = 0, decimal dividend = 0)
        {
            if (depth == null)
            {
                throw new ArgumentNullException(nameof(depth));
            }

            return(depth.ImpliedVolatility(new BlackScholes(depth.Security, securityProvider, dataProvider)
            {
                RiskFree = riskFree, Dividend = dividend
            }, currentTime));
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: codez0mb1e/BinanceBot
        static async Task Main(string[] args)
        {
            // 1. create connections with exchange
            var credentials = new ApiCredentials(ApiKey, Secret);

            using IBinanceClient binanceRestClient         = new BinanceClient(new BinanceClientOptions { ApiCredentials = credentials });
            using IBinanceSocketClient binanceSocketClient = new BinanceSocketClient(new BinanceSocketClientOptions { ApiCredentials = credentials });


            // 2. test connection
            Logger.Info("Testing connection...");
            var pingResult = await binanceRestClient.PingAsync();

            Logger.Info($"Ping time: {pingResult.Data} ms");


            // 3. get order book
            var marketDepthManager = new MarketDepthManager(binanceRestClient, binanceSocketClient);
            var marketDepth        = new MarketDepth(Symbol);


            marketDepth.MarketDepthChanged += (sender, e) =>
            {
                Clear();

                WriteLine("Price : Volume");

                WriteLine(
                    JsonConvert.SerializeObject(
                        new
                {
                    LastUpdate = e.UpdateTime,
                    Asks       = e.Asks.Reverse().Take(OrderBookDepth).Select(s => $"{s.Price} : {s.Volume}"),
                    Bids       = e.Bids.Take(OrderBookDepth).Select(s => $"{s.Price} : {s.Volume}")
                },
                        Formatting.Indented));

                WriteLine("Press Enter to stop streaming market depth...");

                SetCursorPosition(0, 0);
            };


            // build order book
            await marketDepthManager.BuildAsync(marketDepth, OrderBookDepth);

            // stream order book updates
            marketDepthManager.StreamUpdates(marketDepth, OrderBookUpdateLimit);


            WriteLine("Press Enter to exit...");
            ReadLine();
        }
        protected sealed override void QuotingProcess()
        {
            try
            {
                if (!OrderSynchronizer.IsAnyOrdersInWork &&
                    PositionSynchronizer.IsPosAndTradesEven)
                {
                    Quote bestQuote = MarketDepth.GetSuitableBestLimitQuote(QuotingSide);

                    if (bestQuote == null)
                    {
                        return;
                    }

                    decimal price  = Security.ShrinkPrice(bestQuote.Price + QuotePriceShift);
                    decimal volume = Math.Abs(Volume) - Math.Abs(Position);

                    if (volume <= 0 || price <= 0)
                    {
                        return;
                    }

                    if (IsLimitPriceAcceptableForQuoting(price))
                    {
                        var order = this.CreateOrder(QuotingSide, price, volume);

                        order.WhenRegistered(Connector)
                        .Do(() => ProcessNicePriceOrder(order))
                        .Once()
                        .Apply(this);

                        OrderSynchronizer.PlaceOrder(order);
                    }
                    else if (IsLimitOrdersAlwaysRepresent && StopQuotingPrice > 0)
                    {
                        var order = this.CreateOrder(QuotingSide, StopQuotingPrice, volume);

                        order.WhenRegistered(Connector)
                        .Do(() => ProcessBadPriceOrder(order))
                        .Once()
                        .Apply(this);

                        OrderSynchronizer.PlaceOrder(order);
                    }
                }
            }
            catch (Exception ex)
            {
                this.AddErrorLog(ex);
                PrimaryStopping();
            }
        }
コード例 #27
0
        private void SendMdFromTrade(Trade trade)
        {
            MarketDepth myDepth = _depths.Find(depth => depth.SecurityNameCode == trade.SecurityNameCode);

            if (myDepth == null)
            {
                myDepth = new MarketDepth();
                myDepth.SecurityNameCode = trade.SecurityNameCode;
                _depths.Add(myDepth);
            }

            myDepth.Time = DateTime.Now;

            Security mySecurity = _securities.Find(security => security.Name == myDepth.SecurityNameCode);

            if (mySecurity == null)
            {
                return;
            }

            List <MarketDepthLevel> bids = myDepth.Bids;
            List <MarketDepthLevel> asks = myDepth.Asks;

            if (asks == null || asks.Count == 0)
            {
                asks = new List <MarketDepthLevel>();
                bids = new List <MarketDepthLevel>();

                asks.Add(new MarketDepthLevel());
                bids.Add(new MarketDepthLevel());

                myDepth.Bids = bids;
                myDepth.Asks = asks;
            }

            if (myDepth.Bids.Count > 1 &&
                myDepth.Asks.Count > 1)
            {
                return;
            }

            myDepth.Asks[0].Price = trade.Price + mySecurity.PriceStep;
            myDepth.Bids[0].Price = trade.Price - mySecurity.PriceStep;

            myDepth.Asks[0].Ask = 1;
            myDepth.Bids[0].Bid = 1;

            if (MarketDepthEvent != null)
            {
                MarketDepthEvent(myDepth.GetCopy());
            }
        }
コード例 #28
0
        private void RaiseNewMarketDepth(MarketDepth marketDepth)
        {
            NewMarketDepth.SafeInvoke(marketDepth);

            var multiEvt = NewMarketDepths;

            if (multiEvt == null)
            {
                return;
            }

            multiEvt.SafeInvoke(new[] { marketDepth });
        }
コード例 #29
0
        private void RaiseMarketDepthChanged(MarketDepth marketDepth)
        {
            MarketDepthChanged.SafeInvoke(marketDepth);

            var multiEvt = MarketDepthsChanged;

            if (multiEvt == null)
            {
                return;
            }

            multiEvt.SafeInvoke(new[] { marketDepth });
        }
コード例 #30
0
ファイル: TinkoffServer.cs プロジェクト: zilveer/OsEngine
        void _client_UpdateMarketDepth(MarketDepth myDepth)
        {
            if (ServerTime != DateTime.MinValue &&
                myDepth.Time == DateTime.MinValue)
            {
                myDepth.Time = ServerTime;
            }

            if (MarketDepthEvent != null)
            {
                MarketDepthEvent(myDepth);
            }
        }
コード例 #31
0
		/// <summary>
		/// Создать <see cref="MarketDepthIndicatorSource"/>.
		/// </summary>
		/// <param name="depth">Стакан.</param>
		/// <param name="getPart">Конвертер стакана, через который можно получить его параметр (например, цену лучшего бида <see cref="MarketDepth.BestBid"/>, середину спреда и т.д.).</param>
		public MarketDepthIndicatorSource(MarketDepth depth, Func<MarketDepth, decimal> getPart)
		{
			if (depth == null)
				throw new ArgumentNullException("depth");

			if (getPart == null)
				throw new ArgumentNullException("getPart");

			_depth = depth;
			_getPart = getPart;

			_depth.DepthChanged += OnDepthChanged;
		}
コード例 #32
0
        /// <summary>
        /// Добавить новый стакан.
        /// </summary>
        /// <param name="depth">Новый стакан.</param>
        protected virtual void AddMarketDepth(MarketDepth depth)
        {
            if (depth == null)
            {
                throw new ArgumentNullException("depth");
            }

            //Trace.WriteLine("MDA " +dc.Security+":"+dc._DebugId+":"+ dc.LastChangeTime.ToString("HHmmss.fff"));
            if (depth.Bids.Length > 0 || depth.Asks.Length > 0)
            {
                _depthsBuffer.Add(depth.Security, depth.Clone());
            }
        }
コード例 #33
0
        protected override void OnStarted()
        {
            DoStrategyPreparation(new Security[] { Security }, new Security[] { Security }, new Portfolio[] { Portfolio });

            if (_spread <= 0)
            {
                throw new ArgumentException("Spread cannot be below zero: " + _spread);
            }
            if (_lot <= 0)
            {
                throw new ArgumentException("Lot cannot be below zero: " + _lot);
            }
            if (Security.PriceStep == null)
            {
                throw new ArgumentException("Cannot read security price set, probably data still loading... :" + Security.PriceStep);
            }
            if (LimitedFuturesValueAbs < 0)
            {
                throw new ArgumentException("limitation of futures positions is established by value >=0 : " + LimitedFuturesValueAbs);
            }

            if (_sideForEnterToPosition == Sides.Sell)
            {
                LimitedFuturesValueAbs = LimitedFuturesValueAbs != 0 ? LimitedFuturesValueAbs * -1 : decimal.MinValue;
            }
            else
            {
                LimitedFuturesValueAbs = LimitedFuturesValueAbs != 0 ? LimitedFuturesValueAbs : decimal.MaxValue;
            }

            md = GetMarketDepth(Security);
            TimingController.SetTimingMethod(SpreadingProcess);

            Security.WhenMarketDepthChanged(Connector)
            .Do(() =>
            {
                TimingController.TimingMethodHappened();
                SpreadingProcess();
            })
            .Apply(this);

            this.WhenStopping()
            .Do(() =>
            {
                ChildStrategies.Clear();
            })
            .Once()
            .Apply(this);

            base.OnStarted();
        }
コード例 #34
0
        private void EventsOnOnQuote(OrderBook orderBook)
        {
            lock (quoteLock)
            {
                string curName = orderBook.sec_code + "_" + orderBook.class_code;

                if (subscribedBook.Find(name => name == curName) == null)
                {
                    return;
                }

                if (orderBook.bid == null || orderBook.offer == null)
                {
                    return;
                }

                MarketDepth myDepth = new MarketDepth();

                myDepth.SecurityNameCode = curName;
                myDepth.Time             = DateTime.Now;

                myDepth.Bids = new List <MarketDepthLevel>();
                for (int i = 0; i < orderBook.bid.Length; i++)
                {
                    myDepth.Bids.Add(new MarketDepthLevel()
                    {
                        Bid   = Convert.ToDecimal(orderBook.bid[i].quantity),
                        Price = Convert.ToDecimal(orderBook.bid[i].price),
                        Ask   = 0
                    });
                }

                myDepth.Bids.Reverse();

                myDepth.Asks = new List <MarketDepthLevel>();
                for (int i = 0; i < orderBook.offer.Length; i++)
                {
                    myDepth.Asks.Add(new MarketDepthLevel()
                    {
                        Ask   = Convert.ToDecimal(orderBook.offer[i].quantity),
                        Price = Convert.ToDecimal(orderBook.offer[i].price),
                        Bid   = 0
                    });
                }

                if (MarketDepthEvent != null)
                {
                    MarketDepthEvent(myDepth);
                }
            }
        }
コード例 #35
0
 /// <summary>
 /// updated market depth
 /// обновился стакан котировок
 /// </summary>
 private void ClientUpdateMarketDepth(MarketDepth marketDepth)
 {
     try
     {
         if (MarketDepthEvent != null)
         {
             MarketDepthEvent(marketDepth);
         }
     }
     catch (Exception error)
     {
         SendLogMessage(error.ToString(), LogMessageType.Error);
     }
 }
コード例 #36
0
        protected override void Initialize()
        {
            //Global Init
            for (var s = 0; s < array_value_index; s++)
            {
                aVolume[s] = 0;
            }
            today_bid = Symbol.Bid;
            old_askbid_middle = ((Symbol.Ask + Symbol.Bid) / 2);
            _marketDepth = MarketData.GetMarketDepth(Symbol);
            index = MarketSeries.Close.Count - 1;
            old_day = MarketSeries.OpenTime[index].DayOfYear;
            start_time = MarketSeries.OpenTime[index].Year * MarketSeries.OpenTime[index].Day * MarketSeries.OpenTime[index].Hour * MarketSeries.OpenTime[index].Millisecond;

            //Cycle
            _marketDepth.Updated += Calc_And_Show_Chart;

        }
コード例 #37
0
ファイル: Connector_Raise.cs プロジェクト: RakotVT/StockSharp
		private void RaiseMarketDepthChanged(MarketDepth marketDepth)
		{
			MarketDepthChanged?.Invoke(marketDepth);
			MarketDepthsChanged?.Invoke(new[] { marketDepth });
		}
コード例 #38
0
 private void EmitNewMarketDepth(IFIXInstrument instrument, MarketDepth marketDepth)
 {
     if (NewMarketDepth != null)
     {
         NewMarketDepth(this, new MarketDepthEventArgs(marketDepth, instrument, this));
     }
 }
コード例 #39
0
		private void UpdateIfDepthDirty()
		{
			IEnumerable<MarketDepthPair> top = null;

			lock (_lastDepthSync)
			{
				if (_needToClear)
				{
					_needToClear = false;
					top = Enumerable.Empty<MarketDepthPair>();
				}
				else if (_lastDepth != null)
				{
					top = _lastDepth.GetTopPairs(MaxDepth);
				}
				else if (_lastQuoteMsg != null)
				{
					top = _lastQuoteMsg.ToMarketDepth(_prevSecurity).GetTopPairs(MaxDepth);
				}

				_lastDepth = null;
			}

			if (top == null)
				return;
			
			var index = 0;

			foreach (var pair in top)
			{
				var bid = _quotes[GetQuoteIndex(Sides.Buy, index)];
				if (pair.Bid != null)
				{
					bid.Init(pair.Bid, _ordersRegistry.GetContainer(pair.Bid.Price), _stopOrdersRegistry.GetContainer(pair.Bid.Price)/*, trades.TryGetValue(pair.Bid.Price), myTrades.TryGetValue(pair.Bid.Price)*/);
					bid.IsBest = index == 0;
				}
				else
					bid.Init();

				var ask = _quotes[GetQuoteIndex(Sides.Sell, index)];
				if (pair.Ask != null)
				{
					ask.Init(pair.Ask, _ordersRegistry.GetContainer(pair.Ask.Price), _stopOrdersRegistry.GetContainer(pair.Ask.Price)/*, trades.TryGetValue(pair.Ask.Price), myTrades.TryGetValue(pair.Ask.Price)*/);
					ask.IsBest = index == 0;
				}
				else
					ask.Init();

				index++;
			}

			for (var i = 0; i < (MaxDepth - index); i++)
			{
				_quotes[GetQuoteIndex(Sides.Buy, index + i)].Init();
				_quotes[GetQuoteIndex(Sides.Sell, index + i)].Init();
			}
		}
コード例 #40
0
		/// <summary>
		/// To upfate the order book.
		/// </summary>
		/// <param name="depth">Market depth.</param>
		public void UpdateDepth(MarketDepth depth)
		{
			if (depth == null)
				throw new ArgumentNullException(nameof(depth));

			lock (_lastDepthSync)
				_lastDepth = depth;

			if (_prevSecurity == depth.Security)
				return;

			_prevSecurity = depth.Security;
			UpdateFormat(depth.Security);
		}
コード例 #41
0
		internal OrderBookUpdate(MarketDepth marketDepth)
		{
			this.marketDepth = marketDepth;
		}
コード例 #42
0
ファイル: Connector_Raise.cs プロジェクト: kknet/StockSharp
		private void RaiseMarketDepthChanged(MarketDepth marketDepth)
		{
			MarketDepthChanged.SafeInvoke(marketDepth);

			var multiEvt = MarketDepthsChanged;

			if (multiEvt == null)
				return;

			multiEvt.SafeInvoke(new[] { marketDepth });
		}
コード例 #43
0
		/// <summary>
		/// Создать <see cref="MarketDepthIndicatorSource"/>.
		/// </summary>
		/// <param name="depth">Стакан.</param>
		public MarketDepthIndicatorSource(MarketDepth depth)
			: this(depth, MarketDepthIndicatorValue.ByMiddle)
		{
		}
コード例 #44
0
		/// <summary>
		/// Создать <see cref="DepthCandleBuilderSourceValue"/>.
		/// </summary>
		/// <param name="depth">Стакан.</param>
		public DepthCandleBuilderSourceValue(MarketDepth depth)
		{
			Depth = depth;
		}
コード例 #45
0
		public void EmitMarketDepth(global::OpenQuant.API.Instrument instrument, DateTime time, BidAsk side, OrderBookAction action, double price, int size, int position)
		{
			MarketDepth marketDepth = new MarketDepth(time, string.Empty, position, global::OpenQuant.API.EnumConverter.Convert(action), global::OpenQuant.API.EnumConverter.Convert(side), price, size);
			if (this.NewMarketDepth != null)
			{
				this.NewMarketDepth(this, new MarketDepthEventArgs(marketDepth, instrument.instrument, this));
			}
		}
コード例 #46
0
        private static void CalculateArbitrageResult(MarketDepth dogeFiatBid, MarketDepth dogeBtcAsk, MarketDepth btcFiatAsk,
            string currencyCode)
        {
            decimal availableDogeVolume;
            decimal availableUsdVolume = btcFiatAsk.Quantity * btcFiatAsk.Price;
            availableDogeVolume = Math.Round(Math.Min(dogeFiatBid.Quantity,
                Math.Min(dogeBtcAsk.Quantity, availableUsdVolume / dogeFiatBid.Price)
            ), 8);
            decimal dogeVolumeInUsd = Math.Round(dogeFiatBid.Price * availableDogeVolume * (1.0m - VOS_DOGE_RATE), 8);
            decimal dogeVolumeInBtc = Math.Round(dogeVolumeInUsd / btcFiatAsk.Price * (1.0m - VOS_BTC_RATE), 8);
            decimal dogeVolumeAfterTransfer = dogeVolumeInBtc - TRANSFER_FEE;

            decimal resultingDoge = Math.Round(dogeVolumeAfterTransfer / dogeBtcAsk.Price * (1.0m - VIRCUREX_BTC_RATE), 8);
            decimal profit = Math.Round(resultingDoge - availableDogeVolume, 8);
            decimal profitPercent = Math.Round(profit / availableDogeVolume * 100, 2);

            if (profitPercent > 4.9m)
            {
                Console.WriteLine("Available volume: "
                    + availableDogeVolume);
                Console.WriteLine(currencyCode + ": "
                    + dogeVolumeInUsd);
                Console.WriteLine("BTC: "
                    + dogeVolumeInBtc);
                Console.WriteLine("Result: "
                    + resultingDoge + " DOGE");
                Console.WriteLine("Profit: "
                    + profitPercent + "%");
            }
            else
            {
                Console.WriteLine("No viable trade via "
                    + currencyCode + " ("
                    + profitPercent + "% profit)");
            }
        }
コード例 #47
0
ファイル: Volume.cs プロジェクト: Mikai47/cAlgoBot
 protected override void Initialize()
 {
     GBPUSD = MarketData.GetMarketDepth(Symbol);
     GBPUSD.Updated += OnGbpUsdUpdated;
 }
コード例 #48
0
//--------------------------------------        
        protected override void Initialize()
        {
            _marketDepth = MarketData.GetMarketDepth(Symbol);
            _marketDepth.Updated += MarketDepthUpdated;

            foreach (var entry in _marketDepth.BidEntries)
            {
                PreviousBidList.Add(new Previouslist 
                {
                    Preis = entry.Price,
                    Volumen = entry.Volume
                });
            }

            foreach (var entry in _marketDepth.AskEntries)
            {
                PreviousAskList.Add(new Previouslist 
                {
                    Preis = entry.Price,
                    Volumen = entry.Volume
                });
            }

            LowFilterM = LowFilter * 1000000;
            HighFilterM = HighFilter * 1000000;
            fname = string.Format("{0}{1}{2}{3}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "\\", FileName == "" ? Symbol.Code : FileName, ".csv");
            if (ReadFromFile && System.IO.File.Exists(fname) == true)
            {
                using (StreamReader Fstream = new StreamReader(fname))
                {
                    string line;
                    while ((line = Fstream.ReadLine()) != null)
                    {
                        try
                        {
                            string[] words = line.Split(Delimiters);
                            double vol = Convert.ToDouble(words[1]);
                            if (vol >= HighFilterM || vol < LowFilterM)
                                continue;
                            int bago = BarsAgo(Convert.ToDateTime(words[0]));
                            if (bago == -1)
                                continue;
                            int bidx = MarketSeries.Close.Count - 1 - bago;
                            if (double.IsNaN(AskVolumes[bidx]))
                                AskVolumes[bidx] = 0;
                            if (double.IsNaN(BidVolumes[bidx]))
                                BidVolumes[bidx] = 0;
                            switch (words[2])
                            {
                                case "A":
                                    AskVolumes[bidx] += (vol / 1000000);
                                    break;
                                case "B":
                                    BidVolumes[bidx] -= (vol / 1000000);
                                    break;
                            }
                            AskBidDifference[bidx] = AskVolumes[bidx] + BidVolumes[bidx];
                        } catch
                        {
                            continue;
                        }
                    }
                }
            }
            if (WriteToFile)
            {
                if (System.IO.File.Exists(fname) == false)
                    System.IO.File.WriteAllText(fname, "");
                Timer.Start(WriteInterval);
            }
        }
コード例 #49
0
 public void Init(Security security)
 {
     _depth = security.Trader.GetMarketDepth(security);
     _depth.QuotesChanged += OnQuotesChanged;
     _depth.Trader.RegisterQuotes(_depth.Security);
 }
コード例 #50
0
		public object Convert(MarketDepth marketDepth)
		{
			return new OrderBookUpdate(marketDepth);
		}
コード例 #51
0
ファイル: Connector_Raise.cs プロジェクト: kknet/StockSharp
		private void RaiseNewMarketDepth(MarketDepth marketDepth)
		{
			NewMarketDepth.SafeInvoke(marketDepth);

			var multiEvt = NewMarketDepths;

			if (multiEvt == null)
				return;

			multiEvt.SafeInvoke(new[] { marketDepth });
		}
コード例 #52
0
        // converts marketdepth to MemoryStream and writes to the file
        private static void DepthToFile(MarketDepth depth, string filePath)
        {
            using (var mem = new MemoryStream(200))
            {
                for (var i = depth.Asks.GetUpperBound(0); i >= 0; i--)
                {
                    var bytes = Encoding.UTF8.GetBytes(QuoteToString(depth.Asks[i]));
                    mem.Write(bytes, 0, bytes.Length);
                }

                for (var i = 0; i <= depth.Bids.GetUpperBound(0); i++)
                {
                    var bytes = Encoding.UTF8.GetBytes(QuoteToString(depth.Bids[i]));
                    mem.Write(bytes, 0, bytes.Length);
                }

                using (var file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    mem.WriteTo(file);
            }
        }
コード例 #53
0
		public void Init(Security security)
		{
			_depth = Connector.GetMarketDepth(security);
			_depth.QuotesChanged += OnQuotesChanged;
			Connector.RegisterMarketDepth(_depth.Security);
		}
コード例 #54
0
		private void OnQuote(int tableId, int rowId, object fields)
		{
			var values = (object[])fields;
			var security = _orderBooks.SyncGet(d => d.TryGetValue(tableId));
			if (security == null)
				return;

			var table = QuotesTable[tableId];
			var depth = _orderBookData.ContainsKey(tableId) ? _orderBookData[tableId] : _orderBookData[tableId] = new MarketDepth(security);
			var id = table.GetValue<int>(values, AlorQuotesColumns.Id);

			var quote = new Quote
			{
				Security = depth.Security,
				OrderDirection = table.GetValue<string>(values, AlorQuotesColumns.Direction).ToOrderDirection(),
				Price = table.GetValue<decimal>(values, AlorQuotesColumns.Price),
				Volume = table.GetValue<int>(values, AlorQuotesColumns.Volume),
			};
			table.FillNonMandatoryInfo(quote, values);

            //if (id == 1 && depth.Count != 0)
            //    RaiseMarketDepthChanged(GetMarketDepth(security).Update(depth.Bids, depth.Asks, true));

            //if (id == 1)
            //    depth.Update(ArrayHelper<Quote>.EmptyArray, ArrayHelper<Quote>.EmptyArray, true);

			depth.UpdateQuote(quote);
		}
コード例 #55
0
ファイル: Program.cs プロジェクト: zjxbetter/StockSharp
		static void Main()
		{
			try
			{
				// для теста выбираем бумагу Лукойл
				const string secCode = "LKOH";

				var quikPath = QuikTerminal.GetDefaultPath();

				if (quikPath.IsEmpty())
				{
					Console.WriteLine(LocalizedStrings.Str2984);
					return;
				}

				Console.WriteLine(LocalizedStrings.Str2985 + quikPath);

				Console.Write(LocalizedStrings.Str2986);
				var account = Console.ReadLine();

				using (var waitHandle = new AutoResetEvent(false))
				{
					// создаем подключение к Quik-у
					using (var trader = new QuikTrader(quikPath) { IsDde = true })
					{
						// необходимо раскомментировать, если идет работа с РТС Стандарт
						//trader.FormatTransaction += builder => builder.RemoveInstruction(Transaction.TimeInForce);

						// подписываемся на событие успешного подключения
						// все действия необходимо производить только после подключения
						trader.Connected += () =>
						{
							Console.WriteLine(LocalizedStrings.Str2169);

							// извещаем об успешном соединени
							waitHandle.Set();
						};

						Console.WriteLine(LocalizedStrings.Str2170);

						trader.DdeTables = new[] { trader.SecuritiesTable, trader.MyTradesTable, trader.EquityPositionsTable,
						                   trader.EquityPortfoliosTable, trader.OrdersTable };

						trader.Connect();

						// дожидаемся события об успешном соединении
						waitHandle.WaitOne();

						trader.NewPortfolios += portfolios =>
						{
							if (_portfolio == null)
							{
								// находим нужный портфель и присваиваем его переменной _portfolio
								_portfolio = portfolios.FirstOrDefault(p => p.Name == account);

								if (_portfolio != null)
								{
									Console.WriteLine(LocalizedStrings.Str2171Params, account);

									// если инструмент и стакан уже появились,
									// то извещаем об этом основной поток для выставления заявки
									if (_lkoh != null && _depth != null)
										waitHandle.Set();
								}
							}
						};

						// подписываемся на событие появление инструментов
						trader.NewSecurities += securities =>
						{
							if (_lkoh == null)
							{
								// находим Лукойл и присваиваем ее переменной lkoh
								_lkoh = securities.FirstOrDefault(sec => sec.Code == secCode);

								if (_lkoh != null)
								{
									Console.WriteLine(LocalizedStrings.Str2987);

									// запускаем экспорт стакана
									trader.RegisterMarketDepth(_lkoh);

									if (_portfolio != null && _depth != null)
										waitHandle.Set();
								}
							}
						};

						// подписываемся на событие появления моих новых сделок
						trader.NewMyTrades += myTrades =>
						{
							foreach (var myTrade in myTrades)
							{
								var trade = myTrade.Trade;
								Console.WriteLine(LocalizedStrings.Str2173Params, trade.Id, trade.Price, trade.Security.Code, trade.Volume, trade.Time);
							}
						};

						// подписываемся на событие обновления стакана
						trader.MarketDepthsChanged += depths =>
						{
							if (_depth == null && _lkoh != null)
							{
								_depth = depths.FirstOrDefault(d => d.Security == _lkoh);

								if (_depth != null)
								{
									Console.WriteLine(LocalizedStrings.Str2988);

									// если портфель и инструмент уже появился, то извещаем об этом основной поток для выставления заявки
									if (_portfolio != null && _lkoh != null)
										waitHandle.Set();
								}
							}
						};

						Console.WriteLine(LocalizedStrings.Str2989Params.Put(account));

						// дожидаемся появления портфеля и инструмента
						waitHandle.WaitOne();

						// 0.1% от изменения цены
						const decimal delta = 0.001m;

						// запоминаем первоначальное значение середины спреда
						var firstMid = _lkoh.BestPair.SpreadPrice / 2;
						if (_lkoh.BestBid == null || firstMid == null)
							throw new Exception(LocalizedStrings.Str2990);

						Console.WriteLine(LocalizedStrings.Str2991Params, _lkoh.BestBid.Price + firstMid);

						while (true)
						{
							var mid = _lkoh.BestPair.SpreadPrice / 2;

							// если спред вышел за пределы нашего диапазона
							if (mid != null &&
									((firstMid + firstMid * delta) <= mid ||
									(firstMid - firstMid * delta) >= mid)
								)
							{
								var order = new Order
								{
									Portfolio = _portfolio,
									Price = _lkoh.ShrinkPrice(_lkoh.BestBid.Price + mid.Value),
									Security = _lkoh,
									Volume = 1,
									Direction = Sides.Buy,
								};
								trader.RegisterOrder(order);
								Console.WriteLine(LocalizedStrings.Str1157Params, order.Id);
								break;
							}
							else
								Console.WriteLine(LocalizedStrings.Str2176Params, _lkoh.BestBid.Price + mid);

							// ждем 1 секунду
							Thread.Sleep(1000);
						}

						// останавливаем подключение
						trader.Disconnect();
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}
		}
コード例 #56
0
 protected override void Initialize()
 {
     _MarketDepth = MarketData.GetMarketDepth(Symbol);
     _MarketDepth.Updated += OnUpdated;
 }
コード例 #57
0
ファイル: Program.cs プロジェクト: polanski10/stocksharp
        static void Main()
        {
            try
            {
                // для теста выбираем бумагу Лукойл
                const string secCode = "LKOH";

                var quikPath = QuikTerminal.GetDefaultPath();

                if (quikPath.IsEmpty())
                {
                    Console.WriteLine("Не найден ни один запущенный Quik");
                    return;
                }

                Console.WriteLine("Запущенный Quik найден по пути " + quikPath);

                Console.Write("Введите код клиента, через который будет выставлена заявка: ");
                var account = Console.ReadLine();

                using (var waitHandle = new AutoResetEvent(false))
                {
                    // создаем шлюз к Quik-у
                    using (var trader = new QuikTrader(quikPath))
                    {
                        // необходимо раскомментировать, если идет работа с РТС Стандарт
                        //trader.FormatTransaction += builder => builder.RemoveInstruction(TransactionBuilder.ExecutionCondition);

                        // подписываемся на событие успешного подключения
                        // все действия необходимо производить только после подключения
                        trader.Connected += () =>
                        {
                            Console.WriteLine("Подключение было произведено успешно.");

                            // извещаем об успешном соединени
                            waitHandle.Set();
                        };

                        Console.WriteLine("Производим подключение...");

                        trader.Connect();

                        // дожидаемся события об успешном соединении
                        waitHandle.WaitOne();

                        trader.NewPortfolios += portfolios =>
                        {
                            if (_portfolio == null)
                            {
                                // находим Лукойл и присваиваем ее переменной lkoh
                                _portfolio = portfolios.FirstOrDefault(p => p.Name == account);

                                if (_portfolio != null)
                                {
                                    Console.WriteLine("Портфель {0} появился.", account);

                                    // если инструмент и стакан уже появились,
                                    // то извещаем об этом основной поток для выставления заявки
                                    if (_lkoh != null && _depth != null)
                                        waitHandle.Set();
                                }
                            }
                        };

                        // подписываемся на событие появление инструментов
                        trader.NewSecurities += securities =>
                        {
                            if (_lkoh == null)
                            {
                                // находим Лукойл и присваиваем ее переменной lkoh
                                _lkoh = securities.FirstOrDefault(sec => sec.Code == secCode);

                                if (_lkoh != null)
                                {
                                    Console.WriteLine("Инструмент Лукойл появился.");

                                    // запускаем экспорт стакана
                                    trader.RegisterQuotes(_lkoh);

                                    if (_portfolio != null && _depth != null)
                                        waitHandle.Set();
                                }
                            }
                        };

                        // подписываемся на событие появления моих новых сделок
                        trader.NewMyTrades += myTrades =>
                        {
                            foreach (var myTrade in myTrades)
                            {
                                var trade = myTrade.Trade;
                                Console.WriteLine("Сделка {0} по цене {1} по бумаге {2} по объему {3} в {4}.", trade.Id, trade.Price, trade.Security.Code, trade.Volume, trade.Time);
                            }
                        };

                        // подписываемся на событие обновления стакана
                        trader.QuotesChanged += depths =>
                        {
                            if (_depth == null && _lkoh != null)
                            {
                                _depth = depths.FirstOrDefault(d => d.Security == _lkoh);

                                if (_depth != null)
                                {
                                    Console.WriteLine("Стакан Лукойла появился.");

                                    // если портфель и инструмент уже появился, то извещаем об этом основной поток для выставления заявки
                                    if (_portfolio != null && _lkoh != null)
                                        waitHandle.Set();
                                }
                            }
                        };

                        Console.WriteLine("Дожидаемся появления в программе инструмента Лукойл и портфеля {0}...".Put(account));

                        // запускаем экспорт по DDE
                        trader.StartExport(trader.SecuritiesTable, trader.MyTradesTable, trader.EquityPositionsTable,
                                           trader.EquityPortfoliosTable, trader.OrdersTable);

                        // дожидаемся появления портфеля и инструмента
                        waitHandle.WaitOne();

                        // 0.1% от изменения цены
                        const decimal delta = 0.001m;

                        // запоминаем первоначальное значение середины спреда
                        var firstMid = _lkoh.BestPair.SpreadPrice / 2;
                        if (_lkoh.BestBid == null)
                            throw new Exception("Нет лучшего бида для котировки.");

                        Console.WriteLine("Первоначальное значение середины спреда {0:0.##}", _lkoh.BestBid.Price + firstMid);

                        while (true)
                        {
                            var mid = _lkoh.BestPair.SpreadPrice / 2;

                            // если спред вышел за пределы нашего диапазона
                            if	(
                                    ((firstMid + firstMid * delta) <= mid) ||
                                    ((firstMid - firstMid * delta) >= mid)
                                )
                            {
                                var order = new Order
                                {
                                    Portfolio = _portfolio,
                                    Price = _lkoh.ShrinkPrice(_lkoh.BestBid.Price + mid),
                                    Security = _lkoh,
                                    Volume = 1,
                                    Direction = OrderDirections.Buy,
                                };
                                trader.RegisterOrder(order);
                                Console.WriteLine("Заявка {0} зарегистрирована.", order.Id);
                                break;
                            }
                            else
                                Console.WriteLine("Текущее значение середины спреда {0:0.##}", _lkoh.BestBid.Price + mid);

                            // ждем 1 секунду
                            Thread.Sleep(1000);
                        }

                        // останавливаем экспорт по DDE
                        trader.StopExport(trader.SecuritiesTable, trader.MyTradesTable, trader.EquityPositionsTable,
                                          trader.EquityPortfoliosTable, trader.OrdersTable);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }