Skip to content

Commit

Permalink
switched CustomRateProvider to use bitbank style endpoint because it …
Browse files Browse the repository at this point in the history
…supports bid/ask and multiple currencies instead of just one
  • Loading branch information
amperstrand committed Nov 7, 2023
1 parent 6cd1795 commit 9279134
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions BTCPayServer.Rating/Providers/CustomRateProvider.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
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 CustomRateProvider : IRateProvider
Expand All @@ -14,14 +18,30 @@ public CustomRateProvider(HttpClient httpClient)
_httpClient = httpClient ?? new HttpClient();
}

public RateSourceInfo RateSourceInfo => new RateSourceInfo("custom", "Custom", "https://customrates.local/api/price?from_currency=BTC&to_currency=Bits");
public RateSourceInfo RateSourceInfo => new RateSourceInfo("custom", "Custom", "https://customrates.local/tickers");

public async Task<PairRate[]> GetRatesAsync(CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync("https://customrates.local/api/price?from_currency=BTC&to_currency=Bits", cancellationToken);
var response = await _httpClient.GetAsync("https://customrates.local/tickers", cancellationToken);
var jobj = await response.Content.ReadAsAsync<JObject>(cancellationToken);
var value = jobj["public_price"]["to_price"].Value<decimal>();
return new[] { new PairRate(new CurrencyPair("BTC", "BITS"), new BidAsk(value)) };
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())
.Where(p => p["buy"].Type != JTokenType.Null && p["sell"].Type != JTokenType.Null)
.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);
}
}
}

0 comments on commit 9279134

Please sign in to comment.