From 18bde7391efb9c6bd6ea7846891ab5d16276a809 Mon Sep 17 00:00:00 2001 From: David Vazgenovich Shakaryan Date: Mon, 31 May 2021 06:11:22 -0700 Subject: initial import A bit messy and missing error handling in some places. --- assets.c | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 assets.c (limited to 'assets.c') diff --git a/assets.c b/assets.c new file mode 100644 index 0000000..a4e0043 --- /dev/null +++ b/assets.c @@ -0,0 +1,100 @@ +#include "quotes.h" +#include "assets.h" + +#include +#include +#include + +char *ASSET_TYPE_NAMES[] = { + FOREACH_ASSET_TYPE(GENERATE_STRING) +}; + +void asset_free(struct asset *a) +{ + free(a->symbol); + free(a); +} + +int asset_cmp(const void *a, const void *b) +{ + struct asset *aa = *(struct asset **)a; + struct asset *bb = *(struct asset **)b; + + if (aa->type > bb->type) + return 1; + else if (aa->type < bb->type) + return -1; + else + if (aa->usd_tot > bb->usd_tot) + return -1; + else if (aa->usd_tot < bb->usd_tot) + return 1; + else + return 0; +} + +void add_quotes_to_assets(struct asset **assets, int n_assets, + struct quote **quotes, int n_quotes) +{ + for (int i = 0; i < n_assets; ++i) { + struct quote *quote = quote_find(quotes, n_quotes, assets[i]->symbol, + "USD"); + if (quote) { + assets[i]->usd = true; + assets[i]->usd_pr = quote->price; + assets[i]->usd_ch = quote->change_percent; + assets[i]->usd_tot = assets[i]->amt * quote->price * + (quote->multiplier ? quote->multiplier : 1); + } + + quote = quote_find(quotes, n_quotes, assets[i]->symbol, "BTC"); + if (quote) { + assets[i]->btc = true; + assets[i]->btc_pr = quote->price; + assets[i]->btc_ch = quote->change_percent; + assets[i]->btc_tot = assets[i]->amt * quote->price * + (quote->multiplier ? quote->multiplier : 1); + } else if (strcmp(assets[i]->symbol, "BTC") == 0) { + assets[i]->btc = true; + assets[i]->btc_pr = 1; + assets[i]->btc_tot = assets[i]->amt; + } + } +} + +int add_totals(struct asset **assets, int n_assets) +{ + struct asset **totals = calloc(4, sizeof(*totals)); + totals[3] = calloc(1, sizeof(**totals)); + + for (int i = 0; i < n_assets; ++i) { + if (assets[i]->usd) { + totals[3]->usd = true; + totals[3]->usd_tot += assets[i]->usd_tot; + if (!totals[assets[i]->type]) + totals[assets[i]->type] = calloc(1, sizeof(**totals)); + totals[assets[i]->type]->usd = true; + totals[assets[i]->type]->usd_tot += assets[i]->usd_tot; + } + if (assets[i]->btc) { + totals[3]->btc = true; + totals[3]->btc_tot += assets[i]->btc_tot; + if (!totals[assets[i]->type]) + totals[assets[i]->type] = calloc(1, sizeof(**totals)); + totals[assets[i]->type]->btc = true; + totals[assets[i]->type]->btc_tot += assets[i]->btc_tot; + } + } + + int c = 0; + for (int i = 0; i < 4; ++i) { + if (totals[i]) { + totals[i]->symbol = strdup(ASSET_TYPE_NAMES[i]); + totals[i]->type = TOTAL; + assets[n_assets + c++] = totals[i]; + } + } + + free(totals); + return c; +} -- cgit v1.2.3-70-g09d2