-- symbols table
-- Stores metadata for each trading symbol
CREATE TABLE symbols (
    id SERIAL PRIMARY KEY,
    symbol VARCHAR(50) NOT NULL UNIQUE,
    base_asset VARCHAR(50),
    quote_asset VARCHAR(50),
    exchange VARCHAR(50),
    instrument_type VARCHAR(20) CHECK (instrument_type IN ('crypto', 'stock', 'forex', 'commodity')),
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_symbols_exchange ON symbols(exchange);
CREATE INDEX idx_symbols_type ON symbols(instrument_type);

-- candles_1h table
-- Stores hourly OHLCV data for each symbol
CREATE TABLE candles_1h (
    id BIGSERIAL PRIMARY KEY,
    symbol_id INT NOT NULL REFERENCES symbols(id) ON DELETE CASCADE,
    open_time TIMESTAMPTZ NOT NULL,
    close_time TIMESTAMPTZ NOT NULL,
    open NUMERIC(18,8) NOT NULL,
    high NUMERIC(18,8) NOT NULL,
    low NUMERIC(18,8) NOT NULL,
    close NUMERIC(18,8) NOT NULL,
    volume NUMERIC(20,8),
    trades_count INT,
    quote_volume NUMERIC(20,8),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE UNIQUE INDEX idx_candles_symbol_time ON candles_1h(symbol_id, open_time);
CREATE INDEX idx_candles_open_time ON candles_1h(open_time);

-- live_prices table
-- Stores the latest live market prices per symbol
CREATE TABLE live_prices (
    symbol_id INT PRIMARY KEY REFERENCES symbols(id) ON DELETE CASCADE,
    price NUMERIC(18,8) NOT NULL,
    bid NUMERIC(18,8),
    ask NUMERIC(18,8),
    bid_size NUMERIC(18,8),
    ask_size NUMERIC(18,8),
    last_updated TIMESTAMPTZ DEFAULT NOW(),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_live_prices_price ON live_prices(price);
