Bchavez Coinbase.Pro Save

:chart_with_upwards_trend: A .NET/C# implementation of the Coinbase Pro API.

Project README

Build status Nuget Users

Coinbase.Pro for .NET/C# Library

Project Description

A .NET implementation for the Coinbase Pro API.

:loudspeaker: HEY! Be sure to checkout these other Coinbase API integrations:

  • Coinbase - For Coinbase wallet account integration.
  • Coinbase.Commerce - For e-commerce, merchants, and websites selling products or services looking to receive cryptocurrency as payment.

Minimum Requirements

  • .NET Standard 2.0 or later
  • .NET Framework 4.6.1 or later
  • TLS 1.2 or later

Note: If you are using .NET Framework 4.6.1 you will need to ensure your application is using TLS 1.2 or later. This can be configured via the registry (link 1, link 2) or configured at application startup by setting the following value in ServicePointManager:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Crypto Tip Jar

Download & Install

Nuget Package Coinbase.Pro

Install-Package Coinbase.Pro

Getting Started

To get started, simply create a new CoinbaseProClient object as shown below:

var client = new CoinbaseProClient(new Config
   {
      ApiKey = "my-api-key",
      Secret = "my-api-secret",
      Passphrase = "my-api-passphrase",
      //Override the ApiUrl property to use Sandbox.
      //ApiUrl = "https://api-public.sandbox.pro.coinbase.com"
   });

snippet source | anchor

By default, the ApiUrl property is set to use production. If you want to use the sandbox, set the ApiUrl property to https://api-public.sandbox.pro.coinbase.com as described in the documentation here. Setting the ApiUrl property will override the production REST API URL that is set by default.

Once you have a CoinbaseProClient object, you can call any one of the many API endpoints listed here. Extensive examples can be found here. For your reference, a link to the Coinbase Pro developer documentation can be found here.

As an example, to create a limit order on the buy side of the ETH-USD order book for 2 ETH at 100 USD each, do the following:

var order = await client.Orders.PlaceLimitOrderAsync(
   OrderSide.Buy, "ETH-USD", size: 2, limitPrice: 100m);

order.Dump();

snippet source | anchor

The order object returned by the trading engine will have similar values to the following JSON object:

{
  "id": "ba3d3318-d1f0-4f9d-ae6f-1bda6ff370fa",
  "price": 100.00000000,
  "size": 2.00000000,
  "product_id": "ETH-USD",
  "side": "buy",
  "stp": "dc",
  "type": "limit",
  "time_in_force": "GTC",
  "post_only": true,
  "created_at": "2018-11-30T05:11:54.000355+00:00",
  "fill_fees": 0.0000000000000000,
  "filled_size": 0.00000000,
  "executed_value": 0.0000000000000000,
  "status": "pending",
  "settled": false,
  "funds": 0.0,
  "specified_funds": 0.0
}

Full API Support

Private Endpoints
Market Data Endpoints
WebSocket Feed

Error Handling

When errors occur after calling an API, Coinbase Pro delivers error messages in the response body of a failed HTTP call. First wrap your call in a try/catch statement and handle the Exception ex. Next, get the error message of a failed API call by calling GetErrorMessageAsync() extension method on the exception. The GetErrorMessageAsync() extension method will read the response body of the failed HTTP call as shown below:

try
{
   var order = await client.Orders.PlaceLimitOrderAsync(
      OrderSide.Buy, "BTCX-USDX", size: 1, limitPrice: 5000m);
}
catch( Exception ex )
{
   var errorMsg = await ex.GetErrorMessageAsync();
   Console.WriteLine(errorMsg);
}
//OUTPUT: "Product not found"

snippet source | anchor

Pagination

Some Coinbase Pro APIs are paginable. However, Coinbase Pro's paging can be a little confusing at first. So, let's review. Consider the following diagram below that illustrates the Current Point In Time over a paginable set of data with an item size of 5 items per page:

    Five Items Per Page (limit=5)
     
Past                         Future
Older                         Newer
11   15 16   20     21   25 26   30
[items] [items]     [items] [items]
              ^
      After <-|-> Before
              ^
              |
    Current Point In Time

Suppose you grabbed the most recent trades from var trades = client.MarketData.GetTradesAsync("ETH-USD", limit: 5). The data you captured in trades is the Current Point In Time with the most recent trade 20 as shown in the diagram above.

  • To enumerate older trades beyond the initial page:

