Пример #1
0
        public void ClearTest()
        {
            object[] symbols = new object[] { "IBM", "AAPL", "C" };
            isFiresOnSymbolsRemoved = false;
            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            s.OnSymbolsRemoved += OnSymbolsRemoved;
            s.AddSymbols(symbols);
            Assert.Greater(s.GetSymbols().Count, 0);

            s.Clear();
            Assert.True(isFiresOnSymbolsRemoved);
            Assert.AreEqual(s.GetSymbols().Count, 0);

            //try to add symbols again after Clear
            s.AddSymbols(symbols);
            Assert.Greater(s.GetSymbols().Count, 0);

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    s.Clear();
                });
            });
        }
Пример #2
0
        public void ConnectTest()
        {
            IDXEndpoint endpoint = DXEndpoint.Create();

            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);

            Assert.Catch(typeof(ArgumentNullException), () => {
                endpoint.Connect(null);
            });
            Assert.Catch(typeof(ArgumentNullException), () => {
                endpoint.Connect(string.Empty);
            });
            Assert.Catch(typeof(ArgumentNullException), () => {
                endpoint.Connect("   ");
            });
            Assert.Catch(() => {
                endpoint.Connect("not-valid-address");
            });
            endpoint.Connect(testServerAddress);
            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);
            endpoint.Connect(demoServerAddress);
            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);

            //try to connect after disconnect
            endpoint.Disconnect();
            Assert.AreEqual(endpoint.State, DXEndpointState.NotConnected);
            endpoint.Connect(demoServerAddress);
            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);
        }
Пример #3
0
        public void RemoveEventListenerTest()
        {
            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxEventType>(typeof(IDxOrder));

            Assert.Catch(typeof(ArgumentNullException), () =>
            {
                s.RemoveEventListener(null);
            });

            var listenersCount = 10;
            var listenersList  = new List <IDXFeedEventListener <IDxEventType> >(listenersCount);

            for (var i = 0; i < listenersCount; i++)
            {
                listenersList.Add(new EventListener());

                s.AddEventListener(listenersList.Last());
            }
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    s.RemoveEventListener(listenersList[i % listenersCount]);
                });
            });
        }
Пример #4
0
        public void IsClosedTest()
        {
            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            Assert.False(s.IsClosed);
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.False(s.IsClosed);
            });

            s.Close();
            Assert.True(s.IsClosed);

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    Assert.True(s.IsClosed);
                });
            });

            //try to close subscription via closing endpoint
            s = DXFeed.GetInstance().CreateSubscription <IDxOrder>();
            Assert.False(s.IsClosed);
            DXEndpoint.GetInstance().Close();
            Assert.True(s.IsClosed);
        }
Пример #5
0
        public void DetachSubscriptionTest()
        {
            //create default endpoint
            DXEndpoint.Create();

            //try to detach null subscription
            Assert.Catch(typeof(ArgumentNullException), () =>
            {
                DXFeed.GetInstance().DetachSubscription <IDxOrder>(null);
            });

            //try to detach already detached subscription
            var s = DXFeed.GetInstance().CreateSubscription <IDxOrder>();

            DXFeed.GetInstance().DetachSubscription(s);
            DXFeed.GetInstance().DetachSubscription(s);

            //try to detach another not attached subscription
            DXFeedSubscription <IDxOrder> other = new DXFeedSubscription <IDxOrder>(DXEndpoint.GetInstance() as DXEndpoint);

            DXFeed.GetInstance().DetachSubscription(other);

            //thread-safety case
            DXEndpoint.Create();
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    var newSubscription = new DXFeedSubscription <IDxOrder>(DXEndpoint.GetInstance() as DXEndpoint);
                    DXFeed.GetInstance().AttachSubscription(newSubscription);
                    DXFeed.GetInstance().DetachSubscription(newSubscription);
                });
            });
        }
Пример #6
0
        public void CreateTimeSeriesSubscriptionTest()
        {
            var symbol = "SYMA";
            var s      = DXEndpoint.Create().Feed.CreateTimeSeriesSubscription <IDxCandle>();

            s.AddSymbols(symbol);
            TestListener eventListener = new TestListener();

            s.AddEventListener(eventListener);

            var playedCandle = new PlayedCandle(symbol, Tools.DateToUnixTime(DateTime.Now), 123, 100, 12.34, 56.78, 9.0, 43.21, 1000, 999, 1001, 1002, 1, 777, 888, EventFlag.RemoveSymbol);

            EventPlayer <IDxCandle> eventPlayer = new EventPlayer <IDxCandle>(s as DXFeedSubscription <IDxCandle>);

            eventPlayer.PlayEvents(symbol, playedCandle);
            Assert.AreEqual(eventListener.GetEventCount <IDxCandle>(symbol), 1);
            IDxCandle receivedCandle = eventListener.GetLastEvent <IDxCandle>().Event;

            Assert.AreEqual(symbol, receivedCandle.EventSymbol.ToString());
            CompareCandles(playedCandle, receivedCandle);

            //thread-safety case
            DXEndpoint.Create();
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    DXEndpoint.GetInstance().Feed.CreateTimeSeriesSubscription <IDxCandle>();
                });
            });
        }
Пример #7
0
        public void GetSymbolsTest()
        {
            object[] symbols = new object[] { "IBM", "AAPL", "C" };
            isFiresOnSymbolsRemoved = false;
            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            s.AddSymbols(symbols);
            Assert.AreEqual(symbols.Length, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(symbols));

            //try to change returned symbols set
            s.GetSymbols().Add("MSFT");
            Assert.AreEqual(symbols.Length, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(symbols));

            //try to add new symbol into subscription
            s.AddSymbols("XBT/USD");
            IList <object> newSymbols = new List <object>(symbols);

            newSymbols.Add("XBT/USD");
            Assert.AreEqual(newSymbols.Count, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(newSymbols));

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.True(s.GetSymbols().SetEquals(newSymbols));
            });
        }
Пример #8
0
        public void FeedTest()
        {
            IDXEndpoint endpoint = DXEndpoint.Create();

            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);

            Assert.IsNotNull(endpoint.Feed);
        }
Пример #9
0
        public void CreateSubscriptionTypesTest()
        {
            //create default endpoint
            DXEndpoint.Create();

            //try to create subscription with invalid event types parameters
            //all attempts to create subscription in this block must be failed with exception
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateSubscription <IDxOrder>(typeof(IDxCandle), typeof(IDxQuote));
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateSubscription <IDxIndexedEvent>(typeof(IDxCandle), typeof(IDxQuote));
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateSubscription <IDxLastingEvent>(typeof(IDxOrder), typeof(IDxQuote));
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateSubscription <IDxMarketEvent>(typeof(IDxCandle));
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateSubscription <IDxMarketEvent>(typeof(string));
            });

            var symbol = "SYMA";
            var s      = DXFeed.GetInstance().CreateSubscription <IDxEventType>(typeof(IDxOrder), typeof(IDxTrade));

            s.AddSymbols(symbol);
            TestListener eventListener = new TestListener();

            s.AddEventListener(eventListener);

            EventPlayer <IDxEventType> eventPlayer = new EventPlayer <IDxEventType>(s as DXFeedSubscription <IDxEventType>);
            var playedOrder = new PlayedOrder(symbol, 0, 0x4e54560000000006, 0, 0, 0, 0, 100, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA");

            eventPlayer.PlayEvents(symbol, playedOrder);
            var playedTrade = new PlayedTrade(symbol, 0, 0, 0, 'B', 123.456, 100, 123, 1.1, 0, 2.2, 0.0, Direction.Undefined, false, Scope.Regional);

            eventPlayer.PlayEvents(symbol, playedTrade);

            Assert.AreEqual(eventListener.GetEventCount <IDxOrder>(symbol), 1);
            Assert.AreEqual(eventListener.GetEventCount <IDxTrade>(symbol), 1);

            //thread-safety case
            DXEndpoint.Create();
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    DXFeed.GetInstance().CreateSubscription <IDxEventType>(typeof(IDxOrder), typeof(IDxTrade));
                });
            });
        }
Пример #10
0
 /// <summary>
 ///     Returns a default application-wide singleton instance of DXEndpoint with a default
 ///     role.
 ///     Most applications use only a single data-source and should rely on this method to
 ///     get one.
 /// </summary>
 /// <returns>Instance of DXEndpoint with a default role.</returns>
 public static IDXEndpoint GetInstance()
 {
     if (endpointInstance == null)
     {
         lock (instanceLocker)
         {
             endpointInstance = new DXEndpoint();
             endpointInstance.Connect(DefaultAddress);
         }
     }
     return(endpointInstance);
 }
Пример #11
0
        public void PasswordTest()
        {
            IDXEndpoint endpoint = DXEndpoint.Create();

            Assert.Catch(typeof(ArgumentNullException), () => {
                endpoint.Password(null);
            });
            Assert.Catch(typeof(ArgumentNullException), () => {
                endpoint.Password(string.Empty);
            });
            Assert.AreEqual(endpoint, endpoint.Password("test"));
        }
Пример #12
0
        /// <summary>
        ///     Creates detached subscription for a single event type.
        /// </summary>
        /// <param name="endpoint">The <see cref="DXEndpoint"/> instance.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="endpoint"/> is null.</exception>
        /// <exception cref="ArgumentException">If type E is not event class.</exception>
        /// <exception cref="DxException">Internal error.</exception>
        public DXFeedSubscription(DXEndpoint endpoint) : this()
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            endpoint.OnClosing += Endpoint_OnClosing;

            subscriptionInstance = endpoint.Connection.CreateSubscription(
                EventTypeUtil.GetEventsType(typeof(E)),
                new DXFeedEventHandler <E>(eventListeners, eventListenerLocker));
        }
Пример #13
0
 /// <summary>
 ///     Creates an new endpoint.
 /// </summary>
 /// <returns>The created endpoint.</returns>
 public static IDXEndpoint Create()
 {
     lock (instanceLocker)
     {
         if (endpointInstance != null && endpointInstance.State != DXEndpointState.Closed)
         {
             endpointInstance.Close();
         }
         endpointInstance = new DXEndpoint();
         endpointInstance.Connect(DefaultAddress);
     }
     return(endpointInstance);
 }
        public void ParallelFromTimeStampTest()
        {
            var s = DXEndpoint.Create().Feed.CreateTimeSeriesSubscription <IDxCandle>();

            Random random = new Random();

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    s.FromTimeStamp = Tools.DateToUnixTime(DateTime.Now.AddDays(random.Next(-356, 0)));
                });
            });
        }
Пример #15
0
        public void CloseTest()
        {
            isFiresOnSubscriptionClosed = false;
            isFiresOnSymbolsRemoved     = false;
            var expectedEventSet  = new HashSet <Type>(new Type[] { typeof(IDxOrder) });
            var expectedSymbolSet = new HashSet <string>();
            var eventListener     = new EventListener();

            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxEventType>(typeof(IDxOrder));

            s.OnSubscriptionClosed += OnSubscriptionClosed;
            s.OnSymbolsAdded       += OnSymbolsAdded;
            s.OnSymbolsRemoved     += OnSymbolsRemoved;
            s.AddSymbols("IBM");
            s.Close();

            //try to call methods after closing subscription
            Assert.True(isFiresOnSubscriptionClosed);
            Assert.True(s.IsClosed);
            Assert.True(s.EventTypes.SetEquals(expectedEventSet));
            Assert.True(s.ContainsEventType(typeof(IDxOrder)));

            s.Clear();
            Assert.True(s.GetSymbols().SetEquals(expectedSymbolSet));

            isFiresOnSymbolsAdded = false;
            s.SetSymbols("AAPL");
            Assert.False(isFiresOnSymbolsAdded);
            Assert.True(s.GetSymbols().SetEquals(expectedSymbolSet));

            s.AddSymbols("C");
            Assert.False(isFiresOnSymbolsAdded);
            Assert.True(s.GetSymbols().SetEquals(expectedSymbolSet));

            s.RemoveSymbols("IBM");
            Assert.False(isFiresOnSymbolsRemoved);
            Assert.True(s.GetSymbols().SetEquals(expectedSymbolSet));

            s.AddEventListener(eventListener);
            s.RemoveEventListener(eventListener);

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    s.Close();
                });
            });
        }
Пример #16
0
        public void CreateTimeSeriesSubscriptionTypesTest()
        {
            //create default endpoint
            DXEndpoint.Create();

            //try to create subscription with invalid event types parameters
            //all attempts to create subscription in this block must be failed with exception
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateTimeSeriesSubscription <IDxTimeSeriesEvent>(typeof(IDxCandle), typeof(IDxQuote));
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateTimeSeriesSubscription <IDxTimeSeriesEvent>(typeof(IDxOrder), typeof(IDxQuote));
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                DXFeed.GetInstance().CreateTimeSeriesSubscription <IDxTimeSeriesEvent>(typeof(string));
            });

            var symbol = "SYMA";
            var s      = DXFeed.GetInstance().CreateTimeSeriesSubscription <IDxTimeSeriesEvent>(typeof(IDxCandle), typeof(IDxGreeks));

            s.AddSymbols(symbol);
            TestListener eventListener = new TestListener();

            s.AddEventListener(eventListener);

            EventPlayer <IDxTimeSeriesEvent> eventPlayer = new EventPlayer <IDxTimeSeriesEvent>(s as DXFeedSubscription <IDxTimeSeriesEvent>);
            var playedCandle = new PlayedCandle(symbol, Tools.DateToUnixTime(DateTime.Now), 123, 100, 12.34, 56.78, 9.0, 43.21, 1000, 999, 1001, 1002, 1, 777, 888, EventFlag.RemoveSymbol);

            eventPlayer.PlayEvents(symbol, playedCandle);
            var playedGreeks = new PlayedGreeks(symbol, EventFlag.RemoveSymbol, 1, Tools.DateToUnixTime(DateTime.Now), 456.789, 11, 555, 666, 777, 888, 999);

            eventPlayer.PlayEvents(symbol, playedGreeks);

            Assert.AreEqual(eventListener.GetEventCount <IDxCandle>(symbol), 1);
            Assert.AreEqual(eventListener.GetEventCount <IDxGreeks>(symbol), 1);

            //thread-safety case
            DXEndpoint.Create();
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    DXFeed.GetInstance().CreateTimeSeriesSubscription <IDxTimeSeriesEvent>(typeof(IDxCandle), typeof(IDxGreeks));
                });
            });
        }
Пример #17
0
        public void RemoveSymbolsTest()
        {
            object[] symbolsSet = new object[] { "IBM", CandleSymbol.ValueOf("AAPL{=d}"), "C", "XBT/USD" };
            isFiresOnSymbolsRemoved = false;
            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            s.OnSymbolsRemoved += OnSymbolsRemoved;
            s.AddSymbols(symbolsSet);

            s.RemoveSymbols(null);
            s.RemoveSymbols(new List <object>());
            s.RemoveSymbols(new object[] { });
            Assert.Catch(typeof(ArgumentNullException), () =>
            {
                s.RemoveSymbols(new List <object>(new object[] { null }));
            });

            ICollection <object> removeCollection = new List <object>(
                new object[] { CandleSymbol.ValueOf("AAPL{=d}"), "C", "XBT/USD" }
                );

            s.RemoveSymbols(removeCollection);
            Assert.True(isFiresOnSymbolsRemoved);
            Assert.AreEqual(1, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(new object[] { "IBM" }));
            isFiresOnSymbolsRemoved = false;
            s.RemoveSymbols("IBM");
            Assert.True(isFiresOnSymbolsRemoved);
            Assert.AreEqual(0, s.GetSymbols().Count);

            var totalSymbolsCount = 0;

            foreach (var set in SimulatedSymbolsSet)
            {
                s.AddSymbols(set);
                totalSymbolsCount += set.Length;
            }
            Assert.AreEqual(totalSymbolsCount, s.GetSymbols().Count);
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    s.RemoveSymbols(SimulatedSymbolsSet[i % SimulatedSymbolsSet.Length]);
                });
            });
            Assert.AreEqual(0, s.GetSymbols().Count);
        }
Пример #18
0
        public void StateTest()
        {
            IDXEndpoint endpoint = DXEndpoint.Create();

            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);

            endpoint.Disconnect();
            Assert.AreEqual(endpoint.State, DXEndpointState.NotConnected);

            endpoint.Connect(demoServerAddress);
            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);

            endpoint.Close();
            Assert.AreEqual(endpoint.State, DXEndpointState.Closed);
            endpoint.Connect(demoServerAddress);
            Assert.AreEqual(endpoint.State, DXEndpointState.Closed);
        }
Пример #19
0
        public void AddSymbolsTest()
        {
            object[] symbolsSet1      = new object[] { "IBM", CandleSymbol.ValueOf("AAPL{=d}"), "C" };
            object[] symbolsSetString = new object[] { "IBM", "AAPL{=d}", "C" };
            object   symbolSet2       = "XBT/USD";

            isFiresOnSymbolsAdded = false;
            var s = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            s.OnSymbolsAdded += OnSymbolsAdded;

            s.AddSymbols(null);
            s.AddSymbols(new List <object>());
            s.AddSymbols(new object[] { });
            Assert.Catch(typeof(ArgumentNullException), () =>
            {
                s.AddSymbols(new List <object>(new object[] { null }));
            });

            s.AddSymbols(symbolsSet1);
            Assert.True(isFiresOnSymbolsAdded);
            Assert.AreEqual(symbolsSetString.Length, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(symbolsSetString));

            isFiresOnSymbolsAdded = false;
            object[] newSymbolSet = symbolsSetString.Concat(new object[] { symbolSet2 }).ToArray();
            s.AddSymbols(symbolSet2);
            Assert.True(isFiresOnSymbolsAdded);
            Assert.AreEqual(newSymbolSet.Length, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(newSymbolSet));

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    s.AddSymbols(SimulatedSymbolsSet[i % SimulatedSymbolsSet.Length]);
                });
            });
            foreach (var set in SimulatedSymbolsSet)
            {
                newSymbolSet = newSymbolSet.Concat(set).ToArray();
            }
            Assert.AreEqual(newSymbolSet.Length, s.GetSymbols().Count);
            Assert.True(s.GetSymbols().SetEquals(newSymbolSet));
        }
