forked from DigitalRuby/ExchangeSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseOption.cs
240 lines (201 loc) · 5.48 KB
/
BaseOption.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using ExchangeSharp;
using ExchangeSharpConsole.Utilities;
#if DEBUG
using System.Diagnostics;
using CommandLine;
#endif
namespace ExchangeSharpConsole.Options
{
public abstract class BaseOption
{
#if DEBUG
[Option("debug", HelpText = "Waits for a debugger to be attached.")]
public bool Debug { get; set; }
public async Task CheckDebugger()
{
if (!Debug)
{
return;
}
using (var proc = Process.GetCurrentProcess())
{
Console.Error.WriteLine($"Connect debugger to PID: {proc.Id}.");
Console.Error.WriteLine("Waiting...");
}
while (!Debugger.IsAttached)
{
await Task.Delay(100);
}
}
#endif
public bool IsInteractiveSession
=> !(Console.IsInputRedirected || Console.IsOutputRedirected || Console.IsErrorRedirected);
public abstract Task RunCommand();
protected void Authenticate(IExchangeAPI api)
{
Console.Write("Enter Public Api Key: ");
var publicApiKey = GetSecureInput();
api.PublicApiKey = publicApiKey;
Console.WriteLine();
Console.Write("Enter Private Api Key: ");
var privateApiKey = GetSecureInput();
api.PrivateApiKey = privateApiKey;
Console.WriteLine();
Console.Write("Enter Passphrase: ");
var passphrase = GetSecureInput();
api.Passphrase = passphrase;
Console.WriteLine();
}
protected SecureString GetSecureInput()
{
if (!IsInteractiveSession)
{
throw new NotSupportedException(
"It still not supported to read secure input without a interactive terminal session."
);
}
var pwd = new SecureString();
while (true)
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
break;
}
if (i.Key == ConsoleKey.Backspace)
{
if (pwd.Length <= 0)
continue;
pwd.RemoveAt(pwd.Length - 1);
Console.Write("\b \b");
}
// KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc
else if (i.KeyChar != '\u0000')
{
pwd.AppendChar(i.KeyChar);
Console.Write("*");
}
}
return pwd;
}
protected void Assert(bool expression)
{
if (!expression)
{
throw new ApplicationException("Test failure, unexpected result");
}
}
protected void WaitInteractively()
{
if (!IsInteractiveSession)
{
Console.Error.WriteLine("Ignoring interactive action.");
return;
}
Console.Write("Press any key to continue...");
Console.ReadKey(true);
Console.CursorLeft = 0;
}
protected IExchangeAPI GetExchangeInstance(string exchangeName)
{
return ExchangeAPI.GetExchangeAPI(exchangeName);
}
protected async Task RunWebSocket(string exchangeName, Func<IExchangeAPI, Task<IWebSocket>> getWebSocket)
{
using var api = ExchangeAPI.GetExchangeAPI(exchangeName);
Console.WriteLine("Connecting web socket to {0}...", api.Name);
IWebSocket socket = null;
var tcs = new TaskCompletionSource<bool>();
// ReSharper disable once AccessToModifiedClosure
var disposable = KeepSessionAlive(() =>
{
socket?.Dispose();
tcs.TrySetResult(true);
});
try
{
socket = await getWebSocket(api);
socket.Connected += _ =>
{
Console.WriteLine("Web socket connected.");
return Task.CompletedTask;
};
socket.Disconnected += _ =>
{
Console.WriteLine("Web socket disconnected.");
// ReSharper disable once AccessToDisposedClosure
disposable.Dispose();
return Task.CompletedTask;
};
await tcs.Task;
}
catch
{
disposable.Dispose();
throw;
}
}
/// <summary>
/// Makes the app keep running after main thread has exited
/// </summary>
/// <param name="callback">A callback for when the user press CTRL-C or Q</param>
protected static IDisposable KeepSessionAlive(Action callback = null)
=> new ConsoleSessionKeeper(callback);
protected static async Task<string[]> ValidateMarketSymbolsAsync(IExchangeAPI api, string[] marketSymbols)
{
var apiSymbols = (await api.GetMarketSymbolsAsync()).ToArray();
if (marketSymbols is null || marketSymbols.Length == 0)
{
return apiSymbols;
}
return ValidateMarketSymbolsInternal(api, marketSymbols, apiSymbols)
.ToArray();
}
private static IEnumerable<string> ValidateMarketSymbolsInternal(
IExchangeAPI api,
string[] marketSymbols,
string[] apiSymbols
)
{
foreach (var marketSymbol in marketSymbols)
{
var apiSymbol = apiSymbols.FirstOrDefault(
a => a.Equals(marketSymbol, StringComparison.OrdinalIgnoreCase)
);
if (!string.IsNullOrWhiteSpace(apiSymbol))
{
//return this for proper casing
yield return apiSymbol;
continue;
}
var validSymbols = string.Join(",", apiSymbols.OrderBy(s => s));
throw new ArgumentException(
$"Symbol {marketSymbol} does not exist in API {api.Name}.\n" +
$"Valid symbols: {validSymbols}"
);
}
}
protected void PrintOrderBook(ExchangeOrderBook orderBook)
{
Console.WriteLine($"{"BID",-22} | {"ASK",22}");
Console.WriteLine("---");
var length = orderBook.Asks.Count;
if (orderBook.Bids.Count > length)
{
length = orderBook.Bids.Count;
}
for (var i = 0; i < length; i++)
{
var (_, ask) = orderBook.Asks.ElementAtOrDefault(i);
var (_, bid) = orderBook.Bids.ElementAtOrDefault(i);
Console.WriteLine($"{bid.Price,10} ({bid.Amount,9:N2}) | " +
$"{ask.Price,10} ({ask.Amount,9:N})");
}
}
}
}