Fix for Bitpay suddenly including BCH in Fiat rates

This commit is contained in:
Rick Falkvinge
2017-12-21 11:51:38 +01:00
parent 38e4927c9b
commit 9d48503e15
6 changed files with 143 additions and 49 deletions
+4 -2
View File
@@ -4,16 +4,17 @@ namespace Swarmops.Basic.Types.Financial
{
public class BasicCurrency : IHasIdentity
{
public BasicCurrency (int currencyId, string code, string name, string sign)
public BasicCurrency (int currencyId, string code, string name, string sign, bool isCrypto)
{
this.CurrencyId = currencyId;
this.Code = code;
this.Name = name;
this.Sign = sign;
this.IsCrypto = isCrypto;
}
public BasicCurrency (BasicCurrency original)
: this (original.CurrencyId, original.Code, original.Name, original.Sign)
: this (original.CurrencyId, original.Code, original.Name, original.Sign, original.IsCrypto)
{
// empty copy ctor
}
@@ -23,6 +24,7 @@ namespace Swarmops.Basic.Types.Financial
public string Code { get; private set; }
public string Name { get; private set; }
public string Sign { get; private set; }
public bool IsCrypto { get; private set; }
public int Identity
{
+3 -2
View File
@@ -12,7 +12,7 @@ namespace Swarmops.Database
#region Field reading code
private const string currencyFieldSequence =
" CurrencyId,Code,Name,Sign " + // 0-3
" CurrencyId,Code,Name,Sign,IsCrypto " + // 0-4
"FROM Currencies ";
private static BasicCurrency ReadCurrencyFromDataReader (IDataRecord reader)
@@ -21,8 +21,9 @@ namespace Swarmops.Database
string code = reader.GetString (1);
string name = reader.GetString (2);
string sign = reader.GetString (3);
int isCrypto = reader.GetInt32(4);
return new BasicCurrency (currencyId, code, name, sign);
return new BasicCurrency (currencyId, code, name, sign, isCrypto != 0? true: false);
}
#endregion
+43 -42
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
@@ -39,57 +40,21 @@ namespace Swarmops.Logic.Financial
public static void Create()
{
int exchangeRateSnapshotId = 0;
// We're getting rates against the fiat currencies from BitPay and crypto-to-crypto from Shapeshift.
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
string fiatRateDataRaw = client.DownloadString("https://bitpay.com/api/rates");
// BitPay doesn't provide valid JSON - the rate field isn't enclosed in quotes - so we can't use JSON Deserialization; we'll
// have to use Regex matching instead.
string regexPattern = @"\{\""code\"":\""([A-Z]+)\"",\""name\"":\""([^\""]+)\"",\""rate\"":([0-9\.]+)\}";
Regex regex = new Regex (regexPattern);
Match match = regex.Match (fiatRateDataRaw);
int bitcoinId = GetOrCreateCryptocurrency("BTC");
if (match.Success)
{
// We have at least one match, so prepare a new ExchangeRate snapshot
exchangeRateSnapshotId = SwarmDb.GetDatabaseForWriting().CreateExchangeRateSnapshot();
}
while (match.Success)
{
string currencyCode = match.Groups[1].Value;
string currencyName = match.Groups[2].Value;
double btcRate = Double.Parse (match.Groups[3].Value, NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture);
btcRate /= 1000000.0; // We're operating in microbitcoin, so adjust the stored exchange rate accordingly (right-shift six decimal places)
int currencyId = GetOrCreateFiatCurrency (currencyCode, currencyName);
SwarmDb.GetDatabaseForWriting()
.CreateExchangeRateDatapoint (exchangeRateSnapshotId, currencyId, bitcoinId, btcRate);
match = match.NextMatch();
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
BitpayRateDatapoint[] fiatRates = (BitpayRateDatapoint[]) serializer.Deserialize<BitpayRateDatapoint[]> (fiatRateDataRaw);
int bitcoinId = GetOrCreateCryptocurrency("BTC");
int exchangeRateSnapshotId = SwarmDb.GetDatabaseForWriting().CreateExchangeRateSnapshot();
// Download Shapeshift data
string cryptoRateDataRaw = client.DownloadString("https://shapeshift.io/marketinfo");
ShapeshiftRateDatapoint[] cryptoRates =
(ShapeshiftRateDatapoint[]) serializer.Deserialize<ShapeshiftRateDatapoint[]>(cryptoRateDataRaw);
(ShapeshiftRateDatapoint[])serializer.Deserialize<ShapeshiftRateDatapoint[]>(cryptoRateDataRaw);
if (exchangeRateSnapshotId > 0) // test that we're making a snapshot first
{
@@ -103,18 +68,54 @@ namespace Swarmops.Logic.Financial
if (coinCode != "BCH")
{
btcRate /= 1000000.0;
// We're operating in microbitcoin, so adjust the stored exchange rate right six decimal places
// EXCEPT for Bitcoin Cash which ALSO operates in microbitcoin
// We're operating in microbitcoin, so adjust the stored exchange rate right six decimal places
// EXCEPT for Bitcoin Cash which ALSO operates in microbitcoin
}
int coinId = GetOrCreateCryptocurrency(coinCode);
SwarmDb.GetDatabaseForWriting().
CreateExchangeRateDatapoint(exchangeRateSnapshotId, coinId, bitcoinId, btcRate);
}
}
}
Console.WriteLine(cryptoRateDataRaw);
// Download BitPay data
string fiatRateDataRaw = client.DownloadString("https://bitpay.com/api/rates");
// BitPay doesn't provide valid JSON - the rate field isn't enclosed in quotes - so we can't use JSON Deserialization; we'll
// have to use Regex matching instead.
string regexPattern = @"\{\""code\"":\""([A-Z]+)\"",\""name\"":\""([^\""]+)\"",\""rate\"":([0-9\.]+)\}";
Regex regex = new Regex (regexPattern);
Match match = regex.Match (fiatRateDataRaw);
while (match.Success)
{
string currencyCode = match.Groups[1].Value;
string currencyName = match.Groups[2].Value;
double btcRate = Double.Parse (match.Groups[3].Value, NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture);
btcRate /= 1000000.0; // We're operating in microbitcoin, so adjust the stored exchange rate accordingly (right-shift six decimal places)
int currencyId = GetOrCreateFiatCurrency (currencyCode, currencyName);
Currency currency = Currency.FromIdentityAggressive(currencyId);
// Only store if it's not a cryptocurrency provided by Shapeshift
if (!currency.IsCrypto)
{
SwarmDb.GetDatabaseForWriting()
.CreateExchangeRateDatapoint(exchangeRateSnapshotId, currencyId, bitcoinId, btcRate);
}
match = match.NextMatch();
}
// BitpayRateDatapoint[] fiatRates = (BitpayRateDatapoint[]) serializer.Deserialize<BitpayRateDatapoint[]> (fiatRateDataRaw);
// Console.WriteLine(cryptoRateDataRaw);
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ namespace Swarmops.Frontend
// BEGIN TEST CODE
// VatReports.CreateNewReports();
// ExchangeRateSnapshot.Create();
// END TEST CODE
+20 -2
View File
@@ -1,5 +1,6 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" Inherits="Swarmops.Frontend.Pages.v5.Ledgers.BalanceTransactions" Codebehind="BalanceTransactions.aspx.cs" CodeFile="BalanceTransactions.aspx.cs" %>
<%@ Register TagPrefix="Swarmops5" TagName="ComboBudgets" Src="~/Controls/v5/Financial/ComboBudgets.ascx" %>
<%@ Register TagPrefix="Swarmops5" TagName="CurrencyTextBox" Src="~/Controls/v5/Financial/CurrencyTextBox.ascx" %>
<%@ Register TagPrefix="Swarmops5" TagName="DropDown" Src="~/Controls/v5/Base/DropDown.ascx" %>
<%@ Register TagPrefix="Swarmops5" TagName="ModalDialog" Src="~/Controls/v5/Base/ModalDialog.ascx" %>
@@ -298,11 +299,28 @@
</div>
</div>
</div>
<p><input type="radio" id="RadioPurchase" name="TxOptions" value="Purchase" /><label for="RadioPurchase">&nbsp;<asp:Label runat="server" ID="Label2" Text="Mark this as a direct-from-account purchase? XYZ" /></label></p>
<div id="radioOptionPurchase" class="radioOption">
<div class="entryFields">
<Swarmops5:ComboBudgets Layout="Vertical" ID="DropBudgetsPurchase" runat="server" ListType="All" />
<div class="stacked-input-control"><input type="text" value="#Description#" id="inputTextPurchaseDescription"/></div>
<div class="onVatEnabled" style="display: none"><Swarmops5:CurrencyTextBox ID="CurrencyPurchaseVat" runat="server" Layout="Vertical"/></div>
<Swarmops5:FileUpload ID="UploadPurchase" runat="server"/>
<input type="button" value='#Balance#' class="buttonAccentColor" onclick="onBalanceTransaction(); return false;" id="buttonExecutePurchase"/>
</div>
<div class="entryLabels">
<div class="stacked-input-control"><asp:Label runat="server" ID="LabelPurchaseBudget" Text="Charge purchase to this budget XYZ" /></div>
<div class="stacked-input-control"><asp:Label runat="server" ID="LabelPurchaseDescriptionUpdate" Text="Update transaction description XYZ" /></div>
<div class="stacked-input-control"><asp:Label runat="server" ID="LabelPurchaseVatAmount" Text="VAT part of the amount XYZ" /></div>
<div class="stacked-input-control"><asp:Label runat="server" ID="LabelPurchaseUploadReceipt" Text="Upload the receipt or other documentation XYZ" /></div>
</div>
<div style="clear:both"></div>
</div>
<p><input type="radio" id="RadioBalance" name="TxOptions" value="Balance" /><label for="RadioBalance">&nbsp;<asp:Label runat="server" ID="LabelRadioBalance" Text="Balance the transaction manually? XYZ" /></label></p>
<div id="radioOptionBalance" class="radioOption"> <!-- this should go last -->
<div class="entryFields">
<Swarmops5:ComboBudgets ID="DropBudgetBalance" runat="server" ListType="All" />&#8203;<br/>
<input type="button" value='#Balance#' class="buttonAccentColor" onclick="onBalanceTransaction(); return false;" id="buttonExecuteBalance"/>
<Swarmops5:ComboBudgets ID="DropBudgetBalance" runat="server" Layout="Vertical" ListType="All" />
<div class="stacked-input-control"><input type="button" value='#Balance#' class="buttonAccentColor" onclick="onBalanceTransaction(); return false;" id="buttonExecuteBalance"/></div>
</div>
<div class="entryLabels">
<asp:Label runat="server" ID="LabelDescribeBalance" Text="Balance the difference against XYZ" />
@@ -210,6 +210,78 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers {
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelDescribeOutboundInvoice;
/// <summary>
/// Label2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label2;
/// <summary>
/// DropBudgetsPurchase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Swarmops.Controls.Financial.ComboBudgets DropBudgetsPurchase;
/// <summary>
/// CurrencyPurchaseVat control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Swarmops.Frontend.Controls.Financial.CurrencyTextBox CurrencyPurchaseVat;
/// <summary>
/// UploadPurchase control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Swarmops.Controls.Base.FileUpload UploadPurchase;
/// <summary>
/// LabelPurchaseBudget control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelPurchaseBudget;
/// <summary>
/// LabelPurchaseDescriptionUpdate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelPurchaseDescriptionUpdate;
/// <summary>
/// LabelPurchaseVatAmount control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelPurchaseVatAmount;
/// <summary>
/// LabelPurchaseUploadReceipt control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LabelPurchaseUploadReceipt;
/// <summary>
/// LabelRadioBalance control.
/// </summary>