'API call frequency limit reached. Please wait a minute and try again.']; } if (strpos($response, 'Invalid API call') !== false) { return ['error' => 'Invalid API call. Please check the symbol.']; } $data = json_decode($response, true); if (json_last_error() === JSON_ERROR_NONE) { if (isset($data['Note'])) { return ['error' => 'API call frequency limit reached. Please wait a minute and try again.']; } if (isset($data['Error Message'])) { return ['error' => $data['Error Message']]; } return $data; } // If not JSON, assume it's CSV (for listing_status) return $response; } function get_all_listed_stocks() { $params = [ 'function' => 'LISTING_STATUS', 'state' => 'active' // Only active stocks ]; return call_finance_api($params); } function get_stock_overview($symbol) { $params = [ 'function' => 'OVERVIEW', 'symbol' => $symbol ]; return call_finance_api($params); } function get_stock_quote($symbol) { $params = [ 'function' => 'GLOBAL_QUOTE', 'symbol' => $symbol ]; return call_finance_api($params); } // Function to add a stock to the watchlist, now with data fetching function add_stock_with_details($symbol, $pdo) { $overview = get_stock_overview($symbol); // Wait a bit before the next call to respect API limits sleep(15); $quote = get_stock_quote($symbol); if (isset($overview['error']) || isset($quote['error'])) { // Don't add to DB if API fails return ['success' => false, 'message' => ($overview['error'] ?? $quote['error'])]; } if (empty($overview['Name']) || empty($overview['MarketCapitalization'])) { // If overview fails or is empty, we can't proceed. return ['success' => false, 'message' => 'Could not retrieve complete data for symbol.']; } else { $company_name = $overview['Name']; $price = isset($quote['Global Quote']['05. price']) ? (float)$quote['Global Quote']['05. price'] : 0; $change_percent_raw = isset($quote['Global Quote']['10. change percent']) ? $quote['Global Quote']['10. change percent'] : '0%'; $change_percent = rtrim($change_percent_raw, '%'); } $stmt = $pdo->prepare("INSERT INTO watchlist (symbol, company_name, price, change_percent) VALUES (?, ?, ?, ?)"); $result = $stmt->execute([$symbol, $company_name, $price, $change_percent]); return ['success' => $result]; }