C# data streaming example

Hello,

Does anybody has C# code - which demonstrate - data streaming at every 1min?

  • is it possible to stream multiple data?

Thanks
DM.

1 Like
1 Like

Thanks for your reply.
I have few more questions

  1. DataStreamingClient will only work when the market is open?

  2. Does it work for extended hours - pre-market / post-market?

  3. Today is Saturday - June 26 - 2021 at 9:41PM and at this time market is close, I see my code is failing for subscription, is it because the market is close, thatā€™s why it is failing or something wrong in my code?

  4. For your reference I am attaching my code, I really appreciate it if you can pinpoint what mistake I am doing it.

  5. I have a funded account, but initially, I want to try a free plan for data streaming, for this use case I should choose the mode of operation - should be Paper or Live?

following is code that gets executed in my background worker - dowork function.

    string AlpacaAccountNumber_Live = "000000000"; //replaced actual with 0
    string AlpacaEndPoint_Live = "https://api.alpaca.markets";
    string AlpacaApiKeyId_Live = "00000000000000000000"; //replaced actual with 0
    string AlpacaSecretKey_Live = "0000000000000000000000000000000000000000"; //replaced actual with 0

    string AlpacaAccountNumber_Paper = "00000000"; //replaced actual with 0
    string AlpacaEndPoint_Paper = "https://paper-api.alpaca.markets";
    string AlpacaApiKeyId_Paper = "00000000000000000000"; //replaced actual with 0
    string AlpacaSecretKey_Paper = "0000000000000000000000000000000000000000"; //replaced actual with 0

    string AlpacaEndPoint = "";
    string AlpacaApiKeyId = "";
    string AlpacaSecretKey = "";
    SecretKey my_secret_key = null;
    Alpaca.Markets.IAlpacaDataStreamingClient mAlpacaDataStreamingClient = null;


    private void mBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        string result = "";

        string s1 = mLive ? "LIVE" : "PAPER";
        string s2 = mFree ? "FREE" : "PAID";
        Console.WriteLine("MODE = " + s1 + ", " + s2);

        if (mLive == true)
        {
            AlpacaApiKeyId = AlpacaApiKeyId_Live;
            AlpacaSecretKey = AlpacaSecretKey_Live;
        }
        else
        {
            AlpacaApiKeyId = AlpacaApiKeyId_Paper;
            AlpacaSecretKey = AlpacaSecretKey_Paper;
        }

        my_secret_key = new SecretKey(AlpacaApiKeyId, AlpacaSecretKey);

        if (true == mLive)
        {
            mAlpacaDataStreamingClient = Environments.Live.GetAlpacaDataStreamingClient(my_secret_key);
        }
        else
        {
            mAlpacaDataStreamingClient = Environments.Paper.GetAlpacaDataStreamingClient(my_secret_key);
        }

        **mAlpacaDataStreamingClient.ConnectAndAuthenticateAsync().Wait();** //is this correct?

        Console.WriteLine("Alpaca streaming client opened.");

        var subscription = mAlpacaDataStreamingClient.GetMinuteBarSubscription("INTC");

        subscription.Received += async (bar) =>
        {
            await HandleMinuteBar(bar);
        };

        mAlpacaDataStreamingClient.Subscribe(subscription);

        if (true == subscription.Subscribed)
        {
            result = "OK. successfully subscribed";
        }
        else
        {
            result = "ERROR:: failed to subscribed.";
        }
        Console.WriteLine(result);
    }

Iā€™m not sure about all your questions but Iā€™ll try to answer:

  • 1 & 2 - AFAIK right now you can connect at any time but data will be streamed only during market hours. At least for the free data subscription.
  • 3, 4 & 5 - Hard to answer without exact error/exception message details. But most probably the problem is incorrect environment usage. You have to use the ā€˜Paperā€™ environment for constructing the IAlpacaDataSubsciptionClient in case of a free subscription.

See more details here about proper IEnvionment usage for the free/paid subscriptions. I think it would be better for you to ask Alpaca support via email about your access key for both REST and WS data.

