I am trying to get a very simple algorithmic trading bot going. I have set up a couple functions to retrieve data from the Alpha Vantage API and determine whether to buy or sell a stock based on the 50 and 200 day Simple Moving Averages for the stock. The functions work perfectly when I call it once, but when I call it on a for-each loop of all stocks in the S&P 500, I get an error. I believe this is due to async/await, but I am not sure. What am I doing wrong?
const functions = require("firebase-functions");
const Alpaca = require("@alpacahq/alpaca-trade-api");
const axios = require("axios");
// @ts-ignore
const cts = require("check-ticker-symbol");
const sp500 = require("./sp500");
const { Configuration, OpenAIApi } = require("openai");
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest(async (request, response) => {
// const obj = {};
// sp500.forEach(async (ticker) => {
// if (cts.valid(ticker)) {
// obj[ticker] = await buyOrSellStock(ticker);
// }
// });
response.send(JSON.stringify(await buyOrSellStock("MSFT")));
});
const shouldBuyStock = async (tickerSymbol) => {
if (!cts.valid(tickerSymbol)) return false;
const avg50 = await getMovingAverage(tickerSymbol, 50);
const avg200 = await getMovingAverage(tickerSymbol, 200);
if (avg50 < avg200) {
return true;
} else {
return false;
}
};
const shouldSellStock = async (tickerSymbol) => {
if (!cts.valid(tickerSymbol)) return false;
const avg50 = await getMovingAverage(tickerSymbol, 50);
const avg200 = await getMovingAverage(tickerSymbol, 200);
if (avg50 > avg200) {
return true;
} else {
return false;
}
};
const getData = async (tickerSymbol) => {
const url = `https://www.alphavantage.co/query?function=SMA&symbol=${tickerSymbol}&interval=weekly&time_period=10&series_type=open&apikey=0TIV9NUUX4QSRHM6`;
const params = {
function: "SMA",
symbol: tickerSymbol,
interval: "daily",
time_period: 10,
series_type: "open",
apikey: process.env.ALPHA_VANTAGE_API_KEY,
};
const response = await axios.get(url, { params });
return response.data;
};
const getMovingAverage = async (ticker, days) => {
const data = await getData(ticker);
const keys50 = Object.keys(data["Technical Analysis: SMA"]).slice(0, days);
let sum = 0;
keys50.forEach(
(value) => (sum += parseInt(data["Technical Analysis: SMA"][value]["SMA"]))
);
const average = sum / days;
return average;
};
const buyOrSellStock = async (ticker) => {
if (await shouldBuyStock(ticker)) {
return `${ticker}: buy`;
} else if (await shouldSellStock(ticker)) {
return `${ticker}: sell`;
} else {
return `${ticker}: don't buy or sell`;
}
};
When I uncomment the loop in the HTTP function and send the obj object as the response, I get an empty object and an error that says " const keys50 = Object.keys(data["Technical Analysis: SMA"]).slice(0, days); ^ TypeError: Cannot convert undefined or null to object". The project structure is default firebase functions using firebase init functions