Пример #1
0
        public object Put(QuoteMessage model)
        {
            object json;

            try
            {
                model = repository.Update(model);

                json = new
                {
                    total   = 1,
                    data    = model,
                    success = true
                };
            }
            catch (Exception ex)
            {
                LogManager.Write("ERROR:" + Environment.NewLine + "\tMETHOD = " + this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name + Environment.NewLine + "\tMESSAGE = " + ex.Message);

                json = new
                {
                    message = ex.Message,
                    success = false
                };
            };

            return(json);
        }
Пример #2
0
        private async Task ProcessQuoteAsync(QuoteMessage quote)
        {
            var entity = await _priceWriter.GetAsync(Price.GetPk(), quote.AssetPair);

            var writerTask = Task.CompletedTask;

            if (entity != null)
            {
                if (quote.IsBuy)
                {
                    entity.Bid = (decimal)quote.Price;
                }
                else
                {
                    entity.Ask = (decimal)quote.Price;
                }

                entity.UpdatedDt = quote.Timestamp;

                writerTask = _priceWriter.InsertOrReplaceAsync(entity);
            }

            await Task.WhenAll(
                _database.HashSetAsync(RedisService.GetMarketDataKey(quote.AssetPair),
                                       quote.IsBuy ? nameof(MarketSlice.Bid) : nameof(MarketSlice.Ask),
                                       quote.Price.ToString(CultureInfo.InvariantCulture)),
                writerTask);
        }
        private Task ProcessQuoteAsync(QuoteMessage quote)
        {
            try
            {
                var validationErrors = ValidateQuote(quote);
                if (validationErrors.Any())
                {
                    var message = string.Join("\r\n", validationErrors);
                    _log.WriteWarning( nameof(ProcessQuoteAsync), quote, message);

                    return Task.CompletedTask;
                }

                _quotesManager.ProcessQuote(
                    MarketType.Spot,
                    quote.AssetPair, 
                    quote.IsBuy ? QuotePriceType.Bid : QuotePriceType.Ask, 
                    quote.Price, 
                    quote.Timestamp);
            }
            catch (Exception)
            {
                _log.WriteWarning(nameof(ProcessQuoteAsync), quote, "Failed to process quote");
                throw;
            }
            
            return Task.CompletedTask;
        }
Пример #4
0
        private static IReadOnlyCollection <string> ValidateQuote(QuoteMessage quote)
        {
            var errors = new List <string>();

            if (quote == null)
            {
                errors.Add("Quote is null.");
            }
            else
            {
                if (string.IsNullOrEmpty(quote.AssetPair))
                {
                    errors.Add("Empty 'AssetPair'");
                }
                if (quote.Timestamp.Kind != DateTimeKind.Utc)
                {
                    errors.Add($"Invalid 'Timestamp' Kind (UTC is required): '{quote.Timestamp.Kind}'");
                }
                if (quote.Price <= 0)
                {
                    errors.Add($"Not positive price: '{quote.Price}'");
                }
            }

            return(errors);
        }
Пример #5
0
        /// <summary>
        /// Parses a single quote message from a reading file.
        /// </summary>
        /// <param name="r">the <c>BinaryReader</c> object reading the target file.</param>
        /// <returns>The parsed <c>QuoteMessage</c> object or null if all available objects have been read.</returns>
        private QuoteMessage ReadQuoteMessage()
        {
            try
            {
                QuoteMessage result = null;

                int    length     = IPAddress.NetworkToHostOrder(m_reader.ReadInt32());
                ushort funcCode   = Bytes.NetworkToHostOrder(m_reader.ReadUInt16());
                int    bodyLength = IPAddress.NetworkToHostOrder(m_reader.ReadInt32());

                byte[] body  = new byte[length];
                int    count = m_reader.Read(body, BidMessage.HeaderLength, bodyLength);

                if (count == bodyLength)
                {
                    result = (QuoteMessage)BidMessage.Create(FunctionCodes.Quote, body, 0, length);
                }

                return(result);
            }
            catch (EndOfStreamException)
            {
                return(null);
            }
        }
