Certainly! I'll help you integrate the execution time logging snippet into your consolidateTrades function seamlessly. Below is the updated function with the execution time properly implemented. This function processes data from the "Trade Log_Raw" sheet, consolidates it, and outputs the results to the "Trade Log" sheet. Additionally, it logs the execution time in cell N1 and records the last update timestamp in cell B1 of the "Trade Log" sheet.
function consolidateTrades() {
const startTime = new Date(); // Start time for execution time logging
let outputSheet; // Declare outputSheet outside of the try block
try {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const rawSheet = spreadsheet.getSheetByName('Trade Log_Raw');
if (!rawSheet) {
SpreadsheetApp.getUi().alert('Sheet "Trade Log_Raw" not found');
return;
}
// Get headers from the first row (columns A to K)
const headersRange = rawSheet.getRange(1, 1, 1, 11); // Columns A (1) to K (11)
const headers = headersRange.getValues()[0];
// Get data starting from row 3 (columns A to K)
const lastRowRaw = rawSheet.getLastRow();
if (lastRowRaw < 3) {
SpreadsheetApp.getUi().alert('No data found to consolidate.');
return;
}
const dataRange = rawSheet.getRange(3, 1, lastRowRaw - 2, 11); // Columns A (1) to K (11)
const data = dataRange.getValues();
const consolidatedData = [];
// Create a map to store consolidated results
const tradeMap = new Map();
// Iterate over each row of data
data.forEach(row => {
// Create a unique key based on selected columns (excluding fees)
const key = [row[0], row[1], row[2], row[3], row[5], row[8], row[9], row[10]].join('|');
if (!tradeMap.has(key)) {
// Initialize a new trade entry with fees and total set to 0
tradeMap.set(key, {
type: row[0],
date: row[1],
security: row[2],
action: row[3],
quantity: 0,
price: row[5],
fees: 0, // Initialize fees to 0 for aggregation
total: 0,
assetClass: row[8],
broker: row[9],
user: row[10]
});
}
const trade = tradeMap.get(key);
trade.quantity += Number(row[4]) || 0; // Aggregate Quantity
trade.fees += parseFloat(row[6]) || 0; // Aggregate Fees (ensure numerical)
trade.total += parseFloat(row[7]) || 0; // Aggregate Total
});
// Convert map to array for output
tradeMap.forEach(trade => {
consolidatedData.push([
trade.type,
trade.date,
trade.security,
trade.action,
trade.quantity,
trade.price,
trade.fees, // Aggregated Fees
trade.total,
trade.assetClass,
trade.broker,
trade.user
]);
});
// Output to the output sheet ("Trade Log"), without touching row 1 and 2
outputSheet = spreadsheet.getSheetByName('Trade Log');
if (!outputSheet) {
outputSheet = spreadsheet.insertSheet('Trade Log');
// If it's a new sheet, write headers to row 1
outputSheet.getRange(1, 1, 1, 11).setValues([headers]);
} else {
// Clear contents from row 3 onwards (do not clear formatting), limit to columns A to K
const lastRowOutput = outputSheet.getLastRow();
if (lastRowOutput > 2) {
outputSheet.getRange(3, 1, lastRowOutput - 2, 11).clearContent(); // Columns A (1) to K (11)
}
}
// Set the consolidated data starting from row 3
if (consolidatedData.length > 0) {
outputSheet.getRange(3, 1, consolidatedData.length, 11).setValues(consolidatedData); // Columns A (1) to K (11)
}
// Optionally, you can inform the user that consolidation was successful
SpreadsheetApp.getUi().alert('Trade consolidation completed successfully.');
} catch (e) {
SpreadsheetApp.getUi().alert('An error occurred: ' + e.message);
return; // Exit the function if an error occurs
}
// Record the last update date and time in cell B1 of the output sheet
if (outputSheet) { // Check if outputSheet is defined
const now = new Date();
const formattedNow = Utilities.formatDate(now, "Asia/Kolkata", "dd-MMM-yyyy HH:mm:ss");
outputSheet.getRange('B1').setValue(formattedNow); // Write to cell B1
}
// Calculate and log execution time in cell N1 of the output sheet
if (outputSheet) { // Ensure outputSheet is defined before writing
const endTime = new Date();
const executionTime = ((endTime - startTime) / 1000).toFixed(2); // Time in seconds, rounded to 2 decimal places
outputSheet.getRange('N1').setValue(`Execution time: ${executionTime} seconds`);
}
}
Explanation of the Integration
-
Start Time Logging:
- The function begins by recording the start time using
const startTime = new Date();. This marks the beginning of the execution for timing purposes.
-
Processing and Consolidation:
- The function accesses the
"Trade Log_Raw" sheet and retrieves headers from the first row.
- It then fetches data starting from the third row to avoid headers and any potential summary rows.
- Using a
Map, it consolidates trades based on a unique key derived from selected columns (excluding fees). It aggregates quantity, fees, and total for each unique trade.
-
Output to "Trade Log" Sheet:
- The function checks if the
"Trade Log" sheet exists. If not, it creates the sheet and sets the headers.
- If the sheet exists, it clears existing data from row 3 onwards to prepare for the new consolidated data.
- The consolidated data is then written starting from row 3.
-
Error Handling:
- The entire processing is wrapped in a
try-catch block to handle any unexpected errors gracefully. If an error occurs, an alert is shown to the user, and the function exits.
-
Recording Last Update Timestamp:
- After successful consolidation, the current date and time are formatted and written to cell
B1 of the "Trade Log" sheet. This provides a reference for when the last consolidation occurred.
-
Logging Execution Time:
- The function calculates the execution time by subtracting
startTime from the current time (endTime).
- The result is converted to seconds and rounded to two decimal places for readability.
- This execution time is then written to cell
N1 of the "Trade Log" sheet in the format Execution time: X.XX seconds.
Additional Recommendations
-
Validation: Ensure that the "Trade Log_Raw" sheet has the expected structure and that there are no empty cells in critical columns to prevent unexpected behavior.
-
Performance Optimization: For large datasets, consider optimizing the script by minimizing calls to the spreadsheet (e.g., batch operations) to enhance performance.
-
Permissions: Ensure that the script has the necessary permissions to read and write to the sheets involved. You might need to authorize the script when running it for the first time.
-
Scheduling: If you want this consolidation to happen automatically at regular intervals, consider setting up a trigger (e.g., time-driven trigger) in Google Apps Script.
How to Use the Function
-
Access Google Apps Script:
- Open your Google Spreadsheet.
- Navigate to
Extensions > Apps Script to open the Apps Script editor.
-
Add the Function:
- Copy and paste the above
consolidateTrades function into the script editor.
- Save the script (you can name it appropriately, e.g.,
TradeConsolidation).
-
Run the Function:
- Click the
Run button (▶️) in the Apps Script editor.
- The first time you run the script, it will prompt you to authorize the necessary permissions.
-
Automate (Optional):
- To automate the consolidation process, set up a trigger by clicking on the clock icon in the Apps Script editor.
- Configure the trigger to run
consolidateTrades at your desired frequency (e.g., daily, hourly).
-
Verify the Output:
- After running the function, check the
"Trade Log" sheet.
- You should see the consolidated trade data starting from row 3.
- Cell
B1 will display the last update timestamp.
- Cell
N1 will show the execution time of the script.
By following the above steps, your consolidateTrades function will effectively process and consolidate your trade data, providing useful execution metrics directly within your "Trade Log" sheet.