btcpayserver/BTCPayServer.Rating/Providers/BitbankRateProvider.cs
Jonathan Underwood e3def45c83
Update Bitbank API (#3157)
Co-authored-by: Kukks <evilkukka@gmail.com>
2021-11-25 09:34:49 +01:00

44 lines
1.7 KiB
C#

using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Rating;
using Newtonsoft.Json.Linq;
namespace BTCPayServer.Services.Rates
{
public class BitbankRateProvider : IRateProvider
{
private readonly HttpClient _httpClient;
public BitbankRateProvider(HttpClient httpClient)
{
_httpClient = httpClient ?? new HttpClient();
}
public async Task<PairRate[]> GetRatesAsync(CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync("https://public.bitbank.cc/tickers", cancellationToken);
var jobj = await response.Content.ReadAsAsync<JObject>(cancellationToken);
var data = jobj.ContainsKey("data") ? jobj["data"] : null;
if (jobj["success"]?.Value<int>() != 1)
{
var errorCode = data is null? "Unknown": data["code"].Value<string>();
throw new Exception(
$"BitBank Rates API Error: {errorCode}. See https://github.com/bitbankinc/bitbank-api-docs/blob/master/errors.md for more details.");
}
return ((data as JArray) ?? new JArray())
.Select(item => new PairRate(CurrencyPair.Parse(item["pair"].ToString()), CreateBidAsk(item as JObject)))
.ToArray();
}
private static BidAsk CreateBidAsk(JObject o)
{
var buy = o["buy"].Value<decimal>();
var sell = o["sell"].Value<decimal>();
// Bug from their API (https://github.com/btcpayserver/btcpayserver/issues/741)
return buy < sell ? new BidAsk(buy, sell) : new BidAsk(sell, buy);
}
}
}