I have trading bots that are running on Alpaca. I wanted to send myself periodic updates on the performance of the portion. While there are methods one could email via python, I decided Google Apps Script was best for my needs.
Google Apps Script Code
function sendAccountInfoEmail() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// Replace with your Alpaca API credentials
var api_key = 'Enter API Key';
var api_secret = 'Enter API Secret';
var alpaca_url = 'https://paper-api.alpaca.markets'; #this can be changed to be live
var headers = {
'APCA-API-KEY-ID': api_key,
'APCA-API-SECRET-KEY': api_secret
};
// Fetch account information from Alpaca
var response = UrlFetchApp.fetch(alpaca_url + '/v2/account', {
method: 'get',
headers: headers
});
var accountInfo = JSON.parse(response.getContentText());
var subject = 'Alpaca Account Update';
var body = '<html><body><h1>Account Information</h1>';
var to_email = 'Enter To Email';
body += '<table border="1" cellpadding="5">';
body += '<tr><th>Item</th><th>Value</th></tr>';
body += '<tr><td>Buying Power</td><td>' + formatNumber(accountInfo.buying_power) + '</td></tr>';
body += '<tr><td>Non Marginable Buying Power</td><td>' + formatNumber(accountInfo.non_marginable_buying_power) + '</td></tr>';
body += '<tr><td>Cash</td><td>' + formatNumber(accountInfo.cash) + '</td></tr>';
body += '<tr><td>Position Market Value</td><td>' + formatNumber(accountInfo.portfolio_value) + '</td></tr>';
body += '<tr><td>Day\'s P&L</td><td>' + formatNumber(accountInfo.equity - accountInfo.last_equity) + '</td></tr>';
body += '</table></body></html>';
// Send the email
MailApp.sendEmail(to_email, subject, '', { htmlBody: body });
}
# this formats the tabular df to be more presentable/easier to read in email
function formatNumber(number) {
return Number(number).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Email Result