Hello,
Thank you for your reply.
I checked and updated my code, now I am using a paper account only for data streaming.

I am able to open dataStreamClient, connectAndAuthenticateAsync also works.

My problem is it is failing to do subscription, after subscribing method, I go for checking subscription status and at that, it returns false. today is Sunday so the market is closed, I will try on Monday when the market opens.

I donā€™t see any crash or error message, is there any way to turn ON logging so we know what is happening?

mAlpacaDataStreamingClient.Subscribe(subscription);
if (true == subscription.Subscribed)
{
result = ā€œOK. successfully subscribedā€;
}
else
{
result = ā€œERROR:: failed to subscribed.ā€;
}

I am attaching my code, if anybody finds any mistake, please let me know.

private void mBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var t = Task.Run(() => PerformDataStreaming() );
t.Wait();
string result = t.Result;
Console.WriteLine(ā€œRESULT=ā€ + result);
}

    private async Task<string> PerformDataStreaming()
    { 
        string result = "";           
            //free = paper
            AlpacaApiKeyId = AlpacaApiKeyId_Paper;
            AlpacaSecretKey = AlpacaSecretKey_Paper;
    

        my_secret_key = new SecretKey(AlpacaApiKeyId, AlpacaSecretKey);

            //free=paper
            mAlpacaDataStreamingClient = Environments.Paper.GetAlpacaDataStreamingClient(my_secret_key);

        await mAlpacaDataStreamingClient.ConnectAndAuthenticateAsync();

        Console.WriteLine("Alpaca streaming client opened.");

        var subscription = mAlpacaDataStreamingClient.GetMinuteBarSubscription("INTC");
        subscription.Received += async bar =>
        {
            await HandleMinuteBar(bar);
        };

        mAlpacaDataStreamingClient.Subscribe(subscription);

        if (true == subscription.Subscribed)
        {
            result = "OK. successfully subscribed";
        }
        else
        {
            result = "ERROR:: failed to subscribed.";
        }
        Console.WriteLine(result);
        return result;
    }
1 Like

I finally found the root cause, after changing rules in the firewall, real-time data streaming is working as expected.
thanks for your help.
-DM

Thanks for posting your example, I was under the assumption that when you created the quoteSubscription it was subscribed, but seeing your example you have to subscribe.
I also noticed that you must use the paper version which connects to the IEX exchange.

Hi,
I have replicated the example, but the subscription fails.
Have you an idea of whatā€™s wrong?
I wrote:

var alpacaDataStreamingClient = Environments.Paper.GetAlpacaDataStreamingClient(new SecretKey(ID.API_KEY, ID.API_SECRET));
await alpacaDataStreamingClient.ConnectAndAuthenticateAsync();
Console.WriteLine("Alpaca streaming client opened.");

var subscription = alpacaDataStreamingClient.GetMinuteBarSubscription("AAPL");

subscription.Received += async bar =>
{
    Console.WriteLine($"Trade received for the {bar.Symbol} contract");
};
         
await alpacaDataStreamingClient.SubscribeAsync(subscription);

Unfortunately, the client fails to connect. When I write:

if (true == subscription.Subscribed)
            {
                Console.WriteLine("Subscription successful");
            }
            else
            {
                Console.WriteLine("Error: Subscription failed");
            }

I always obtain: ā€œError: Subscription failedā€

Thanks!

Sorry for the delayed answer - forum update emails are marked as spam by Google.

The Subscribed property is updated only after receiving subscription confirmation from the server side. If you check this property right after the SubscribeAsync method call, it most probably will return false.

There is an event OnSubscribedChanged that you can use for checking the Subscribed property change value. But in most cases, you just subscribe to the Received event and wait for bars/trades/quotes.

And of course, I strongly recommend you to verify the ConnectAndAuthenticateAsync value and do any subscription only if the client is connected and properly authenticated. The OnError and OnWarning events can provide you with more information about any problems that happen inside this streaming client.