{"id":25638491,"url":"https://github.com/marfusios/coinbase-client-websocket","last_synced_at":"2025-04-15T00:22:05.578Z","repository":{"id":40910048,"uuid":"196570143","full_name":"Marfusios/coinbase-client-websocket","owner":"Marfusios","description":"🛠️ C# client for Coinbase Pro websocket API","archived":false,"fork":false,"pushed_at":"2024-02-16T15:32:56.000Z","size":370,"stargazers_count":19,"open_issues_count":3,"forks_count":9,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-02-06T00:51:29.027Z","etag":null,"topics":["api-client","bitcoin","coinbase","coinbase-pro","cryptocurrency","dotnet-core","exchange","websocket","websockets"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Marfusios.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-07-12T11:46:06.000Z","updated_at":"2025-01-04T02:33:26.000Z","dependencies_parsed_at":"2023-01-25T05:15:45.955Z","dependency_job_id":null,"html_url":"https://github.com/Marfusios/coinbase-client-websocket","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marfusios%2Fcoinbase-client-websocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marfusios%2Fcoinbase-client-websocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marfusios%2Fcoinbase-client-websocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marfusios%2Fcoinbase-client-websocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Marfusios","download_url":"https://codeload.github.com/Marfusios/coinbase-client-websocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240261051,"owners_count":19773428,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-client","bitcoin","coinbase","coinbase-pro","cryptocurrency","dotnet-core","exchange","websocket","websockets"],"created_at":"2025-02-23T02:31:36.659Z","updated_at":"2025-02-23T02:31:47.495Z","avatar_url":"https://github.com/Marfusios.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Logo](coinbase-logo-alt.png)\n# Coinbase Pro websocket API client [![Build Status](https://travis-ci.org/Marfusios/coinbase-client-websocket.svg?branch=master)](https://travis-ci.org/Marfusios/coinbase-client-websocket) [![NuGet version](https://badge.fury.io/nu/Coinbase.Client.Websocket.svg)](https://badge.fury.io/nu/Coinbase.Client.Websocket)\n\nThis is a C# implementation of the Coinbase Pro websocket API found here:\n\nhttps://docs.pro.coinbase.com\n\n[Releases and breaking changes](https://github.com/Marfusios/coinbase-client-websocket/releases)\n\n### License: \n    Apache License 2.0\n\n### Features\n\n* installation via NuGet ([Coinbase.Client.Websocket](https://www.nuget.org/packages/Coinbase.Client.Websocket))\n* public and authenticated API\n* targeting .NET Standard 2.0 (.NET Core, Linux/MacOS compatible)\n* reactive extensions ([Rx.NET](https://github.com/Reactive-Extensions/Rx.NET))\n* integrated logging abstraction ([LibLog](https://github.com/damianh/LibLog))\n\n### Usage\n\n```csharp\nvar exitEvent = new ManualResetEvent(false);\nvar url = CoinbaseValues.ApiWebsocketUrl;\n\nusing (var communicator = new CoinbaseWebsocketCommunicator(url))\n{\n    using (var client = new CoinbaseWebsocketClient(communicator))\n    {\n        client.Streams.TradesStream.Subscribe(x =\u003e\n        {\n            Log.Information($\"Trade executed [{x.ProductId}] {x.TradeSide} price: {x.Price} size: {x.Size}\");\n        });\n\n        communicator.ReconnectionHappened.Subscribe(async type =\u003e\n        {\n            Log.Information($\"Reconnection happened, type: {type}, resubscribing..\");\n            var subscription = new SubscribeRequest\n            {\n                ProductIds = new[]\n                {\n                    \"BTC-EUR\",\n                    //\"BTC-USD\"\n                },\n                Channels = new[]\n                {\n                    ChannelSubscriptionType.Ticker,\n                    ChannelSubscriptionType.Matches,\n                    //ChannelSubscriptionType.Level2\n                }\n            };\n\n            client.Send(subscription);\n        });\n\n        communicator.Start().Wait();\n\n        exitEvent.WaitOne(TimeSpan.FromSeconds(30));\n    }\n}\n```\n\nMore usage examples:\n* integration tests ([link](test_integration/Coinbase.Client.Websocket.Tests.Integration))\n* console sample ([link](test_integration/Coinbase.Client.Websocket.Sample/Program.cs))\n* desktop sample ([link](test_integration/Coinbase.Client.Websocket.Sample.WinForms))\n\n### API coverage\n\n| PUBLIC                 |    Covered     |  \n|------------------------|:--------------:|\n| Heartbeat              |  ✔            |\n| Errors                 |  ✔            |\n| Subscribe              |  ✔            |\n| Unsubscribe            |  ✔            |\n| Orderbook L2           |  ✔            |\n| Trades (matches)       |  ✔            |\n| Ticker                 |  ✔            |\n| Status                 |                |\n\n| AUTHENTICATED          |    Covered     |  \n|------------------------|:--------------:|\n| Received               |                |\n| Open                   |                |\n| Done                   |                |\n| Match                  |                |\n| Change                 |                |\n| Activate               |                |\n\n**Pull Requests are welcome!**\n\n### Other websocket libraries\n\n\u003ctable\u003e\n\u003ctr\u003e\n\n\u003ctd\u003e\n\u003ca href=\"https://github.com/Marfusios/crypto-websocket-extensions\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/Marfusios/crypto-websocket-extensions/master/cwe_logo.png\" height=\"80px\"\u003e\u003c/a\u003e\n\u003cbr /\u003e\n\u003ca href=\"https://github.com/Marfusios/crypto-websocket-extensions\"\u003eExtensions\u003c/a\u003e\n\u003cbr /\u003e\n\u003cspan\u003eAll order books together, etc.\u003c/span\u003e\n\u003c/td\u003e\n\n\u003ctd\u003e\n\u003ca href=\"https://github.com/Marfusios/bitmex-client-websocket\"\u003e\u003cimg src=\"https://user-images.githubusercontent.com/1294454/27766319-f653c6e6-5ed4-11e7-933d-f0bc3699ae8f.jpg\"\u003e\u003c/a\u003e\n\u003cbr /\u003e\n\u003ca href=\"https://github.com/Marfusios/bitmex-client-websocket\"\u003eBitmex\u003c/a\u003e\n\u003c/td\u003e\n\n\u003ctd\u003e\n\u003ca href=\"https://github.com/Marfusios/bitfinex-client-websocket\"\u003e\u003cimg src=\"https://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpg\"\u003e\u003c/a\u003e\n\u003cbr /\u003e\n\u003ca href=\"https://github.com/Marfusios/bitfinex-client-websocket\"\u003eBitfinex\u003c/a\u003e\n\u003c/td\u003e\n\n\u003ctd\u003e\n\u003ca href=\"https://github.com/Marfusios/binance-client-websocket\"\u003e\u003cimg src=\"https://user-images.githubusercontent.com/1294454/29604020-d5483cdc-87ee-11e7-94c7-d1a8d9169293.jpg\"\u003e\u003c/a\u003e\n\u003cbr /\u003e\n\u003ca href=\"https://github.com/Marfusios/binance-client-websocket\"\u003eBinance\u003c/a\u003e\n\u003c/td\u003e\n\n\u003c/tr\u003e\n\u003c/table\u003e\n\n### Reconnecting\n\nThere is a built-in reconnection which invokes after 1 minute (default) of not receiving any messages from the server. It is possible to configure that timeout via `communicator.ReconnectTimeoutMs`. Also, there is a stream `ReconnectionHappened` which sends information about a type of reconnection. However, if you are subscribed to low rate channels, it is very likely that you will encounter that timeout - higher the timeout to a few minutes or call `PingRequest` by your own every few seconds. \n\nIn the case of Coinbase outage, there is a built-in functionality which slows down reconnection requests (could be configured via `communicator.ErrorReconnectTimeoutMs`, the default is 1 minute).\n\nBeware that you **need to resubscribe to channels** after reconnection happens. You should subscribe to `Streams.InfoStream`, `Streams.AuthenticationStream` and send subscriptions requests (see [#12](https://github.com/Marfusios/bitfinex-client-websocket/issues/12) for example). \n\n### Backtesting\n\nThe library is prepared for backtesting. The dependency between `Client` and `Communicator` is via abstraction `ICoinbaseCommunicator`. There are two communicator implementations: \n* `CoinbaseWebsocketCommunicator` - a realtime communication with Coinbase via websocket API.\n* `CoinbaseFileCommunicator` - a simulated communication, raw data are loaded from files and streamed. If you are **interested in buying historical raw data** (trades, order book events), contact me.\n\nFeel free to implement `ICoinbaseCommunicator` on your own, for example, load raw data from database, cache, etc. \n\nUsage: \n\n```csharp\nvar communicator = new CoinbaseFileCommunicator();\ncommunicator.FileNames = new[]\n{\n    \"data/coinbase_raw_xbtusd_2018-11-13.txt\"\n};\ncommunicator.Delimiter = \";;\";\n\nvar client = new CoinbaseWebsocketClient(communicator);\nclient.Streams.TradesStream.Subscribe(response =\u003e\n{\n    // do something with trade\n});\n\nawait communicator.Start();\n```\n\n\n### Multi-threading\n\nObservables from Reactive Extensions are single threaded by default. It means that your code inside subscriptions is called synchronously and as soon as the message comes from websocket API. It brings a great advantage of not to worry about synchronization, but if your code takes a longer time to execute it will block the receiving method, buffer the messages and may end up losing messages. For that reason consider to handle messages on the other thread and unblock receiving thread as soon as possible. I've prepared a few examples for you: \n\n#### Default behavior\n\nEvery subscription code is called on a main websocket thread. Every subscription is synchronized together. No parallel execution. It will block the receiving thread. \n\n```csharp\nclient\n    .Streams\n    .TradesStream\n    .Subscribe(trade =\u003e { code1 });\n\nclient\n    .Streams\n    .BookStream\n    .Subscribe(book =\u003e { code2 });\n\n// 'code1' and 'code2' are called in a correct order, according to websocket flow\n// ----- code1 ----- code1 ----- ----- code1\n// ----- ----- code2 ----- code2 code2 -----\n```\n\n#### Parallel subscriptions \n\nEvery single subscription code is called on a separate thread. Every single subscription is synchronized, but different subscriptions are called in parallel. \n\n```csharp\nclient\n    .Streams\n    .TradesStream\n    .ObserveOn(TaskPoolScheduler.Default)\n    .Subscribe(trade =\u003e { code1 });\n\nclient\n    .Streams\n    .BookStream\n    .ObserveOn(TaskPoolScheduler.Default)\n    .Subscribe(book =\u003e { code2 });\n\n// 'code1' and 'code2' are called in parallel, do not follow websocket flow\n// ----- code1 ----- code1 ----- code1 -----\n// ----- code2 code2 ----- code2 code2 code2\n```\n\n #### Parallel subscriptions with synchronization\n\nIn case you want to run your subscription code on the separate thread but still want to follow websocket flow through every subscription, use synchronization with gates: \n\n```csharp\nprivate static readonly object GATE1 = new object();\nclient\n    .Streams\n    .TradesStream\n    .ObserveOn(TaskPoolScheduler.Default)\n    .Synchronize(GATE1)\n    .Subscribe(trade =\u003e { code1 });\n\nclient\n    .Streams\n    .BookStream\n    .ObserveOn(TaskPoolScheduler.Default)\n    .Synchronize(GATE1)\n    .Subscribe(book =\u003e { code2 });\n\n// 'code1' and 'code2' are called concurrently and follow websocket flow\n// ----- code1 ----- code1 ----- ----- code1\n// ----- ----- code2 ----- code2 code2 ----\n```\n\n### Async/Await integration\n\nUsing `async/await` in your subscribe methods is a bit tricky. Subscribe from Rx.NET doesn't `await` tasks, \nso it won't block stream execution and cause sometimes undesired concurrency. For example: \n\n```csharp\nclient\n    .Streams\n    .TradesStream\n    .Subscribe(async trade =\u003e {\n        // do smth 1\n        await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else\n        // do smth 2\n    });\n```\n\nThat `await Task.Delay` won't block stream and subscribe method will be called multiple times concurrently. \nIf you want to buffer messages and process them one-by-one, then use this: \n\n```csharp\nclient\n    .Streams\n    .TradesStream\n    .Select(trade =\u003e Observable.FromAsync(async () =\u003e {\n        // do smth 1\n        await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else\n        // do smth 2\n    }))\n    .Concat() // executes sequentially\n    .Subscribe();\n```\n\nIf you want to process them concurrently (avoid synchronization), then use this\n\n```csharp\nclient\n    .Streams\n    .TradesStream\n    .Select(trade =\u003e Observable.FromAsync(async () =\u003e {\n        // do smth 1\n        await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else\n        // do smth 2\n    }))\n    .Merge() // executes concurrently\n    // .Merge(4) you can limit concurrency with a parameter\n    // .Merge(1) is same as .Concat()\n    // .Merge(0) is invalid (throws exception)\n    .Subscribe();\n```\n\nMore info on [Github issue](https://github.com/dotnet/reactive/issues/459).\n\nDon't worry about websocket connection, those sequential execution via `.Concat()` or `.Merge(1)` has no effect on receiving messages. \nIt won't affect receiving thread, only buffers messages inside `TradesStream`. \n\nBut beware of [producer-consumer problem](https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem) when the consumer will be too slow. Here is a [StackOverflow issue](https://stackoverflow.com/questions/11010602/with-rx-how-do-i-ignore-all-except-the-latest-value-when-my-subscribe-method-is/15876519#15876519) \nwith an example how to ignore/discard buffered messages and always process only the last one. \n\n### Desktop application (WinForms or WPF)\n\nDue to the large amount of questions about integration of this library into a desktop application (old full .NET Framework), I've prepared WinForms example ([link](test_integration/Coinbase.Client.Websocket.Sample.WinForms)). \n\n![WinForms example screen](test_integration/Coinbase.Client.Websocket.Sample.WinForms/winforms_example_app.png)\n\n### Available for help\nI do consulting, please don't hesitate to contact me if you have a custom solution you would like me to implement ([web](http://mkotas.cz/), \n\u003cm@mkotas.cz\u003e)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarfusios%2Fcoinbase-client-websocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarfusios%2Fcoinbase-client-websocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarfusios%2Fcoinbase-client-websocket/lists"}