Darren solved this for me with the script below. New problem arises when I run the script again, even though the condition current >=target
is met, the new timestamp does not appear. The timestamp cell should only be locked if the timestamp is there. The script is behaving as if the cell is locked and hence, it does not write the timestamp to it. Any thoughts appreciated.
function check_stock_targets() {
// Replace each of the below with actual column/sheet names
const SHEET_NAME = 'Stocks';
const SYMBOL = 'Symbol';
const CURRENT = 'Current Price';
const LAST_UPDATE = 'Last Update';
const TARGET = 'Target';
const TIME_LOCK = 'Target Hit At';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(SHEET_NAME);
var headers = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues().shift();
var symbol_index = headers.indexOf(SYMBOL);
var current_index = headers.indexOf(CURRENT);
var last_update_index = headers.indexOf(LAST_UPDATE);
var target_index = headers.indexOf(TARGET);
var time_lock_index = headers.indexOf(TIME_LOCK);
var data = sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
var current_row = 2;
data.forEach(function (row) {
var time_lock = row[time_lock_index];
if (time_lock === '') {
var current = row[current_index];
var target = row[target_index];
if (current >= target) {
var last_update = row[last_update_index];
var symbol = row[symbol_index];
console.log("Target for %s hit at %s, locking", symbol, last_update);
sheet.getRange(current_row,time_lock_index+1).setValue(last_update).setNumberFormat("yyyy-mm-dd hh:mm");
}
}
current_row++;
});
}
I would run that as a timed trigger, perhaps once every 5 minutes.