Пример #6
0
        /// <summary>
        /// Reads the opened file and parses its content.
        /// Goes to states <c>Read</c> and <c>Close</c>.
        /// </summary>
        /// <returns>Time to wait till next state is run, in milliseconds.</returns>
        private int Read()
        {
            ChangeStatus(QuoteProviderStatus.Read);

            Thread.Sleep(10); // release CPU time

            try
            {
                QuoteMessage message = ReadQuoteMessage();

                if (message == null)
                {
                    m_runByState = Close;
                    return(0);
                }

                OnQuoteMessageReceived(message);
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ex, true);
                m_runByState = Close;
            }

            return(0);
        }
        public async Task ProcessSpotQuoteAsync(QuoteMessage quote)
        {
            var assetPair = await _assetPairsManager.TryGetEnabledPairAsync(quote.AssetPair);

            if (assetPair == null)
            {
                return;
            }

            var changedUpdates = new ConcurrentBag <CandleUpdateResult>();
            var midPriceQuote  = _midPriceQuoteGenerator.TryGenerate(
                quote.AssetPair,
                quote.IsBuy,
                quote.Price,
                quote.Timestamp,
                assetPair.Accuracy);

            try
            {
                // Updates all intervals in parallel

                var processingTasks = _intervals
                                      .Select(timeInterval => Task.Factory.StartNew(() =>
                {
                    ProcessQuoteInterval(
                        quote.AssetPair,
                        quote.Timestamp,
                        quote.Price,
                        quote.IsBuy,
                        timeInterval,
                        midPriceQuote,
                        changedUpdates);
                }));

                await Task.WhenAll(processingTasks);

                // Publishes updated candles

                if (!changedUpdates.IsEmpty)
                {
                    var publisher = await _candlesPublisherProvider.GetForAssetPair(assetPair.Id);

                    await publisher.PublishAsync(changedUpdates);
                }
            }
            catch (Exception)
            {
                // Failed to publish one or several candles, so processing should be cancelled

                foreach (var updateResult in changedUpdates)
                {
                    _candlesGenerator.Undo(updateResult);
                }

                throw;
            }
        }
        public Task UpdatePairAsync(QuoteMessage quote)
        {
            var assetPair = _pairs.AddOrUpdate(
                key: quote.AssetPair,
                addValueFactory: assetPairId => Create(quote),
                updateValueFactory: (assetPairId, pair) => UpdateAssetPairPrice(pair, quote));

            return(Task.WhenAll(_myNoSqlWriterWrapper.TryInsertOrReplaceAsync(AssetPairPriceNoSql.Create(assetPair)),
                                _redisService.AddAssetPairPriceAsync(assetPair)));
        }
Пример #9
0
 void TWSUtilities_OnTick(object sender, TWSTickEventArgs e)
 {
     if (m_quoteEventHandler != null)
     {
         QuoteMessage quote = BuildQuoteMessage(e);
         if (quote != null)
         {
             m_quoteEventHandler(null, new QuoteEventArgs(quote, e.ClientObject));
         }
     }
 }
Пример #10
0
        // this is the method used to process real-time streaming quotes
        public void NewQuote(QuoteMessage quote)
        {
            ILog log = LogManager.GetLogger(typeof(ThreeDucksStrategy));

            log.DebugFormat("Quote received: {0} {1} {2}", quote.SymbolName, quote.timestamp.ToString(), quote.Price);

            foreach (SmaMetric m in _metrics[quote.SymbolName])
            {
                m.Add(quote.timestamp, quote.Price);
            }
        }
 void BloombergQuoteListener_OnMessage(object sender, BloombergMessageEventArgs e)
 {
     if (m_quoteEventHandler != null)
     {
         QuoteMessage quote = BuildQuoteMessage(e.Message, e.SubscriptionId);
         if (quote != null)
         {
             m_quoteEventHandler(null, new QuoteEventArgs(quote, e.SubscriptionId.QuoteObject));
         }
     }
 }
 private async Task ProcessQuote(QuoteMessage entry)
 {
     try
     {
         await _cacheService.UpdatePairAsync(entry);
     }
     catch (Exception ex)
     {
         _log.Error(ex);
     }
 }
        private AssetPairPrice Create(QuoteMessage quote)
        {
            var pair = new AssetPairPrice
            {
                AssetPair         = quote.AssetPair,
                AskPriceTimestamp = DateTime.MinValue,
                BidPriceTimestamp = DateTime.MinValue
            };

            UpdateAssetPairPrice(pair, quote);

            return(pair);
        }
