Skip to content

Instantly share code, notes, and snippets.

@learntheropes
Last active March 3, 2021 08:57
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save learntheropes/abb5dd9fab96c7c2990a23ef12138778 to your computer and use it in GitHub Desktop.
Save learntheropes/abb5dd9fab96c7c2990a23ef12138778 to your computer and use it in GitHub Desktop.
Bittrex private and public API for Google Apps Script (Google Sheet)
// work in progress
// you need a bittrex API key and secret with read account option enabled
// I assume that all the keys are in the "keys" spreadsheet. The key is in cell B5 and the secret in cell C5
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("keys");
var key = sheet.getRange("B5").getValue()
var secret = sheet.getRange("C5").getValue();
var baseUrl = 'https://bittrex.com/api/v1.1/';
var nonce = Math.floor(new Date().getTime()/1000);
/**
* Used to retrieve all balances from your account.
* @return the balance of any currency that is not 0.
*/
function bittrexGetbalances() {
var finals = [];
var results = bittrexPrivateRequest("account/getbalances");
Logger.log(results)
results.forEach(function(result,index) {
finals.push({'currency': result.Currency, 'balance': result.Balance})
});
Logger.log(finals)
return json2array_(finals);
};
/**
* Used to retrieve the balance from your account for a specific currency.
* @param {string} a string literal for the currency (ex: LTC).
* @return the currency balance.
* @customfunction
*/
function bittrexGetbalance(currency) {
var payload = { "currency" : currency };
var results = bittrexPrivateRequest("account/getbalance",payload);
return results.Balance;
};
function bittrexPublicRequest(command,payload){
var uri = uriCreator_(command,payload);
var response = UrlFetchApp.fetch(uri);
var dataAll = JSON.parse(response.getContentText());
if (dataAll.success = true) {
return dataAll.result
} else {
return dataAll.message
}
}
function bittrexPrivateRequest(command,payload){
var uri = uriCreator_(command,payload,true)
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, uri, secret);
// Signature copied from comments:
var apisign = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var headers = {
"apisign": apisign
}
var params = {
"method": "get",
"headers": headers,
"payload": payload
}
var response = UrlFetchApp.fetch(uri, params);
var dataAll = JSON.parse(response.getContentText());
if (dataAll.success = true) {
return dataAll.result
} else {
return dataAll.message
}
};
function uriCreator_(command,payload,private){
if (payload) {
var payloadEncoded = Object.keys(payload).map(function(param) {
return encodeURIComponent(param) + '=' + encodeURIComponent(payload[param]);
}).join('&');
}
if (private) {
uri = baseUrl.concat(command + "?apikey=" + key + "&nonce=" + nonce + "&" + payloadEncoded)
} else {
uri = baseUrl.concat("public/" + command + "?" + payloadEncoded)
}
return uri
};
function json2array_(data){
var results = [];
var keys = [];
var values = [];
for (var i in data){
for (var key in data[i]){
if (i == 0) keys.push(key);
values.push(data[i][key]);
}
if (i == 0){
results.push(keys);
keys = [];
}
results.push(values);
values = [];
}
return results;
};
@Bruttagente
Copy link

Hello, taking inspiration from your script I'm trying to build mine for retrieving only balances from Bittrex. This is the code I've written:

`function getBalance() {

var ss = SpreadsheetApp.openById("******");
var data = ss.getSheetByName("Data");
var key = ss.getSheetByName("Api").getRange('A2').getValue();
var secret = ss.getSheetByName("Api").getRange('B2').getValue();
var baseUrl = 'https://bittrex.com/api/v1.1/';
var nonce = Math.floor(new Date().getTime()/1000);

var command = "/account/getbalances";
var uri = baseUrl.concat(command + "?apikey=" + key + "&nonce=" + nonce);

var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512,
uri,
secret);

signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')

var headers = {
"apisign": signature
}

var params = {
"method": "get",
"headers": headers,
}

var response = UrlFetchApp.fetch(uri, params);
var json = JSON.parse(response.getContentText());

var blnc = [];
blnc.push(['Balance']);

for(var key in json.result)
{
blnc[0].push(json.result[key]);
}

askRange = data.getRange(2, 1, blnc.length, 1);
askRange.setValues(blnc);

}`

But it doesn't work, I cannot retrive balances and I get no errors from the script. Any idea? thank you

@learntheropes
Copy link
Author

learntheropes commented Jul 17, 2017

@Bruttagente this one works:


/**
 * Used to retrieve all balances from your account.
 * @return the balance of any currency that is not 0.
 */
function bittrexGetbalances() {
  var finals = [];
  var results = bittrexPrivateRequest("account/getbalances");
  Logger.log(results)
  results.forEach(function(result) {
    finals.push({'currency': result.Currency, 'balance': result.Balance})
  });
  Logger.log(finals)
  return finals;
};

This one is nice, replaced everywhere:

signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')

@raphant
Copy link

raphant commented Jul 20, 2017

Thanks a million Coinfused!

Everything seems to work perfectly according to the logs. However, there is no data being displayed on the worksheet itself.

@learntheropes
Copy link
Author

@enanje fixed. There was a function moved to another file.

@ykypeH
Copy link

ykypeH commented Aug 21, 2017

Hi @Coinfused,
Thanks a lot for your script.
But I still don't see results on the worksheet. What is the another file you're taking about in your previous comment?

@koltregaskes
Copy link

Thanks for this. Do any of these functions grab the order history?

@sushisoosh
Copy link

sushisoosh commented Sep 22, 2017

I'm not sure what I should add as a payload. I'm trying to get the orderhistory for my account. bittrexPrivateRequest("getorderhistory",). It keeps saying payload needs to be an object and not a string... (when I supply count=50 for example).
Edit:
I figured it out, don't call bittrexprivaterequest from within a cell, but only within the script. Add:

function bittrexGetOrderHistoryV1() {
  var results = bittrexPrivateRequest("account/getorderhistory");
  Logger.log(results);
  return json2array_(results);
};

function bittrexGetDepositAddress(currency) {
  var payload = { "currency" : currency };
  var results = bittrexPrivateRequest("account/getdepositaddress",payload);
 
  if(results.Address && results.Address != null){
    return results.Address;
  }
  else return "";
};

which you can call from within a cell

@leejie8008
Copy link

Hi, met some problems and would appreciate if you can help. The API and connection is success, but when it retrieve the balance, it also retrieve all the coins which the balance are 0. How can I filter those out. Thanks.

@clumsyzombie
Copy link

I feel a bit lost here I put the code in and I am use to telling it to post results to a set page. What do you put in the Dell for it to use that section

@clumsyzombie
Copy link

You shouldn't you just in the cell place =bittrexGetbalances and it should go out and download all your balances? Is there more to it. Please let me understand when i do this I get
Error
Unknown range name: 'BITTREXGETBALANCES'

@clumsyzombie
Copy link

ok so looks like
=bittrexGetbalances()
and
=bittrexGetOrderHistoryV1()

is all that working for this script am I correct. Sorry I am learning

@clumsyzombie
Copy link

@leejie8008 looks like it pulls everything you have a wallet on BTW

@launganik
Copy link

Thanks. Pretty helpful

@teecis
Copy link

teecis commented Jan 5, 2018

None of you unfortunately answered, how the sheet itself can be generated? I added the keys to key sheet, but don't get any results being displayed. Please help!

@Coincoincoincoin
Copy link

Hey could somebody clarify how I would send a buy order with this code?
Ive tried:
bittrexPrivateRequest("Buy",)
but I do not know what to insert in the field "Payload".
I am aware that i have to insert the currency, the amount and the rate; but do not know in which format
Many thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment