private static void Display(AggregateTrade trade)
        {
            lock (_sync)
            {
                _trades[trade.Symbol] = trade;

                if (_displayTask.IsCompleted)
                {
                    // Delay to allow multiple data updates between display updates.
                    _displayTask = Task.Delay(100)
                                   .ContinueWith(_ =>
                    {
                        AggregateTrade[] latestsTrades;
                        lock (_sync)
                        {
                            latestsTrades = _trades.Values.ToArray();
                        }

                        Console.SetCursorPosition(0, 0);

                        foreach (var t in latestsTrades)
                        {
                            Console.WriteLine($" {t.Time.ToLocalTime()} - {t.Symbol.PadLeft(8)} - {(t.IsBuyerMaker ? "Sell" : "Buy").PadLeft(4)} - {t.Quantity:0.00000000} @ {t.Price:0.00000000}{(t.IsBestPriceMatch ? "*" : " ")} - [ID: {t.Id}] - {t.Time.ToTimestamp()}".PadRight(119));
                            Console.WriteLine();
                        }

                        Console.WriteLine(_message);
                    });
                }
            }
        }
Example #2
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="time">The event time.</param>
        /// <param name="trade">The aggregate trade.</param>
        public AggregateTradeEventArgs(DateTime time, AggregateTrade trade)
            : base(time)
        {
            Throw.IfNull(trade, nameof(trade));

            Trade = trade;
        }
Example #3
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="time">The event time.</param>
        /// <param name="token">The cancellation token.</param>
        /// <param name="trade">The aggregate trade.</param>
        public AggregateTradeEventArgs(DateTime time, CancellationToken token, AggregateTrade trade)
            : base(time, token)
        {
            Throw.IfNull(trade, nameof(trade));

            Trade = trade;
        }
Example #4
0
        public void Serialization()
        {
            var           symbol           = Symbol.BTC_USDT;
            const long    id               = 12345;
            const decimal price            = 5000;
            const decimal quantity         = 1;
            var           timestamp        = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            const long    firstTradeId     = 123456;
            const long    lastTradeId      = 234567;
            const bool    isBuyerMaker     = true;
            const bool    isBestPriceMatch = true;

            var trade = new AggregateTrade(symbol, id, price, quantity, firstTradeId, lastTradeId, timestamp, isBuyerMaker, isBestPriceMatch);

            var json = JsonConvert.SerializeObject(trade);

            trade = JsonConvert.DeserializeObject <AggregateTrade>(json);

            Assert.Equal(symbol, trade.Symbol);
            Assert.Equal(id, trade.Id);
            Assert.Equal(price, trade.Price);
            Assert.Equal(quantity, trade.Quantity);
            Assert.Equal(firstTradeId, trade.FirstTradeId);
            Assert.Equal(lastTradeId, trade.LastTradeId);
            Assert.Equal(timestamp, trade.Timestamp);
            Assert.Equal(isBuyerMaker, trade.IsBuyerMaker);
            Assert.Equal(isBestPriceMatch, trade.IsBestPriceMatch);
        }
Example #5
0
 internal static void Display(AggregateTrade trade)
 {
     lock (ConsoleSync)
     {
         Console.WriteLine($"  {trade.Time.ToLocalTime()} - {trade.Symbol.PadLeft(8)} - {(trade.IsBuyerMaker ? "Sell" : "Buy").PadLeft(4)} - {trade.Quantity:0.00000000} @ {trade.Price:0.00000000}{(trade.IsBestPriceMatch ? "*" : " ")} - [ID: {trade.Id}] - {trade.Time.ToTimestamp()}");
     }
 }
