public async Task <bool> ConnectStreamApis() { var dataTask = _alpacaDataStreamingClient.ConnectAndAuthenticateAsync(); var tradingTask = _alpacaTradingStreamingClient.ConnectAndAuthenticateAsync(); return((await dataTask) == AuthStatus.Authorized && (await tradingTask) == AuthStatus.Authorized); }
public async Task Run() { alpacaTradingClient = Environments.Paper.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET)); polygonDataClient = Environments.Paper.GetPolygonDataClient(API_KEY); // Connect to Alpaca's websocket and listen for updates on our orders. alpacaStreamingClient = Environments.Paper.GetAlpacaStreamingClient(new SecretKey(API_KEY, API_SECRET)); alpacaStreamingClient.ConnectAndAuthenticateAsync().Wait(); alpacaStreamingClient.OnTradeUpdate += HandleTradeUpdate; // First, cancel any existing orders so they don't impact our buying power. var orders = await alpacaTradingClient.ListOrdersAsync(new ListOrdersRequest()); foreach (var order in orders) { await alpacaTradingClient.DeleteOrderAsync(order.OrderId); } // Figure out when the market will close so we can prepare to sell beforehand. var calendars = (await alpacaTradingClient .ListCalendarAsync(new CalendarRequest().SetTimeInterval(DateTime.Today.GetInclusiveIntervalFromThat()))) .ToList(); var calendarDate = calendars.First().TradingDateUtc; var closingTime = calendars.First().TradingCloseTimeUtc; 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 polygonDataClient.ListAggregatesAsync( new AggregatesRequest(symbol, new AggregationPeriod(1, AggregationPeriodUnit.Minute)) .SetInclusiveTimeInterval(today, today.AddDays(1))); var lastBars = bars.Items.Skip(Math.Max(0, bars.Items.Count() - 20)); foreach (var bar in lastBars) { if (bar.TimeUtc?.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. polygonStreamingClient = Environments.Live.GetPolygonStreamingClient(API_KEY); polygonStreamingClient.ConnectAndAuthenticateAsync().Wait(); Console.WriteLine("Polygon client opened."); polygonStreamingClient.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 polygonStreamingClient.DisconnectAsync(); } else { // Decide whether to buy or sell and submit orders. await HandleMinuteAgg(agg); } }; polygonStreamingClient.SubscribeMinuteAgg(symbol); }