forked from Marfusios/bitfinex-client-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
370 lines (295 loc) · 17.8 KB
/
Program.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
using System;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading;
using System.Threading.Tasks;
using Bitfinex.Client.Websocket.Client;
using Bitfinex.Client.Websocket.Requests;
using Bitfinex.Client.Websocket.Requests.Subscriptions;
using Bitfinex.Client.Websocket.Responses;
using Bitfinex.Client.Websocket.Responses.Fundings;
using Bitfinex.Client.Websocket.Responses.Trades;
using Bitfinex.Client.Websocket.Utils;
using Bitfinex.Client.Websocket.Websockets;
using Serilog;
using Serilog.Events;
namespace Bitfinex.Client.Websocket.Sample
{
class Program
{
private static readonly ManualResetEvent ExitEvent = new ManualResetEvent(false);
private static readonly string API_KEY = "your_api_key";
private static readonly string API_SECRET = "";
static void Main(string[] args)
{
InitLogging();
AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
AssemblyLoadContext.Default.Unloading += DefaultOnUnloading;
Console.CancelKeyPress += ConsoleOnCancelKeyPress;
Console.WriteLine("|=======================|");
Console.WriteLine("| BITFINEX CLIENT |");
Console.WriteLine("|=======================|");
Console.WriteLine();
Log.Debug("====================================");
Log.Debug(" STARTING ");
Log.Debug("====================================");
var url = BitfinexValues.ApiWebsocketUrl;
using (var communicator = new BitfinexWebsocketCommunicator(url))
{
communicator.Name = "Bitfinex-1";
communicator.ReconnectTimeout = TimeSpan.FromSeconds(30);
communicator.ReconnectionHappened.Subscribe(info =>
Log.Information($"Reconnection happened, type: {info.Type}"));
using (var client = new BitfinexWebsocketClient(communicator))
{
client.Streams.InfoStream.Subscribe(info =>
{
Log.Information($"Info received version: {info.Version}, reconnection happened, resubscribing to streams");
SendSubscriptionRequests(client).Wait();
});
SubscribeToStreams(client);
communicator.Start();
ExitEvent.WaitOne();
}
}
Log.Debug("====================================");
Log.Debug(" STOPPING ");
Log.Debug("====================================");
Log.CloseAndFlush();
}
private static async Task SendSubscriptionRequests(BitfinexWebsocketClient client)
{
//client.Send(new ConfigurationRequest(ConfigurationFlag.Timestamp | ConfigurationFlag.Sequencing));
client.Send(new PingRequest() {Cid = 123456});
//client.Send(new TickerSubscribeRequest("BTC/USD"));
//client.Send(new TickerSubscribeRequest("ETH/USD"));
//client.Send(new TradesSubscribeRequest("BTC/USD"));
//client.Send(new TradesSubscribeRequest("NEC/ETH")); // Nectar coin from ETHFINEX
//client.Send(new FundingsSubscribeRequest("BTC"));
//client.Send(new FundingsSubscribeRequest("USD"));
//client.Send(new CandlesSubscribeRequest("BTC/USD", BitfinexTimeFrame.OneMinute));
//client.Send(new CandlesSubscribeRequest("ETH/USD", BitfinexTimeFrame.OneMinute));
//client.Send(new BookSubscribeRequest("BTC/USD", BitfinexPrecision.P0, BitfinexFrequency.Realtime));
//client.Send(new BookSubscribeRequest("BTC/USD", BitfinexPrecision.P3, BitfinexFrequency.Realtime));
//client.Send(new BookSubscribeRequest("ETH/USD", BitfinexPrecision.P0, BitfinexFrequency.Realtime));
//client.Send(new BookSubscribeRequest("fUSD", BitfinexPrecision.P0, BitfinexFrequency.Realtime));
client.Send(new RawBookSubscribeRequest("BTCUSD", "100"));
//client.Send(new RawBookSubscribeRequest("fUSD", "25"));
//client.Send(new RawBookSubscribeRequest("fBTC", "25"));
//client.Send(new StatusSubscribeRequest("liq:global"));
//client.Send(new StatusSubscribeRequest("deriv:tBTCF0:USTF0"));
if (!string.IsNullOrWhiteSpace(API_SECRET))
{
client.Authenticate(API_KEY, API_SECRET);
#pragma warning disable 4014
Task.Run(async () =>
#pragma warning restore 4014
{
Task.Delay(2000).Wait();
// Place BUY order
//await client.Send(new NewOrderRequest(1, 100, "ETH/USD", OrderType.Limit, 0.2, 103) {Flags = OrderFlag.PostOnly});
//await client.Send(new NewOrderRequest(2, 101, "ETH/USD", OrderType.Limit, 0.2, 102) {Flags = OrderFlag.PostOnly});
//await client.Send(new NewOrderRequest(33, 102, "ETH/USD", OrderType.Limit, 0.2, 101) {Flags = OrderFlag.PostOnly});
// Place SELL order
//await client.Send(new NewOrderRequest(1, 200, "ETH/USD", OrderType.Limit, -0.2, 108) {Flags = OrderFlag.PostOnly});
//await client.Send(new NewOrderRequest(2, 201, "ETH/USD", OrderType.Limit, -0.2, 109) {Flags = OrderFlag.PostOnly});
//await client.Send(new NewOrderRequest(33, 202, "ETH/USD", OrderType.Limit, -0.2, 110) {Flags = OrderFlag.PostOnly});
Task.Delay(7000).Wait();
// Cancel order separately
//await client.Send(new CancelOrderRequest(new CidPair(100, DateTime.UtcNow)));
//await client.Send(new CancelOrderRequest(new CidPair(200, DateTime.UtcNow)));
Task.Delay(7000).Wait();
// Cancel order multi
//await client.Send(new CancelMultiOrderRequest(new[]
//{
// new CidPair(101, DateTime.UtcNow),
// new CidPair(201, DateTime.UtcNow)
//}));
Task.Delay(2000).Wait();
//await client.Send(CancelMultiOrderRequest.CancelGroup(33));
//await client.Send(CancelMultiOrderRequest.CancelEverything());
// request calculations
// await client.Send(new CalcRequest(new[]
// {
// "margin_base",
// "balance",
// }));
});
}
}
private static void SubscribeToStreams(BitfinexWebsocketClient client)
{
// public streams:
client.Streams.ConfigurationStream.Subscribe(x =>
Log.Information($"Configuration happened {x.Status}, flags: {x.Flags}, server timestamp enabled: {client.Configuration.IsTimestampEnabled}"));
client.Streams.PongStream.Subscribe(pong => Log.Information($"Pong received! Id: {pong.Cid}"));
client.Streams.TickerStream.Subscribe(ticker =>
Log.Information($"{ticker.ServerSequence} {ticker.Pair} - last price: {ticker.LastPrice}, bid: {ticker.Bid}, ask: {ticker.Ask}, {ShowServerTimestamp(client, ticker)}"));
client.Streams.TradesSnapshotStream.Subscribe(trades =>
{
foreach (var x in trades)
{
Log.Information(
$"{x.ServerSequence} Trade {x.Pair} from snapshot. Time: {x.Mts:mm:ss.fff}, Amount: {x.Amount}, Price: {x.Price}, {ShowServerTimestamp(client, x)}");
}
});
client.Streams.TradesStream.Where(x => x.Type == TradeType.Executed).Subscribe(x =>
Log.Information($"{x.ServerSequence} Trade {x.Pair} executed. Time: {x.Mts:mm:ss.fff}, Amount: {x.Amount}, Price: {x.Price}, {ShowServerTimestamp(client, x)}"));
client.Streams.FundingStream.Where(x => x.Type == FundingType.Executed).Subscribe(x =>
Log.Information($"Funding, Symbol {x.Symbol} executed. Time: {x.Mts:mm:ss.fff}, Amount: {x.Amount}, Rate: {x.Rate}, Period: {x.Period}"));
client.Streams.CandlesStream.Subscribe(candles =>
{
candles.CandleList.OrderBy(x => x.Mts).ToList().ForEach(x =>
{
Log.Information(
$"Candle(Pair : {candles.Pair} TimeFrame : {candles.TimeFrame.GetStringValue()}) --> {x.Mts} High : {x.High} Low : {x.Low} Open : {x.Open} Close : {x.Close}");
});
});
client.Streams.BookStream.Subscribe(book =>
Log.Information(
book.Period <= 0 ?
$"{book.ServerSequence} Book | channel: {book.ChanId} pair: {book.Pair}, price: {book.Price}, amount {book.Amount}, count: {book.Count}, {ShowServerTimestamp(client, book)}" :
$"{book.ServerSequence} Book | channel: {book.ChanId} sym: {book.Symbol}, rate: {book.Rate*100}% (p.a. {(book.Rate*100*365):F}%), period: {book.Period} amount {book.Amount}, count: {book.Count}, {ShowServerTimestamp(client, book)}"));
client.Streams.RawBookStream.Subscribe(book =>
{
Log.Information(
book.OrderId > 0
? $"{book.ServerSequence} RawBook | channel: {book.ChanId} pair: {book.Pair}, order: {book.OrderId}, price: {book.Price}, amount {book.Amount} {ShowServerTimestamp(client, book)}"
: $"{book.ServerSequence} RawBook | channel: {book.ChanId} sym: {book.Symbol}, offer: {book.OfferId}, period: {book.Period} days, rate {book.Rate*100}% (p.a. {(book.Rate*100*365):F}%) {ShowServerTimestamp(client, book)}");
});
client.Streams.CandlesStream.Subscribe(candles =>
{
candles.CandleList.OrderBy(x => x.Mts).ToList().ForEach(x =>
{
Log.Information(
$"Candle(Pair : {candles.Pair} TimeFrame : {candles.TimeFrame.GetStringValue()}) --> {x.Mts} High : {x.High} Low : {x.Low} Open : {x.Open} Close : {x.Close}");
});
});
client.Streams.BookChecksumStream.Subscribe(x =>
Log.Information($"{x.ServerSequence} [CHECKSUM] {x.Pair}-{x.ChanId} {x.Checksum}"));
// Private streams:
client.Streams.AuthenticationStream.Subscribe(auth => Log.Information($"Authenticated: {auth.IsAuthenticated}"));
client.Streams.WalletStream
.Subscribe(wallet =>
Log.Information($"Wallet {wallet.Currency} balance: {wallet.Balance} type: {wallet.Type}"));
client.Streams.OrdersStream.Subscribe(orders =>
{
foreach (var info in orders)
{
Log.Information($"Order #{info.Cid} group: {info.Gid} snapshot: {info.Pair} - {info.Type} - {info.Amount} @ {info.Price} | {info.OrderStatus}");
}
});
client.Streams.OrderCreatedStream.Subscribe(async info =>
{
Log.Information(
$"Order #{info.Cid} group: {info.Gid} created: {info.Pair} - {info.Type} - {info.Amount} @ {info.Price} | {info.OrderStatus}");
// Update order
//await Task.Delay(5000);
//await client.Send(new UpdateOrderRequest(info.Id)
//{
// Price = info.Price - 1,
// Amount = info.Amount + 0.1 * Math.Sign(info.Amount ?? 0),
// Flags = OrderFlag.PostOnly
//});
});
client.Streams.OrderUpdatedStream.Subscribe(info =>
Log.Information($"Order #{info.Cid} group: {info.Gid} updated: {info.Pair} - {info.Type} - {info.Amount} @ {info.Price} | {info.OrderStatus}"));
client.Streams.OrderCanceledStream.Subscribe(info =>
Log.Information($"Order #{info.Cid} group: {info.Gid} {info.OrderStatus}: {info.Pair} - {info.Type} - {info.Amount} @ {info.Price}"));
client.Streams.PrivateTradeStream.Subscribe(trade =>
Log.Information($"Private trade {trade.Pair} executed. Time: {trade.MtsCreate:mm:ss.fff}, Amount: {trade.ExecAmount}, Price: {trade.ExecPrice}, " +
$"Fee: {trade.Fee} {trade.FeeCurrency}, type: {trade.OrderType}, " +
$"{ShowServerSequence(client, trade)}, {ShowServerTimestamp(client, trade)}"));
client.Streams.PositionsStream.Subscribe(positions =>
{
foreach (var info in positions)
{
Log.Information($"Position snapshot: {info.Pair} - {info.Status} - {info.Amount} @ {info.BasePrice} " +
$"| PL: {info.ProfitLoss} {info.ProfitLossPercentage}% " +
$"{ShowServerSequence(client, info)}, {ShowServerTimestamp(client, info)}");
}
});
client.Streams.PositionCreatedStream.Subscribe(info =>
Log.Information($"Position created: {info.Pair} - {info.Status} - {info.Amount} @ {info.BasePrice} " +
$"| PL: {info.ProfitLoss} {info.ProfitLossPercentage}% " +
$"{ShowServerTimestamp(client, info)}"));
client.Streams.PositionUpdatedStream.Subscribe(info =>
Log.Information($"Position updated: {info.Pair} - {info.Status} - {info.Amount} @ {info.BasePrice} " +
$"| PL: {info.ProfitLoss} {info.ProfitLossPercentage}% " +
$"{ShowServerTimestamp(client, info)}"));
client.Streams.PositionCanceledStream.Subscribe(info =>
Log.Information($"Position canceled: {info.Pair} - {info.Status} - {info.Amount} @ {info.BasePrice} " +
$"| PL: {info.ProfitLoss} {info.ProfitLossPercentage}% " +
$"{ShowServerTimestamp(client, info)}"));
client.Streams.NotificationStream.Subscribe(notification =>
Log.Information(
$"Notification: {notification.Text} code: {notification.Code}, status: {notification.Status}, type : {notification.Type}"));
client.Streams.BalanceInfoStream.Subscribe(info =>
Log.Information($"Balance, total: {info.TotalAum}, net: {info.NetAum}"));
client.Streams.MarginInfoStream.Subscribe(info =>
Log.Information(
$"Margin, balance: {info.MarginBalance}, required: {info.MarginRequired}, net: {info.MarginNet}, p/l: {info.UserPl}, swaps: {info.UserSwaps}"));
client.Streams.DerivativePairStream.Subscribe(info =>
{
Log.Information(
$"Derivative status, symbol: {info.Symbol}, derivPrice: {info.DerivPrice}, spot price: {info.SpotPrice}, insurance fund balance: {info.InsuranceFundBalance}, funding: {info.FundingAccrued}, funding step: {info.FundingStep}");
});
client.Streams.LiquidationFeedStream.Subscribe(info =>
{
Log.Information(
$"Liquidation, symbol: {info.Symbol}, position id: {info.PosId}, amount: {info.Amount}, base price: {info.BasePrice}, is match: {info.IsMatch}, market sold: {info.IsMarketSold}");
});
// Unsubscription example:
//client.Streams.SubscriptionStream.ObserveOn(TaskPoolScheduler.Default).Subscribe(info =>
//{
// if(!info.Channel.Contains("book"))
// return;
// Task.Delay(5000).Wait();
// var channelId = info.ChanId;
// client.Send(new UnsubscribeRequest() {ChanId = channelId}).Wait();
//});
}
private static string ShowServerTimestamp(BitfinexWebsocketClient client, ResponseBase response)
{
if(!client.Configuration.IsTimestampEnabled)
return string.Empty;
return $"server timestamp: {response.ServerTimestamp:mm:ss.fff}";
}
private static string ShowServerSequence(BitfinexWebsocketClient client, ResponseBase response)
{
if(!client.Configuration.IsSequencingEnabled)
return string.Empty;
return $"sequence: {response.ServerSequence} / {response.ServerPrivateSequence}";
}
private static void InitLogging()
{
var executingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var logPath = Path.Combine(executingDir, "logs", "verbose.log");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.File(logPath, rollingInterval: RollingInterval.Day)
.WriteTo.ColoredConsole(LogEventLevel.Debug, outputTemplate:
"[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
}
private static void CurrentDomainOnProcessExit(object sender, EventArgs eventArgs)
{
Log.Warning("Exiting process");
ExitEvent.Set();
}
private static void DefaultOnUnloading(AssemblyLoadContext assemblyLoadContext)
{
Log.Warning("Unloading process");
ExitEvent.Set();
}
private static void ConsoleOnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Log.Warning("Canceling process");
e.Cancel = true;
ExitEvent.Set();
}
}
}