-
-
Notifications
You must be signed in to change notification settings - Fork 83
Alpaca REST API
All REST endpoints described here, here, and here also available as asynchronous methods of Alpaca.Markets.IAlpacaTradingClient, Alpaca.Markets.IAlpacaDataClient, and Alpaca.Markets.IAlpacaCryptoDataClient interfaces respectively. All these methods return read-only interfaces for related JSON objects or read-only lists/dictionaries of immutable objects deserialized from JSON and represented via read-only interfaces.
For creating an instance of each client interface we recommend using special extension methods of the IEnvironment interface designed for this task.
For Alpaca.Markets.IAlpacaTradingClient interface:
var client = Environments.Paper.GetAlpacaTradingClient(new SecretKey(KEY_ID, SECRET_KEY));
For Alpaca.Markets.IAlpacaDataClient interface:
var client = Environments.Paper.AlpacaDataClient(new SecretKey(KEY_ID, SECRET_KEY));
For Alpaca.Markets.IAlpacaCryptoDataClient interface:
var client = Environments.Paper.AlpacaCryptoDataClient(new SecretKey(KEY_ID, SECRET_KEY));
You can read more about these extension methods on this Wiki page.
The Alpaca Data API v2 returns historical data sets by pages. You can read more about default page size and next page token concept in the documentation. By default SDK returns full information received from the server-side so you can implement pagination manually on your side.
But if you need a simple and convenient way for getting a whole data set in one call you can use helper methods GetHistoricalBarsAsAsyncEnumerable, GetHistoricalQuotesAsAsyncEnumerable, and GetHistoricalTradesAsAsyncEnumerable available in the Alpaca.Markets.Extensions package. Each of these methods returns an instance of the System.Collections.Generic.IAsyncEnumerable interface and does all pagination-handling activity for you.
var client = Environments.Paper.AlpacaDataClient(new SecretKey(KEY_ID, SECRET_KEY));
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(150));
await foreach(var bar in client
.GetHistoricalBarsAsAsyncEnumerable(
new HistoricalBarsRequest("AAPL", DateTime.Today.AddDays(-5), DateTime.Today, BarTimeFrame.Hour))
.WithCancellation(cancellationTokenSource.Token))
{
Console.WriteLine($"{bar.TimeUtc}: {bar.Open}");
}
If the C# compiler tells you that the GetHistoricalBarsAsAsyncEnumerable
method doesn't exist it means that you've just forgotten to add the next line into your C# file using
section:
using Alpaca.Markets.Extensions;
Please, keep in mind that C# await foreach
statement will not execute any code behind the loop body until enumerable completion - in this example, it will happen after 150 seconds, but you can use the cancellation token received from the outer code.