-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
WebSocketSnippets.cs
85 lines (69 loc) · 2.17 KB
/
WebSocketSnippets.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Threading.Tasks;
using Coinbase.Pro.Models;
using Coinbase.Pro.WebSockets;
using WebSocket4Net;
class WebSocketSnippets
{
void CoinbaseProWebSocket()
{
#region CoinbaseProWebSocket
//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"
});
#endregion
}
void UnauthenticatedCoinbaseProWebSocket()
{
#region UnauthenticatedCoinbaseProWebSocket
var socket = new CoinbaseProWebSocket();
#endregion
}
async Task SubscribingToEvents(CoinbaseProWebSocket socket)
{
#region SubscribingToEvents
//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));
#endregion
}
#region RawSocket_MessageReceived
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}");
}
}
}
#endregion
}