private static async Task connectAndAuthenticate(
            PolygonSockClient client)
        {
            var waitObject = new AutoResetEvent(false);

            client.Connected += (status) =>
            {
                Assert.Equal(AuthStatus.Authorized, status);
                waitObject.Set();
            };

            await client.ConnectAsync();

            Assert.True(waitObject.WaitOne(
                            TimeSpan.FromSeconds(10)));
        }
Exemple #2
0
        public async Task Run()
        {
            restClient = new RestClient(API_KEY, API_SECRET, API_URL, apiVersion: 2);

            // Connect to Alpaca's websocket and listen for updates on our orders.
            sockClient = new SockClient(API_KEY, API_SECRET, API_URL);
            sockClient.ConnectAndAuthenticateAsync().Wait();

            sockClient.OnTradeUpdate += HandleTradeUpdate;

            // First, cancel any existing orders so they don't impact our buying power.
            var orders = await restClient.ListOrdersAsync();

            foreach (var order in orders)
            {
                await restClient.DeleteOrderAsync(order.OrderId);
            }

            // Figure out when the market will close so we can prepare to sell beforehand.
            var calendars    = (await restClient.ListCalendarAsync(DateTime.Today)).ToList();
            var calendarDate = calendars.First().TradingDate;
            var closingTime  = calendars.First().TradingCloseTime;

            closingTime = new DateTime(calendarDate.Year, calendarDate.Month, calendarDate.Day, closingTime.Hour, closingTime.Minute, closingTime.Second);

            var today = DateTime.Today;
            // Get the first group of bars from today if the market has already been open.
            var bars = await restClient.ListMinuteAggregatesAsync(symbol, 1, today, today.AddDays(1));

            var lastBars = bars.Items.Skip(Math.Max(0, bars.Items.Count() - 20));

            foreach (var bar in lastBars)
            {
                if (bar.Time.Date == today)
                {
                    closingPrices.Add(bar.Close);
                }
            }

            Console.WriteLine("Waiting for market open...");
            await AwaitMarketOpen();

            Console.WriteLine("Market opened.");

            // Connect to Polygon's websocket and listen for price updates.
            polygonSockClient = new PolygonSockClient(API_KEY);
            polygonSockClient.ConnectAndAuthenticateAsync().Wait();
            Console.WriteLine("Polygon client opened.");
            polygonSockClient.MinuteAggReceived += async(agg) =>
            {
                // If the market's close to closing, exit position and stop trading.
                TimeSpan minutesUntilClose = closingTime - DateTime.UtcNow;
                if (minutesUntilClose.TotalMinutes < 15)
                {
                    Console.WriteLine("Reached the end of trading window.");
                    await ClosePositionAtMarket();

                    await polygonSockClient.DisconnectAsync();
                }
                else
                {
                    // Decide whether to buy or sell and submit orders.
                    await HandleMinuteAgg(agg);
                }
            };
            polygonSockClient.SubscribeSecondAgg(symbol);
        }