Пример #14
0
 /// <summary>
 /// Notifies all listeners that a <c>QuoteMessage</c> object has been successfully received.
 /// </summary>
 /// <param name="message">the <c>QuoteMessage</c> object that has just been received.</param>
 protected virtual void OnQuoteMessageReceived(QuoteMessage message)
 {
     foreach (IQuoteDataListener listener in m_listeners)
     {
         try
         {
             listener.OnQuoteMessageReceived(message);
         }
         catch (Exception ex)
         {
             Debug.WriteLine("==>{0} call {1}.OnQuoteMessageReceived() failed, Error: {2}", this, listener.ListenerName, ex.Message);
         }
     }
 }
Пример #15
0
        /// <summary>
        /// Examines the entire buffer and parses all <c>QuoteMessage</c>s in it.
        /// </summary>
        private void ParseMessages()
        {
            while (m_writeIndex - m_readIndex > BidMessage.HeaderLength)
            {
                int    length     = 0;
                ushort funcCode   = 0;
                int    bodyLength = 0;

                for (; m_writeIndex - m_readIndex >= BidMessage.HeaderLength; m_readIndex++)
                {
                    int offset = m_readIndex;

                    length  = m_buffer.ToInt32(offset);
                    offset += sizeof(int);

                    funcCode = m_buffer.ToUInt16(offset);
                    offset  += sizeof(ushort);

                    bodyLength = m_buffer.ToInt32(offset);

                    if (length - bodyLength == BidMessage.HeaderLength)
                    {
                        break;
                    }
                }

                // loop guard is true iff the next message is successfully located
                // break if this fails or only part of next message is found
                if (m_writeIndex - m_readIndex < BidMessage.HeaderLength || m_writeIndex - m_readIndex < length)
                {
                    break;
                }

                if (funcCode == (ushort)FunctionCodes.Quote)
                {
                    QuoteMessage message = (QuoteMessage)BidMessage.Create(FunctionCodes.Quote, m_buffer, m_readIndex, length);
                    OnQuoteMessageReceived(message);
                }

                m_readIndex += length;
            }

            // incomplete message
            if (m_readIndex != 0)
            {
                Array.Copy(m_buffer, m_readIndex, m_buffer, 0, m_writeIndex - m_readIndex);
                m_writeIndex -= m_readIndex;
                m_readIndex   = 0;
            }
        }
Пример #16
0
        private string ConstructDetailFromTemplate(string template, QuoteMessage message)
        {
            string result = template;

            foreach (QuoteFieldTags tag in Enum.GetValues(typeof(QuoteFieldTags)))
            {
                string tagText = Enum.GetName(typeof(QuoteFieldTags), tag);
                if (result.Contains(tagText))
                {
                    result = result.Replace(string.Format("$({0})", tagText), message.GetFieldValueAsString(message.GetIndexFromTag(tag)));
                }
            }

            return(result);
        }
        public void AddQuoteAndCheckSignal()
        {
            ThreeDucksStrategy tds = new ThreeDucksStrategy();

            tds.startWatching("GOOG");
            QuoteMessage q = new QuoteMessage();

            q.SymbolName = "GOOG";
            q.timestamp  = DateTime.Now;
            q.Price      = 10;
            tds.NewQuote(q);

            StrategySummary s = tds.getSummary("GOOG");

            Assert.AreEqual("GOOG", s.SymbolName);
            Assert.IsNotNull(s.AsOf);
            Assert.AreEqual(StrategySignal.None, s.CurrentSignal);
        }
Пример #18
0
        private void MessageReceived(object s, MessageReceivedEventArgs e)
        {
            QuoteMessage message = null;

            try
            {
                message = JsonConvert.DeserializeObject <QuoteMessage>(e.Message);
            }
            catch (Exception ex)
            {
                ErrorOccured(this, ex.Message);
            }

            if (message != null && message.Ok && message.Quote != null && QuoteReceived != null)
            {
                QuoteReceived(this, message.Quote);
            }
        }
        private void ProcessQuoteInterval(
            string assetPair,
            DateTime timestamp,
            double price,
            bool isBuy,
            CandleTimeInterval timeInterval,
            QuoteMessage midPriceQuote,
            ConcurrentBag <CandleUpdateResult> changedUpdateResults)
        {
            // Updates ask/bid candle

            if (_generateBidAndAsk)
            {
                var candleUpdateResult = _candlesGenerator.UpdateQuotingCandle(
                    assetPair,
                    timestamp,
                    price,
                    isBuy ? CandlePriceType.Bid : CandlePriceType.Ask,
                    timeInterval);

                if (candleUpdateResult.WasChanged)
                {
                    changedUpdateResults.Add(candleUpdateResult);
                }
            }

            // Updates mid candle

            if (midPriceQuote != null)
            {
                var midPriceCandleUpdateResult = _candlesGenerator.UpdateQuotingCandle(
                    midPriceQuote.AssetPair,
                    midPriceQuote.Timestamp,
                    midPriceQuote.Price,
                    CandlePriceType.Mid,
                    timeInterval);

                if (midPriceCandleUpdateResult.WasChanged)
                {
                    changedUpdateResults.Add(midPriceCandleUpdateResult);
                }
            }
        }