Пример #20
0
        public void CloseTest()
        {
            isFiresOnClosing = false;
            IDXEndpoint endpoint = DXEndpoint.Create();

            endpoint.OnClosing += Endpoint_OnClosing;
            Assert.True(endpoint.State == DXEndpointState.Connected || endpoint.State == DXEndpointState.Connecting);

            endpoint.Close();
            Assert.AreEqual(endpoint.State, DXEndpointState.Closed);
            Assert.True(isFiresOnClosing);

            endpoint.Connect(demoServerAddress);
            Assert.AreEqual(endpoint.State, DXEndpointState.Closed);

            endpoint.Disconnect();
            Assert.AreEqual(endpoint.State, DXEndpointState.Closed);
        }
Пример #21
0
        public void EventTypesTest()
        {
            var orderSubscription = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            Assert.True(orderSubscription.EventTypes.SetEquals(new HashSet <Type>(new Type[] { typeof(IDxOrder) })));

            ISet <Type> allTypesSet = DXEndpoint.GetInstance().GetEventTypes();

            Type[] subscriptionTypes   = allTypesSet.AsEnumerable().ToArray();
            var    allTypeSubscription = DXEndpoint.GetInstance().Feed.CreateSubscription <IDxEventType>(subscriptionTypes);

            Assert.True(allTypeSubscription.EventTypes.SetEquals(allTypesSet));

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.True(allTypeSubscription.EventTypes.SetEquals(allTypesSet));
            });
        }
Пример #22
0
        /// <summary>
        ///     Creates detached snapshot subscription for a single event type.
        /// </summary>
        /// <param name="endpoint">The <see cref="DXEndpoint"/> instance.</param>
        /// <param name="time">Unix time in the past - number of milliseconds from 1.1.1970.</param>
        /// <param name="source">The source of the event.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="endpoint"/> is null.</exception>
        /// <exception cref="ArgumentException">If type E is not event class.</exception>
        /// <exception cref="DxException">Internal error.</exception>
        internal DXFeedSubscription(DXEndpoint endpoint, long time, IndexedEventSource source) : this()
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            endpoint.OnClosing += Endpoint_OnClosing;

            subscriptionInstance = endpoint.Connection.CreateSnapshotSubscription(
                EventTypeUtil.GetEventsType(typeof(E)),
                time,
                new DXFeedEventHandler <E>(eventListeners, eventListenerLocker));
            if (source != IndexedEventSource.DEFAULT)
            {
                subscriptionInstance.SetSource(source.Name);
            }
        }
Пример #23
0
        public void ContainEventTypeTest()
        {
            ISet <Type> allTypesSet = DXEndpoint.GetInstance().GetEventTypes();

            var orderSubscription = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            Assert.True(orderSubscription.ContainsEventType(typeof(IDxOrder)));
            foreach (Type t in allTypesSet.Except(new Type[] { typeof(IDxOrder) }))
            {
                Assert.False(orderSubscription.ContainsEventType(t));
            }

            Type[] subscriptionTypes       = new Type[] { typeof(IDxOrder), typeof(IDxCandle) };
            var    orderCandleSubscription = DXEndpoint.GetInstance().Feed.CreateSubscription <IDxEventType>(subscriptionTypes);

            foreach (Type t in subscriptionTypes)
            {
                Assert.True(orderCandleSubscription.ContainsEventType(t));
            }
            foreach (Type t in allTypesSet.Except(subscriptionTypes))
            {
                Assert.False(orderCandleSubscription.ContainsEventType(t));
            }

            subscriptionTypes = allTypesSet.AsEnumerable().ToArray();
            var allTypeSubscription = DXEndpoint.GetInstance().Feed.CreateSubscription <IDxEventType>(subscriptionTypes);

            foreach (Type t in allTypesSet)
            {
                Assert.True(allTypeSubscription.ContainsEventType(t));
            }

            Assert.False(allTypeSubscription.ContainsEventType(null));

            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                foreach (Type t in allTypesSet)
                {
                    Assert.True(allTypeSubscription.ContainsEventType(t));
                }
            });
        }
Пример #24
0
        /// <summary>
        ///     Creates detached subscription for the given list of event types.
        /// </summary>
        /// <param name="endpoint">The <see cref="DXEndpoint"/> instance.</param>
        /// <param name="eventTypes">The list of event types.</param>
        /// <exception cref="ArgumentNullException">
        ///     If <paramref name="endpoint"/> or <paramref name="eventTypes"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     If <paramref name="eventTypes"/> are empty or any type of
        ///     <paramref name="eventTypes"/> is not event class.
        /// </exception>
        /// <exception cref="DxException">Internal error.</exception>
        public DXFeedSubscription(DXEndpoint endpoint, params Type[] eventTypes) : this(eventTypes)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            foreach (Type t in eventTypes)
            {
                if (!typeof(E).IsAssignableFrom(t))
                {
                    throw new ArgumentException(string.Format("The type {0} is not {1}", t, typeof(E)));
                }
            }

            endpoint.OnClosing += Endpoint_OnClosing;

            subscriptionInstance = endpoint.Connection.CreateSubscription(
                EventTypeUtil.GetEventsType(eventTypes),
                new DXFeedEventHandler <E>(eventListeners, eventListenerLocker));
        }
