The function you've provided, consolidateTrades(), is a Google Apps Script intended to be run within a Google Sheets environment. Its primary purpose is to read raw trade data from a sheet named 'Trade Log_Raw', consolidate similar trades by grouping them based on certain criteria, and then output the consolidated data into another sheet named 'Trade Log'. Additionally, it records the last update timestamp in cell K1 of the output sheet.
Here's a detailed step-by-step explanation of what the function does:
1. Function Initialization
function consolidateTrades() {
let outputSheet;
try {
// ... rest of the code ...
} catch (e) {
SpreadsheetApp.getUi().alert('An error occurred: ' + e.message);
}
// ... code to record the last update timestamp ...
}
- Purpose: The function
consolidateTrades is defined, and an outputSheet variable is declared outside the try block for later use.
- Error Handling: A
try-catch block is used to handle any errors that may occur during the execution of the code.
2. Accessing the Spreadsheet and Sheets
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getSheetByName('Trade Log_Raw');
if (!sheet) {
SpreadsheetApp.getUi().alert('Sheet "Trade Log_Raw" not found');
return;
}
- Retrieve Active Spreadsheet: Accesses the active spreadsheet where the script is running.
- Get 'Trade Log_Raw' Sheet: Attempts to retrieve the sheet named 'Trade Log_Raw'.
- Error Handling: If the sheet is not found, it alerts the user and exits the function.
3. Reading Headers and Data
// Get headers from the first row (columns A to K)
const headersRange = sheet.getRange(1, 1, 1, 11); // Columns 1 (A) to 11 (K)
const headers = headersRange.getValues()[0];
// Get data starting from row 3 (columns A to K)
const dataRange = sheet.getRange(3, 1, sheet.getLastRow() - 2, 11);
const data = dataRange.getValues();
if (data.length === 0) {
SpreadsheetApp.getUi().alert('No data found to consolidate.');
return;
}
- Headers: Reads the headers from row 1, columns A to K.
- Data: Reads the data from row 3 onwards (skipping the first two rows), columns A to K.
- Data Check: If there's no data, alerts the user and exits the function.
4. Initializing Consolidation Structures
const consolidatedData = [];
const tradeMap = new Map();
- Consolidated Data Array: Will hold the final consolidated trade data.
- Trade Map: A
Map object used to group and consolidate trades based on specific keys.
5. Consolidating Trades
data.forEach(row => {
const key = [row[0], row[1], row[2], row[3], row[5], row[8], row[9], row[10]].join('|');
if (!tradeMap.has(key)) {
tradeMap.set(key, {
type: row[0],
date: row[1],
security: row[2],
action: row[3],
quantity: 0,
price: row[5],
fees: row[6],
total: 0,
assetClass: row[8],
broker: row[9],
user: row[10]
});
}
const trade = tradeMap.get(key);
trade.quantity += row[4];
trade.total += row[7];
});
- Iterate Over Each Row: Loops through each row of data from the raw trade log.
- Creating a Unique Key:
- The key is constructed by concatenating specific fields:
- Type (row[0])
- Date (row[1])
- Security (row[2])
- Action (row[3])
- Price (row[5])
- Asset Class (row[8])
- Broker (row[9])
- User (row[10])
- Fields are joined using a pipe
| to create a unique string identifier for each unique trade type.
- Grouping Trades:
- If Key Doesn't Exist: A new entry is added to the
tradeMap with initial values.
- If Key Exists: The existing trade's
quantity and total are updated by adding the current row's quantity and total.
6. Preparing the Consolidated Data
tradeMap.forEach(trade => {
consolidatedData.push([
trade.type,
trade.date,
trade.security,
trade.action,
trade.quantity,
trade.price,
trade.fees,
trade.total,
trade.assetClass,
trade.broker,
trade.user
]);
});
- Converting Map to Array: Iterates over the
tradeMap entries and pushes them into the consolidatedData array.
- Data Structure: Each entry in
consolidatedData is an array representing a row of consolidated trade data.
7. Writing to the 'Trade Log' Sheet
a. Accessing or Creating the 'Trade Log' Sheet
outputSheet = spreadsheet.getSheetByName('Trade Log');
if (!outputSheet) {
outputSheet = spreadsheet.insertSheet('Trade Log');
} else {
const lastRow = outputSheet.getLastRow();
if (lastRow > 2) {
outputSheet.getRange(3, 1, lastRow - 2, 11).clearContent();
}
}
- Get 'Trade Log' Sheet: Tries to retrieve the sheet named 'Trade Log'.
- Create Sheet if Not Exists: If the sheet doesn't exist, creates a new sheet with that name.
- Clearing Previous Data: If the sheet exists, it clears the contents from row 3 onwards (excluding formatting), only for columns A to K.
- This ensures old data doesn't interfere with the new consolidated data.
b. Handling Headers in Output Sheet
const existingHeaders = outputSheet.getRange(1, 1, 1, 11).getValues()[0];
const headersExist = existingHeaders.every(cell => cell !== "");
if (!headersExist) {
outputSheet.getRange(1, 1, 1, 11).setValues([headers]);
} else {
outputSheet.getRange(1, 1, 1, 11).clearContent();
outputSheet.getRange(1, 1, 1, 11).setValues([headers]);
}
- Check if Headers Exist: Reads the first row of the output sheet to check if headers are present.
- Write Headers if Missing: If headers are missing, writes the headers obtained from the raw data.
- Update Headers: If headers exist, clears them and writes the new headers to ensure they are up-to-date.
c. Writing the Consolidated Data
if (consolidatedData.length > 0) {
outputSheet.getRange(3, 1, consolidatedData.length, 11).setValues(consolidatedData);
}
- Write Data to Sheet: Writes the consolidated data to the output sheet starting from row 3, columns A to K.
- Condition: Only writes if there is data in
consolidatedData.
8. Recording the Last Update Timestamp
if (outputSheet) {
let now = new Date();
let formattedNow = Utilities.formatDate(now, "Asia/Kolkata", "dd-MMM-yyyy HH:mm:ss");
outputSheet.getRange('K1').setValue(formattedNow);
}
- Check Output Sheet: Ensures that
outputSheet is defined before proceeding.
- Get Current Date and Time: Retrieves the current date and time.
- Format Timestamp: Formats the timestamp to 'dd-MMM-yyyy HH:mm:ss' in the 'Asia/Kolkata' time zone.
- Write Timestamp: Writes the formatted timestamp to cell K1 of the output sheet.
9. Error Handling
} catch (e) {
SpreadsheetApp.getUi().alert('An error occurred: ' + e.message);
}
- If any error occurs during the execution of the code inside the
try block, it is caught here.
- An alert is displayed to the user with the error message.
Key Points and Additional Details
- Data Columns Overview:
- Columns A to K (1 to 11) are used throughout the script, corresponding to the following data fields (assuming standard trade data fields):
- Type
- Date
- Security
- Action
- Quantity
- Price
- Fees
- Total
- Asset Class
- Broker
- User
- Consolidation Logic:
- Trades are grouped together if they have the same values in the fields used to create the key.
- Summation Fields:
- Quantity (
trade.quantity): Sum of the quantities of grouped trades.
- Total (
trade.total): Sum of the totals of grouped trades.
- Formatting:
- The script intentionally avoids altering any formatting in the sheets.
- Only data content is manipulated; cell formatting remains as is.
Example Scenario
Suppose you have the following raw trade data in the 'Trade Log_Raw' sheet:
| Type | Date | Security | Action | Quantity | Price | Fees | Total | Asset Class | Broker | User |
|---|
| Buy | 01-Oct-23 | XYZ | Open | 100 | 10 | 2 | 1000 | Equity | BrokerA | User1 |
| Buy | 01-Oct-23 | XYZ | Open | 50 | 10 | 1 | 500 | Equity | BrokerA | User1 |
| Sell | 02-Oct-23 | ABC | Close | 200 | 15 | 3 | 3000 | Equity | BrokerB | User2 |
- The first two rows have the same key based on the fields used (except for Quantity and Total).
- After consolidation, the 'Trade Log' sheet will have:
| Type | Date | Security | Action | Quantity | Price | Fees | Total | Asset Class | Broker | User |
|---|
| Buy | 01-Oct-23 | XYZ | Open | 150 | 10 | 2 | 1500 | Equity | BrokerA | User1 |
| Sell | 02-Oct-23 | ABC | Close | 200 | 15 | 3 | 3000 | Equity | BrokerB | User2 |
- Quantity and Total for the first group are summed.
Overall Purpose
The function automates the process of consolidating raw trade data by:
- Grouping Similar Trades: Based on specified criteria (type, date, security, action, price, asset class, broker, user).
- Summing Quantities and Totals: For grouped trades to reflect the aggregate values.
- Updating an Output Sheet: So users have a consolidated view of their trades without manual intervention.
- Time-Stamping: Helps users know when the data was last consolidated.
Possible Use Cases
- Portfolio Management: Consolidate trades to see total positions opened or closed on a particular security.
- Reporting: Generate daily or periodic reports of trading activity.
- Data Cleanup: Remove duplication and aggregate data for analysis.
- Auditing: Maintain a record of when data was last updated for compliance purposes.
Notes and Considerations
- Data Integrity: Ensure that the raw data in 'Trade Log_Raw' is accurate before running the function.
- Unique Key Construction: Be aware that changing the fields used to create the key will affect how trades are grouped.
- Time Zone: The timestamp uses the 'Asia/Kolkata' time zone. Adjust if needed.
- Error Alerts: If alerts are frequent, consider adding more robust error handling or logging.
I hope this explanation clarifies what the consolidateTrades() function is doing. If you have any questions or need further assistance with modifying or enhancing the script, feel free to ask!