Пример #20
0
        public object Delete(QuoteMessage model)
        {
            object json;

            try
            {
                bool result = repository.Remove(model);
                json = new
                {
                    success = result
                };
            } catch (Exception ex) {
                json = new
                {
                    success = false,
                    message = ex.Message
                };
            }

            return(json);
        }
        private AssetPairPrice UpdateAssetPairPrice(AssetPairPrice pair, QuoteMessage quote)
        {
            if (quote.IsBuy)
            {
                if (pair.BidPriceTimestamp < quote.Timestamp)
                {
                    pair.BidPrice          = quote.Price;
                    pair.BidPriceTimestamp = quote.Timestamp;
                }
            }
            else
            {
                if (pair.AskPriceTimestamp < quote.Timestamp)
                {
                    pair.AskPrice          = quote.Price;
                    pair.AskPriceTimestamp = quote.Timestamp;
                }
            }

            return(pair);
        }
Пример #22
0
        private async Task ProcessQuoteAsync(QuoteMessage quote)
        {
            try
            {
                var validationErrors = ValidateQuote(quote);
                if (validationErrors.Any())
                {
                    var message = string.Join("\r\n", validationErrors);
                    await _log.WriteWarningAsync(nameof(SpotQuotesSubscriber), nameof(ProcessQuoteAsync), quote.ToJson(), message);

                    return;
                }

                await _candlesManager.ProcessSpotQuoteAsync(quote);
            }
            catch (Exception)
            {
                await _log.WriteWarningAsync(nameof(SpotQuotesSubscriber), nameof(ProcessQuoteAsync), quote.ToJson(), "Failed to process quote");

                throw;
            }
        }
        public void TestForSellSignal()
        {
            Dictionary <string, string> settings = new Dictionary <string, string>();

            settings.Add("FIRST_DUCK_SECONDS", "1");
            settings.Add("SECOND_DUCK_SECONDS", "1");
            settings.Add("THIRD_DUCK_SECONDS", "1");
            settings.Add("MOVING_AVERAGE_WINDOW", "2");

            ThreeDucksStrategy tds = new ThreeDucksStrategy(settings);

            tds.startWatching("GOOG");

            QuoteMessage q1 = new QuoteMessage(10, new DateTime(2013, 06, 13, 0, 0, 1), "GOOG");
            QuoteMessage q2 = new QuoteMessage(5, new DateTime(2013, 06, 13, 0, 0, 2), "GOOG");

            tds.NewQuote(q1);
            tds.NewQuote(q2);

            StrategySummary result = tds.getSummary("GOOG");

            Assert.AreEqual(StrategySignal.Sell, result.CurrentSignal);
        }
Пример #24
0
        // determines if we need to raise any alerts as a result of the most recent quote
        public void CheckSignals(QuoteMessage quote)
        {
            int buy_ducks  = 0;
            int sell_ducks = 0;

            foreach (SmaMetric m in _metrics[quote.SymbolName])
            {
                if (quote.Price > m.Avg)
                {
                    buy_ducks++;
                }
                if (quote.Price < m.Avg)
                {
                    sell_ducks++;
                }
            }
            if (buy_ducks == 3)
            {
                _signals[quote.SymbolName] = StrategySignal.Buy;
                if (_watchForBuy.Contains(quote.SymbolName))
                {
                    _alerter.BuyAlert(quote.SymbolName, DEFAULT_BUY_SIZE, quote.Price);
                }
            }
            else if (sell_ducks == 3)
            {
                _signals[quote.SymbolName] = StrategySignal.Sell;
                if (_watchForSell.Contains(quote.SymbolName))
                {
                    _alerter.SellAlert(quote.SymbolName, quote.Price);
                }
            }
            else
            {
                _signals[quote.SymbolName] = StrategySignal.None;
            }
        }