Пример #25
0
        public void CreateSubscriptionTest()
        {
            var symbol = "SYMA";
            var s      = DXEndpoint.Create().Feed.CreateSubscription <IDxOrder>();

            s.AddSymbols(symbol);
            TestListener eventListener = new TestListener();

            s.AddEventListener(eventListener);

            var playedOrder = new PlayedOrder(symbol, 0, 0x4e54560000000006, 0, 0, 0, 0, 100, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA");

            EventPlayer <IDxOrder> eventPlayer = new EventPlayer <IDxOrder>(s as DXFeedSubscription <IDxOrder>);

            eventPlayer.PlayEvents(symbol, playedOrder);
            Assert.AreEqual(eventListener.GetEventCount <IDxOrder>(symbol), 1);

            IDxOrder receivedOrder = eventListener.GetLastEvent <IDxOrder>().Event;

            Assert.AreEqual(symbol, receivedOrder.EventSymbol);
            CompareOrders(playedOrder, receivedOrder);

            //try to create subscription on closed endpoint
            DXEndpoint.GetInstance().Close();
            Assert.Catch(typeof(InvalidOperationException), () =>
            {
                DXFeed.GetInstance().CreateSubscription <IDxOrder>();
            });

            //thread-safety case
            DXEndpoint.Create();
            Parallel.For(ParallelFrom, ParallelTo, i =>
            {
                Assert.DoesNotThrow(() =>
                {
                    DXFeed.GetInstance().CreateSubscription <IDxOrder>();
                });
            });
        }
        public void ResetFromTimeStampTest()
        {
            string       symbol        = "SYMA";
            TestListener eventListener = new TestListener();
            var          s             = DXEndpoint.Create().Feed.CreateTimeSeriesSubscription <IDxCandle>();

            s.OnSubscriptionClosed += OnSubscriptionClosed;
            s.OnSymbolsAdded       += OnSymbolsAdded;
            s.OnSymbolsRemoved     += OnSymbolsRemoved;
            s.AddEventListener(eventListener);
            s.AddSymbols(symbol);
            Assert.AreEqual(long.MaxValue, s.FromTimeStamp);

            //try to change FromTimeStamp property
            isFiresOnSubscriptionClosed = false;
            isFiresOnSymbolsAdded       = false;
            isFiresOnSymbolsRemoved     = false;
            long fromTime = Tools.DateToUnixTime(DateTime.Now.AddMonths(-1));

            s.FromTimeStamp = fromTime;
            Assert.AreEqual(fromTime, s.FromTimeStamp);
            Assert.True(s.GetSymbols().SetEquals(new object[] { symbol }));
            Assert.True(s.EventTypes.SetEquals(new Type[] { typeof(IDxCandle) }));
            Assert.False(isFiresOnSubscriptionClosed);
            Assert.False(isFiresOnSymbolsAdded);
            Assert.False(isFiresOnSymbolsRemoved);

            var playedCandle = new PlayedCandle(symbol, Tools.DateToUnixTime(DateTime.Now), 123, 100, 12.34, 56.78, 9.0, 43.21, 1000, 999, 1001, 1002, 1, 777, 888, EventFlag.RemoveSymbol);

            EventPlayer <IDxCandle> eventPlayer = new EventPlayer <IDxCandle>(s as DXFeedSubscription <IDxCandle>);

            eventPlayer.PlayEvents(symbol, playedCandle);
            Assert.AreEqual(eventListener.GetEventCount <IDxCandle>(symbol), 1);
            IDxCandle receivedCandle = eventListener.GetLastEvent <IDxCandle>().Event;

            Assert.AreEqual(symbol, receivedCandle.EventSymbol.ToString());
            DXFeedTest.CompareCandles(playedCandle, receivedCandle);
        }
Пример #27
0
        public void GetIndexedEventsPromiseTest()
        {
            //create default endpoint
            DXEndpoint.Create();
            var symbol = "SYMA";

            //try to create promise with invalid parameters
            Assert.Catch(typeof(ArgumentException), () =>
            {
                try
                {
                    DXFeed.GetInstance().GetIndexedEventsPromise <IDxOrder>(null, OrderSource.NTV, CancellationToken.None).Wait();
                }
                catch (AggregateException ae)
                {
                    foreach (var inner in ae.InnerExceptions)
                    {
                        throw inner;
                    }
                }
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                try
                {
                    DXFeed.GetInstance().GetIndexedEventsPromise <IDxOrder>(symbol, null, CancellationToken.None).Wait();
                }
                catch (AggregateException ae)
                {
                    foreach (var inner in ae.InnerExceptions)
                    {
                        throw inner;
                    }
                }
            });

            //try to cancel promise
            CancellationTokenSource cancelSource = new CancellationTokenSource();
            Task <List <IDxOrder> > promise      = DXFeed.GetInstance().GetIndexedEventsPromise <IDxOrder>(symbol, OrderSource.NTV, cancelSource.Token);

            cancelSource.CancelAfter(TimeSpan.FromSeconds(2));
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try wait promise with timeout
            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
            promise      = DXFeed.GetInstance().GetIndexedEventsPromise <IDxOrder>(symbol, OrderSource.NTV, cancelSource.Token);
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try close endpoint while promise waiting
            Task closeEndpointTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                DXEndpoint.GetInstance().Close();
            });

            promise = DXFeed.GetInstance().GetIndexedEventsPromise <IDxOrder>(symbol, OrderSource.NTV, CancellationToken.None);
            try
            {
                Task.WaitAll(promise, closeEndpointTask);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get promise on closed endpoint
            promise = DXFeed.GetInstance().GetIndexedEventsPromise <IDxOrder>(symbol, OrderSource.NTV, CancellationToken.None);
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get last event succesfully
            DateTime date         = DateTime.Now;
            var      playedOrders = new PlayedOrder[] {
                new PlayedOrder(symbol, 0, 0x4e54560000000006, Tools.DateToUnixTime(date), 0, 0, 100, 100, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                new PlayedOrder(symbol, 0, 0x4e54560000000005, Tools.DateToUnixTime(date.AddMinutes(-1)), 0, 0, 100.5, 101, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                new PlayedOrder(symbol, 0, 0x4e54560000000004, Tools.DateToUnixTime(date.AddMinutes(-2)), 0, 0, 101, 102, 25, Scope.Order, Side.Sell, 'A', OrderSource.NTV, "AAAA"),
                new PlayedOrder(symbol, 0, 0x4e54560000000003, Tools.DateToUnixTime(date.AddMinutes(-3)), 0, 0, 100, 103, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                new PlayedOrder(symbol, 0, 0x4e54560000000002, Tools.DateToUnixTime(date.AddMinutes(-4)), 0, 0, 100.4, 104, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                new PlayedOrder(symbol, 0, 0x4e54560000000001, Tools.DateToUnixTime(date.AddMinutes(-5)), 0, 0, 100.3, 105, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                new PlayedOrder(symbol, 0, 0x4e54560000000000, Tools.DateToUnixTime(date.AddMinutes(-6)), 0, 0, 100.2, 106, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA")
            };
            Task eventPlayerTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                EventPlayer <IDxOrder> eventPlayer = new EventPlayer <IDxOrder>(GetSubscriptionFromFeed <IDxOrder>(symbol));
                eventPlayer.PlaySnapshot(symbol, playedOrders);
            });

            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            promise      = DXEndpoint.Create().Feed.GetIndexedEventsPromise <IDxOrder>(symbol, OrderSource.NTV, cancelSource.Token);
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(promise, eventPlayerTask);
            });

            var receivedOrders = promise.Result;

            receivedOrders.Reverse();
            Assert.AreEqual(playedOrders.Length, receivedOrders.Count);
            for (int i = 0; i < playedOrders.Length; i++)
            {
                Assert.AreEqual(symbol, receivedOrders[i].EventSymbol);
                CompareOrders(playedOrders[i], receivedOrders[i]);
            }

            //thread-safety case
            DXEndpoint.Create();
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                var threadSymbol       = symbol + i.ToString();
                var threadPlayedOrders = new PlayedOrder[] {
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000006, Tools.DateToUnixTime(date), 0, 0, 100, 100, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000005, Tools.DateToUnixTime(date.AddMinutes(-1)), 0, 0, 100.5, 101, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000004, Tools.DateToUnixTime(date.AddMinutes(-2)), 0, 0, 101, 102, 25, Scope.Order, Side.Sell, 'A', OrderSource.NTV, "AAAA"),
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000003, Tools.DateToUnixTime(date.AddMinutes(-3)), 0, 0, 100, 103, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000002, Tools.DateToUnixTime(date.AddMinutes(-4)), 0, 0, 100.4, 104, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000001, Tools.DateToUnixTime(date.AddMinutes(-5)), 0, 0, 100.3, 105, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA"),
                    new PlayedOrder(threadSymbol, 0, 0x4e54560000000000, Tools.DateToUnixTime(date.AddMinutes(-6)), 0, 0, 100.2, 106, 25, Scope.Order, Side.Buy, 'A', OrderSource.NTV, "AAAA")
                };
                tasks.Add(Task.Run(() =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(2));
                    var eventPlayer = new EventPlayer <IDxOrder>(GetSubscriptionFromFeed <IDxOrder>(threadSymbol));
                    eventPlayer.PlaySnapshot(threadSymbol, threadPlayedOrders);
                }));
                var threadPromise = DXEndpoint.GetInstance().Feed
                                    .GetIndexedEventsPromise <IDxOrder>(threadSymbol, OrderSource.NTV, new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token)
                                    .ContinueWith((resultPromise) =>
                {
                    foreach (var o in resultPromise.Result)
                    {
                        Assert.AreEqual(threadSymbol, o.EventSymbol);
                    }
                });
                tasks.Add(threadPromise);
            }
            ;
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(tasks.ToArray());
            });
        }