//Get the initial page, items 16 through 20
var trades = await client.MarketData.GetTradesAsync("ETC-USD", limit: 5);

//Get the next batch of older trades after the current page.
while( trades.After is not null )
{
   trades = await client.MarketData.GetTradesAsync("ETC-USD", limit: 5, after: trades.After);
}

snippet source | anchor

Now suppose time advances, more trades happen in the market. Given the Current Point In Time with the initial page of items 16-20.

  • To enumerate newer trades beyond the initial page:

//Get the initial page, items 16 through 20
var trades = await client.MarketData.GetTradesAsync("ETC-USD", limit: 5);

//Some time advances, trades execute.

//Now, get the next batch of newer trades before the current page.
while( trades.Before is not null )
{
   trades = await client.MarketData.GetTradesAsync("ETC-USD", limit: 5, before: trades.Before);
}

snippet source | anchor

More information about pagination can be found here.

WebSocket Feeds

This library also supports live WebSocket feeds. There are two types Authenticated and Unauthenticated feeds.

Unauthenticated WebSocket

To create an unauthenticated feed, simply do the following:

var socket = new CoinbaseProWebSocket();

snippet source | anchor

Authenticated WebSocket

To create an authenticated feed, doing the following:

//authenticated feed
var socket = new CoinbaseProWebSocket(new WebSocketConfig
   {
      ApiKey = "my-api-key",
      Secret = "my-api-secret",
      Passphrase = "my-api-passphrase",
      //Override the SocketUri property to use Sandbox.
      //SocketUri = "wss://ws-feed-public.sandbox.pro.coinbase.com"
   });

snippet source | anchor

By default, the SocketUri property is set to use production. If you want to use the sandbox, set the SocketUri property to wss://ws-feed-public.sandbox.pro.coinbase.com as described in the documentation here. Setting the SocketUri property will override the production Websocket feed URL that is set by default.

Subscribing to Events over WebSocket

Be sure to check the documentation here to know all the events you can subscribe to. The following example demonstrates how to continue setting up the WebSocket for simple heartbeat events.

//Using authenticated or unauthenticated instance `socket`
//Connect the websocket,
//when this connect method completes, the socket is ready or failure occured.
var result = await socket.ConnectAsync();
if( !result.Success ) throw new Exception("Failed to connect.");

//add an event handler for the message received event on the raw socket
socket.RawSocket.MessageReceived += RawSocket_MessageReceived;

//create a subscription of what to listen to
var sub = new Subscription
   {
      ProductIds =
         {
            "BTC-USD",
         },
      Channels =
         {
            "heartbeat",
         }
   };

//send the subscription upstream
await socket.SubscribeAsync(sub);

//now wait for data.
await Task.Delay(TimeSpan.FromMinutes(1));

snippet source | anchor

Once your subscription is sent upstream, you should start receiving events over the WebSocket. The following example shows how to process incoming messages as they arrive:

void RawSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
   //Try parsing the e.Message JSON.
   if( WebSocketHelper.TryParse(e.Message, out var msg) )
   {
      if( msg is HeartbeatEvent hb )
      {
         Console.WriteLine($"Sequence: {hb.Sequence}, Last Trade Id: {hb.LastTradeId}");
      }
   }
}

snippet source | anchor

A complete working example can be found here and here.

If you'd like to use your own WebSocket implementation, the WebSocketHelper is a helpful utility class for creating authenticated JSON subscription messages.


Easy peasy! Happy crypto trading! :tada:

Reference

Building

  • Download the source code.
  • Run build.cmd.

Upon successful build, the results will be in the \__compile directory. If you want to build NuGet packages, run build.cmd pack and the NuGet packages will be in __package.

Contributors

Created by Brian Chavez.

A big thanks to GitHub and all contributors:


Note: This application/third-party library is not directly supported by Coinbase Inc. Coinbase Inc. makes no claims about this application/third-party library. This application/third-party library is not endorsed or certified by Coinbase Inc.

Open Source Agenda is not affiliated with "Bchavez Coinbase.Pro" Project. README Source: bchavez/Coinbase.Pro

Open Source Agenda Badge

Open Source Agenda Rating