I'm trying to build a spreadsheet based around DataDT's excellent API for 1-minute Forex data. It's simple: for a given date & time, I need the Open and Close price from DataDT. For example, in the following cases, Date+time are the input and Open and Close would be the output.
In other words, it would go from this:
Date Time Pair Open Close
04/03/2019 20:30 USDJPY
04/03/2019 21:30 USDJPY
04/03/2019 22:41 USDJPY
to this:
Date Time Pair Open Close
04/03/2019 20:30 USDJPY 111.478 111.475
04/03/2019 21:30 USDJPY 111.482 111.465
04/03/2019 22:41 USDJPY 111.456 111.458
(Link to the GSpreadsheet)
I've been trying to fetch the data from the API following Ben Collins' excellent tutorial on connecting api's to GSpreadsheets, but given that the objects in this API have quite a different format, I haven't figured a way to handle them.
This is my Google Appscript code so far:
function callDataDT() {
// Call the DataDT API
var response = UrlFetchApp.fetch("http://www.datadt.com/api/data/AUDCAD/1/20190403/20190404?api_token=s3MoVn4GAJRJhKcdNJ6zZugFN2C92SBv");
var json = response.getContentText();
var data = JSON.parse(json);
}
function displayFXData() {
// pick up the search term from the Google Sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var datetime = sheet.getRange(2,13).getValue();
var forexArray = [data]
Logger.log(forexArray);
}
To resume, I'm trying to understand how to 1) fetch only objects with a date_time equal to the date_time in the spreadsheet, 2) Output the Open and Close values for that object in the spreadsheet, and 3) Iterate for every non-empty line.
I apologize in advance if this question comes off as too basic. I'm still a beginner with Javascript but I've been trying for days to try to understand how to solve this, to no avail. I appreciate any tips you might give me.
As a side note, I wonder if it's possible to modify the URL directly so that it only outputs objects with a given date_time, but I don't think it's possible.
Thank you for reading,
David.-
This one uses your filter value
function getDataDT1(filter) {
var sr=3
var filter=filter||'';//You can test this function by providing a default here like '2019-04-03 20:28:00'
var r=UrlFetchApp.fetch("http://www.datadt.com/api/data/AUDCAD/1/20190403/20190404?api_token=s3MoVn4GAJRJhKcdNJ6zZugFN2C92SBv");
var data=JSON.parse(r.getContentText("UTF-8"));
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.clearContents();
var pair='USDJPY';
var a=[['','','Without V8','',''],['Date','Time','Pair','Open','Close']];
if(filter) {//if the filter is null then no filtering takes place
var dat=new Date(filter);
var dtv=new Date(dat.getFullYear(),dat.getMonth(),dat.getDate(),dat.getHours(),dat.getMinutes()).valueOf();
}
data.forEach(function(r,i){
var dt=r.DATE_TIME.split(' ');
var sd=new Date(r.DATE_TIME);
var sdv=new Date(sd.getFullYear(),sd.getMonth(),sd.getDate(),sd.getHours(),sd.getMinutes()).valueOf();
if(sdv==dtv || !filter) {//no filtering if filter is null
var d=dt[0].split('-');
var t=dt[1].split(':');
var ds=Utilities.formatString('%s/%s/%s',d[1],d[2],d[0]);
var ts=Utilities.formatString('%s:%s',t[0],t[1]);
a.push([ds,ts,pair,data[i].OPEN.toFixed(3),data[i].CLOSE.toFixed(3)]);
}
});
if(a) {
sh.getRange(sh.getLastRow()+1,1,a.length,a[0].length).setValues(a);
}else{
SpreadsheetApp.getUi().alert('No items found');
}
}
Related
I'm Attempting to create a Merge between some sheet Data, a doc template and a final doc template.
Mainly, I have access to these files like this:
var contratotemplate = DocumentApp.openById(contratotemplateId);
var contratonovo = DocumentApp.openById(contratonovoId);
var ws = SpreadsheetApp.openById(planilhaId).getSheetByName("Contratos Ref Marca");
Than, used this code to pick each Data from a Range that I want.
var data = ws.getRange(3,1,1,ws.getLastColumn()).getValues();
The Problem is here when I try to replacetext with cell information from my sheet trough another function callback (the one that actually replace text with info):
data.forEach(function(r){
CriarMailMerge(
r[30].getDate()+"/"+r[30].getMonth()+"/"+r[30].getFullYear(),
paragrafosTemplate,
contratonovo);
});
The result is this:
11/5/2019 //in contratonovoId field supposed to have the correct date.
I've already tried .toLocaleDateString()
The result is:
June, 11 2019.
Which solves my problem, but I can't find a way to bring that info into Brazilian Portuguese.
Can u guys help me?
I Used this and worked:
r[30].getDate()+"/"+("0" + (r[30].getMonth() + 1)).slice(-2)+"/"+r[30].getFullYear(),
RESULT
11/06/2019
Goal: Trying to copy part of some text from one cell on a spread sheet and pasting it on to another one.
I am still new to Javascript to please forgive if im going about this all wrong.
So on one spread sheet some information gets populated automatically from a service I use. I want to take part of that information and copy and paste it onto another spread sheet.
For this example the date gets populated in the cell A1 "February 28, 2017 at 10:38AM." I want to only copy the date February 28, 2017 and paste it onto another google sheet.
This is what my current code looks like:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById("abc1234");
var source_sheet = ss.getSheetByName("Text");
var target_sheet = target.getSheetByName("Bills");
var sheet = ss.getSheets()[0];
var range = sheet.getRange("A1:D4");
var cell = range.getCell(1, 1);
var string1 = cell.getValue();
var string2 = string1.split(" ", 2);
var target_range = target_sheet.getRange("J4");
string2.copyTo(target_range);
//Logger.log(string2);
}
The error I receive when i do this is:
TypeError: Cannot find function copyTo in object February,28,. (line 13, file "Test")
This maybe something simple i jsut cont figure it out
You need to use .setValue() to set the value of the range. So to set your range to the value in string2 you would replace line 13 with:
target_range.setValue(string2);
See the Tutorials for some examples of scripts. Especially the Workflows and end-to-end examples.
I've been busy trying to use the build-in javascript in Google Spreadsheet, however, not having worked in either javascript or Google Spreadsheet, i'm having a few difficulties.
My script is supposed to read a number (1-3) in a cell, and from that number parse an image to the cell below (I've been using the setFormula command for this).
So far it's working for 1 cell (B6 as i've choosen right now), but i would like to loop through a column with numbers in every other cell (So that after the script has run, it's number-picture-number-picture etc) - i just can't figure out how.
The code i'm using right now:
function numbtoimage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var url = 'IMAGE("https://dl.dropboxusercontent.com/s/bpqy8o796casqjl/belt.JPG?dl=0", 2)';
var url2 = 'IMAGE("https://dl.dropboxusercontent.com/s/4q8sakhkpot0h65/belt2.JPG?dl=0",2)';
var url3 = 'IMAGE("https://dl.dropboxusercontent.com/s/kvsf4z6z45rcg53/belt3.JPG?dl=0",2)';
var cell = sheet.getRange("B6")
var data = cell.getValue()
if(data==1) {cell.offset(1, 0, 1).setFormula(url);}
else if(data==2) {cell.offset(1, 0, 1).setFormula(url2);}
else if(data==3) {cell.offset(1, 0, 1).setFormula(url3);}
}
I've looked at This similar problem, but have been unable to make it work for my case.
Any help is greatly and truly appreciated!
Nicklas
You need some sort of loop to go through the data. I Would suggest a FOR loop.
Your script is currently written to get one single cell value, rather than all the values.
So it might be an idea to get all values in one go, then check whats in them.
Also from you question, it's not clear where the numbers will be found.
Only in column B?
Here is a quick example (untested), that goes through column B looking for a number and it should insert the link in the cell below based on that number. This code is based on your original example and untested but hopefully it helps.
function numbtoimage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var url = 'IMAGE("https://dl.dropboxusercontent.com/s/bpqy8o796casqjl/belt.JPG?dl=0", 2)';
var url2 = 'IMAGE("https://dl.dropboxusercontent.com/s/4q8sakhkpot0h65/belt2.JPG?dl=0",2)';
var url3 = 'IMAGE("https://dl.dropboxusercontent.com/s/kvsf4z6z45rcg53/belt3.JPG?dl=0",2)';
var values = sheet.getValues();
for(i=0; i < values.lenth ; i++){
if(values[i][1]==1) {sheet.getRange(i+2, 2).setFormula(url);}
else if(values[i][1]==2) {sheet.getRange(i+2, 2).setFormula(url2);}
else if(values[i][1]==3) {sheet.getRange(i+2, 2).setFormula(url3);}
}
}
I'm new to this site for the main purpose that I plan to pursue a career in programming. I've landed my first job at an engineering company who is asking me to set up a system in which they can easily determine the time between a job being filed, and it's completion. We're using spreadsheet docs right now to accomplish certain pieces of this.
I'm looking to create a custom function in Google Docs that will allow me to traverse the array of values in row C and then compare it with a number that the function was called with, compare the number to the number in the array and give me which one is the smaller number. EDIT: The function will be called on another sheet called "parsed data" located in the same project file. It's purpose is to automatically file the order number of a current project (just for the sake of being organized) All the other functions I plan to implement will be based off of this order number being correct.
So far, I've gathered this much (I'm learning this on the fly because I still lack experience, so bear with me.)
{
/**created by Alexander Bickford for use at Double E Company
*sorts through a range of values to determine the lowest next value
*returns lowest determined value of next cell
*/
//List Of To Be Implemented Functions
// sheet.appendRow
function setValue(num)
{
var ss = SpreadsheetApp.getActiveSpreadsheet('parsed data');
var ss = ss.getSheets()[0];
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange;i++) //Loop to traverse the C range and find the lowest value.
{
if(num<=range[3][i])
{
}
else
num = range[3][i];
}
return num;
}
}
when I call the function in the spreadsheet, I'm getting an error passed that says:
error: ReferenceError: "SPREADSHEET_ID_GOES_HERE" is not defined. (line 8, file "Code")
Google predefines some functions at the top that look like this:
/**
* Retrieves all the rows in the active spreadsheet that contain data and logs the
* values for each row.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function readRows() { <---Line 8 in the file
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
Logger.log(row);
}
};
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the readRows() function specified above.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};
End Code I don't need */
I assume it has something to do with the earlier lines (I pointed out line 8). Any thoughts?
Below code is working fine for me.
var ss = SpreadsheetApp.getActiveSheet();
var myRange = ss.getRange("C:C").getValues();
newValues = [];
for(i=1;i<=myRange.length;i++)
{
Logger.log(myRange[i]);
}
Looking at your code, it seems like you have a few problems.
You seem to be mixing up "sheets" with "spreadsheet", and your redundant declaration of "ss" as a variable is bound to cause you some problems.
You seem to be passing in arguments to the incorrect methods. I had this same problem when working with the Google App script earlier. It took a lot of poking around Google's Documentation (which you should really take a look at: https://developers.google.com/apps-script/). You seem to be making the same mistake I did, coding by analogy. looking at Google's sample code and trying to replicate is bound to bump you into some trouble.
Some useful advice:
The most confusing thing to wrap your head around is the structure: spreadsheet>>sheet>>range, you have to explicitely deal with the one's on top before moving to the one's on the bottom.
Remove the 'parsed data' argument from getActiveSpreadsheet(), it should be blank. What you want to use is "getSheetByName("parsed data")" and pass that into a sheet variable.
In your for loop, you also need to use the ".length" method, or use the ".getLastRow()" method with a sheet object to find the last row in your sheet.
Your code might look something like this:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("parsed data");
var endRowNumber = sheet1.getLastRow();
//insert rest of code
Good evening,
I'm trying to use some coding skills to help manipulate a spreadsheet in Google Docs and think the logic I've worked out is sound - but the script just returns results as 'Range'.
Essentially the script is a nested loop and (should) take values from six points in a row of data (starting in 11) and plonk them into a long vertical (column 38). Then it should move onto the next row.
I think it works, but the results just come back as 'Range' and can't see how to put the values into range, if that's what this means.
I also realise that it might be more effective to use a single array to gather the data on an individual array, but I'm still trying to get to grips with the syntax.
Here's my code:
function Transform() {
//load spreadsheet data and initialise variables
var sheet = SpreadsheetApp.getActiveSheet();
var firstrow = 11;//this is a manual figure
var d = firstrow;
var valuerplc = sheet.getRange(firstrow, 38);
var value =1;
for(var c=firstrow; c<sheet.getLastRow(); c++){
for (var e=3; e<33; e=e+6){
var mon = sheet.getRange(c, e);
valuerplc = sheet.getRange(d, 38);
valuerplc.setValue(mon);
}
d++;
}
}
Can anyone help, or at least point me in the right direction, please?
You've been caught with a common newbie problem, having trouble differentiating between Ranges and Values.
A Range expresses a region of a spreadsheet, with methods that give you access to various characteristics of the object. The contents, or data that you see in a spreadsheet is accessible via the .getValue() method (for one cell) or .getValues() (for more than one cell).
Change:
var mon = sheet.getRange(c, e);
To:
var mon = sheet.getRange(c, e).getValue();
... and you'll have the data that's in that range, as a String, Number or Date, depending on what was there.
The variable names you've selected may lead to confusion, it's worthwhile being careful with that. For example, look at valuerplc. The name implies that it's a value, which can be confused with .getValue() and .setValue(). But the way that it's used is as a Range, as in valuerplc.setValue(mon), so it's clearly NOT a value.
function Transform() {
//load spreadsheet data and initialise variables
var sheet = SpreadsheetApp.getActiveSheet();
var firstrow = 11;//this is a manual figure
var d = firstrow;
var valuerplc = sheet.getRange(firstrow, 38);
var value =1;
for(var c=firstrow; c<sheet.getLastRow(); c++){
for (var e=3; e<33; e=e+6){
var mon = sheet.getRange(c, e).getValue();
valuerplc = sheet.getRange(d, 38);
valuerplc.setValue(mon);
}
d++;
}
}