I want to retrieve the current prices of specific crypto currencies and update some fields in my google sheet.
Here a short codesnippet:
var api_url = "API-URL";
var response = UrlFetchApp.fetch(api_url);
var dataAll = JSON.parse(response.getContentText());
#When executing the URL in a Browser, I get this for dataAll:
dataAll content on Browser
#When executing it in the Google Script Editor, the Google Runtime Environment has this
dataAll content
#Here the rawdata response of the api-url call in JSON-Format with just 1 crypto entry in the data:
{"status":{"timestamp":"2021-04-01T21:11:59.721Z","error_code":0,"error_message":null,"elapsed":13,"credit_count":1,"notice":null,"total_count":4567},"data":[{"id":1,"name":"Bitcoin","symbol":"BTC","slug":"bitcoin","num_market_pairs":9477,"date_added":"2013-04-28T00:00:00.000Z","tags":["mineable","pow","sha-256","store-of-value","state-channels","coinbase-ventures-portfolio","three-arrows-capital-portfolio","polychain-capital-portfolio","binance-labs-portfolio","arrington-xrp-capital","blockchain-capital-portfolio","boostvc-portfolio","cms-holdings-portfolio","dcg-portfolio","dragonfly-capital-portfolio","electric-capital-portfolio","fabric-ventures-portfolio","framework-ventures","galaxy-digital-portfolio","huobi-capital","alameda-research-portfolio","a16z-portfolio","1confirmation-portfolio","winklevoss-capital","usv-portfolio","placeholder-ventures-portfolio","pantera-capital-portfolio","multicoin-capital-portfolio","paradigm-xzy-screener"],"max_supply":21000000,"circulating_supply":18670918,"total_supply":18670918,"platform":null,"cmc_rank":1,"last_updated":"2021-04-01T21:11:03.000Z","quote":{"CHF":{"price":55752.47839320199,"volume_24h":59267607529.77155,"percent_change_1h":0.02671823,"percent_change_24h":0.05924755,"percent_change_7d":11.47320017,"percent_change_30d":24.2882489,"percent_change_60d":81.38470939,"percent_change_90d":102.84247336,"market_cap":1040949952376.2463,"last_updated":"2021-04-01T21:11:15.000Z"}}}]}
For better readability I just pasted it into e.g. Notepad++ and went for Menu > JSON Viewer > Format JSON.
I know it's really basic, but how the heck can I now iterate through this encapsulated Object and dig to the appropriate level so I can read the price? I only want to pick a specific cryptocurrency, e.g. Ethereum which has id: 1027 and take its price for further purposes.
I want to be able to pick just the entries that fit to my portfolio (e.g. distinguish with id:) and take its price for a specific cell update in my google sheet.
Thanks a lot for your help in advance!
Best regards
Doniberi
if you want to get data by name just filter it
const api_url = 'API-URL';
const response = UrlFetchApp.fetch(api_url);
const dataAll = JSON.parse(response.getContentText());
const etherealData = dataAll.data.find(item => item.name === 'Ethereum');
function postDataToSheet() {
const ss=SpreadsheetApp.getActive();
const selected=['Symbol1','Symbol2']
const api_url = "API-URL";
let r= UrlFetchApp.fetch(api_url);
let rjson = r.getContentText();
let robj = JSON.parse(rjson);
let vs=[];
const ts=robj.status.timestamp;
const tc=robj.status.total_count;
vs.push(['TimeStamp',ts,'']);
vs.push('Total Count',tc,'');
vs.push(['Id','Symbol','Price']);
//***************************************************
//use this one to put them all on a sheet
robj.data.forEach((item,i)=>{
vs.push([item.id,item.symbol,item.quote.CHF.price])
});
const sh=ss.getSheetByName('Sheet1');
sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
//***************************************************
//use this one to put only the selected on a sheet
robj.data.forEach((item,i)=>{
if(~selected.index(item.symbol)) {
vs.push([item.id,item.symbol,item.quote.CHF.price])
}
});
const sh=ss.getSheetByName('Sheet1');
sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
}
If you only need current price I'm pretty sure you can remove all the code and use something like =IMPORTDATA("https://cryptoprices.cc/BTC/") to fetch crypto prices.
No complex parsing, no authentication, no limitations.
i have an api endpoint https://countriesnode.herokuapp.com/v1/countries.
Now i am fetching all the countries by
axios.get('https://countriesnode.herokuapp.com/v1/countries')
it returns successfully. Besides I want to fetch single countries with the country code like 'BB' .and i am trying with params and my object is like below
axios.get('https://countriesnode.herokuapp.com/v1/countries',
{
params: {
code: codeId
}
but it returns all the data like above rather than showing a single country with the following code. I also want to extract only the currency and area code. I wanted to try like this, don't know it gonna work or not.
.then(axios.spread((object) => {
console.log('Currency: ', object.data.currency);
console.log('Area code: ', object.data.emojiU);
}));
please someone help me... It took me almose the hole day for this but not able to success.
As per your comment, if you want to get the data of a specific country, you only have to append the country code id to the URL:
const codeId = 'BB';
axios.get(`https://countriesnode.herokuapp.com/v1/countries/${codeId}`)
Would give you the data for Barbados.
If you want to access the currency attribute you can do so with the code:
const codeId = 'BB';
axios.get(`https://countriesnode.herokuapp.com/v1/countries/${codeId}`).then(function(response) {
const currency = response.data.currency;
});
I have this code
const request = new XMLHttpRequest();
request.responseType = "document";
request.overrideMimeType("text/html");
const xml = '<?xml version="1.0" encoding="UTF-8">
<places>
<store>
<coordinates>x, y</coordinates>
<name>store1</name>
<stock>
<item>
<itemname>tshirt</itemname>
<instock>5</instock>
</item>
</stock>
</store>
</places>'
Edit: I felt my first question wasn't really clear, so here I go again:
I want to get use elements in the itemname tag to search in the this XML and return the store information like the name and coordinates and assign them both to variables I could use further down my code using JavaScript. Suggestions?
You can implement it by calling API each time whenver a key is pressed a event will be fired Ex- onkeypress=myFunction() and call your API inside your function and show the response below your search bar this is also called elastic searh
I'm designing a web app for Document Managers, and there is a 'settings' page, where the user sees a pair of checkboxes formatted to look like the iphone toggle buttons. they work and all, but whenever the user leaves the website or refreshes the page the state of those buttons is reset back to the default. is there a way to save the state of them using localStorage or do i need to use cookies? EDIT in the JavaScript file (code shown below) there are two functions, one called saveSettings and the other loadSettings, but if i have to do it all in one function then please tell me. END OF EDIT any help at all would be greatly appreciates. so far i have;
localStorage.CheckboxName = $('#CheckboxName').val();
to save the checkbox to localStorage and;
$('#CheckboxName').val(localStorage.CheckboxName);
but it won't save. Am i doing something wrong?
EDIT
here's the HTML code of the two checkboxes;
<li style = 'color: #FFFFFF;'>Notifications<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'notifications' id = 'notifications' /></span></li>
<li style = 'color: #FFFFFF;'>Preview<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'preview' id = 'preview' checked = "true" /></span></li>
END OF EDIT
Any help would be amazing, thanks in advance x
I'm not sure, but I've always believed that it was like this :
window.localStorage.setItem('CheckboxName', $('#CheckboxName').val());
$('#CheckboxName').val(window.localStorage.getItem('CheckboxName'));
You could try the following
$("#CheckboxName").is(':checked')?'checked':'not' and save the output, seems to be what is suggested here:
How to use local storage to retain checkbox states for filtering items
To store an Item just remember that the store only holds strings.
Eg.
var val = $('#CheckboxName').val();
window.localStorage.setItem(key, JSON.stringify(val));
So when you read the value back you need to deserialize the string.
var str = window.localStorage.getItem(key);
var obj = $.parseJSON(str);
Or you could just do string comparison whatever suites your needs better in your case what I would do is store an object of id value pairs in one storage key and deserialize them all to work with proper object
Eg.
var val = {
CheckboxName1: true,
CheckboxName2: false,
CheckboxName3: false, // ect....
};
window.localStorage.setItem(key, JSON.stringify(val));
Trying to get more than just the stock information at the current time period, and I can't figure out if Google Finance allows for retrieving information for more than just one date. For example, if I wanted to find out the Google Stock value over the last 30 days and return that data as a list... how would I go about doing this?
Using the code below only gets me a single value:
class GoogleFinanceAPI:
def __init__(self):
self.prefix = "http://finance.google.com/finance/info?client=ig&q="
def get(self,symbol,exchange):
url = self.prefix+"%s:%s"%(exchange,symbol)
u = urllib2.urlopen(url)
content = u.read()
obj = json.loads(content[3:])
return obj[0]
c = GoogleFinanceAPI()
quote = c.get("MSFT","NASDAQ")
print quote
Here is a recipe to get a historical values from Google Finance:
http://code.activestate.com/recipes/576495-get-a-stock-historical-value-from-google-finance/
It looks like it returns the data in .csv format.
Edit: Here is your script modified to get the .csv. It works for me.
import urllib2
import csv
class GoogleFinanceAPI:
def __init__(self):
self.url = "http://finance.google.com/finance/historical?client=ig&q={0}:{1}&output=csv"
def get(self,symbol,exchange):
page = urllib2.urlopen(self.url.format(exchange,symbol))
content = page.readlines()
page.close()
reader = csv.reader(content)
for row in reader:
print row
c = GoogleFinanceAPI()
c.get("MSFT","NASDAQ")
The best way to go forward is use the API's provided by Google. Specifically look for returns parameter where you specify how long you want.
Instead, if you want to do it via Python, find out query pattern as where the date entry goes and substitute it in the URL and do a GET, parse the result and include it in your result list.