Example #6
0
        /// <summary>
        /// Deserialize JSON and raise <see cref="AggregateTradeEventArgs"/> event.
        /// </summary>
        /// <param name="json"></param>
        /// <param name="symbol"></param>
        /// <param name="token"></param>
        /// <param name="callback"></param>
        protected override void DeserializeJsonAndRaiseEvent(string json, Symbol symbol, CancellationToken token,
                                                             Action <AggregateTradeEventArgs> callback = null)
        {
            Throw.IfNullOrWhiteSpace(json, nameof(json));

            Logger?.LogDebug($"{nameof(AggregateTradeWebSocketClient)}: \"{json}\"");

            try
            {
                var jObject = JObject.Parse(json);

                var eventType = jObject["e"].Value <string>();

                if (eventType == "aggTrade")
                {
                    var eventTime = jObject["E"].Value <long>();

                    var trade = new AggregateTrade(
                        jObject["s"].Value <string>(),  // symbol
                        jObject["a"].Value <long>(),    // aggregate trade ID
                        jObject["p"].Value <decimal>(), // price
                        jObject["q"].Value <decimal>(), // quantity
                        jObject["f"].Value <long>(),    // first trade ID
                        jObject["l"].Value <long>(),    // last trade ID
                        jObject["T"].Value <long>(),    // trade time (timestamp)
                        jObject["m"].Value <bool>(),    // is buyer the market maker?
                        jObject["M"].Value <bool>());   // is best price match?

                    var eventArgs = new AggregateTradeEventArgs(eventTime, token, trade);

                    try
                    {
                        callback?.Invoke(eventArgs);
                        AggregateTrade?.Invoke(this, eventArgs);
                    }
                    catch (OperationCanceledException) { }
                    catch (Exception e)
                    {
                        if (!token.IsCancellationRequested)
                        {
                            Logger?.LogError(e, $"{nameof(AggregateTradeWebSocketClient)}: Unhandled aggregate trade event handler exception.");
                        }
                    }
                }
                else
                {
                    Logger?.LogWarning($"{nameof(AggregateTradeWebSocketClient)}.{nameof(DeserializeJsonAndRaiseEvent)}: Unexpected event type ({eventType}).");
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception e)
            {
                if (!token.IsCancellationRequested)
                {
                    Logger?.LogError(e, $"{nameof(AggregateTradeWebSocketClient)}.{nameof(DeserializeJsonAndRaiseEvent)}");
                }
            }
        }
Example #7
0
        protected override Task HandleMessageAsync(IEnumerable <Action <AggregateTradeEventArgs> > callbacks, string stream, string json, CancellationToken token = default)
        {
            try
            {
                var jObject = JObject.Parse(json);

                var eventType = jObject["e"].Value <string>();

                if (eventType == "aggTrade")
                {
                    var eventTime = jObject["E"].Value <long>().ToDateTime();

                    var trade = new AggregateTrade(
                        jObject["s"].Value <string>(),  // symbol
                        jObject["a"].Value <long>(),    // aggregate trade ID
                        jObject["p"].Value <decimal>(), // price
                        jObject["q"].Value <decimal>(), // quantity
                        jObject["f"].Value <long>(),    // first trade ID
                        jObject["l"].Value <long>(),    // last trade ID
                        jObject["T"].Value <long>()     // trade time
                        .ToDateTime(),
                        jObject["m"].Value <bool>(),    // is buyer the market maker?
                        jObject["M"].Value <bool>());   // is best price match?

                    var eventArgs = new AggregateTradeEventArgs(eventTime, token, trade);

                    try
                    {
                        if (callbacks != null)
                        {
                            foreach (var callback in callbacks)
                            {
                                callback(eventArgs);
                            }
                        }

                        AggregateTrade?.Invoke(this, eventArgs);
                    }
                    catch (OperationCanceledException) { /* ignore */ }
                    catch (Exception e)
                    {
                        Logger?.LogWarning(e, $"{nameof(AggregateTradeClient)}: Unhandled aggregate trade event handler exception.  [thread: {Thread.CurrentThread.ManagedThreadId}]");
                    }
                }
                else
                {
                    Logger?.LogWarning($"{nameof(AggregateTradeClient)}.{nameof(HandleMessageAsync)}: Unexpected event type ({eventType}).  [thread: {Thread.CurrentThread.ManagedThreadId}]");
                }
            }
            catch (OperationCanceledException) { /* ignore */ }
            catch (Exception e)
            {
                Logger?.LogError(e, $"{nameof(AggregateTradeClient)}.{nameof(HandleMessageAsync)}: Failed.  [thread: {Thread.CurrentThread.ManagedThreadId}]");
            }

            return(Task.CompletedTask);
        }
 private decimal getPercentagePriceIncrease()
 {
     if (this.aggregateTrades.Count() > 0)
     {
         AggregateTrade mostRecentTrade = this.aggregateTrades.First();
         AggregateTrade oldestTrade     = this.aggregateTrades.Last();
         return((mostRecentTrade.price - oldestTrade.price) / oldestTrade.price);
     }
     return(0);
 }
Example #9
0
        //static void Main(String[] args)
        //{
        //    var binanceClient = new BinanceClient(new ApiClient("test", "test"));
        //    IList<string> symbolList = new List<string>(); symbolList.Add("XRPETH"); /*symbolList.Add("TRXETH"); symbolList.Add("MANAETH"); symbolList.Add("XVGETH");*/
        //    int timeBetweenTradeCheck = 5000;
        //    bool match = false;

        //    var initialPercentageIncreaseThreshold = roundDecimal(-.02m);
        //    /* Initial Currency Finding Config*/
        //    int tradeIntervalInMinutes = 3;

        //    while (true)
        //    {
        //        while (!match)
        //        {
        //            foreach (var symbol in symbolList)
        //            {
        //                var trades = getAggTrades(binanceClient, symbol, tradeIntervalInMinutes).Result; // Oldest trade is first

        //                var perInc = getPercentagePriceIncrease(trades.Last().Price, trades.First().Price);
        //                if (perInc >= initialPercentageIncreaseThreshold)
        //                {
        //                    Console.WriteLine($"Match found for {symbol} - {perInc}, starting socket...");
        //                    binanceClient.ListenTradeEndpoint(symbol.ToLower(), AggregateTradesHandler);
        //                    match = true;
        //                }
        //            }

        //            Thread.Sleep(timeBetweenTradeCheck);
        //        }
        //        Console.ReadKey(true);
        //    }
        //}

        //static async Task<IEnumerable<AggregateTrade>> getAggTrades(BinanceClient bClient, string symbol, int tradeInterval)
        //{
        //    long endTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        //    long startTime = DateTimeOffset.Now.AddMinutes(-tradeInterval).ToUnixTimeMilliseconds();
        //    var trades = await bClient.GetAggregateTrades(symbol, 200);
        //    return trades;
        //}

        //static decimal getPercentagePriceIncrease(decimal newestTrade, decimal oldestTrade)
        //{
        //    return roundDecimal((newestTrade - oldestTrade) / oldestTrade);
        //}

        //static decimal roundDecimal(decimal number)
        //{
        //    return Math.Round(number, 8);
        //}

        //private static void AggregateTradesHandler(AggregateTradeMessage data)
        //{
        //    Console.WriteLine(data.Price);
        //}

        public static decimal getPercentagePriceIncrease(IList <AggregateTrade> trades)
        {
            if (trades.Count() > 0)
            {
                AggregateTrade mostRecentTrade = trades.First();
                AggregateTrade oldestTrade     = trades.Last();
                return((mostRecentTrade.price - oldestTrade.price) / oldestTrade.price);
            }
            return(0);
        }
Example #10
0
 private Interface.Model.AggregateTrade NewAggregateTrade(AggregateTrade at)
 {
     return(new Interface.Model.AggregateTrade
     {
         Symbol = at.Symbol,
         Id = at.Id,
         Price = at.Price,
         Quantity = at.Quantity,
         Time = at.Time,
         IsBuyerMaker = at.IsBuyerMaker,
         IsBestPriceMatch = at.IsBestPriceMatch,
         FirstTradeId = at.FirstTradeId,
         LastTradeId = at.LastTradeId
     });
 }
Example #11
0
 private static Core.Model.AggregateTrade NewAggregateTrade(AggregateTrade at)
 {
     return(new Core.Model.AggregateTrade
     {
         Symbol = at.Symbol,
         Exchange = Exchange.Binance,
         Id = at.Id,
         Price = at.Price,
         Quantity = at.Quantity,
         Time = at.Time,
         IsBuyerMaker = at.IsBuyerMaker,
         IsBestPriceMatch = at.IsBestPriceMatch,
         FirstTradeId = at.FirstTradeId,
         LastTradeId = at.LastTradeId
     });
 }
        public virtual string Serialize(AggregateTrade trade)
        {
            var jObject = new JObject
            {
                new JProperty(Key_Symbol, trade.Symbol),
                new JProperty(Key_Id, trade.Id),
                new JProperty(Key_Price, trade.Price.ToString(CultureInfo.InvariantCulture)),
                new JProperty(Key_Quantity, trade.Quantity.ToString(CultureInfo.InvariantCulture)),
                new JProperty(Key_FirstTradeId, trade.FirstTradeId),
                new JProperty(Key_LastTradeId, trade.LastTradeId),
                new JProperty(Key_Time, trade.Timestamp),
                new JProperty(Key_IsBuyerMaker, trade.IsBuyerMaker),
                new JProperty(Key_IsBestPriceMatch, trade.IsBestPriceMatch)
            };

            return(jObject.ToString(Formatting.None));
        }
        public virtual string Serialize(AggregateTrade trade)
        {
            Throw.IfNull(trade, nameof(trade));

            var jObject = new JObject
            {
                new JProperty(KeySymbol, trade.Symbol),
                new JProperty(KeyId, trade.Id),
                new JProperty(KeyPrice, trade.Price.ToString(CultureInfo.InvariantCulture)),
                new JProperty(KeyQuantity, trade.Quantity.ToString(CultureInfo.InvariantCulture)),
                new JProperty(KeyFirstTradeId, trade.FirstTradeId),
                new JProperty(KeyLastTradeId, trade.LastTradeId),
                new JProperty(KeyTime, trade.Time.ToTimestamp()),
                new JProperty(KeyIsBuyerMaker, trade.IsBuyerMaker),
                new JProperty(KeyIsBestPriceMatch, trade.IsBestPriceMatch)
            };

            return(jObject.ToString(Formatting.None));
        }
Example #14
0
        public void Throws()
        {
            var time = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;

            var           symbol           = Symbol.BTC_USDT;
            const long    id               = 12345;
            const decimal price            = 5000;
            const decimal quantity         = 1;
            const long    firstTradeId     = 123456;
            const long    lastTradeId      = 234567;
            const bool    isBuyerMaker     = true;
            const bool    isBestPriceMatch = true;

            var trade = new AggregateTrade(symbol, id, price, quantity, firstTradeId, lastTradeId, time, isBuyerMaker, isBestPriceMatch);

            using (var cts = new CancellationTokenSource())
            {
                Assert.Throws <ArgumentNullException>("trade", () => new AggregateTradeEventArgs(time, cts.Token, null));
            }
        }
Example #15
0
        public void Properties()
        {
            var time = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;

            var           symbol           = Symbol.BTC_USDT;
            const long    id               = 12345;
            const decimal price            = 5000;
            const decimal quantity         = 1;
            const long    firstTradeId     = 123456;
            const long    lastTradeId      = 234567;
            const bool    isBuyerMaker     = true;
            const bool    isBestPriceMatch = true;

            var trade = new AggregateTrade(symbol, id, price, quantity, firstTradeId, lastTradeId, time, isBuyerMaker, isBestPriceMatch);

            var args = new AggregateTradeEventArgs(time, trade);

            Assert.Equal(time, args.Time);
            Assert.Equal(trade, args.Trade);
        }
Example #16
0
        public void Equality()
        {
            var           symbol           = Symbol.BTC_USDT;
            const long    id               = 12345;
            const decimal price            = 5000;
            const decimal quantity         = 1;
            var           timestamp        = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            const long    firstTradeId     = 123456;
            const long    lastTradeId      = 234567;
            const bool    isBuyerMaker     = true;
            const bool    isBestPriceMatch = true;

            var trade = new AggregateTrade(symbol, id, price, quantity, firstTradeId, lastTradeId, timestamp, isBuyerMaker, isBestPriceMatch);

            var serializer = new AggregateTradeSerializer();

            var json = serializer.Serialize(trade);

            var other = serializer.Deserialize(json);

            Assert.True(trade.Equals(other));
        }
        public void Properties()
        {
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            var           symbol           = Symbol.BTC_USDT;
            const long    id               = 12345;
            const decimal price            = 5000;
            const decimal quantity         = 1;
            const long    firstTradeId     = 123456;
            const long    lastTradeId      = 234567;
            const bool    isBuyerMaker     = true;
            const bool    isBestPriceMatch = true;

            var trade = new AggregateTrade(symbol, id, price, quantity, firstTradeId, lastTradeId, timestamp, isBuyerMaker, isBestPriceMatch);

            using (var cts = new CancellationTokenSource())
            {
                var args = new AggregateTradeEventArgs(timestamp, cts.Token, trade);

                Assert.Equal(timestamp, args.Timestamp);
                Assert.Equal(trade, args.Trade);
            }
        }
Example #18
0
        public void Properties()
        {
            var           symbol           = Symbol.BTC_USDT;
            const long    id               = 12345;
            const decimal price            = 5000;
            const decimal quantity         = 1;
            var           time             = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;
            const long    firstTradeId     = 123456;
            const long    lastTradeId      = 234567;
            const bool    isBuyerMaker     = true;
            const bool    isBestPriceMatch = true;

            var trade = new AggregateTrade(symbol, id, price, quantity, firstTradeId, lastTradeId, time, isBuyerMaker, isBestPriceMatch);

            Assert.Equal(symbol, trade.Symbol);
            Assert.Equal(id, trade.Id);
            Assert.Equal(price, trade.Price);
            Assert.Equal(quantity, trade.Quantity);
            Assert.Equal(firstTradeId, trade.FirstTradeId);
            Assert.Equal(lastTradeId, trade.LastTradeId);
            Assert.Equal(time, trade.Time);
            Assert.Equal(isBuyerMaker, trade.IsBuyerMaker);
            Assert.Equal(isBestPriceMatch, trade.IsBestPriceMatch);
        }
        /// <summary>
        /// Get the most recent trades from trade (EXCLUSIVE).
        /// </summary>
        /// <param name="api"></param>
        /// <param name="trade"></param>
        /// <param name="limit"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Task <IEnumerable <AggregateTrade> > GetAggregateTradesAsync(this IBinanceApi api, AggregateTrade trade, int limit = default, CancellationToken token = default)
        {
            Throw.IfNull(api, nameof(api));
            Throw.IfNull(trade, nameof(trade));

            return(api.GetAggregateTradesFromAsync(trade.Symbol, trade.Id + 1, limit, token));
        }
Example #20
0
        protected override void OnWebSocketEvent(WebSocketStreamEventArgs args, IEnumerable <Action <AggregateTradeEventArgs> > callbacks)
        {
            Logger?.LogDebug($"{nameof(AggregateTradeWebSocketClient)}: \"{args.Json}\"");

            try
            {
                var jObject = JObject.Parse(args.Json);

                var eventType = jObject["e"].Value <string>();

                if (eventType == "aggTrade")
                {
                    var eventTime = jObject["E"].Value <long>();

                    var trade = new AggregateTrade(
                        jObject["s"].Value <string>(),  // symbol
                        jObject["a"].Value <long>(),    // aggregate trade ID
                        jObject["p"].Value <decimal>(), // price
                        jObject["q"].Value <decimal>(), // quantity
                        jObject["f"].Value <long>(),    // first trade ID
                        jObject["l"].Value <long>(),    // last trade ID
                        jObject["T"].Value <long>(),    // trade time (timestamp)
                        jObject["m"].Value <bool>(),    // is buyer the market maker?
                        jObject["M"].Value <bool>());   // is best price match?

                    var eventArgs = new AggregateTradeEventArgs(eventTime, args.Token, trade);

                    try
                    {
                        if (callbacks != null)
                        {
                            foreach (var callback in callbacks)
                            {
                                callback(eventArgs);
                            }
                        }
                        AggregateTrade?.Invoke(this, eventArgs);
                    }
                    catch (OperationCanceledException) { }
                    catch (Exception e)
                    {
                        if (!args.Token.IsCancellationRequested)
                        {
                            Logger?.LogError(e, $"{nameof(AggregateTradeWebSocketClient)}: Unhandled aggregate trade event handler exception.");
                        }
                    }
                }
                else
                {
                    Logger?.LogWarning($"{nameof(AggregateTradeWebSocketClient)}.{nameof(OnWebSocketEvent)}: Unexpected event type ({eventType}).");
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception e)
            {
                if (!args.Token.IsCancellationRequested)
                {
                    Logger?.LogError(e, $"{nameof(AggregateTradeWebSocketClient)}.{nameof(OnWebSocketEvent)}");
                }
            }
        }
Example #21
0
        static void Main(string[] args)
        {
            int     timeBetweenTradeCheck                = 15000;
            int     tradeIntervalInMinutes               = 3;
            decimal initialPercentageIncreaseThreshold   = Convert.ToDecimal(.025);
            decimal secondaryPercentageIncreaseThreshold = Convert.ToDecimal(.001);
            decimal sellPriceFallThreshold               = Convert.ToDecimal(.038);
            decimal maxPercentDecreaseDuringBuying       = Convert.ToDecimal(.025);
            int     tradeStorageInterval           = 50;
            IList <AggregateTrade> aggregateTrades = new List <AggregateTrade>();
            decimal        sellPrice     = Convert.ToDecimal(0);
            IList <string> symbolList    = new List <string>(); symbolList.Add("XRPETH"); symbolList.Add("TRXETH"); symbolList.Add("MANAETH"); symbolList.Add("XVGETH");
            bool           match         = false;
            decimal        wallet        = Convert.ToDecimal(.25);
            decimal        percentMarkup = Convert.ToDecimal(.003);

            WebSocket buyingTradesSocket = new WebSocket("wss://stream.binance.com:9443/ws/ethbtc@depth");

            WebSocket sellingTradesSocket = new WebSocket("wss://stream.binance.com:9443/ws/ethbtc@depth");



            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("https://api.binance.com/api/v1/aggTrades");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            IList <AggregateTrade> trades = new List <AggregateTrade>();
            decimal percentageIncrease    = 0;

            while (true)
            {
                while (!match)
                {
                    long currentTime  = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                    long intervalTime = DateTimeOffset.Now.AddMinutes(-tradeIntervalInMinutes).ToUnixTimeMilliseconds(); // 2 minute time intervals
                    foreach (string symbol in symbolList)
                    {
                        HttpResponseMessage response = client.GetAsync("?symbol=" + symbol + "&startTime=" + intervalTime + "&endTime=" + currentTime).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            aggregateTrades.Clear(); // Clear previous failed buys / sells
                            trades = JsonConvert.DeserializeObject <List <AggregateTrade> >(response.Content.ReadAsStringAsync().Result);
                            trades.Reverse();        // Newest trade comes last from the API
                            percentageIncrease = getPercentagePriceIncrease(trades);
                            if (percentageIncrease > initialPercentageIncreaseThreshold)
                            {
                                Console.WriteLine($"Found match for {symbol}. Newest Trade: {trades.First().price} at quantity {trades.First().quantity} Oldest Trade {trades.Last().price} at quantity {trades.Last().quantity}, starting socket");
                                /***********LOOKING TO START BUYING HERE*******************/
                                sellingTradesSocket            = new WebSocket("wss://stream.binance.com:9443/ws/" + symbol.ToLower() + "@aggTrade");
                                sellingTradesSocket.Log.Output = (_, __) => { };
                                sellingTradesSocket.OnMessage += (sender, e) =>
                                {
                                    //if (aggregateTrades.Count() == tradeStorageInterval)
                                    //    aggregateTrades.Remove(aggregateTrades.Last());
                                    aggregateTrades.Insert(0, JsonConvert.DeserializeObject <AggregateTrade>(e.Data)); // Most recent data is positioned first

                                    decimal percentageIncreaseSingleCurrency = getPercentagePriceIncrease(aggregateTrades);
                                    Console.WriteLine($"Percentage Increase for {symbol}: {percentageIncreaseSingleCurrency}");
                                    if (percentageIncreaseSingleCurrency > secondaryPercentageIncreaseThreshold)
                                    {
                                        IList <decimal> purchaseInfo = makePurchase(wallet, percentMarkup, aggregateTrades);
                                        sellPrice = purchaseInfo.ElementAt(0);
                                        decimal buyPrice = purchaseInfo.ElementAt(1);
                                        Console.WriteLine($"Successfully Bought. Selling Price: {sellPrice}");
                                        sellingTradesSocket.Close();
                                        /*****************LOOKING TO START SELLING HERE *********************/
                                        buyingTradesSocket            = new WebSocket(sellingTradesSocket.Url.ToString());
                                        buyingTradesSocket.Log.Output = (_, __) => { };
                                        buyingTradesSocket.OnMessage += (senderr, ee) =>
                                        {
                                            AggregateTrade trade = JsonConvert.DeserializeObject <AggregateTrade>(ee.Data);
                                            if (trade.price >= sellPrice)
                                            {
                                                wallet += (wallet * percentMarkup);
                                                Console.WriteLine($"SOLD! Wallet balance is now {wallet}");
                                                match = false;
                                                buyingTradesSocket.Close();
                                            }
                                            var pricePercentage = (trade.price - buyPrice) / trade.price;
                                            if (pricePercentage < -sellPriceFallThreshold) // Sell failed, abondon
                                            {
                                                wallet -= (wallet * sellPriceFallThreshold);
                                                Console.WriteLine($"Price fell too low to: {trade.price} - PANIC SELLING! New wallet balance {wallet}");
                                                match = false;
                                                buyingTradesSocket.Close();
                                            }
                                        };
                                        buyingTradesSocket.Connect();
                                    }
                                    else if (percentageIncreaseSingleCurrency < -maxPercentDecreaseDuringBuying)
                                    {
                                        Console.WriteLine($"{symbol} fell below the threshold {maxPercentDecreaseDuringBuying} during buying phase at {percentageIncreaseSingleCurrency} - ABONDON!");
                                        sellingTradesSocket.Close();
                                        match = false;
                                    }
                                };
                                sellingTradesSocket.Connect();
                                match = true;
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                        }
                    }
                    Thread.Sleep(timeBetweenTradeCheck);
                }
            }


            //    //var ws = new WebSocket("wss://stream.binance.com:9443/ws/xrpeth@aggTrade");
            //    //IList<AggregateTrade> xrpTradeInfo = new List<AggregateTrade>();
            //    //decimal xrpPricePercentageIncreaseThreshold = Convert.ToDecimal(.008);
            //    //decimal wallet = Convert.ToDecimal(.25);
            //    //decimal percentMarkup = Convert.ToDecimal(.001);
            //    //decimal sellPrice = 1;
            //    //ws.OnMessage += (sender, e) =>
            //    //{
            //    //    if (xrpTradeInfo.Count() == 50) // Only store last 100 trades
            //    //        xrpTradeInfo.Remove(xrpTradeInfo.Last());
            //    //    xrpTradeInfo.Insert(0, JsonConvert.DeserializeObject<AggregateTrade>(e.Data)); // Most recent data is positioned first
            //    //    if (getPercentagePriceIncrease(xrpTradeInfo) > xrpPricePercentageIncreaseThreshold)
            //    //    {
            //    //       sellPrice = makePurchase(wallet, percentMarkup, xrpTradeInfo, ws);
            //    //    }

            //    //};
            //    //ws.ConnectAsync();


            //    //while(sellPrice == 1)
            //    //{

            //    //}
            //    //ws.CloseAsync();
            //    //var ws1 = new WebSocket("wss://stream.binance.com:9443/ws/xrpeth@aggTrade");
            //    //Console.WriteLine("Looking for purchase...");
            //    //ws1.OnMessage += (sender, e) =>
            //    //{
            //    //    Console.WriteLine("Looking for buyer");
            //    //    AggregateTrade trade = JsonConvert.DeserializeObject<AggregateTrade>(e.Data);
            //    //    if (trade.price >= sellPrice)
            //    //    {
            //    //        Console.WriteLine("SOLD!");
            //    //        ws1.CloseAsync();
            //    //    }
            //    //};
            //    //ws1.ConnectAsync();

            //    //var ws2 = new WebSocket("wss://stream.binance.com:9443/ws/mtheth@aggTrade");
            //    //IList<AggregateTrade> mthTradeInfo = new List<AggregateTrade>();
            //    //decimal mthPricePercentageIncreaseThreshold = Convert.ToDecimal(.02);
            //    //ws.OnMessage += (sender, e) =>
            //    //{
            //    //    Console.WriteLine("In MTH");
            //    //    if (xrpTradeInfo.Count() == 10) // Only store last 100 trades
            //    //        xrpTradeInfo.Remove(xrpTradeInfo.Last());

            //    //    mthTradeInfo.Insert(0, JsonConvert.DeserializeObject<AggregateTrade>(e.Data)); // Most recent data is positioned first

            //    //    if (getPercentagePriceIncrease(mthTradeInfo) > mthPricePercentageIncreaseThreshold)
            //    //    {
            //    //        Console.WriteLine("BUYING MTH");
            //    //    }

            //    //};
            //    //ws2.ConnectAsync();



            //    //Console.WriteLine($"Buying at {mostRecentTrade.price}");
            //    //decimal sellPrice = mostRecentTrade.price + (mostRecentTrade.price * Convert.ToDecimal(.01));
            //    //Console.WriteLine($"Attempting to sell at {sellPrice}");

            //    //while(mostRecentTrade.price < sellPrice)
            //    //{
            //    //    HttpResponseMessage response = client.GetAsync("?symbol=ETHBTC&limit=100").Result;
            //    //    if (response.IsSuccessStatusCode)
            //    //    {
            //    //        trades = JsonConvert.DeserializeObject<List<AggregateTrade>>(response.Content.ReadAsStringAsync().Result);
            //    //        mostRecentTrade = trades.Last();
            //    //        Console.WriteLine($"Most recent trade price: {mostRecentTrade.price}, Looking for {sellPrice}");
            //    //    }
            //    //    else
            //    //    {
            //    //        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            //    //    }
            //    //    Thread.Sleep(2000);
            //    //}
            //}
        }