Пример #25
0
        /// <summary>
        /// The main processing state: the client is successfully logged on
        /// and we process its requests until Logout.
        /// </summary>
        public void LoggedOn()
        {
            // Messages from client
            Receive<HeartbeatMessage>(message =>
            {
                _lastHeartbeatArrivalTime = DateTime.UtcNow; //TODO: The server could timestamp messages as they arrive to avoid checking the time here?
                _inboundSequenceNumber = message.MessageSequenceNumber;
            });

            Receive<LogoutMessage>(message =>
            {
                _log.Debug("Received Logout message from client.");
                _inboundSequenceNumber = message.MessageSequenceNumber;
                _fixInterpreterActor.Tell(new LogoutMessage(_serverCompID, _clientCompID, _outboundSequenceNumber++));
                BecomeShutDown();
            });

            Receive<QuoteRequestMessage>(message =>
            {
                if (_instrumentOfferRates != null &&
                    _instrumentOfferRates.ContainsKey(message.Symbol))
                {
                    _log.Debug("Responding to RFQ for " + message.Symbol);

                    string quoteID = "Quote" + _outboundSequenceNumber;

                    var quote = new QuoteMessage(_serverCompID, _clientCompID,
                        _outboundSequenceNumber++, message.QuoteReqID, quoteID,
                        message.Symbol, _instrumentOfferRates[message.Symbol]);

                    _fixInterpreterActor.Tell(quote);
                }
                else
                {
                    _log.Error("Unable to quote client for requested instrument: " +
                        message.Symbol);
                    //TODO: Implement unable to quote message
                }
            });

            // Exogenous system messages
            Receive<Shutdown>(message =>
            {
                _log.Debug("Shutting down.");
                _fixInterpreterActor.Tell(new LogoutMessage(_serverCompID, _clientCompID, _outboundSequenceNumber++));
                BecomeWaitingForClientLogout();
            });

            // Internal messages
            Receive<SendHeartbeat>(message =>
            {
                _log.Debug("Sending heartbeat message.");
                var heartbeatMessage = new HeartbeatMessage(_serverCompID, _clientCompID,
                    _outboundSequenceNumber++);
                _fixInterpreterActor.Tell(heartbeatMessage);
            });

            Receive<PerformAdmin>(message =>
            {
                // Check a heartbeat was received in the last 2 * heartbeat interval,
                // otherwise assume connection is lost and shut down.
                // This is the only method employed to check the connection.
                if (DateTime.UtcNow - _lastHeartbeatArrivalTime > _heartbeatInterval + _heartbeatInterval)
                {
                    _log.Debug("Heartbeat message has not been received from client.");
                    _log.Debug("Sending TestRequest to client.");

                    var testRequest = new TestRequestMessage(_serverCompID, _clientCompID,
                        _outboundSequenceNumber++, "1");
                    _fixInterpreterActor.Tell(testRequest);
                    // We expect to receive a heartbeat with matching TestReqID

                    BecomeWaitingForTestRequestResponse();
                }
            });
        }