Пример #28
0
        public void GetTimeSeriesPromiseTest()
        {
            //create default endpoint
            DXEndpoint.Create();
            var symbol = "SYMA";

            //try to create promise with invalid parameters
            Assert.Catch(typeof(ArgumentException), () =>
            {
                try
                {
                    DXFeed.GetInstance().GetTimeSeriesPromise <IDxGreeks>(null, 0, 0, CancellationToken.None).Wait();
                }
                catch (AggregateException ae)
                {
                    foreach (var inner in ae.InnerExceptions)
                    {
                        throw inner;
                    }
                }
            });

            //try to cancel promise
            CancellationTokenSource  cancelSource = new CancellationTokenSource();
            Task <List <IDxGreeks> > promise      = DXFeed.GetInstance().GetTimeSeriesPromise <IDxGreeks>(symbol, 0, 0, cancelSource.Token);

            cancelSource.CancelAfter(TimeSpan.FromSeconds(2));
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try wait promise with timeout
            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
            promise      = DXFeed.GetInstance().GetTimeSeriesPromise <IDxGreeks>(symbol, 0, 0, cancelSource.Token);
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try close endpoint while promise waiting
            Task closeEndpointTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                DXEndpoint.GetInstance().Close();
            });

            promise = DXFeed.GetInstance().GetTimeSeriesPromise <IDxGreeks>(symbol, 0, 0, CancellationToken.None);
            try
            {
                Task.WaitAll(promise, closeEndpointTask);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get promise on closed endpoint
            promise = DXFeed.GetInstance().GetTimeSeriesPromise <IDxGreeks>(symbol, 0, 0, CancellationToken.None);
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get last event succesfully
            DateTime date         = DateTime.Now;
            var      playedGreeks = new PlayedGreeks[] {
                new PlayedGreeks(symbol, 0, 5, Tools.DateToUnixTime(date), 156.789, 111, 155, 166, 177, 188, 199),
                new PlayedGreeks(symbol, 0, 4, Tools.DateToUnixTime(date.AddMinutes(-1)), 256.789, 211, 255, 266, 277, 288, 299),
                new PlayedGreeks(symbol, 0, 3, Tools.DateToUnixTime(date.AddMinutes(-2)), 356.789, 311, 355, 366, 377, 388, 399),
                new PlayedGreeks(symbol, 0, 2, Tools.DateToUnixTime(date.AddMinutes(-3)), 456.789, 411, 455, 466, 477, 488, 499),
                new PlayedGreeks(symbol, 0, 1, Tools.DateToUnixTime(date.AddMinutes(-4)), 556.789, 511, 555, 566, 577, 588, 599),
            };
            var expectedGreeks = new PlayedGreeks[] {
                new PlayedGreeks(symbol, 0, 4, Tools.DateToUnixTime(date.AddMinutes(-1)), 256.789, 211, 255, 266, 277, 288, 299),
                new PlayedGreeks(symbol, 0, 3, Tools.DateToUnixTime(date.AddMinutes(-2)), 356.789, 311, 355, 366, 377, 388, 399),
                new PlayedGreeks(symbol, 0, 2, Tools.DateToUnixTime(date.AddMinutes(-3)), 456.789, 411, 455, 466, 477, 488, 499)
            };
            Task eventPlayerTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                EventPlayer <IDxGreeks> eventPlayer = new EventPlayer <IDxGreeks>(GetSubscriptionFromFeed <IDxGreeks>(symbol));
                eventPlayer.PlaySnapshot(symbol, playedGreeks);
            });

            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            promise      = DXEndpoint.Create().Feed.GetTimeSeriesPromise <IDxGreeks>(symbol, Tools.DateToUnixTime(date.AddMinutes(-3)), Tools.DateToUnixTime(date.AddMinutes(-1)), cancelSource.Token);
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(promise, eventPlayerTask);
            });

            var receivedGreeks = promise.Result;

            receivedGreeks.Reverse();
            Assert.AreEqual(expectedGreeks.Length, receivedGreeks.Count);
            for (int i = 0; i < expectedGreeks.Length; i++)
            {
                Assert.AreEqual(symbol, receivedGreeks[i].EventSymbol.ToString());
                CompareGreeks(expectedGreeks[i], receivedGreeks[i]);
            }

            //thread-safety case
            DXEndpoint.Create();
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                var threadSymbol       = symbol + i.ToString();
                var threadPlayedGreeks = new PlayedGreeks[] {
                    new PlayedGreeks(symbol, 0, 5, Tools.DateToUnixTime(date), 156.789, 111, 155, 166, 177, 188, 199),
                    new PlayedGreeks(symbol, 0, 4, Tools.DateToUnixTime(date.AddMinutes(-1)), 256.789, 211, 255, 266, 277, 288, 299),
                    new PlayedGreeks(symbol, 0, 3, Tools.DateToUnixTime(date.AddMinutes(-2)), 356.789, 311, 355, 366, 377, 388, 399),
                    new PlayedGreeks(symbol, 0, 2, Tools.DateToUnixTime(date.AddMinutes(-3)), 456.789, 411, 455, 466, 477, 488, 499),
                    new PlayedGreeks(symbol, 0, 1, Tools.DateToUnixTime(date.AddMinutes(-4)), 556.789, 511, 555, 566, 577, 588, 599),
                };
                tasks.Add(Task.Run(() =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(2));
                    var eventPlayer = new EventPlayer <IDxGreeks>(GetSubscriptionFromFeed <IDxGreeks>(threadSymbol));
                    eventPlayer.PlaySnapshot(threadSymbol, threadPlayedGreeks);
                }));
                var threadPromise = DXEndpoint.GetInstance().Feed
                                    .GetTimeSeriesPromise <IDxGreeks>(threadSymbol, Tools.DateToUnixTime(date.AddMinutes(-3)), Tools.DateToUnixTime(date.AddMinutes(-1)), new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token)
                                    .ContinueWith((resultPromise) =>
                {
                    foreach (var g in resultPromise.Result)
                    {
                        Assert.AreEqual(threadSymbol, g.EventSymbol);
                    }
                });
                tasks.Add(threadPromise);
            }
            ;
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(tasks.ToArray());
            });
        }
