Skip to content

Commit f2bdde4

Browse files
authored
Merge pull request #22 from morpheums/development
Fixing issue calling GetPriceChange24H method for a single ticker. Me…
2 parents 64efb0c + 0cfadf1 commit f2bdde4

File tree

5 files changed

+105
-23
lines changed

5 files changed

+105
-23
lines changed

Binance.API.Csharp.Client.Test/BinanceTest.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@ public void GetAggregateTrades()
4747
[TestMethod]
4848
public void GetPriceChange24H()
4949
{
50-
var priceChangeInfo = binanceClient.GetPriceChange24H().Result;
50+
var singleTickerInfo = binanceClient.GetPriceChange24H("ETHBTC").Result;
51+
52+
var allTickersInfo = binanceClient.GetPriceChange24H().Result;
5153
}
5254

5355
[TestMethod]

Binance.API.Csharp.Client/ApiClient.cs

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
using Binance.API.Csharp.Client.Models.Enums;
99
using WebSocketSharp;
1010
using Binance.API.Csharp.Client.Models.WebSocket;
11+
using System.Net;
12+
using Newtonsoft.Json.Linq;
1113

1214
namespace Binance.API.Csharp.Client
1315
{
@@ -39,18 +41,53 @@ public async Task<T> CallAsync<T>(ApiMethod method, string endpoint, bool isSign
3941

4042
if (isSigned)
4143
{
42-
parameters += (!string.IsNullOrWhiteSpace(parameters) ? "&timestamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now);
44+
// Joining provided parameters
45+
parameters += (!string.IsNullOrWhiteSpace(parameters) ? "&timestamp=" : "timestamp=") + Utilities.GenerateTimeStamp(DateTime.Now.ToUniversalTime());
46+
47+
// Creating request signature
4348
var signature = Utilities.GenerateSignature(_apiSecret, parameters);
4449
finalEndpoint = $"{endpoint}?{parameters}&signature={signature}";
4550
}
4651

4752
var request = new HttpRequestMessage(Utilities.CreateHttpMethod(method.ToString()), finalEndpoint);
48-
4953
var response = await _httpClient.SendAsync(request).ConfigureAwait(false);
50-
response.EnsureSuccessStatusCode();
54+
if (response.IsSuccessStatusCode)
55+
{
56+
// Api return is OK
57+
response.EnsureSuccessStatusCode();
58+
59+
// Get the result
60+
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
61+
62+
// Serialize and return result
63+
return JsonConvert.DeserializeObject<T>(result);
64+
}
65+
66+
// We received an error
67+
if (response.StatusCode == HttpStatusCode.GatewayTimeout)
68+
{
69+
throw new Exception("Api Request Timeout.");
70+
}
71+
72+
// Get te error code and message
73+
var e = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
74+
75+
// Error Values
76+
var eCode = 0;
77+
string eMsg = "";
78+
if (e.IsValidJson())
79+
{
80+
try
81+
{
82+
var i = JObject.Parse(e);
83+
84+
eCode = i["code"]?.Value<int>() ?? 0;
85+
eMsg = i["msg"]?.Value<string>();
86+
}
87+
catch { }
88+
}
5189

52-
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
53-
return JsonConvert.DeserializeObject<T>(result);
90+
throw new Exception(string.Format("Api Error Code: {0} Message: {1}", eCode, eMsg));
5491
}
5592

5693
/// <summary>

Binance.API.Csharp.Client/Binance.API.Csharp.Client.nuspec

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@
22
<package >
33
<metadata>
44
<id>Binance.API.Csharp.Client</id>
5-
<version>1.2.1</version>
5+
<version>1.4.0</version>
66
<title>Binance.API.Csharp.Client</title>
77
<authors>Jose Mejia</authors>
88
<owners>Jose Mejia</owners>
99
<projectUrl>https://github.com/morpheums/Binance.API.Csharp.Helper</projectUrl>
1010
<iconUrl>https://github.com/morpheums/Binance.API.Csharp.Client/blob/master/Binance.API.Csharp.Client/BinanceLogo.png?raw=true</iconUrl>
1111
<requireLicenseAcceptance>false</requireLicenseAcceptance>
1212
<description>C#.NET client for Binance Exchange API.</description>
13-
<releaseNotes>Fixing issue including dependencies dlls.</releaseNotes>
13+
<releaseNotes>Fixing issue calling GetPriceChange24H method for a single ticker. Methods now return original error code and messages.
14+
</releaseNotes>
1415
<copyright>Copyright 2017</copyright>
1516
<tags>Criptocurrency Binance API dotnet csharp wrapper</tags>
1617
<dependencies>

Binance.API.Csharp.Client/BinanceClient.cs

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ public async Task<IEnumerable<Candlestick>> GetCandleSticks(string symbol, TimeI
172172
}
173173

174174
var args = $"symbol={symbol.ToUpper()}&interval={interval.GetDescription()}"
175-
+ (startTime .HasValue ? $"&startTime={startTime.Value.GetUnixTimeStamp()}" : "")
175+
+ (startTime.HasValue ? $"&startTime={startTime.Value.GetUnixTimeStamp()}" : "")
176176
+ (endTime.HasValue ? $"&endTime={endTime.Value.GetUnixTimeStamp()}" : "")
177177
+ $"&limit={limit}";
178178

@@ -193,7 +193,17 @@ public async Task<IEnumerable<PriceChangeInfo>> GetPriceChange24H(string symbol
193193
{
194194
var args = string.IsNullOrWhiteSpace(symbol) ? "" : $"symbol={symbol.ToUpper()}";
195195

196-
var result = await _apiClient.CallAsync<IEnumerable< PriceChangeInfo>>(ApiMethod.GET, EndPoints.TickerPriceChange24H, false, args);
196+
var result = new List<PriceChangeInfo>();
197+
198+
if (!string.IsNullOrEmpty(symbol))
199+
{
200+
var data = await _apiClient.CallAsync<PriceChangeInfo>(ApiMethod.GET, EndPoints.TickerPriceChange24H, false, args);
201+
result.Add(data);
202+
}
203+
else
204+
{
205+
result = await _apiClient.CallAsync<List<PriceChangeInfo>>(ApiMethod.GET, EndPoints.TickerPriceChange24H, false, args);
206+
}
197207

198208
return result;
199209
}
@@ -233,7 +243,7 @@ public async Task<IEnumerable<OrderBookTicker>> GetOrderBookTicker()
233243
/// <param name="timeInForce">Indicates how long an order will remain active before it is executed or expires.</param>
234244
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
235245
/// <returns></returns>
236-
public async Task<NewOrder> PostNewOrder(string symbol, decimal quantity, decimal price, OrderSide side, OrderType orderType = OrderType.LIMIT, TimeInForce timeInForce = TimeInForce.GTC, decimal icebergQty = 0m, long recvWindow = 6000000)
246+
public async Task<NewOrder> PostNewOrder(string symbol, decimal quantity, decimal price, OrderSide side, OrderType orderType = OrderType.LIMIT, TimeInForce timeInForce = TimeInForce.GTC, decimal icebergQty = 0m, long recvWindow = 5000)
237247
{
238248
//Validates that the order is valid.
239249
ValidateOrderValue(symbol, orderType, price, quantity, icebergQty);
@@ -259,7 +269,7 @@ public async Task<NewOrder> PostNewOrder(string symbol, decimal quantity, decima
259269
/// <param name="timeInForce">Indicates how long an order will remain active before it is executed or expires.</param>
260270
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
261271
/// <returns></returns>
262-
public async Task<dynamic> PostNewOrderTest(string symbol, decimal quantity, decimal price, OrderSide side, OrderType orderType = OrderType.LIMIT, TimeInForce timeInForce = TimeInForce.GTC, decimal icebergQty = 0m, long recvWindow = 6000000)
272+
public async Task<dynamic> PostNewOrderTest(string symbol, decimal quantity, decimal price, OrderSide side, OrderType orderType = OrderType.LIMIT, TimeInForce timeInForce = TimeInForce.GTC, decimal icebergQty = 0m, long recvWindow = 5000)
263273
{
264274
//Validates that the order is valid.
265275
ValidateOrderValue(symbol, orderType, price, quantity, icebergQty);
@@ -282,7 +292,7 @@ public async Task<dynamic> PostNewOrderTest(string symbol, decimal quantity, dec
282292
/// <param name="origClientOrderId">origClientOrderId of the order to retrieve.</param>
283293
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
284294
/// <returns></returns>
285-
public async Task<Order> GetOrder(string symbol, long? orderId = null, string origClientOrderId = null, long recvWindow = 6000000)
295+
public async Task<Order> GetOrder(string symbol, long? orderId = null, string origClientOrderId = null, long recvWindow = 5000)
286296
{
287297
var args = $"symbol={symbol.ToUpper()}&recvWindow={recvWindow}";
288298

@@ -317,7 +327,7 @@ public async Task<Order> GetOrder(string symbol, long? orderId = null, string or
317327
/// <param name="origClientOrderId">origClientOrderId of the order to cancel.</param>
318328
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
319329
/// <returns></returns>
320-
public async Task<CanceledOrder> CancelOrder(string symbol, long? orderId = null, string origClientOrderId = null, long recvWindow = 6000000)
330+
public async Task<CanceledOrder> CancelOrder(string symbol, long? orderId = null, string origClientOrderId = null, long recvWindow = 5000)
321331
{
322332
if (string.IsNullOrWhiteSpace(symbol))
323333
{
@@ -350,7 +360,7 @@ public async Task<CanceledOrder> CancelOrder(string symbol, long? orderId = null
350360
/// <param name="symbol">Ticker symbol.</param>
351361
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
352362
/// <returns></returns>
353-
public async Task<IEnumerable<Order>> GetCurrentOpenOrders(string symbol, long recvWindow = 6000000)
363+
public async Task<IEnumerable<Order>> GetCurrentOpenOrders(string symbol, long recvWindow = 5000)
354364
{
355365
if (string.IsNullOrWhiteSpace(symbol))
356366
{
@@ -370,7 +380,7 @@ public async Task<IEnumerable<Order>> GetCurrentOpenOrders(string symbol, long r
370380
/// <param name="limit">Limit of records to retrieve.</param>
371381
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
372382
/// <returns></returns>
373-
public async Task<IEnumerable<Order>> GetAllOrders(string symbol, long? orderId = null, int limit = 500, long recvWindow = 6000000)
383+
public async Task<IEnumerable<Order>> GetAllOrders(string symbol, long? orderId = null, int limit = 500, long recvWindow = 5000)
374384
{
375385
if (string.IsNullOrWhiteSpace(symbol))
376386
{
@@ -387,7 +397,7 @@ public async Task<IEnumerable<Order>> GetAllOrders(string symbol, long? orderId
387397
/// </summary>
388398
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
389399
/// <returns></returns>
390-
public async Task<AccountInfo> GetAccountInfo(long recvWindow = 6000000)
400+
public async Task<AccountInfo> GetAccountInfo(long recvWindow = 5000)
391401
{
392402
var result = await _apiClient.CallAsync<AccountInfo>(ApiMethod.GET, EndPoints.AccountInformation, true, $"recvWindow={recvWindow}");
393403

@@ -400,7 +410,7 @@ public async Task<AccountInfo> GetAccountInfo(long recvWindow = 6000000)
400410
/// <param name="symbol">Ticker symbol.</param>
401411
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
402412
/// <returns></returns>
403-
public async Task<IEnumerable<Trade>> GetTradeList(string symbol, long recvWindow = 6000000)
413+
public async Task<IEnumerable<Trade>> GetTradeList(string symbol, long recvWindow = 5000)
404414
{
405415
if (string.IsNullOrWhiteSpace(symbol))
406416
{
@@ -421,7 +431,7 @@ public async Task<IEnumerable<Trade>> GetTradeList(string symbol, long recvWindo
421431
/// <param name="addressName">Address name.</param>
422432
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
423433
/// <returns></returns>
424-
public async Task<WithdrawResponse> Withdraw(string asset, decimal amount, string address, string addressName = "", long recvWindow = 6000000)
434+
public async Task<WithdrawResponse> Withdraw(string asset, decimal amount, string address, string addressName = "", long recvWindow = 5000)
425435
{
426436
if (string.IsNullOrWhiteSpace(asset))
427437
{
@@ -454,7 +464,7 @@ public async Task<WithdrawResponse> Withdraw(string asset, decimal amount, strin
454464
/// <param name="endTime">End time.</param>
455465
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
456466
/// <returns></returns>
457-
public async Task<DepositHistory> GetDepositHistory(string asset, DepositStatus? status = null, DateTime? startTime = null, DateTime? endTime = null, long recvWindow = 6000000)
467+
public async Task<DepositHistory> GetDepositHistory(string asset, DepositStatus? status = null, DateTime? startTime = null, DateTime? endTime = null, long recvWindow = 5000)
458468
{
459469
if (string.IsNullOrWhiteSpace(asset))
460470
{
@@ -481,7 +491,7 @@ public async Task<DepositHistory> GetDepositHistory(string asset, DepositStatus?
481491
/// <param name="endTime">End time.</param>
482492
/// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param>
483493
/// <returns></returns>
484-
public async Task<WithdrawHistory> GetWithdrawHistory(string asset, WithdrawStatus? status = null, DateTime? startTime = null, DateTime? endTime = null, long recvWindow = 6000000)
494+
public async Task<WithdrawHistory> GetWithdrawHistory(string asset, WithdrawStatus? status = null, DateTime? startTime = null, DateTime? endTime = null, long recvWindow = 5000)
485495
{
486496
if (string.IsNullOrWhiteSpace(asset))
487497
{
@@ -612,7 +622,6 @@ public string ListenUserDataEndpoint(ApiClientAbstract.MessageHandler<AccountUpd
612622

613623
return listenKey;
614624
}
615-
616625
#endregion
617626
}
618627
}

Binance.API.Csharp.Client/Utils/ExtensionMethods.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System;
1+
using Newtonsoft.Json;
2+
using Newtonsoft.Json.Linq;
3+
using System;
24
using System.ComponentModel;
35
using System.Linq;
46
using System.Reflection;
@@ -32,5 +34,36 @@ public static string GetUnixTimeStamp(this DateTime baseDateTime)
3234
var dtOffset = new DateTimeOffset(baseDateTime);
3335
return dtOffset.ToUnixTimeMilliseconds().ToString();
3436
}
37+
38+
/// <summary>
39+
/// Validates if string is a valid JSON
40+
/// </summary>
41+
/// <param name="stringValue">String to validate</param>
42+
/// <returns></returns>
43+
public static bool IsValidJson(this string stringValue)
44+
{
45+
if (string.IsNullOrWhiteSpace(stringValue))
46+
{
47+
return false;
48+
}
49+
50+
var value = stringValue.Trim();
51+
52+
if ((value.StartsWith("{") && value.EndsWith("}")) || //For object
53+
(value.StartsWith("[") && value.EndsWith("]"))) //For array
54+
{
55+
try
56+
{
57+
var obj = JToken.Parse(value);
58+
return true;
59+
}
60+
catch (JsonReaderException)
61+
{
62+
return false;
63+
}
64+
}
65+
66+
return false;
67+
}
3568
}
3669
}

0 commit comments

Comments
 (0)