<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Live Forex & Crypto Prices (Bid/Ask)</title>
  <!-- Bootstrap 5 CDN -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    body { padding: 20px; }
    .small-muted { font-size: .85rem; color: #6c757d; }
  </style>
</head>
<body>
  <div class="container">
    <h2 class="mb-3">Live Prices — Forex (bid/ask) & Crypto (major pairs)</h2>

    <div class="row mb-3">
      <div class="col-md-6">
        <div class="card shadow-sm">
          <div class="card-body">
            <h5 class="card-title">Forex — Major pairs + Precious Metals</h5>
            <p class="small-muted">Source: Alpha Vantage (needs API key)</p>
            <div class="table-responsive">
              <table class="table table-sm table-striped" id="forex-table">
                <thead>
                  <tr>
                    <th>Pair</th>
                    <th>Bid (Buy)</th>
                    <th>Ask (Sell)</th>
                    <th>Rate</th>
                    <th>Updated</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <div class="col-md-6">
        <div class="card shadow-sm">
          <div class="card-body">
            <h5 class="card-title">Crypto — Major pairs</h5>
            <p class="small-muted">Source: Binance public API</p>
            <div class="table-responsive">
              <table class="table table-sm table-striped" id="crypto-table">
                <thead>
                  <tr>
                    <th>Symbol</th>
                    <th>Bid (Buy)</th>
                    <th>Ask (Sell)</th>
                    <th>Spread</th>
                    <th>Updated</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mb-3 d-flex gap-2">
      <button id="refresh-now" class="btn btn-primary btn-sm">Refresh Now</button>
      <button id="toggle-auto" class="btn btn-outline-secondary btn-sm">Auto: ON (5s)</button>
      <div class="ms-auto small-muted align-self-center">Last full refresh: <span id="last-refresh">—</span></div>
    </div>

    <div class="alert alert-info small" id="note">
      Set your Alpha Vantage API key in the JavaScript variable <code>ALPHAVANTAGE_API_KEY</code>.
    </div>
  </div>

<script>
/* Live Forex & Crypto page with AJAX POST only on price change */

const ALPHAVANTAGE_API_KEY = 'PCUTPPMEWF0J5V98'; // <<--- set your key
const API_POST_URL = 'https://aurofxmarket.in/Rest/update_crypto_price';         // <<--- set your endpoint


const forexPairs = [
  { from: 'AUD', to: 'CAD', label: 'AUD/CAD' },
  { from: 'AUD', to: 'CHF', label: 'AUD/CHF' },
  { from: 'AUD', to: 'JPY', label: 'AUD/JPY' },
  { from: 'AUD', to: 'NZD', label: 'AUD/NZD' },
  { from: 'AUD', to: 'USD', label: 'AUD/USD' },
  { from: 'CAD', to: 'CHF', label: 'CAD/CHF' },
  { from: 'CAD', to: 'JPY', label: 'CAD/JPY' },
  { from: 'CHF', to: 'JPY', label: 'CHF/JPY' },
  { from: 'EUR', to: 'AUD', label: 'EUR/AUD' },
  { from: 'EUR', to: 'CAD', label: 'EUR/CAD' },
  { from: 'EUR', to: 'CHF', label: 'EUR/CHF' },
  { from: 'EUR', to: 'GBP', label: 'EUR/GBP' },
  { from: 'EUR', to: 'JPY', label: 'EUR/JPY' },
  { from: 'EUR', to: 'NOK', label: 'EUR/NOK' },
  { from: 'EUR', to: 'NZD', label: 'EUR/NZD' },
  { from: 'EUR', to: 'USD', label: 'EUR/USD' },
  { from: 'GBP', to: 'AUD', label: 'GBP/AUD' },
  { from: 'GBP', to: 'CAD', label: 'GBP/CAD' },
  { from: 'GBP', to: 'CHF', label: 'GBP/CHF' },
  { from: 'GBP', to: 'JPY', label: 'GBP/JPY' },
  { from: 'GBP', to: 'USD', label: 'GBP/USD' },
  { from: 'NZD', to: 'CAD', label: 'NZD/CAD' },
  { from: 'NZD', to: 'CHF', label: 'NZD/CHF' },
  { from: 'NZD', to: 'JPY', label: 'NZD/JPY' },
  { from: 'NZD', to: 'USD', label: 'NZD/USD' },
  { from: 'USD', to: 'CAD', label: 'USD/CAD' },
  { from: 'USD', to: 'CHF', label: 'USD/CHF' },
  { from: 'USD', to: 'JPY', label: 'USD/JPY' },
  { from: 'USD', to: 'SEK', label: 'USD/SEK' },
  { from: 'USD', to: 'ZAR', label: 'USD/ZAR' }
];

const cryptoSymbols = ['BTCUSDT','ETHUSDT','BNBUSDT','XRPUSDT','LTCUSDT'];

// Store last known prices
let lastForexPrices = {};
let lastCryptoPrices = {};

let autoRefresh = true;
let refreshIntervalMs = 5000;
let autoTimer = null;

function prettyDateNow() {
  return new Date().toLocaleString();
}

// Send price update to backend
function sendPriceToAPI(pair, bid, ask){
  $.ajax({
    url: API_POST_URL,
    method: 'POST',
    data: { pair, bid, ask, timestamp: prettyDateNow()},
    success: function(res){ 
        
        console.log(res);
        //console.log('Sent price:', pair, bid, ask);
        
    },
    error: function(err){ console.error('Failed to send price for', pair, err); }
  });
}

function initTables() {
  const $fbody = $('#forex-table tbody').empty();
  forexPairs.forEach(p => {
    $fbody.append(`<tr id="fx-${p.from}${p.to}">
      <td>${p.label}</td>
      <td class="bid">-</td>
      <td class="ask">-</td>
      <td class="rate">-</td>
      <td class="updated">-</td>
    </tr>`);
  });

  const $cbody = $('#crypto-table tbody').empty();
  cryptoSymbols.forEach(s => {
    $cbody.append(`<tr id="crypto-${s}">
      <td>${s}</td>
      <td class="bid">-</td>
      <td class="ask">-</td>
      <td class="spread">-</td>
      <td class="updated">-</td>
    </tr>`);
  });
}

// Fetch single FX pair
function fetchForexPair(pair){
  const url = `https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=${pair.from}&to_currency=${pair.to}&apikey=${ALPHAVANTAGE_API_KEY}`;
  return $.getJSON(url);
}

// Update Forex prices
function updateForexAll(){
  const delayBetween = 1200;
  forexPairs.forEach((p, idx) => {
    setTimeout(() => {
      fetchForexPair(p)
        .done(data => {
          const root = data['Realtime Currency Exchange Rate'] || data;
          const bid = root['8. Bid Price'] || '-';
          const ask = root['9. Ask Price'] || '-';
          const rate = root['5. Exchange Rate'] || '-';
          const ts = root['6. Last Refreshed'] || prettyDateNow();

          const $row = $(`#fx-${p.from}${p.to}`);
          $row.find('.bid').text(bid);
          $row.find('.ask').text(ask);
          $row.find('.rate').text(rate);
          $row.find('.updated').text(ts);

          // Send AJAX only if changed
          const last = lastForexPrices[p.label] || {};
          if(bid !== last.bid || ask !== last.ask){
           // sendPriceToAPI(p.label, bid, ask);
            lastForexPrices[p.label] = { bid, ask };
          }
        })
        .fail(err => {
          const $row = $(`#fx-${p.from}${p.to}`);
          $row.find('.bid').text('err');
          $row.find('.ask').text('err');
          $row.find('.rate').text('-');
          $row.find('.updated').text('error');
          console.error('FX fetch failed', p, err);
        });
    }, idx * delayBetween);
  });
}

// Fetch crypto
function fetchCryptoSymbol(sym){
  return $.getJSON(`https://api.binance.com/api/v3/ticker/bookTicker?symbol=${sym}`);
}

// Update crypto prices
function updateCryptoAll(){
  cryptoSymbols.forEach(sym => {
    fetchCryptoSymbol(sym)
      .done(data => {
        const bid = data.bidPrice || '-';
        const ask = data.askPrice || '-';
        const spread = (bid && ask) ? (parseFloat(ask) - parseFloat(bid)).toString() : '-';
        const ts = prettyDateNow();

        const $row = $(`#crypto-${sym}`);
        $row.find('.bid').text(bid);
        $row.find('.ask').text(ask);
        $row.find('.spread').text(spread);
        $row.find('.updated').text(ts);

        const last = lastCryptoPrices[sym] || {};
        if(bid !== last.bid || ask !== last.ask){
          sendPriceToAPI(sym, bid, ask);
          lastCryptoPrices[sym] = { bid, ask };
        }
      })
      .fail(err => {
        const $row = $(`#crypto-${sym}`);
        $row.find('.bid').text('err');
        $row.find('.ask').text('err');
        $row.find('.spread').text('-');
        $row.find('.updated').text('error');
        console.error('Crypto fetch failed', sym, err);
      });
  });
}

// Full refresh
function fullRefresh(){
  if (!ALPHAVANTAGE_API_KEY || ALPHAVANTAGE_API_KEY.indexOf('YOUR') === 0) {
    $('#note').addClass('alert-warning').removeClass('alert-info').text('Warning: Set a valid Alpha Vantage API key in the script (ALPHAVANTAGE_API_KEY). Forex calls will fail without it.');
  }
  $('#last-refresh').text(prettyDateNow());
  updateCryptoAll();
  updateForexAll();
}

function startAuto(){
  if (autoTimer) clearInterval(autoTimer);
  autoTimer = setInterval(fullRefresh, refreshIntervalMs);
  $('#toggle-auto').text(`Auto: ON (${refreshIntervalMs/1000}s)`).removeClass('btn-outline-secondary').addClass('btn-success');
}

function stopAuto(){
  if (autoTimer) clearInterval(autoTimer);
  autoTimer = null;
  $('#toggle-auto').text('Auto: OFF').removeClass('btn-success').addClass('btn-outline-secondary');
}

$(function(){
  initTables();
  fullRefresh();
  if (autoRefresh) startAuto();

  $('#refresh-now').on('click', fullRefresh);
  $('#toggle-auto').on('click', () => {
    autoRefresh = !autoRefresh;
    if(autoRefresh) startAuto(); else stopAuto();
  });
});
</script>
</body>
</html>