Пример #26
0
        /// <summary>
        /// Displays the received <c>QuoteMessage</c> object in a console window.
        /// </summary>
        /// <param name="message">the received <c>QuoteMessage</c> object.</param>
        public void OnQuoteMessageReceived(QuoteMessage message)
        {
            if ((object)m_previousMessage != null && !(message > m_previousMessage))
            {
                return;
            }

            Console.WriteLine("Message:");
            Console.WriteLine("--Update timestamp: {0}", message.GetFieldValueAsDateTime(message.GetIndexFromTag(QuoteFieldTags.UpdateTimestamp)));
            Console.WriteLine("--Auction session: {0}", message.AuctionSession);

            if (message is QuoteDataMessage)
            {
                Console.WriteLine("--Initial price flag: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.InitialPriceFlag)));
                Console.WriteLine("--Auction name: {0}", message.GetFieldValueAsString(message.GetIndexFromTag(QuoteFieldTags.AuctionName)));
                Console.WriteLine("--Bid size: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidSize)));

                if (message is SessionAMessage)
                {
                    Console.WriteLine("--Limit price: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.LimitPrice)));
                    Console.WriteLine("--Initial price: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.InitialPrice)));
                    Console.WriteLine("--Auction begin time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.AuctionBeginTime)));
                    Console.WriteLine("--Auction end time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.AuctionEndTime)));
                    Console.WriteLine("--First begin time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.FirstBeginTime)));
                    Console.WriteLine("--First end time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.FirstEndTime)));
                    Console.WriteLine("--Second begin time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.SecondBeginTime)));
                    Console.WriteLine("--Second end time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.SecondEndTime)));
                    Console.WriteLine("--Server time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.ServerTime)));
                    Console.WriteLine("--Bid quantity: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidQuantity)));
                    Console.WriteLine("--Bid price: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidPrice)));
                    Console.WriteLine("--Bid time: {0}", message.GetFieldValueAsDateTime(message.GetIndexFromTag(QuoteFieldTags.BidTime)));
                    Console.WriteLine("--Processed count: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.ProcessedCount)));
                    Console.WriteLine("--Pending count: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.PendingCount)));
                }
                else if (message is SessionBMessage)
                {
                    Console.WriteLine("--Bid quantity: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidQuantity)));
                    Console.WriteLine("--Initial price: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.InitialPrice)));
                    Console.WriteLine("--Auction begin time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.AuctionBeginTime)));
                    Console.WriteLine("--Auction end time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.AuctionEndTime)));
                    Console.WriteLine("--First begin time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.FirstBeginTime)));
                    Console.WriteLine("--First end time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.FirstEndTime)));
                    Console.WriteLine("--Second begin time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.SecondBeginTime)));
                    Console.WriteLine("--Second end time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.SecondEndTime)));
                    Console.WriteLine("--Server time: {0}", message.GetFieldValueAsTimeSpan(message.GetIndexFromTag(QuoteFieldTags.ServerTime)));
                    Console.WriteLine("--Bid price: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidPrice)));
                    Console.WriteLine("--Bid time: {0}", message.GetFieldValueAsDateTime(message.GetIndexFromTag(QuoteFieldTags.BidTime)));
                    Console.WriteLine("--Bid lower: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidLower)));
                    Console.WriteLine("--Bid upper: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.BidUpper)));
                    Console.WriteLine("--Processed count: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.ProcessedCount)));
                    Console.WriteLine("--Pending count: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.PendingCount)));
                }
            }
            else if (message is QuoteTextMessage)
            {
                Console.WriteLine("--Content text: {0}", message.GetFieldValueAsString(message.GetIndexFromTag(QuoteFieldTags.ContentText)));

                if (message is SessionCEFHMessage)
                {
                    // nothing more
                }
                else if (message is SessionDGMessage)
                {
                    Console.WriteLine("--Processed count: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.ProcessedCount)));
                    Console.WriteLine("--Pending count: {0}", message.GetFieldValueAsInt32(message.GetIndexFromTag(QuoteFieldTags.PendingCount)));
                }
            }

            m_previousMessage = message;
            Console.WriteLine();
        }
Пример #27
0
 /// <summary>
 /// Initializes a new instance of the <c>ConsoleViewer</c> class with the given quote data provider.
 /// </summary>
 public ConsoleViewer(IQuoteDataProvider provider)
 {
     m_previousMessage = null;
 }
Пример #28
0
        public object GetAll()
        {
            var queryValues = Request.RequestUri.ParseQueryString();

            int page  = Convert.ToInt32(queryValues["page"]);
            int start = Convert.ToInt32(queryValues["start"]);
            int limit = Convert.ToInt32(queryValues["limit"]);
            int id    = Convert.ToInt32(queryValues["id"]);
            int orden = Convert.ToInt32(queryValues["orden"]);

            string strFieldFilters = queryValues["fieldFilters"];

            FieldFilters fieldFilters = new FieldFilters();

            if (!String.IsNullOrEmpty(strFieldFilters))
            {
                fieldFilters = JsonConvert.DeserializeObject <FieldFilters>(strFieldFilters);
            }


            #region Configuramos el orden de la consulta si se obtuvo como parametro
            string strOrder = !string.IsNullOrWhiteSpace(queryValues["sort"]) ? queryValues["sort"] : "";
            strOrder = strOrder.Replace('[', ' ');
            strOrder = strOrder.Replace(']', ' ');

            Sort sort;

            if (!string.IsNullOrWhiteSpace(strOrder))
            {
                sort = JsonConvert.DeserializeObject <Sort>(strOrder);
            }
            else
            {
                sort = new Sort();
            }
            #endregion

            string query = !string.IsNullOrWhiteSpace(queryValues["query"]) ? queryValues["query"] : "";

            int totalRecords = 0;

            try
            {
                if (id == 0)
                {
                    object json;
                    var    lista = repository.GetList(query, fieldFilters, sort, page, start, limit, ref totalRecords);

                    json = new
                    {
                        total   = totalRecords,
                        data    = lista,
                        success = true
                    };

                    return(json);
                }
                else
                {
                    QuoteMessage model = repository.Get(id);

                    object json = new
                    {
                        data    = model,
                        success = true
                    };

                    return(json);
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("ERROR:" + Environment.NewLine + "\tMETHOD = " + this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name + Environment.NewLine + "\tMESSAGE = " + ex.Message);

                object json = new
                {
                    message = ex.Message,
                    success = false
                };

                return(json);
            }
        }
Пример #29
0
        public void ConvertFixObjectToFixMessage_ReturnsCorrectString_ForQuoteMessage()
        {
            var messageObject = new QuoteMessage("Client", "Bank", 7, "rfq712", "q712", "USDJPY", 119.55);

            string result = new FixParser().ConvertFixObjectToFixMessage(messageObject);

            string expected = "8=FIXT1.1\u00019=71\u000135=S\u000149=Client\u000156=Bank\u000134=7\u0001131=rfq712\u0001117=q712\u000155=USDJPY\u0001133=119.5500\u000110=171\u0001";

            result.Should().Be(expected);
        }
 public Task PublishAsync(QuoteMessage candle)
 {
     return(_publisher.ProduceAsync(candle));
 }
Пример #31
0
        private void OnQuote(QuoteMessage quote, DataSet1.StockQuotesRow row)
        {
            Action a = delegate
            {
                try
                {
                    if (checkBoxLog.Checked)
                    {
                        m_log.Info(quote.ToXml());
                    }

                    bool bUpdated = false;
                    row.Subscribed = (quote.SubscriptionStatus == SubscriptionStatus.Subscribed);

                    if (quote.HasOpen)
                    {
                        row.Open = quote.Open;
                        bUpdated = true;
                    }

                    if (quote.HasPrevClose)
                    {
                        row.PrevClose = quote.PrevClose;
                        bUpdated      = true;
                    }

                    if (quote.HasLast)
                    {
                        if (!row.Closed)
                        {
                            row.LastPrice = quote.Last;
                            bUpdated      = true;
                        }
                    }

                    if (quote.HasBid)
                    {
                        if (!row.Closed)
                        {
                            row.Bid  = quote.Bid;
                            bUpdated = true;
                        }
                    }
                    if (quote.HasAsk)
                    {
                        if (!row.Closed)
                        {
                            row.Ask  = quote.Ask;
                            bUpdated = true;
                        }
                    }
                    if (quote.HasDelta)
                    {
                        if (!row.Closed)
                        {
                            row.Delta = quote.Delta;
                            bUpdated  = true;
                        }
                    }
                    if (quote.HasGamma)
                    {
                        if (!row.Closed)
                        {
                            row.Gamma = quote.Gamma;
                            bUpdated  = true;
                        }
                    }
                    if (quote.HasTheta)
                    {
                        if (!row.Closed)
                        {
                            row.Theta = quote.Theta;
                            bUpdated  = true;
                        }
                    }
                    if (quote.HasVega)
                    {
                        if (!row.Closed)
                        {
                            row.Vega = quote.Vega;
                            bUpdated = true;
                        }
                    }
                    if (quote.HasImpliedVol)
                    {
                        if (!row.Closed)
                        {
                            row.ImpliedVol = quote.ImpliedVol;
                            bUpdated       = true;
                        }
                    }

                    if (quote.HasClose)
                    {
                        row.ClosingPrice = quote.Close;
                        bUpdated         = true;
                    }

                    if (quote.OpenStatus == OpenStatus.Closed)
                    {
                        row.Closed = true;
                        bUpdated   = true;
                    }

                    if (quote.OpenStatus == OpenStatus.Open)
                    {
                        row.Closed = false;
                        bUpdated   = true;
                    }

                    if (bUpdated)
                    {
                        row.Time = DateTime.Now - DateTime.Today;
                    }
                }
                catch (Exception ex)
                {
                    OnError("Error in quote handler", ex);
                }
            };

            if (InvokeRequired)
            {
                BeginInvoke(a);
            }
            else
            {
                a.Invoke();
            }
        }
Пример #32
0
 public void OnQuoteMessageReceived(QuoteMessage message)
 {
     m_viewModel.OnQuoteMessageReceived(message);
 }