private static void cmdGetPositions() { IAlpacaTradingClient client = Core.ServiceProvider.GetService <IAlpacaTradingClient>(); var positions = client.ListPositionsAsync().Result; string resultStr = "\n"; if (positions.Count == 0) { Core.Logger.LogInfo("No Active Positions"); return; } foreach (IPosition position in positions) { resultStr += ($"Symbol: {position.Symbol} \n" + $"Avg Entry: {position.AverageEntryPrice} \n" + $"Quantity: {position.Quantity} \n" + $"Side: {position.Side} \n" + $"Market Value: {position.MarketValue} \n" + $"P/L Amount: {position.UnrealizedProfitLoss} \n" + $"P'L Percent: {position.UnrealizedProfitLossPercent} \n" + $"Change Percent: {position.AssetChangePercent} \n" + $"-------------------------------------------------"); } Core.Logger.LogInfo(resultStr); }
public async Task <object> GetTradeableCash(Data.Format format) { IAlpacaTradingClient trading = null; try { if (format == Data.Format.Live) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { return(null); } trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (format == Data.Format.Paper) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { return(null); } trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } var account = await trading.GetAccountAsync(); return(account.TradableCash); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(ex.Message); } }
public async Task <object> GetTime_LastMarketClose() { IAlpacaTradingClient client = null; try { if (!String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) && !String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { client = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (!String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) && !String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { client = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } else { return(new ArgumentNullException()); } var calendars = client.ListCalendarAsync(new CalendarRequest().SetInclusiveTimeInterval(DateTime.UtcNow - new TimeSpan(30, 0, 0, 0), DateTime.UtcNow)).Result; return(calendars.Where(c => c.TradingCloseTimeUtc.CompareTo(DateTime.UtcNow) <= 0).Last().TradingCloseTimeUtc); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(ex.Message); } }
public async Task ClearOrders(Data.Format format) { IAlpacaTradingClient trading = null; try { if (format == Data.Format.Live) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { return; } trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (format == Data.Format.Paper) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { return; } trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } await trading.DeleteAllOrdersAsync(); return; } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return; } }
public async Task <Trading.OrderResult> PlaceOrder_SellStopLimit( Data.Format format, string symbol, int shares, decimal stopPrice, decimal limitPrice, TimeInForce timeInForce = TimeInForce.Gtc) { IAlpacaTradingClient trading = null; try { if (format == Data.Format.Live) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { return(Trading.OrderResult.Fail); } trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (format == Data.Format.Paper) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { return(Trading.OrderResult.Fail); } trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } // Prevents exceptions or unwanted behavior with Alpaca API var account = await trading.GetAccountAsync(); if (trading == null || account == null || account.IsAccountBlocked || account.IsTradingBlocked || account.TradeSuspendedByUser) { return(Trading.OrderResult.Fail); } // Prevents unintentionally short selling (selling into negative digits, the API interprets that as intent to short-sell) var positions = await trading.ListPositionsAsync(); if (!positions.Any(p => p.Symbol == symbol)) // If there is no position for this symbol { return(Trading.OrderResult.Fail); } var position = await trading.GetPositionAsync(symbol); // If there were no position, this would throw an Exception! if (position == null || position.Quantity < shares) // If the current position doesn't have enough shares { return(Trading.OrderResult.Fail); } var order = await trading.PostOrderAsync(StopLimitOrder.Sell(symbol, shares, stopPrice, limitPrice).WithDuration(timeInForce)); return(Trading.OrderResult.Success); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(Trading.OrderResult.Fail); } }
// TODO: olegra - good candidate for the DateOnly type usage public static async Task <ICalendar?> GetCalendarForSingleDayAsync( this IAlpacaTradingClient client, DateTime date, CancellationToken cancellationToken = default) { var calendars = await client.EnsureNotNull(nameof(client)) .ListCalendarAsync(new CalendarRequest().SetInclusiveTimeInterval(date, date), cancellationToken) .ConfigureAwait(false); return(calendars.SingleOrDefault()); }
public async Task StartPaperClient() { try { //isLoadingAlpaca = true; //redraw = false; client = Environments.Paper .GetAlpacaTradingClient(new SecretKey(KEY_ID, SECRET_KEY)); var clock = await client.GetClockAsync(); if (clock != null) { //lstActivity = await GetAccountActivity(DateTime.Now); await GetAccountData(); await GetCurrentPosition(); await GetOrders(); // Prepare the websocket connection and subscribe to trade_updates. #if alpacaStreamingClient var alpacaStreamingClient = Environments.Paper .GetAlpacaStreamingClient(new SecretKey(KEY_ID, SECRET_KEY)); await alpacaStreamingClient.ConnectAndAuthenticateAsync(); alpacaStreamingClient.OnTradeUpdate += AlpacaStreamingClient_OnTradeUpdate;; #endif // redraw = true; //jsruntime.alert(string.Format(@"Alpaca Paper Trading turned ON. " + // "\n\nTimestamp: {0}" + // "\nNextOpen: {1}" + // "\nNextClose: {2}" + // "\n\nBuying Power: {3}" + // "\nPortfolio Value: {4}" + // "\n\nPosition Quantity: {5}" + // "\nPosition MarketValue: {6}" // , // clock.TimestampUtc.ToLocalTime(), // clock.NextOpenUtc.ToLocalTime(), // clock.NextCloseUtc.ToLocalTime(), // buyingPower, // portfolioValue, // positionQuantity, // positionValue.ToString("c2") // )); } } catch (Exception ex) { jsruntime.alert(ex.Message); } }
public AlpacaClient(AlpacaConfig config) { _config = config; _alpacaTradingClient = config.Alpaca_Use_Live_Api ? Environments.Live.GetAlpacaTradingClient(new SecretKey(_config.Alpaca_Live_App_Id, _config.Alpaca_Live_Secret_Key)) : Environments.Paper.GetAlpacaTradingClient(new SecretKey(_config.Alpaca_Paper_App_Id, _config.Alpaca_Paper_Secret_Key)); _alpacaDataClient = config.Alpaca_Use_Live_Api ? Environments.Live.GetAlpacaDataClient(new SecretKey(_config.Alpaca_Live_App_Id, _config.Alpaca_Live_Secret_Key)) : Environments.Paper.GetAlpacaDataClient(new SecretKey(_config.Alpaca_Paper_App_Id, _config.Alpaca_Paper_Secret_Key)); _alpacaStreamingClient = config.Alpaca_Use_Live_Api ? Environments.Live.GetAlpacaDataStreamingClient(new SecretKey(_config.Alpaca_Live_App_Id, _config.Alpaca_Live_Secret_Key)) : Environments.Paper.GetAlpacaDataStreamingClient(new SecretKey(_config.Alpaca_Paper_App_Id, _config.Alpaca_Paper_Secret_Key)); }
public AlpacaClient( IAlpacaTradingClient alpacaTradingClient, IAlpacaStreamingClient alpacaTradingStreamingClient, IAlpacaDataClient alpacaDataClient, IAlpacaDataStreamingClient alpacaDataStreamingClient ) { _alpacaTradingClient = alpacaTradingClient ?? throw new ArgumentNullException(nameof(alpacaTradingClient)); _alpacaTradingStreamingClient = alpacaTradingStreamingClient ?? throw new ArgumentNullException(nameof(alpacaTradingStreamingClient)); _alpacaDataClient = alpacaDataClient ?? throw new ArgumentNullException(nameof(alpacaDataClient)); _alpacaDataStreamingClient = alpacaDataStreamingClient ?? throw new ArgumentNullException(nameof(alpacaDataStreamingClient)); _stockActions = new Dictionary <string, List <Action <StockInput> > >(StringComparer.OrdinalIgnoreCase); }
public AccountService(ILoggerService logger, IAlpacaTradingClient tradingClient) { Logger = logger; TradingClient = tradingClient; Logger.LogInfo("Fetching Account Data"); Account = TradingClient.GetAccountAsync().Result; if (Account != null) { Logger.LogInfo("Account Data Fetched"); } else { throw new Exception("Could not fetch account data"); } }
public CoreService(ILoggerService loggerService, Settings config, IAlpacaTradingClient tradingClient, IAlpacaStreamingClient streamingClient, IAccountService accountService, ICommandService commandService) { CoreService.Instance = this; LoggerService = loggerService; LoggerService.LogInfo("Initializing Core Service"); Config = config; LoggerService.LogInfo("Fetching Trading Client"); TradingClient = tradingClient; LoggerService.LogInfo("Fetching Streaming Client"); StreamingClient = streamingClient; LoggerService.LogInfo("Initializing Account Service"); AccountService = accountService; CommandService = commandService; RunningTasks = new List <Task>(); }
public async Task <object> GetOrders_Open(Data.Format format) { IAlpacaTradingClient trading = null; IAlpacaDataClient data = null; try { if (format == Data.Format.Live) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { return(null); } trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); data = Environments.Live.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (format == Data.Format.Paper) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { return(null); } trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); data = Environments.Paper.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } return((await trading.ListOrdersAsync( new ListOrdersRequest() { OrderStatusFilter = OrderStatusFilter.Open, LimitOrderNumber = 1000 })) .Select <IOrder, Data.Order>((q) => { return new Data.Order() { Symbol = q.Symbol, Transaction = q.OrderSide == OrderSide.Buy ? Data.Order.Direction.Buy : Data.Order.Direction.Sell, Quantity = (int)q.Quantity }; }) .ToList()); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(ex.Message); } }
public async Task <Trading.OrderResult> PlaceOrder_BuyMarket( Data.Format format, string symbol, int shares, TimeInForce timeInForce = TimeInForce.Gtc, bool useMargin = false) { IAlpacaTradingClient trading = null; IAlpacaDataClient data = null; try { if (format == Data.Format.Live) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { return(Trading.OrderResult.Fail); } trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); data = Environments.Live.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (format == Data.Format.Paper) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { return(Trading.OrderResult.Fail); } trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); data = Environments.Paper.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } var account = await trading.GetAccountAsync(); if (trading == null || account == null || account.IsAccountBlocked || account.IsTradingBlocked || account.TradeSuspendedByUser) { return(Trading.OrderResult.Fail); } var order = await trading.PostOrderAsync(MarketOrder.Buy(symbol, shares).WithDuration(timeInForce)); return(Trading.OrderResult.Success); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(Trading.OrderResult.Fail); } }
public async Task <object> GetAssets() { try { IAlpacaTradingClient trading = null; if (!String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) && !String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (!String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) && !String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } else { return(new ArgumentNullException()); } var assets = await trading.ListAssetsAsync(new AssetsRequest { AssetStatus = AssetStatus.Active }); List <Data.Asset> output = new List <Data.Asset>(); foreach (var asset in assets) { output.Add(new Data.Asset() { ID = asset.AssetId.ToString(), Class = asset.Class.ToString(), Exchange = asset.Exchange.ToString(), Symbol = asset.Symbol, Status = asset.Status.ToString(), Tradeable = asset.IsTradable, Marginable = asset.Marginable, Shortable = asset.Shortable, EasyToBorrow = asset.EasyToBorrow }); } return(output); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(ex.Message); } }
public async Task <object> GetPositions(Data.Format format) { IAlpacaTradingClient client = null; try { if (format == Data.Format.Live) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret)) { return(false); } client = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret)); } else if (format == Data.Format.Paper) { if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret)) { return(false); } client = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret)); } if (client == null) { return(false); } var positions = await client.ListPositionsAsync(); return(positions.Select(p => new Data.Position() { ID = p.AssetId.ToString(), Symbol = p.Symbol, Quantity = p.Quantity }).ToList()); } catch (Exception ex) { await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex); return(null); } }
public async Task Run() { alpacaTradingClient = Environments.Paper.GetAlpacaTradingClient(new SecretKey(API_KEY, API_SECRET)); alpacaDataClient = Environments.Paper.GetAlpacaDataClient(new SecretKey(API_KEY, API_SECRET)); // 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); Console.WriteLine("Waiting for market open..."); await AwaitMarketOpen(); Console.WriteLine("Market opened."); // Check every minute for price updates. TimeSpan timeUntilClose = closingTime - DateTime.UtcNow; while (timeUntilClose.TotalMinutes > 15) { // Cancel old order if it's not already been filled. await alpacaTradingClient.DeleteOrderAsync(lastTradeId); // Get information about current account value. var account = await alpacaTradingClient.GetAccountAsync(); Decimal buyingPower = account.BuyingPower; Decimal portfolioValue = account.Equity; // Get information about our existing position. Int32 positionQuantity = 0; Decimal positionValue = 0; try { var currentPosition = await alpacaTradingClient.GetPositionAsync(symbol); positionQuantity = currentPosition.Quantity; positionValue = currentPosition.MarketValue; } catch (Exception) { // No position exists. This exception can be safely ignored. } var barSet = await alpacaDataClient.GetBarSetAsync( new BarSetRequest(symbol, TimeFrame.Minute) { Limit = 20 }); var bars = barSet[symbol].ToList(); Decimal avg = bars.Average(item => item.Close); Decimal currentPrice = bars.Last().Close; Decimal diff = avg - currentPrice; if (diff <= 0) { // Above the 20 minute average - exit any existing long position. if (positionQuantity > 0) { Console.WriteLine("Setting position to zero."); await SubmitOrder(positionQuantity, currentPrice, OrderSide.Sell); } else { Console.WriteLine("No position to exit."); } } else { // Allocate a percent of our portfolio to this position. Decimal portfolioShare = diff / currentPrice * scale; Decimal targetPositionValue = portfolioValue * portfolioShare; Decimal amountToAdd = targetPositionValue - positionValue; if (amountToAdd > 0) { // Buy as many shares as we can without going over amountToAdd. // Make sure we're not trying to buy more than we can. if (amountToAdd > buyingPower) { amountToAdd = buyingPower; } Int32 qtyToBuy = (Int32)(amountToAdd / currentPrice); await SubmitOrder(qtyToBuy, currentPrice, OrderSide.Buy); } else { // Sell as many shares as we can without going under amountToAdd. // Make sure we're not trying to sell more than we have. amountToAdd *= -1; Int32 qtyToSell = (Int32)(amountToAdd / currentPrice); if (qtyToSell > positionQuantity) { qtyToSell = positionQuantity; } await SubmitOrder(qtyToSell, currentPrice, OrderSide.Sell); } } // Wait another minute. Thread.Sleep(60000); timeUntilClose = closingTime - DateTime.UtcNow; } Console.WriteLine("Market nearing close; closing position."); await ClosePositionAtMarket(); }
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); }
public StockClient(IConfiguration config) { _config = config; Client = Alpaca.Markets.Environments.Paper.GetAlpacaTradingClient(new SecretKey(_config.GetValue <string>("apiKey"), _config.GetValue <string>("apiSecret"))); }
public static async Task <IEnumerable <IAsset> > GetStocks(IAlpacaTradingClient client) { var assets = await client.ListAssetsAsync(new AssetsRequest { AssetStatus = AssetStatus.Active }); return(assets.Where(asset => asset.Exchange == Exchange.Nasdaq)); }
public static IAsyncEnumerable <IAccountActivity> ListAccountActivitiesAsAsyncEnumerable( this IAlpacaTradingClient client, AccountActivitiesRequest request, CancellationToken cancellationToken) => getAllAccountActivitiesPages(client.EnsureNotNull(nameof(client)), getRequestWithoutPageToken(request.EnsureNotNull(nameof(request))), cancellationToken);
public static IAsyncEnumerable <IAccountActivity> ListAccountActivitiesAsAsyncEnumerable( this IAlpacaTradingClient client, AccountActivitiesRequest request) => ListAccountActivitiesAsAsyncEnumerable(client, request, CancellationToken.None);
public AlpacaTradingClientTest(PaperEnvironmentClientsFactoryFixture clientsFactory) { _clientsFactory = clientsFactory; _alpacaTradingClient = clientsFactory.GetAlpacaTradingClient(); }