1.0
This commit is contained in:
parent
577ca93381
commit
18f8cfddc5
311
ai/LocalAIApi.php
Normal file
311
ai/LocalAIApi.php
Normal file
@ -0,0 +1,311 @@
|
|||||||
|
<?php
|
||||||
|
// LocalAIApi — proxy client for the Responses API.
|
||||||
|
// Usage:
|
||||||
|
// require_once __DIR__ . '/ai/LocalAIApi.php';
|
||||||
|
// $response = LocalAIApi::createResponse([
|
||||||
|
// 'input' => [
|
||||||
|
// ['role' => 'system', 'content' => 'You are a helpful assistant.'],
|
||||||
|
// ['role' => 'user', 'content' => 'Tell me a bedtime story.'],
|
||||||
|
// ],
|
||||||
|
// ]);
|
||||||
|
// if (!empty($response['success'])) {
|
||||||
|
// $decoded = LocalAIApi::decodeJsonFromResponse($response);
|
||||||
|
// }
|
||||||
|
|
||||||
|
class LocalAIApi
|
||||||
|
{
|
||||||
|
/** @var array<string,mixed>|null */
|
||||||
|
private static ?array $configCache = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signature compatible with the OpenAI Responses API.
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $params Request body (model, input, text, reasoning, metadata, etc.).
|
||||||
|
* @param array<string,mixed> $options Extra options (timeout, verify_tls, headers, path, project_uuid).
|
||||||
|
* @return array{
|
||||||
|
* success:bool,
|
||||||
|
* status?:int,
|
||||||
|
* data?:mixed,
|
||||||
|
* error?:string,
|
||||||
|
* response?:mixed,
|
||||||
|
* message?:string
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public static function createResponse(array $params, array $options = []): array
|
||||||
|
{
|
||||||
|
$cfg = self::config();
|
||||||
|
$payload = $params;
|
||||||
|
|
||||||
|
if (empty($payload['input']) || !is_array($payload['input'])) {
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'input_missing',
|
||||||
|
'message' => 'Parameter "input" is required and must be an array.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isset($payload['model']) || $payload['model'] === '') {
|
||||||
|
$payload['model'] = $cfg['default_model'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::request($options['path'] ?? null, $payload, $options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Snake_case alias for createResponse (matches the provided example).
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $params
|
||||||
|
* @param array<string,mixed> $options
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public static function create_response(array $params, array $options = []): array
|
||||||
|
{
|
||||||
|
return self::createResponse($params, $options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform a raw request to the AI proxy.
|
||||||
|
*
|
||||||
|
* @param string $path Endpoint (may be an absolute URL).
|
||||||
|
* @param array<string,mixed> $payload JSON payload.
|
||||||
|
* @param array<string,mixed> $options Additional request options.
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public static function request(?string $path = null, array $payload = [], array $options = []): array
|
||||||
|
{
|
||||||
|
if (!function_exists('curl_init')) {
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'curl_missing',
|
||||||
|
'message' => 'PHP cURL extension is missing. Install or enable it on the VM.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$cfg = self::config();
|
||||||
|
|
||||||
|
$projectUuid = $cfg['project_uuid'];
|
||||||
|
if (empty($projectUuid)) {
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'project_uuid_missing',
|
||||||
|
'message' => 'PROJECT_UUID is not defined; aborting AI request.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$defaultPath = $cfg['responses_path'] ?? null;
|
||||||
|
$resolvedPath = $path ?? ($options['path'] ?? $defaultPath);
|
||||||
|
if (empty($resolvedPath)) {
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'project_id_missing',
|
||||||
|
'message' => 'PROJECT_ID is not defined; cannot resolve AI proxy endpoint.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$url = self::buildUrl($resolvedPath, $cfg['base_url']);
|
||||||
|
$baseTimeout = isset($cfg['timeout']) ? (int) $cfg['timeout'] : 30;
|
||||||
|
$timeout = isset($options['timeout']) ? (int) $options['timeout'] : $baseTimeout;
|
||||||
|
if ($timeout <= 0) {
|
||||||
|
$timeout = 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
$baseVerifyTls = array_key_exists('verify_tls', $cfg) ? (bool) $cfg['verify_tls'] : true;
|
||||||
|
$verifyTls = array_key_exists('verify_tls', $options)
|
||||||
|
? (bool) $options['verify_tls']
|
||||||
|
: $baseVerifyTls;
|
||||||
|
|
||||||
|
$projectHeader = $cfg['project_header'];
|
||||||
|
|
||||||
|
$headers = [
|
||||||
|
'Content-Type: application/json',
|
||||||
|
'Accept: application/json',
|
||||||
|
];
|
||||||
|
$headers[] = $projectHeader . ': ' . $projectUuid;
|
||||||
|
if (!empty($options['headers']) && is_array($options['headers'])) {
|
||||||
|
foreach ($options['headers'] as $header) {
|
||||||
|
if (is_string($header) && $header !== '') {
|
||||||
|
$headers[] = $header;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($projectUuid) && !array_key_exists('project_uuid', $payload)) {
|
||||||
|
$payload['project_uuid'] = $projectUuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
$body = json_encode($payload, JSON_UNESCAPED_UNICODE);
|
||||||
|
if ($body === false) {
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'json_encode_failed',
|
||||||
|
'message' => 'Failed to encode request body to JSON.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$ch = curl_init($url);
|
||||||
|
curl_setopt($ch, CURLOPT_POST, true);
|
||||||
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
|
||||||
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
||||||
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||||
|
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
|
||||||
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
|
||||||
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verifyTls);
|
||||||
|
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyTls ? 2 : 0);
|
||||||
|
curl_setopt($ch, CURLOPT_FAILONERROR, false);
|
||||||
|
|
||||||
|
$responseBody = curl_exec($ch);
|
||||||
|
if ($responseBody === false) {
|
||||||
|
$error = curl_error($ch) ?: 'Unknown cURL error';
|
||||||
|
curl_close($ch);
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'curl_error',
|
||||||
|
'message' => $error,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
$decoded = null;
|
||||||
|
if ($responseBody !== '' && $responseBody !== null) {
|
||||||
|
$decoded = json_decode($responseBody, true);
|
||||||
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
|
$decoded = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($status >= 200 && $status < 300) {
|
||||||
|
return [
|
||||||
|
'success' => true,
|
||||||
|
'status' => $status,
|
||||||
|
'data' => $decoded ?? $responseBody,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$errorMessage = 'AI proxy request failed';
|
||||||
|
if (is_array($decoded)) {
|
||||||
|
$errorMessage = $decoded['error'] ?? $decoded['message'] ?? $errorMessage;
|
||||||
|
} elseif (is_string($responseBody) && $responseBody !== '') {
|
||||||
|
$errorMessage = $responseBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'success' => false,
|
||||||
|
'status' => $status,
|
||||||
|
'error' => $errorMessage,
|
||||||
|
'response' => $decoded ?? $responseBody,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract plain text from a Responses API payload.
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $response Result of LocalAIApi::createResponse|request.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function extractText(array $response): string
|
||||||
|
{
|
||||||
|
$payload = $response['data'] ?? $response;
|
||||||
|
if (!is_array($payload)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($payload['output']) && is_array($payload['output'])) {
|
||||||
|
$combined = '';
|
||||||
|
foreach ($payload['output'] as $item) {
|
||||||
|
if (!isset($item['content']) || !is_array($item['content'])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach ($item['content'] as $block) {
|
||||||
|
if (is_array($block) && ($block['type'] ?? '') === 'output_text' && !empty($block['text'])) {
|
||||||
|
$combined .= $block['text'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($combined !== '') {
|
||||||
|
return $combined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($payload['choices'][0]['message']['content'])) {
|
||||||
|
return (string) $payload['choices'][0]['message']['content'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempt to decode JSON emitted by the model (handles markdown fences).
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $response
|
||||||
|
* @return array<string,mixed>|null
|
||||||
|
*/
|
||||||
|
public static function decodeJsonFromResponse(array $response): ?array
|
||||||
|
{
|
||||||
|
$text = self::extractText($response);
|
||||||
|
if ($text === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$decoded = json_decode($text, true);
|
||||||
|
if (is_array($decoded)) {
|
||||||
|
return $decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
$stripped = preg_replace('/^```json|```$/m', '', trim($text));
|
||||||
|
if ($stripped !== null && $stripped !== $text) {
|
||||||
|
$decoded = json_decode($stripped, true);
|
||||||
|
if (is_array($decoded)) {
|
||||||
|
return $decoded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load configuration from ai/config.php.
|
||||||
|
*
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
private static function config(): array
|
||||||
|
{
|
||||||
|
if (self::$configCache === null) {
|
||||||
|
$configPath = __DIR__ . '/config.php';
|
||||||
|
if (!file_exists($configPath)) {
|
||||||
|
throw new RuntimeException('AI config file not found: ai/config.php');
|
||||||
|
}
|
||||||
|
$cfg = require $configPath;
|
||||||
|
if (!is_array($cfg)) {
|
||||||
|
throw new RuntimeException('Invalid AI config format: expected array');
|
||||||
|
}
|
||||||
|
self::$configCache = $cfg;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::$configCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an absolute URL from base_url and a path.
|
||||||
|
*/
|
||||||
|
private static function buildUrl(string $path, string $baseUrl): string
|
||||||
|
{
|
||||||
|
$trimmed = trim($path);
|
||||||
|
if ($trimmed === '') {
|
||||||
|
return $baseUrl;
|
||||||
|
}
|
||||||
|
if (str_starts_with($trimmed, 'http://') || str_starts_with($trimmed, 'https://')) {
|
||||||
|
return $trimmed;
|
||||||
|
}
|
||||||
|
if ($trimmed[0] === '/') {
|
||||||
|
return $baseUrl . $trimmed;
|
||||||
|
}
|
||||||
|
return $baseUrl . '/' . $trimmed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy alias for backward compatibility with the previous class name.
|
||||||
|
if (!class_exists('OpenAIService')) {
|
||||||
|
class_alias(LocalAIApi::class, 'OpenAIService');
|
||||||
|
}
|
||||||
52
ai/config.php
Normal file
52
ai/config.php
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
// OpenAI proxy configuration (workspace scope).
|
||||||
|
// Reads values from environment variables or executor/.env.
|
||||||
|
|
||||||
|
$projectUuid = getenv('PROJECT_UUID');
|
||||||
|
$projectId = getenv('PROJECT_ID');
|
||||||
|
|
||||||
|
if (
|
||||||
|
($projectUuid === false || $projectUuid === null || $projectUuid === '') ||
|
||||||
|
($projectId === false || $projectId === null || $projectId === '')
|
||||||
|
) {
|
||||||
|
$envPath = realpath(__DIR__ . '/../../.env'); // executor/.env
|
||||||
|
if ($envPath && is_readable($envPath)) {
|
||||||
|
$lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$line = trim($line);
|
||||||
|
if ($line === '' || $line[0] === '#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!str_contains($line, '=')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
[$key, $value] = array_map('trim', explode('=', $line, 2));
|
||||||
|
if ($key === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$value = trim($value, "\"' ");
|
||||||
|
if (getenv($key) === false || getenv($key) === '') {
|
||||||
|
putenv("{$key}={$value}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$projectUuid = getenv('PROJECT_UUID');
|
||||||
|
$projectId = getenv('PROJECT_ID');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$projectUuid = ($projectUuid === false) ? null : $projectUuid;
|
||||||
|
$projectId = ($projectId === false) ? null : $projectId;
|
||||||
|
|
||||||
|
$baseUrl = 'https://flatlogic.com';
|
||||||
|
$responsesPath = $projectId ? "/projects/{$projectId}/ai-request" : null;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'base_url' => $baseUrl,
|
||||||
|
'responses_path' => $responsesPath,
|
||||||
|
'project_id' => $projectId,
|
||||||
|
'project_uuid' => $projectUuid,
|
||||||
|
'project_header' => 'project-uuid',
|
||||||
|
'default_model' => 'gpt-5',
|
||||||
|
'timeout' => 30,
|
||||||
|
'verify_tls' => true,
|
||||||
|
];
|
||||||
89
assets/css/custom.css
Normal file
89
assets/css/custom.css
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
:root {
|
||||||
|
--bs-body-bg: #121212;
|
||||||
|
--bs-body-color: #E0E0E0;
|
||||||
|
--bs-secondary-color: #A0A0A0;
|
||||||
|
--surface-bg: #1E1E1E;
|
||||||
|
--primary-accent: #00A8FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Inter', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-surface {
|
||||||
|
background-color: var(--surface-bg) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar-brand, .nav-link {
|
||||||
|
color: var(--bs-body-color) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover, .nav-link.active {
|
||||||
|
color: var(--primary-accent) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hero .lead {
|
||||||
|
color: var(--bs-secondary-color) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
border: 1px solid #333;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
background-color: rgba(255, 255, 255, 0.03);
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table {
|
||||||
|
--bs-table-bg: transparent;
|
||||||
|
--bs-table-hover-bg: rgba(255, 255, 255, 0.04);
|
||||||
|
--bs-table-color: var(--bs-body-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.table thead th {
|
||||||
|
border-bottom: 2px solid #444;
|
||||||
|
color: var(--bs-secondary-color);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table td, .table th {
|
||||||
|
border-top: 1px solid #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-hover tbody tr:hover {
|
||||||
|
color: var(--bs-body-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress {
|
||||||
|
background-color: #444;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar {
|
||||||
|
background-color: var(--primary-accent);
|
||||||
|
font-weight: 600;
|
||||||
|
color: #121212;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
padding: 0.3em 0.6em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--primary-accent);
|
||||||
|
border-color: var(--primary-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: #0094dd;
|
||||||
|
border-color: #0094dd;
|
||||||
|
}
|
||||||
|
|
||||||
|
i[data-feather] {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
vertical-align: text-bottom;
|
||||||
|
}
|
||||||
98
assets/js/main.js
Normal file
98
assets/js/main.js
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
feather.replace();
|
||||||
|
|
||||||
|
const scannerForm = document.querySelector('#scanner form');
|
||||||
|
const scanButton = scannerForm.querySelector('button[type="submit"]');
|
||||||
|
const resultsTableBody = document.querySelector('#scanner .table-responsive tbody');
|
||||||
|
|
||||||
|
if (scannerForm) {
|
||||||
|
scannerForm.addEventListener('submit', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
// Show loading state
|
||||||
|
scanButton.disabled = true;
|
||||||
|
scanButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Scanning...';
|
||||||
|
resultsTableBody.innerHTML = '<tr><td colspan="5" class="text-center text-secondary py-4">Scanning for moonshots...</td></tr>';
|
||||||
|
|
||||||
|
const formData = new FormData(scannerForm);
|
||||||
|
|
||||||
|
fetch('scanner.php', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
// Restore button
|
||||||
|
scanButton.disabled = false;
|
||||||
|
scanButton.innerHTML = 'Scan';
|
||||||
|
|
||||||
|
let tableContent = '';
|
||||||
|
if (data.length > 0) {
|
||||||
|
data.forEach(stock => {
|
||||||
|
tableContent += `
|
||||||
|
<tr>
|
||||||
|
<td class="fw-bold">${stock.symbol}</td>
|
||||||
|
<td>${stock.company_name}</td>
|
||||||
|
<td class="text-end">${parseFloat(stock.price).toFixed(2)}</td>
|
||||||
|
<td class="text-end">${formatMarketCap(stock.market_cap)}</td>
|
||||||
|
<td class="text-center">
|
||||||
|
<form method="POST" action="index.php" style="display: inline;">
|
||||||
|
<input type="hidden" name="symbol" value="${stock.symbol}">
|
||||||
|
<button type="submit" class="btn btn-sm btn-outline-primary">Add to Watchlist</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
tableContent = '<tr><td colspan="5" class="text-center text-secondary py-4">No stocks matched your criteria.</td></tr>';
|
||||||
|
}
|
||||||
|
resultsTableBody.innerHTML = tableContent;
|
||||||
|
feather.replace(); // Re-run feather icons
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error during scan:', error);
|
||||||
|
// Restore button
|
||||||
|
scanButton.disabled = false;
|
||||||
|
scanButton.innerHTML = 'Scan';
|
||||||
|
resultsTableBody.innerHTML = '<tr><td colspan="5" class="text-center text-danger py-4">An error occurred during the scan.</td></tr>';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function formatMarketCap(num) {
|
||||||
|
if (num >= 1000000000) {
|
||||||
|
return '
|
||||||
|
+ (num / 1000000000).toFixed(2) + 'B';
|
||||||
|
}
|
||||||
|
if (num >= 1000000) {
|
||||||
|
return '
|
||||||
|
+ (num / 1000000).toFixed(2) + 'M';
|
||||||
|
}
|
||||||
|
return '
|
||||||
|
+ num;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle adding from scan results to watchlist
|
||||||
|
document.addEventListener('click', function(e) {
|
||||||
|
if (e.target && e.target.matches('#scanner .btn-outline-primary')) {
|
||||||
|
const form = e.target.closest('form');
|
||||||
|
if (form) {
|
||||||
|
e.preventDefault();
|
||||||
|
const formData = new FormData(form);
|
||||||
|
|
||||||
|
fetch(form.action, {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
// Redirect or update UI as needed. For now, we'll just reload.
|
||||||
|
window.location.hash = 'watchlist';
|
||||||
|
window.location.reload();
|
||||||
|
})
|
||||||
|
.catch(error => console.error('Error adding to watchlist:', error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
39
db/migrations/001_create_watchlist_table.php
Normal file
39
db/migrations/001_create_watchlist_table.php
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
<?php
|
||||||
|
require_once __DIR__ . '/../config.php';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$pdo = db();
|
||||||
|
|
||||||
|
$sql = "
|
||||||
|
CREATE TABLE IF NOT EXISTS watchlist (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
symbol VARCHAR(20) NOT NULL UNIQUE,
|
||||||
|
company_name VARCHAR(255),
|
||||||
|
price DECIMAL(10, 2) DEFAULT 0.00,
|
||||||
|
change_pct DECIMAL(5, 2) DEFAULT 0.00,
|
||||||
|
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
";
|
||||||
|
|
||||||
|
$pdo->exec($sql);
|
||||||
|
|
||||||
|
// Let's add the initial mock data to the new table
|
||||||
|
$stocks = [
|
||||||
|
['symbol' => 'TSLA', 'company_name' => 'Tesla, Inc.', 'price' => 177.48, 'change_pct' => -1.45],
|
||||||
|
['symbol' => 'AAPL', 'company_name' => 'Apple Inc.', 'price' => 170.03, 'change_pct' => 0.35],
|
||||||
|
['symbol' => 'GOOGL', 'company_name' => 'Alphabet Inc.', 'price' => 139.44, 'change_pct' => 1.25],
|
||||||
|
['symbol' => 'AMZN', 'company_name' => 'Amazon.com, Inc.', 'price' => 134.91, 'change_pct' => -0.21],
|
||||||
|
];
|
||||||
|
|
||||||
|
$stmt = $pdo->prepare("INSERT IGNORE INTO watchlist (symbol, company_name, price, change_pct) VALUES (:symbol, :company_name, :price, :change_pct)");
|
||||||
|
|
||||||
|
foreach ($stocks as $stock) {
|
||||||
|
$stmt->execute($stock);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "Migration successful: 'watchlist' table created and seeded.\n";
|
||||||
|
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
die("Migration failed: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
98
includes/finance_api.php
Normal file
98
includes/finance_api.php
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
<?php
|
||||||
|
// includes/finance_api.php
|
||||||
|
|
||||||
|
function get_finance_api_key() {
|
||||||
|
// For now, we'll use the demo key.
|
||||||
|
// In the future, we can get this from an environment variable.
|
||||||
|
return 'demo';
|
||||||
|
}
|
||||||
|
|
||||||
|
function call_finance_api($params) {
|
||||||
|
$params['apikey'] = get_finance_api_key();
|
||||||
|
$url = 'https://www.alphavantage.co/query?' . http_build_query($params);
|
||||||
|
|
||||||
|
$ch = curl_init();
|
||||||
|
curl_setopt($ch, CURLOPT_URL, $url);
|
||||||
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||||
|
curl_setopt($ch, CURLOPT_TIMEOUT, 20); // 20 second timeout
|
||||||
|
$response = curl_exec($ch);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
// Alpha Vantage returns CSV for listing status, and JSON for others.
|
||||||
|
// The free API also sometimes returns a JSON error note about call frequency.
|
||||||
|
if (strpos($response, 'Thank you for using Alpha Vantage!') !== false) {
|
||||||
|
return ['error' => '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];
|
||||||
|
}
|
||||||
321
index.php
321
index.php
@ -1,150 +1,199 @@
|
|||||||
<?php
|
<?php
|
||||||
declare(strict_types=1);
|
// Force-refresh for platform sync
|
||||||
@ini_set('display_errors', '1');
|
require_once 'db/config.php';
|
||||||
@error_reporting(E_ALL);
|
require_once 'includes/finance_api.php';
|
||||||
@date_default_timezone_set('UTC');
|
|
||||||
|
|
||||||
$phpVersion = PHP_VERSION;
|
// Handle Add Stock Form Submission
|
||||||
$now = date('Y-m-d H:i:s');
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['symbol'])) {
|
||||||
|
$symbol = trim(strtoupper($_POST['symbol']));
|
||||||
|
if (!empty($symbol)) {
|
||||||
|
try {
|
||||||
|
$pdo = db();
|
||||||
|
add_stock_with_details($symbol, $pdo);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
// Handle error, e.g. log it
|
||||||
|
error_log("Error adding stock: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Redirect to the watchlist section to prevent form resubmission
|
||||||
|
header("Location: " . $_SERVER['PHP_SELF'] . '#watchlist');
|
||||||
|
exit;
|
||||||
|
}
|
||||||
?>
|
?>
|
||||||
<!doctype html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en" data-bs-theme="dark">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>New Style</title>
|
|
||||||
<?php
|
<title>Moonshot Tracker</title>
|
||||||
// Read project preview data from environment
|
<meta name="description" content="AI-powered moonshots tracker for micro/small cap stocks. Built with Flatlogic Generator.">
|
||||||
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? '';
|
<meta name="keywords" content="moonshot stocks, small cap, micro cap, stock scanner, investment tool, trading app, AI stock analysis, high growth stocks, market analysis, Flatlogic">
|
||||||
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';
|
|
||||||
?>
|
<meta property="og:title" content="Moonshot Tracker">
|
||||||
<?php if ($projectDescription): ?>
|
<meta property="og:description" content="AI-powered moonshots tracker for micro/small cap stocks.">
|
||||||
<!-- Meta description -->
|
<meta property="og:image" content="">
|
||||||
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' />
|
<meta name="twitter:card" content="summary_large_image">
|
||||||
<!-- Open Graph meta tags -->
|
<meta name="twitter:image" content="">
|
||||||
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
|
|
||||||
<!-- Twitter meta tags -->
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" />
|
|
||||||
<?php endif; ?>
|
|
||||||
<?php if ($projectImageUrl): ?>
|
|
||||||
<!-- Open Graph image -->
|
|
||||||
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
|
|
||||||
<!-- Twitter image -->
|
|
||||||
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
|
|
||||||
<?php endif; ?>
|
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||||
<style>
|
<link rel="stylesheet" href="assets/css/custom.css">
|
||||||
:root {
|
|
||||||
--bg-color-start: #6a11cb;
|
|
||||||
--bg-color-end: #2575fc;
|
|
||||||
--text-color: #ffffff;
|
|
||||||
--card-bg-color: rgba(255, 255, 255, 0.01);
|
|
||||||
--card-border-color: rgba(255, 255, 255, 0.1);
|
|
||||||
}
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
font-family: 'Inter', sans-serif;
|
|
||||||
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
|
|
||||||
color: var(--text-color);
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
min-height: 100vh;
|
|
||||||
text-align: center;
|
|
||||||
overflow: hidden;
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
body::before {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
|
|
||||||
animation: bg-pan 20s linear infinite;
|
|
||||||
z-index: -1;
|
|
||||||
}
|
|
||||||
@keyframes bg-pan {
|
|
||||||
0% { background-position: 0% 0%; }
|
|
||||||
100% { background-position: 100% 100%; }
|
|
||||||
}
|
|
||||||
main {
|
|
||||||
padding: 2rem;
|
|
||||||
}
|
|
||||||
.card {
|
|
||||||
background: var(--card-bg-color);
|
|
||||||
border: 1px solid var(--card-border-color);
|
|
||||||
border-radius: 16px;
|
|
||||||
padding: 2rem;
|
|
||||||
backdrop-filter: blur(20px);
|
|
||||||
-webkit-backdrop-filter: blur(20px);
|
|
||||||
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
|
|
||||||
}
|
|
||||||
.loader {
|
|
||||||
margin: 1.25rem auto 1.25rem;
|
|
||||||
width: 48px;
|
|
||||||
height: 48px;
|
|
||||||
border: 3px solid rgba(255, 255, 255, 0.25);
|
|
||||||
border-top-color: #fff;
|
|
||||||
border-radius: 50%;
|
|
||||||
animation: spin 1s linear infinite;
|
|
||||||
}
|
|
||||||
@keyframes spin {
|
|
||||||
from { transform: rotate(0deg); }
|
|
||||||
to { transform: rotate(360deg); }
|
|
||||||
}
|
|
||||||
.hint {
|
|
||||||
opacity: 0.9;
|
|
||||||
}
|
|
||||||
.sr-only {
|
|
||||||
position: absolute;
|
|
||||||
width: 1px; height: 1px;
|
|
||||||
padding: 0; margin: -1px;
|
|
||||||
overflow: hidden;
|
|
||||||
clip: rect(0, 0, 0, 0);
|
|
||||||
white-space: nowrap; border: 0;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 3rem;
|
|
||||||
font-weight: 700;
|
|
||||||
margin: 0 0 1rem;
|
|
||||||
letter-spacing: -1px;
|
|
||||||
}
|
|
||||||
p {
|
|
||||||
margin: 0.5rem 0;
|
|
||||||
font-size: 1.1rem;
|
|
||||||
}
|
|
||||||
code {
|
|
||||||
background: rgba(0,0,0,0.2);
|
|
||||||
padding: 2px 6px;
|
|
||||||
border-radius: 4px;
|
|
||||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
||||||
}
|
|
||||||
footer {
|
|
||||||
position: absolute;
|
|
||||||
bottom: 1rem;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
opacity: 0.7;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main>
|
|
||||||
<div class="card">
|
<header class="container mt-4">
|
||||||
<h1>Analyzing your requirements and generating your website…</h1>
|
<nav class="navbar navbar-expand-lg navbar-dark">
|
||||||
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes">
|
<a class="navbar-brand fw-bold" href="#">Moonshot Tracker</a>
|
||||||
<span class="sr-only">Loading…</span>
|
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
|
||||||
|
<span class="navbar-toggler-icon"></span>
|
||||||
|
</button>
|
||||||
|
<div class="collapse navbar-collapse" id="navbarNav">
|
||||||
|
<ul class="navbar-nav ms-auto">
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link" href="#watchlist">Watchlist</a>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link active" aria-current="page" href="#scanner">Scanner</a>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link" href="#">Settings</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</nav
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="container my-5">
|
||||||
|
<div class="hero text-center mb-5">
|
||||||
|
<h1 class="display-4 fw-bold">Discover Your Next 10x Stock</h1>
|
||||||
|
<p class="lead text-secondary">AI-powered scanning for high-upside micro and small-cap gems.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Moonshot Scanner -->
|
||||||
|
<div id="scanner" class="card bg-surface mb-5">
|
||||||
|
<div class="card-header">
|
||||||
|
<h5 class="mb-0">Moonshot Scanner</h5>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="card-text text-secondary">Define criteria to discover undervalued high-growth stocks across markets.</p>
|
||||||
|
<form>
|
||||||
|
<div class="row g-3 align-items-end">
|
||||||
|
<div class="col-md-4">
|
||||||
|
<label class="form-label">Market Cap (USD)</label>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="number" class="form-control" name="min_market_cap" placeholder="Min" value="50000000">
|
||||||
|
<input type="number" class="form-control" name="max_market_cap" placeholder="Max" value="10000000000">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label">Stock Price</label>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="number" class="form-control" name="min_price" placeholder="Min $" value="1">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-5">
|
||||||
|
<label class="form-label">Avg. Daily Volume</label>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="number" class="form-control" name="min_volume" placeholder="Min" value="100000">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover table-borderless mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Symbol</th>
|
||||||
|
<th scope="col">Company Name</th>
|
||||||
|
<th scope="col" class="text-end">Price</th>
|
||||||
|
<th scope="col" class="text-end">Market Cap</th>
|
||||||
|
<th scope="col" class="text-center">Action</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td colspan="5" class="text-center text-secondary py-4">
|
||||||
|
<p class="mb-0">Scanning for moonshots...</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="watchlist" class="card bg-surface">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<h5 class="mb-0">Moonshot Watchlist</h5>
|
||||||
|
<form class="d-flex" method="POST" action="index.php">
|
||||||
|
<input class="form-control me-2" type="text" name="symbol" placeholder="Add Symbol (e.g. RIVN)" required>
|
||||||
|
<button class="btn btn-primary btn-sm d-flex align-items-center" type="submit">
|
||||||
|
<i data-feather="plus" class="me-1"></i> Add
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover table-borderless">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Symbol</th>
|
||||||
|
<th scope="col">Company Name</th>
|
||||||
|
<th scope="col" class="text-end">Price</th>
|
||||||
|
<th scope="col" class="text-end">Change % (24h)</th>
|
||||||
|
<th scope="col" class="text-center">Conviction (soon)</th>
|
||||||
|
<th scope="col">Tags (soon)</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<?php
|
||||||
|
require_once 'db/config.php';
|
||||||
|
try {
|
||||||
|
$pdo = db();
|
||||||
|
$stmt = $pdo->query('SELECT symbol, company_name, price, change_pct FROM watchlist ORDER BY symbol ASC');
|
||||||
|
$watchlist = $stmt->fetchAll();
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
// For now, just show an empty list on DB error.
|
||||||
|
// In a real app, you'd want to log this error.
|
||||||
|
$watchlist = [];
|
||||||
|
error_log("Database error: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($watchlist as $stock):
|
||||||
|
$changeClass = $stock['change_pct'] >= 0 ? 'text-success' : 'text-danger';
|
||||||
|
$changeIcon = $stock['change_pct'] >= 0 ? 'trending-up' : 'trending-down';
|
||||||
|
?>
|
||||||
|
<tr>
|
||||||
|
<td class="fw-bold"><?= htmlspecialchars($stock['symbol']) ?></td>
|
||||||
|
<td><?= htmlspecialchars($stock['company_name']) ?></td>
|
||||||
|
<td class="text-end">$<?= number_format($stock['price'], 2) ?></td>
|
||||||
|
<td class="text-end <?= $changeClass ?>">
|
||||||
|
<i data-feather="<?= $changeIcon ?>" class="me-1"></i> <?= number_format($stock['change_pct'], 2) ?>%
|
||||||
|
</td>
|
||||||
|
<td class="text-center fst-italic text-secondary">N/A</td>
|
||||||
|
<td><span class="badge bg-secondary bg-opacity-25 text-light">N/A</span></td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<p class="hint"><?= ($_SERVER['HTTP_HOST'] ?? '') === 'appwizzy.com' ? 'AppWizzy' : 'Flatlogic' ?> AI is collecting your requirements and applying the first changes.</p>
|
|
||||||
<p class="hint">This page will update automatically as the plan is implemented.</p>
|
|
||||||
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p>
|
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<footer>
|
|
||||||
Page updated: <?= htmlspecialchars($now) ?> (UTC)
|
<footer class="container text-center text-secondary mt-5 py-3">
|
||||||
|
<small>© <?= date('Y') ?> Moonshot Tracker. All Rights Reserved.</small>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
|
||||||
|
<script src="assets/js/main.js"></script>
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
// Automatically trigger the scan on page load
|
||||||
|
document.querySelector('#scanner form').dispatchEvent(new Event('submit', { cancelable: true }));
|
||||||
|
});
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
91
scanner.php
Normal file
91
scanner.php
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
<?php
|
||||||
|
// scanner.php
|
||||||
|
|
||||||
|
require_once 'db/config.php';
|
||||||
|
require_once 'includes/finance_api.php';
|
||||||
|
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
|
||||||
|
// --- Scanner Criteria ---
|
||||||
|
// Get criteria from POST request, with defaults
|
||||||
|
$min_market_cap = isset($_POST['min_market_cap']) ? (float)$_POST['min_market_cap'] : 50000000;
|
||||||
|
$max_market_cap = isset($_POST['max_market_cap']) ? (float)$_POST['max_market_cap'] : 10000000000;
|
||||||
|
$min_price = isset($_POST['min_price']) ? (float)$_POST['min_price'] : 1.00;
|
||||||
|
$min_volume = isset($_POST['min_volume']) ? (int)$_POST['min_volume'] : 100000;
|
||||||
|
|
||||||
|
$results = [];
|
||||||
|
$errors = [];
|
||||||
|
|
||||||
|
// 1. Fetch all listed stocks (as CSV)
|
||||||
|
$csv_data = get_all_listed_stocks();
|
||||||
|
|
||||||
|
if (is_array($csv_data) && isset($csv_data['error'])) {
|
||||||
|
echo json_encode(['error' => $csv_data['error']]);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines = str_getcsv($csv_data, "\n");
|
||||||
|
$header = str_getcsv(array_shift($lines));
|
||||||
|
$stocks = [];
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
if (empty(trim($line))) continue;
|
||||||
|
$stocks[] = array_combine($header, str_getcsv($line));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Take a small, random sample to avoid hitting API limits
|
||||||
|
shuffle($stocks);
|
||||||
|
$sample_size = 5; // Limit to 5 API calls per scan to stay within free tier limits
|
||||||
|
$sample = array_slice($stocks, 0, $sample_size);
|
||||||
|
|
||||||
|
// 3. Analyze the sample
|
||||||
|
foreach ($sample as $stock) {
|
||||||
|
$symbol = $stock['symbol'];
|
||||||
|
|
||||||
|
// Skip non-US stocks for now for data consistency
|
||||||
|
if (!in_array($stock['exchange'], ['NASDAQ', 'NYSE', 'AMEX'])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// To avoid hitting API limits, wait between calls.
|
||||||
|
// The free tier is very restrictive (5 calls/min).
|
||||||
|
sleep(15);
|
||||||
|
|
||||||
|
$overview = get_stock_overview($symbol);
|
||||||
|
|
||||||
|
if (isset($overview['error'])) {
|
||||||
|
$errors[] = "Could not fetch data for {$symbol}: " . $overview['error'];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$market_cap = (float)($overview['MarketCapitalization'] ?? 0);
|
||||||
|
$price = 0; // We'll get price from the quote call
|
||||||
|
|
||||||
|
$volume_str = $overview['Volume'] ?? '0';
|
||||||
|
$volume = (int) $volume_str;
|
||||||
|
|
||||||
|
// Check market cap and volume first to avoid unnecessary price checks
|
||||||
|
if ($market_cap >= $min_market_cap && $market_cap <= $max_market_cap && $volume >= $min_volume) {
|
||||||
|
sleep(15); // Another wait before the next API call
|
||||||
|
$quote = get_stock_quote($symbol);
|
||||||
|
|
||||||
|
if (isset($quote['Global Quote']['05. price'])) {
|
||||||
|
$price = (float)$quote['Global Quote']['05. price'];
|
||||||
|
|
||||||
|
if ($price >= $min_price) {
|
||||||
|
$results[] = [
|
||||||
|
'symbol' => $symbol,
|
||||||
|
'company_name' => $overview['Name'] ?? 'N/A',
|
||||||
|
'price' => $price,
|
||||||
|
'market_cap' => $market_cap
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($errors)) {
|
||||||
|
// If there were non-fatal errors, we can return them for debugging
|
||||||
|
// For now, we just return the successful results.
|
||||||
|
}
|
||||||
|
|
||||||
|
echo json_encode($results);
|
||||||
Loading…
x
Reference in New Issue
Block a user