Last active
February 16, 2018 17:21
-
-
Save dheffx/8eef7f4cb9cd7de0b881edfb9fb20ed1 to your computer and use it in GitHub Desktop.
example of messing with binance/coinbase apis to calculate cross exchange value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs') | |
var _ = require('lodash') | |
var USD_CONVERSIONS = ["ETH", "BTC"] | |
// Array of Arrays where inner Array is SYMBOL(str), SHARES(num) | |
var portfolio_data_file = "portfolio.json" | |
// Example dump of coinbase API | |
var coinbase_data_file = "coinbase.json" | |
// Example dump of binance API | |
var binance_data_file = "binance.json" | |
var portfolio_data = JSON.parse(fs.readFileSync(portfolio_data_file, 'utf8')) | |
var coinbase_data = JSON.parse(fs.readFileSync(coinbase_data_file, 'utf8')) | |
var binance_data = JSON.parse(fs.readFileSync(binance_data_file, 'utf8')) | |
var binance_map = binance_data_to_map(binance_data) | |
var portfolio = _.map(portfolio_data, function(equity) { | |
var currency = equity[0] | |
var shares = equity[1] | |
var entry = { currency: currency, shares: shares } | |
set_rates(entry) | |
calculate_value(entry) | |
return entry | |
}) | |
console.log(portfolio) | |
function calculate_value(entry) { | |
if (entry.rate_per_usd) { | |
entry.primary_value_symbol = 'USD' | |
entry.primary_value = entry.shares * entry.rate_per_usd | |
entry.secondary_value_symbol = 'BTC' | |
entry.secondary_value = entry.shares * entry.rate_per_btc | |
} else { | |
entry.primary_value_symbol = 'BTC' | |
entry.primary_value = entry.shares * entry.rate_per_btc | |
entry.secondary_value_symbol = 'ETH' | |
entry.secondary_value = entry.shares * entry.rate_per_eth | |
} | |
} | |
function set_rates(entry) { | |
if ( _.includes(USD_CONVERSIONS, entry.currency) ) { | |
entry.rate_per_usd = coinbase_data.data.rates[entry.currency] | |
} else { | |
entry.rate_per_eth = binance_map[entry.currency + 'ETH'] | |
} | |
entry.rate_per_btc = entry.currency != 'BTC' ? binance_map[entry.currency + 'BTC'] : 1 | |
} | |
function binance_data_to_map(data) { | |
return _.chain(data).keyBy(function(i) { | |
return i.symbol | |
}).mapValues('price').value() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment