umstellung
This commit is contained in:
@@ -277,34 +277,56 @@ $mm->registerFunction($moduleName, 'fx_refresh', static function (string $baseCu
|
||||
}
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'alpha_vantage_fetch_quote', static function (string $symbol): array {
|
||||
$mm->registerFunction($moduleName, 'bavest_request', static function (
|
||||
string $path,
|
||||
array $payload = [],
|
||||
string $accept = 'application/json',
|
||||
string $method = 'POST'
|
||||
): array {
|
||||
$settings = modules()->settings('boersenchecker');
|
||||
$apiKey = trim((string) ($settings['alpha_vantage_api_key'] ?? ''));
|
||||
$timeout = (int) ($settings['alpha_vantage_timeout_sec'] ?? 12);
|
||||
$apiKey = trim((string) ($settings['bavest_api_key'] ?? ''));
|
||||
$timeout = (int) ($settings['bavest_timeout_sec'] ?? 12);
|
||||
$timeout = $timeout > 0 ? $timeout : 12;
|
||||
$symbol = strtoupper(trim($symbol));
|
||||
|
||||
if ($symbol === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Kein API-Symbol hinterlegt.',
|
||||
];
|
||||
}
|
||||
$method = strtoupper(trim($method));
|
||||
$method = in_array($method, ['GET', 'POST'], true) ? $method : 'POST';
|
||||
|
||||
if ($apiKey === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha-Vantage-API-Key fehlt. Bitte im Modul-Setup hinterlegen.',
|
||||
'message' => 'Bavest-API-Key fehlt. Bitte im Modul-Setup hinterlegen.',
|
||||
];
|
||||
}
|
||||
|
||||
$url = 'https://www.alphavantage.co/query?' . http_build_query([
|
||||
'function' => 'GLOBAL_QUOTE',
|
||||
'symbol' => $symbol,
|
||||
'apikey' => $apiKey,
|
||||
]);
|
||||
$url = 'https://api.bavest.co/v2/' . ltrim($path, '/');
|
||||
$jsonPayload = '';
|
||||
if ($method === 'GET') {
|
||||
if ($payload !== []) {
|
||||
$query = http_build_query($payload, '', '&', PHP_QUERY_RFC3986);
|
||||
if ($query !== '') {
|
||||
$url .= (str_contains($url, '?') ? '&' : '?') . $query;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$jsonPayload = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($jsonPayload)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Bavest-Payload konnte nicht kodiert werden.',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$headers = [
|
||||
'Accept: ' . $accept,
|
||||
'x-api-key: ' . $apiKey,
|
||||
];
|
||||
if ($method === 'POST') {
|
||||
$headers[] = 'Content-Type: application/json';
|
||||
}
|
||||
|
||||
$responseBody = null;
|
||||
$httpCode = 0;
|
||||
$curlError = '';
|
||||
|
||||
if (function_exists('curl_init')) {
|
||||
$ch = curl_init($url);
|
||||
@@ -314,100 +336,216 @@ $mm->registerFunction($moduleName, 'alpha_vantage_fetch_quote', static function
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_TIMEOUT => $timeout,
|
||||
CURLOPT_CONNECTTIMEOUT => min(5, $timeout),
|
||||
CURLOPT_HTTPHEADER => ['Accept: application/json'],
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
]);
|
||||
if ($method === 'POST') {
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
|
||||
}
|
||||
$responseBody = curl_exec($ch);
|
||||
$curlError = curl_error($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Anfrage fehlgeschlagen.'
|
||||
. ($curlError !== '' ? ' ' . $curlError : '')
|
||||
. ($httpCode > 0 ? ' HTTP ' . $httpCode : ''),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'method' => $method,
|
||||
'timeout' => $timeout,
|
||||
'header' => "Accept: application/json\r\n",
|
||||
'header' => implode("\r\n", $headers) . "\r\n",
|
||||
],
|
||||
]);
|
||||
$responseBody = @file_get_contents($url, false, $context);
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Anfrage lieferte keine Daten.',
|
||||
];
|
||||
if ($method === 'POST') {
|
||||
$contextOptions = stream_context_get_options($context);
|
||||
$contextOptions['http']['content'] = $jsonPayload;
|
||||
$context = stream_context_create($contextOptions);
|
||||
}
|
||||
$responseBody = @file_get_contents($url, false, $context);
|
||||
}
|
||||
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Bavest Anfrage fehlgeschlagen.'
|
||||
. ($curlError !== '' ? ' ' . $curlError : '')
|
||||
. ($httpCode > 0 ? ' HTTP ' . $httpCode : ''),
|
||||
];
|
||||
}
|
||||
|
||||
$decoded = json_decode($responseBody, true);
|
||||
if (!is_array($decoded)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Antwort ist kein gueltiges JSON.',
|
||||
'message' => 'Bavest Antwort ist kein gueltiges JSON.',
|
||||
'raw_body' => $responseBody,
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($decoded['Note'])) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Limit-Hinweis: ' . trim((string) $decoded['Note']),
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($decoded['Information'])) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => trim((string) $decoded['Information']),
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($decoded['Error Message'])) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => trim((string) $decoded['Error Message']),
|
||||
];
|
||||
}
|
||||
|
||||
$quote = is_array($decoded['Global Quote'] ?? null) ? $decoded['Global Quote'] : [];
|
||||
$price = $quote['05. price'] ?? null;
|
||||
if (!is_numeric($price)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage lieferte keinen Preis fuer das Symbol ' . $symbol . '.',
|
||||
];
|
||||
foreach (['error', 'message', 'detail'] as $errorKey) {
|
||||
if (isset($decoded[$errorKey]) && is_string($decoded[$errorKey]) && trim($decoded[$errorKey]) !== '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => trim((string) $decoded[$errorKey]),
|
||||
'raw' => $decoded,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'symbol' => (string) ($quote['01. symbol'] ?? $symbol),
|
||||
'price' => (float) $price,
|
||||
'latest_trading_day' => (string) ($quote['07. latest trading day'] ?? ''),
|
||||
'previous_close' => is_numeric($quote['08. previous close'] ?? null) ? (float) $quote['08. previous close'] : null,
|
||||
'change' => is_numeric($quote['09. change'] ?? null) ? (float) $quote['09. change'] : null,
|
||||
'change_percent' => (string) ($quote['10. change percent'] ?? ''),
|
||||
'fetched_at' => date('Y-m-d H:i:s'),
|
||||
'source' => 'alpha_vantage:GLOBAL_QUOTE',
|
||||
'raw' => $quote,
|
||||
'data' => $decoded,
|
||||
];
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'alpha_vantage_search_symbols', static function (string $keywords): array {
|
||||
$settings = modules()->settings('boersenchecker');
|
||||
$apiKey = trim((string) ($settings['alpha_vantage_api_key'] ?? ''));
|
||||
$timeout = (int) ($settings['alpha_vantage_timeout_sec'] ?? 12);
|
||||
$timeout = $timeout > 0 ? $timeout : 12;
|
||||
$keywords = trim($keywords);
|
||||
$mm->registerFunction($moduleName, 'bavest_extract_quote', static function (array $entry): ?array {
|
||||
$candidates = [$entry];
|
||||
foreach (['quote', 'data', 'result', 'security'] as $nestedKey) {
|
||||
if (isset($entry[$nestedKey]) && is_array($entry[$nestedKey])) {
|
||||
$candidates[] = $entry[$nestedKey];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
$price = null;
|
||||
foreach (['price', 'close', 'last', 'lastPrice', 'currentPrice', 'c'] as $priceKey) {
|
||||
if (is_numeric($candidate[$priceKey] ?? null)) {
|
||||
$price = (float) $candidate[$priceKey];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($price === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$timestamp = trim((string) ($candidate['timestamp'] ?? $candidate['time'] ?? $candidate['date'] ?? ''));
|
||||
$timestamp = $timestamp !== '' ? date('Y-m-d H:i:s', strtotime($timestamp) ?: time()) : date('Y-m-d H:i:s');
|
||||
|
||||
return [
|
||||
'symbol' => trim((string) ($candidate['symbol'] ?? $candidate['ticker'] ?? $entry['symbol'] ?? '')),
|
||||
'isin' => trim((string) ($candidate['isin'] ?? $entry['isin'] ?? '')),
|
||||
'price' => $price,
|
||||
'currency' => strtoupper(trim((string) ($candidate['currency'] ?? $candidate['quoteCurrency'] ?? $entry['currency'] ?? 'EUR'))) ?: 'EUR',
|
||||
'fetched_at' => $timestamp,
|
||||
'source' => 'bavest:quote',
|
||||
'raw' => $candidate,
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'bavest_fetch_quote_by_isin', static function (string $isin): array {
|
||||
$isin = strtoupper(trim($isin));
|
||||
if ($isin === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Keine ISIN hinterlegt.',
|
||||
];
|
||||
}
|
||||
|
||||
$response = module_fn('boersenchecker', 'bavest_request', 'timeseries/quote', ['isin' => $isin], 'application/json', 'GET');
|
||||
if (empty($response['ok'])) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
if (isset($data['data']) && is_array($data['data'])) {
|
||||
$data = [
|
||||
'isin' => $isin,
|
||||
'data' => $data['data'],
|
||||
];
|
||||
} else {
|
||||
$data['isin'] = $data['isin'] ?? $isin;
|
||||
}
|
||||
$quote = module_fn('boersenchecker', 'bavest_extract_quote', $data);
|
||||
if (!is_array($quote)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Bavest lieferte keinen Preis fuer die ISIN ' . $isin . '.',
|
||||
];
|
||||
}
|
||||
|
||||
return ['ok' => true] + $quote;
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'bavest_fetch_bulk_quotes', static function (array $instruments): array {
|
||||
$payloadSymbols = [];
|
||||
$indexByIsin = [];
|
||||
foreach ($instruments as $instrument) {
|
||||
if (!is_array($instrument)) {
|
||||
continue;
|
||||
}
|
||||
$isin = strtoupper(trim((string) ($instrument['isin'] ?? '')));
|
||||
if ($isin === '') {
|
||||
continue;
|
||||
}
|
||||
$payloadSymbols[] = ['isin' => $isin];
|
||||
$indexByIsin[$isin] = (int) ($instrument['id'] ?? 0);
|
||||
}
|
||||
|
||||
if ($payloadSymbols === []) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Keine ISIN fuer den Bulk-Abruf verfuegbar.',
|
||||
'quotes' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$response = module_fn('boersenchecker', 'bavest_request', 'bulk', [
|
||||
'symbols' => $payloadSymbols,
|
||||
'endpoint' => 'quote',
|
||||
'params' => new stdClass(),
|
||||
], 'application/json', 'POST');
|
||||
if (empty($response['ok'])) {
|
||||
return $response + ['quotes' => []];
|
||||
}
|
||||
|
||||
$data = $response['data'] ?? [];
|
||||
$items = [];
|
||||
if (is_array($data)) {
|
||||
if (isset($data['data']) && is_array($data['data'])) {
|
||||
$items = $data['data'];
|
||||
} elseif (isset($data['results']) && is_array($data['results'])) {
|
||||
$items = $data['results'];
|
||||
} elseif (array_is_list($data)) {
|
||||
$items = $data;
|
||||
} else {
|
||||
$items = [$data];
|
||||
}
|
||||
}
|
||||
|
||||
$quotes = [];
|
||||
foreach ($items as $offset => $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$quote = module_fn('boersenchecker', 'bavest_extract_quote', $item);
|
||||
if (!is_array($quote)) {
|
||||
continue;
|
||||
}
|
||||
$isin = strtoupper(trim((string) ($quote['isin'] ?? $item['isin'] ?? '')));
|
||||
$instrumentId = $isin !== '' ? ($indexByIsin[$isin] ?? 0) : 0;
|
||||
if ($instrumentId <= 0 && isset($payloadSymbols[$offset]['isin'])) {
|
||||
$instrumentId = (int) ($indexByIsin[(string) $payloadSymbols[$offset]['isin']] ?? 0);
|
||||
$quote['isin'] = (string) $payloadSymbols[$offset]['isin'];
|
||||
}
|
||||
if ($instrumentId <= 0) {
|
||||
continue;
|
||||
}
|
||||
$quotes[$instrumentId] = $quote + ['instrument_id' => $instrumentId];
|
||||
}
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'quotes' => $quotes,
|
||||
'message' => count($quotes) . ' Kurse aus Bavest Bulk geladen.',
|
||||
];
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'bavest_search_symbols', static function (string $keywords): array {
|
||||
$keywords = trim($keywords);
|
||||
if ($keywords === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
@@ -416,118 +554,60 @@ $mm->registerFunction($moduleName, 'alpha_vantage_search_symbols', static functi
|
||||
];
|
||||
}
|
||||
|
||||
if ($apiKey === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha-Vantage-API-Key fehlt. Bitte im Modul-Setup hinterlegen.',
|
||||
'results' => [],
|
||||
];
|
||||
$response = module_fn('boersenchecker', 'bavest_request', 'reference/search/aggregated', [
|
||||
'q' => $keywords,
|
||||
'limit' => 25,
|
||||
], 'application/json', 'GET');
|
||||
if (empty($response['ok'])) {
|
||||
return $response + ['results' => []];
|
||||
}
|
||||
|
||||
$url = 'https://www.alphavantage.co/query?' . http_build_query([
|
||||
'function' => 'SYMBOL_SEARCH',
|
||||
'keywords' => $keywords,
|
||||
'apikey' => $apiKey,
|
||||
]);
|
||||
|
||||
$responseBody = null;
|
||||
|
||||
if (function_exists('curl_init')) {
|
||||
$ch = curl_init($url);
|
||||
if ($ch !== false) {
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_TIMEOUT => $timeout,
|
||||
CURLOPT_CONNECTTIMEOUT => min(5, $timeout),
|
||||
CURLOPT_HTTPHEADER => ['Accept: application/json'],
|
||||
]);
|
||||
$responseBody = curl_exec($ch);
|
||||
$curlError = curl_error($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Suche fehlgeschlagen.'
|
||||
. ($curlError !== '' ? ' ' . $curlError : '')
|
||||
. ($httpCode > 0 ? ' HTTP ' . $httpCode : ''),
|
||||
'results' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
$data = $response['data'] ?? [];
|
||||
$items = [];
|
||||
if (is_array($data['data']['results'] ?? null)) {
|
||||
$items = $data['data']['results'];
|
||||
} elseif (is_array($data['results'] ?? null)) {
|
||||
$items = $data['results'];
|
||||
}
|
||||
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'timeout' => $timeout,
|
||||
'header' => "Accept: application/json\r\n",
|
||||
],
|
||||
]);
|
||||
$responseBody = @file_get_contents($url, false, $context);
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Suche lieferte keine Daten.',
|
||||
'results' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$decoded = json_decode($responseBody, true);
|
||||
if (!is_array($decoded)) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Suchantwort ist kein gueltiges JSON.',
|
||||
'results' => [],
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($decoded['Note'])) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Limit-Hinweis: ' . trim((string) $decoded['Note']),
|
||||
'results' => [],
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($decoded['Information'])) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => trim((string) $decoded['Information']),
|
||||
'results' => [],
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($decoded['Error Message'])) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => trim((string) $decoded['Error Message']),
|
||||
'results' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$matches = is_array($decoded['bestMatches'] ?? null) ? $decoded['bestMatches'] : [];
|
||||
$results = [];
|
||||
foreach ($matches as $match) {
|
||||
if (!is_array($match)) {
|
||||
foreach ($items as $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$name = trim((string) ($item['name'] ?? $item['companyName'] ?? $item['securityName'] ?? ''));
|
||||
$rootTicker = trim((string) ($item['root_ticker'] ?? ''));
|
||||
$listings = is_array($item['listings'] ?? null) ? $item['listings'] : [];
|
||||
|
||||
$results[] = [
|
||||
'symbol' => trim((string) ($match['1. symbol'] ?? '')),
|
||||
'name' => trim((string) ($match['2. name'] ?? '')),
|
||||
'type' => trim((string) ($match['3. type'] ?? '')),
|
||||
'region' => trim((string) ($match['4. region'] ?? '')),
|
||||
'market_open' => trim((string) ($match['5. marketOpen'] ?? '')),
|
||||
'market_close' => trim((string) ($match['6. marketClose'] ?? '')),
|
||||
'timezone' => trim((string) ($match['7. timezone'] ?? '')),
|
||||
'currency' => trim((string) ($match['8. currency'] ?? '')),
|
||||
'match_score' => trim((string) ($match['9. matchScore'] ?? '')),
|
||||
];
|
||||
foreach ($listings as $listing) {
|
||||
if (!is_array($listing)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$symbol = trim((string) ($listing['symbol'] ?? $rootTicker));
|
||||
$isin = strtoupper(trim((string) ($listing['isin'] ?? '')));
|
||||
$region = trim((string) ($listing['exchange'] ?? $listing['region'] ?? ''));
|
||||
$type = trim((string) ($listing['type'] ?? ''));
|
||||
$currency = strtoupper(trim((string) ($listing['currency'] ?? '')));
|
||||
|
||||
if ($symbol === '' && $name === '' && $isin === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$results[] = [
|
||||
'symbol' => $symbol,
|
||||
'name' => $name,
|
||||
'isin' => $isin,
|
||||
'type' => $type,
|
||||
'region' => $region,
|
||||
'currency' => $currency,
|
||||
'match_score' => '',
|
||||
'raw' => [
|
||||
'security' => $item,
|
||||
'listing' => $listing,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
@@ -537,147 +617,89 @@ $mm->registerFunction($moduleName, 'alpha_vantage_search_symbols', static functi
|
||||
];
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'alpha_vantage_fetch_chart_series', static function (string $symbol): array {
|
||||
$settings = modules()->settings('boersenchecker');
|
||||
$apiKey = trim((string) ($settings['alpha_vantage_api_key'] ?? ''));
|
||||
$timeout = (int) ($settings['alpha_vantage_timeout_sec'] ?? 12);
|
||||
$timeout = $timeout > 0 ? $timeout : 12;
|
||||
$symbol = strtoupper(trim($symbol));
|
||||
|
||||
if ($symbol === '') {
|
||||
return ['ok' => false, 'message' => 'Kein Symbol angegeben.'];
|
||||
}
|
||||
if ($apiKey === '') {
|
||||
return ['ok' => false, 'message' => 'Alpha-Vantage-API-Key fehlt.'];
|
||||
$mm->registerFunction($moduleName, 'bavest_fetch_chart_series', static function (string $isin): array {
|
||||
$isin = strtoupper(trim($isin));
|
||||
if ($isin === '') {
|
||||
return ['ok' => false, 'message' => 'Keine ISIN angegeben.'];
|
||||
}
|
||||
|
||||
$cacheDir = sys_get_temp_dir() . '/boersenchecker-alpha-vantage';
|
||||
$cacheDir = sys_get_temp_dir() . '/boersenchecker-bavest';
|
||||
if (!is_dir($cacheDir)) {
|
||||
@mkdir($cacheDir, 0775, true);
|
||||
}
|
||||
$cachePath = $cacheDir . '/' . md5('historical-price|' . $isin) . '.json';
|
||||
|
||||
$fetchPayload = static function (string $functionName, int $ttl) use ($symbol, $apiKey, $timeout, $cacheDir): array {
|
||||
$cacheKey = md5($functionName . '|' . $symbol . '|' . $apiKey);
|
||||
$cachePath = $cacheDir . '/' . $cacheKey . '.json';
|
||||
if (is_file($cachePath) && (time() - filemtime($cachePath)) < $ttl) {
|
||||
$cached = file_get_contents($cachePath);
|
||||
$decoded = is_string($cached) ? json_decode($cached, true) : null;
|
||||
if (is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
$url = 'https://www.alphavantage.co/query?' . http_build_query([
|
||||
'function' => $functionName,
|
||||
'symbol' => $symbol,
|
||||
'apikey' => $apiKey,
|
||||
'outputsize' => 'compact',
|
||||
]);
|
||||
|
||||
$responseBody = null;
|
||||
if (function_exists('curl_init')) {
|
||||
$ch = curl_init($url);
|
||||
if ($ch !== false) {
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_TIMEOUT => $timeout,
|
||||
CURLOPT_CONNECTTIMEOUT => min(5, $timeout),
|
||||
CURLOPT_HTTPHEADER => ['Accept: application/json'],
|
||||
]);
|
||||
$responseBody = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_string($responseBody) || $responseBody === '') {
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'timeout' => $timeout,
|
||||
'header' => "Accept: application/json\r\n",
|
||||
],
|
||||
]);
|
||||
$responseBody = @file_get_contents($url, false, $context);
|
||||
}
|
||||
|
||||
$decoded = is_string($responseBody) ? json_decode($responseBody, true) : null;
|
||||
if (is_array($decoded) && $decoded !== []) {
|
||||
@file_put_contents($cachePath, json_encode($decoded, JSON_UNESCAPED_UNICODE));
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
$normalizeSeries = static function (array $payload, array $keys): array {
|
||||
foreach ($keys as $key) {
|
||||
$series = $payload[$key] ?? null;
|
||||
if (!is_array($series)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$points = [];
|
||||
foreach ($series as $date => $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$close = $row['4. close'] ?? $row['5. adjusted close'] ?? null;
|
||||
if (!is_numeric($close)) {
|
||||
$close = $row['5. adjusted close'] ?? $row['4. close'] ?? null;
|
||||
}
|
||||
if (!is_numeric($close)) {
|
||||
continue;
|
||||
}
|
||||
$points[] = [
|
||||
'date' => (string) $date,
|
||||
'close' => (float) $close,
|
||||
];
|
||||
}
|
||||
|
||||
usort($points, static fn (array $left, array $right): int => strcmp((string) $left['date'], (string) $right['date']));
|
||||
return $points;
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
$dailyPayload = $fetchPayload('TIME_SERIES_DAILY_ADJUSTED', 6 * 3600);
|
||||
if (($dailyPayload['Information'] ?? null) || ($dailyPayload['Error Message'] ?? null)) {
|
||||
$dailyPayload = $fetchPayload('TIME_SERIES_DAILY', 6 * 3600);
|
||||
}
|
||||
$weeklyPayload = $fetchPayload('TIME_SERIES_WEEKLY_ADJUSTED', 12 * 3600);
|
||||
if (($weeklyPayload['Information'] ?? null) || ($weeklyPayload['Error Message'] ?? null)) {
|
||||
$weeklyPayload = $fetchPayload('TIME_SERIES_WEEKLY', 12 * 3600);
|
||||
}
|
||||
$monthlyPayload = $fetchPayload('TIME_SERIES_MONTHLY_ADJUSTED', 24 * 3600);
|
||||
if (($monthlyPayload['Information'] ?? null) || ($monthlyPayload['Error Message'] ?? null)) {
|
||||
$monthlyPayload = $fetchPayload('TIME_SERIES_MONTHLY', 24 * 3600);
|
||||
$decoded = null;
|
||||
if (is_file($cachePath) && (time() - filemtime($cachePath)) < (6 * 3600)) {
|
||||
$cached = file_get_contents($cachePath);
|
||||
$decoded = is_string($cached) ? json_decode($cached, true) : null;
|
||||
}
|
||||
|
||||
if (!empty($dailyPayload['Note']) || !empty($weeklyPayload['Note']) || !empty($monthlyPayload['Note'])) {
|
||||
if (!is_array($decoded)) {
|
||||
$response = module_fn('boersenchecker', 'bavest_request', 'timeseries/history', [
|
||||
'isin' => $isin,
|
||||
'from' => date('Y-m-d', strtotime('-6 years')),
|
||||
'to' => date('Y-m-d'),
|
||||
], 'application/json', 'GET');
|
||||
if (empty($response['ok'])) {
|
||||
return $response;
|
||||
}
|
||||
$decoded = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
@file_put_contents($cachePath, json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
if (isset($decoded['data']['prices']) && is_array($decoded['data']['prices'])) {
|
||||
$rows = $decoded['data']['prices'];
|
||||
} elseif (isset($decoded['data']) && is_array($decoded['data'])) {
|
||||
$rows = $decoded['data'];
|
||||
} elseif (isset($decoded['results']) && is_array($decoded['results'])) {
|
||||
$rows = $decoded['results'];
|
||||
} elseif (array_is_list($decoded)) {
|
||||
$rows = $decoded;
|
||||
}
|
||||
|
||||
$dailyByDate = [];
|
||||
foreach ($rows as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$date = trim((string) ($row['date'] ?? $row['time'] ?? $row['timestamp'] ?? ''));
|
||||
$close = $row['close'] ?? $row['price'] ?? $row['c'] ?? null;
|
||||
if ($date === '' || !is_numeric($close)) {
|
||||
continue;
|
||||
}
|
||||
$normalizedDate = date('Y-m-d', strtotime($date) ?: time());
|
||||
$dailyByDate[$normalizedDate] = [
|
||||
'date' => date('Y-m-d', strtotime($date) ?: time()),
|
||||
'close' => (float) $close,
|
||||
];
|
||||
}
|
||||
$daily = array_values($dailyByDate);
|
||||
|
||||
usort($daily, static fn (array $left, array $right): int => strcmp((string) $left['date'], (string) $right['date']));
|
||||
if ($daily === []) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Alpha Vantage Limit erreicht. Bitte spaeter erneut versuchen.',
|
||||
'message' => 'Keine historischen Schlusskurse fuer ' . $isin . ' verfuegbar.',
|
||||
];
|
||||
}
|
||||
|
||||
$daily = $normalizeSeries($dailyPayload, ['Time Series (Daily)']);
|
||||
$weekly = $normalizeSeries($weeklyPayload, ['Weekly Adjusted Time Series', 'Weekly Time Series']);
|
||||
$monthly = $normalizeSeries($monthlyPayload, ['Monthly Adjusted Time Series', 'Monthly Time Series']);
|
||||
|
||||
if ($daily === [] && $weekly === [] && $monthly === []) {
|
||||
return [
|
||||
'ok' => false,
|
||||
'message' => 'Keine Zeitreihendaten fuer ' . $symbol . ' verfuegbar.',
|
||||
];
|
||||
}
|
||||
$aggregate = static function (array $points, string $format): array {
|
||||
$result = [];
|
||||
foreach ($points as $point) {
|
||||
$bucket = date($format, strtotime((string) $point['date']) ?: time());
|
||||
$result[$bucket] = $point;
|
||||
}
|
||||
return array_values($result);
|
||||
};
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'symbol' => $symbol,
|
||||
'isin' => $isin,
|
||||
'daily' => $daily,
|
||||
'weekly' => $weekly,
|
||||
'monthly' => $monthly,
|
||||
'weekly' => $aggregate($daily, 'o-W'),
|
||||
'monthly' => $aggregate($daily, 'Y-m'),
|
||||
'source' => 'bavest:timeseries/history',
|
||||
];
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user