Пример #29
0
        public void GetLastEventPromiseTest()
        {
            //create default endpoint
            DXEndpoint.Create();
            var symbol = "SYMA";

            //try to create promise with invalid parameters
            Assert.Catch(typeof(ArgumentException), () =>
            {
                try
                {
                    DXFeed.GetInstance().GetLastEventPromise <IDxTrade>(null, CancellationToken.None).Wait();
                }
                catch (AggregateException ae)
                {
                    foreach (var inner in ae.InnerExceptions)
                    {
                        throw inner;
                    }
                }
            });

            //try to cancel promise
            CancellationTokenSource cancelSource = new CancellationTokenSource();
            Task <IDxLastingEvent>  promise      = DXFeed.GetInstance().GetLastEventPromise <IDxTrade>(symbol, cancelSource.Token);

            cancelSource.CancelAfter(TimeSpan.FromSeconds(2));
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try wait promise with timeout
            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
            promise      = DXFeed.GetInstance().GetLastEventPromise <IDxTrade>(symbol, cancelSource.Token);
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try close endpoint while promise waiting
            Task closeEndpointTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                DXEndpoint.GetInstance().Close();
            });

            promise = DXFeed.GetInstance().GetLastEventPromise <IDxTrade>(symbol, CancellationToken.None);
            try
            {
                Task.WaitAll(promise, closeEndpointTask);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get promise on closed endpoint
            promise = DXFeed.GetInstance().GetLastEventPromise <IDxTrade>(symbol, CancellationToken.None);
            try
            {
                Task.WaitAll(promise);
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get last event succesfully
            var  playedTrade     = new PlayedTrade(symbol, Tools.DateToUnixTime(DateTime.Now), 0, 0, 'B', 123.456, 100, 123, 1.1, 0, 2.2, 0.0, Direction.Undefined, false, Scope.Regional);
            Task eventPlayerTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                EventPlayer <IDxTrade> eventPlayer = new EventPlayer <IDxTrade>(GetSubscriptionFromFeed <IDxTrade>(symbol));
                eventPlayer.PlayEvents(symbol, playedTrade);
            });

            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            promise      = DXEndpoint.Create().Feed.GetLastEventPromise <IDxTrade>(symbol, cancelSource.Token);
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(promise, eventPlayerTask);
            });

            IDxTrade lastTrade = promise.Result as IDxTrade;

            Assert.AreEqual(symbol, lastTrade.EventSymbol);
            CompareTrades(playedTrade, lastTrade);

            //thread-safety case
            DXEndpoint.Create();
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                var threadSymbol      = symbol + i.ToString();
                var threadPlayedTrade = new PlayedTrade(threadSymbol, Tools.DateToUnixTime(DateTime.Now), 0, 0, 'B', 123.456, 100, 123, 1.1, 0, 2.2, 0.0, Direction.Undefined, false, Scope.Regional);
                tasks.Add(Task.Run(() =>
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    var eventPlayer = new EventPlayer <IDxTrade>(GetSubscriptionFromFeed <IDxTrade>(threadSymbol));
                    eventPlayer.PlayEvents(threadSymbol, threadPlayedTrade);
                }));
                var threadPromise = DXEndpoint.GetInstance().Feed
                                    .GetLastEventPromise <IDxTrade>(threadSymbol, new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token)
                                    .ContinueWith((resultPromise) =>
                {
                    IDxTrade threadTrade = resultPromise.Result as IDxTrade;
                    Assert.AreEqual(threadSymbol, threadTrade.EventSymbol);
                });
                tasks.Add(threadPromise);
            }
            ;
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(tasks.ToArray());
            });
        }
Пример #30
0
        public void GetLastEventsPromisesTest()
        {
            //create default endpoint
            DXEndpoint.Create();
            var symbols = new string[] { "SYMA", "SYMB" };

            //try to create promise with invalid parameters
            Assert.Catch(typeof(ArgumentException), () =>
            {
                try
                {
                    Task.WaitAll(DXFeed.GetInstance().GetLastEventsPromises <IDxTrade>(null, CancellationToken.None).ToArray());
                }
                catch (AggregateException ae)
                {
                    foreach (var inner in ae.InnerExceptions)
                    {
                        throw inner;
                    }
                }
            });
            Assert.Catch(typeof(ArgumentException), () =>
            {
                try
                {
                    Task.WaitAll(DXFeed.GetInstance().GetLastEventsPromises <IDxTrade>(new object[] { null }, CancellationToken.None).ToArray());
                }
                catch (AggregateException ae)
                {
                    foreach (var inner in ae.InnerExceptions)
                    {
                        throw inner;
                    }
                }
            });

            //try to cancel promise
            CancellationTokenSource        cancelSource = new CancellationTokenSource();
            List <Task <IDxLastingEvent> > promises     = DXFeed.GetInstance().GetLastEventsPromises <IDxTrade>(symbols, cancelSource.Token);

            cancelSource.CancelAfter(TimeSpan.FromSeconds(2));
            try
            {
                Task.WaitAll(promises.ToArray());
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }


            //try wait promise with timeout
            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
            promises     = DXFeed.GetInstance().GetLastEventsPromises <IDxTrade>(symbols, cancelSource.Token);
            try
            {
                Task.WaitAll(promises.ToArray());
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try close endpoint while promise waiting
            Task closeEndpointTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                DXEndpoint.GetInstance().Close();
            });

            promises = DXFeed.GetInstance().GetLastEventsPromises <IDxTrade>(symbols, CancellationToken.None);
            List <Task> allTasks = new List <Task>();

            foreach (var p in promises)
            {
                allTasks.Add(p);
            }
            allTasks.Add(closeEndpointTask);
            try
            {
                Task.WaitAll(allTasks.ToArray());
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get promise on closed endpoint
            promises = DXFeed.GetInstance().GetLastEventsPromises <IDxTrade>(symbols, CancellationToken.None);
            try
            {
                Task.WaitAll(promises.ToArray());
            }
            catch (AggregateException ae)
            {
                foreach (var inner in ae.InnerExceptions)
                {
                    if (!(inner is OperationCanceledException))
                    {
                        Assert.Fail("Unexpected exception: " + inner);
                    }
                }
            }

            //try to get last event succesfully
            var playedTrades = new PlayedTrade[] {
                new PlayedTrade(symbols[0], Tools.DateToUnixTime(DateTime.Now), 0, 0, 'B', 123.456, 100, 123, 1.1, 0, 2.2, 0.0, Direction.Undefined, false, Scope.Regional),
                new PlayedTrade(symbols[1], Tools.DateToUnixTime(DateTime.Now), 0, 0, 'B', 234.567, 101, 234, 3.2, 0, 4.3, 0.0, Direction.Undefined, false, Scope.Regional)
            };
            Task eventPlayerTask = Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                foreach (var t in playedTrades)
                {
                    EventPlayer <IDxTrade> eventPlayer = new EventPlayer <IDxTrade>(GetSubscriptionFromFeed <IDxTrade>(t.EventSymbol));
                    eventPlayer.PlayEvents(t.EventSymbol, t);
                }
            });

            cancelSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            promises     = DXEndpoint.Create().Feed.GetLastEventsPromises <IDxTrade>(symbols, cancelSource.Token);
            allTasks     = new List <Task>();
            foreach (var p in promises)
            {
                allTasks.Add(p);
            }
            allTasks.Add(eventPlayerTask);
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(allTasks.ToArray());
            });

            Dictionary <string, PlayedTrade> playedTradeDictionary = new Dictionary <string, PlayedTrade>();

            foreach (var t in playedTrades)
            {
                playedTradeDictionary[t.EventSymbol] = t;
            }
            foreach (var p in promises)
            {
                IDxTrade lastTrade = p.Result as IDxTrade;
                Assert.True(playedTradeDictionary.ContainsKey(lastTrade.EventSymbol));
                var playedTrade = playedTradeDictionary[lastTrade.EventSymbol];
                playedTradeDictionary.Remove(lastTrade.EventSymbol);
                CompareTrades(playedTrade, lastTrade);
            }

            //thread-safety case
            DXEndpoint.Create();
            List <Task> threadTasks = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                var threadSymbols      = new string[] { symbols[0] + i.ToString(), symbols[1] + i.ToString() };
                var threadPlayedTrades = new PlayedTrade[] {
                    new PlayedTrade(threadSymbols[0], Tools.DateToUnixTime(DateTime.Now), 0, 0, 'B', 123.456, 100, 123, 1.1, 0, 2.2, 0.0, Direction.Undefined, false, Scope.Regional),
                    new PlayedTrade(threadSymbols[1], Tools.DateToUnixTime(DateTime.Now), 0, 0, 'B', 234.567, 101, 234, 3.2, 0, 4.3, 0.0, Direction.Undefined, false, Scope.Regional)
                };
                HashSet <string> threadPlayedSymbols = new HashSet <string>();
                foreach (var t in threadPlayedTrades)
                {
                    threadTasks.Add(Task.Run(() =>
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(2));
                        var eventPlayer = new EventPlayer <IDxTrade>(GetSubscriptionFromFeed <IDxTrade>(t.EventSymbol));
                        eventPlayer.PlayEvents(t.EventSymbol, t);
                    }));
                    threadPlayedSymbols.Add(t.EventSymbol);
                }
                foreach (var p in DXEndpoint.GetInstance().Feed.GetLastEventsPromises <IDxTrade>(threadSymbols, new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token))
                {
                    threadTasks.Add(p.ContinueWith((resultPromise) =>
                    {
                        IDxTrade threadTrade = resultPromise.Result as IDxTrade;
                        Assert.True(threadPlayedSymbols.Remove(threadTrade.EventSymbol));
                    }));
                }
            }
            ;
            Assert.DoesNotThrow(() =>
            {
                Task.WaitAll(threadTasks.ToArray());
            });
        }