AURIGA · الوثيقة 03

03 · تصميم قواعد البيانات

الاستراتيجية: PostgreSQL للبيانات العلائقية (المستخدم، الحساب، الأمر، القرار) — ClickHouse لكل ما هو سلسلة زمنية — Redis للحالة الساخنة — S3/Iceberg للأرشيف والنماذج — pgvector للتضمينات.


1. مخطط العلاقات (PostgreSQL — schema core)

users ─┬─ user_profiles ── preferences
       ├─ auth_credentials (passkeys, totp, sessions)
       ├─ broker_links ── broker_accounts ── positions ── orders ── fills
       ├─ portfolios ── allocations
       ├─ council_runs ── agent_opinions ── decisions ── trade_plans
       ├─ strategies ── backtests ── paper_runs
       ├─ watchlists ── alerts ── alert_deliveries
       ├─ subscriptions ── invoices ── entitlements
       └─ journal_entries ── behavior_insights
instruments ── instrument_aliases ── venues ── sessions
news_items ── news_embeddings ── eco_events ── earnings_events
audit_log (append-only) · feature_flags · model_registry

2. DDL الأساسي (مختصر لكن قابل للتنفيذ)

CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE users (
  id             uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  email          citext UNIQUE NOT NULL,
  email_verified boolean NOT NULL DEFAULT false,
  locale         text NOT NULL DEFAULT 'ar',
  country        char(2),
  tier           text NOT NULL DEFAULT 'free',       -- free|pro|elite|enterprise
  role           text NOT NULL DEFAULT 'trader',     -- trader|support|analyst|admin
  status         text NOT NULL DEFAULT 'active',     -- active|suspended|deleted
  kyc_status     text NOT NULL DEFAULT 'none',       -- none|pending|verified|rejected
  mfa_required   boolean NOT NULL DEFAULT true,
  created_at     timestamptz NOT NULL DEFAULT now(),
  last_seen_at   timestamptz
);
CREATE INDEX ON users (tier, status);

CREATE TABLE instruments (
  auid        text PRIMARY KEY,                      -- رمز داخلي: FX:EURUSD, EQ:US:AAPL, CR:BTCUSDT
  asset_class text NOT NULL,                         -- fx|equity|crypto|metal|energy|index|commodity|etf|future
  venue       text,
  base        text, quote text,
  tick_size   numeric(18,8) NOT NULL,
  lot_size    numeric(18,8) NOT NULL DEFAULT 1,
  session_tz  text,
  is_active   boolean NOT NULL DEFAULT true,
  metadata    jsonb NOT NULL DEFAULT '{}'::jsonb
);

CREATE TABLE broker_links (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id       uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  broker        text NOT NULL,                       -- ibkr|oanda|alpaca|binance|bybit|kraken|mt5
  mode          text NOT NULL,                       -- paper|live
  credentials   bytea NOT NULL,                      -- مشفّر بـKMS envelope, لا يُقرأ بعد الكتابة
  scopes        text[] NOT NULL,
  withdraw_perm boolean NOT NULL DEFAULT false CHECK (withdraw_perm = false),
  status        text NOT NULL DEFAULT 'pending',
  last_sync_at  timestamptz,
  UNIQUE (user_id, broker, mode)
);

3. القرارات وخطة الصفقة (قلب النظام — audit-first)

CREATE TABLE council_runs (
  id             uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id        uuid REFERENCES users(id) ON DELETE SET NULL,
  auid           text NOT NULL REFERENCES instruments(auid),
  timeframe      text NOT NULL,
  as_of          timestamptz NOT NULL,               -- لحظة البيانات لا لحظة التنفيذ
  data_hash      text NOT NULL,                      -- sha256 لكل مدخلات البيانات
  model_versions jsonb NOT NULL,                     -- {"technical":"m-2026.11", ...}
  council_size   smallint NOT NULL,
  status         text NOT NULL,                      -- running|completed|failed|abstained
  latency_ms     int,
  cost_usd       numeric(10,5),
  created_at     timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON council_runs (auid, created_at DESC);

CREATE TABLE agent_opinions (
  run_id     uuid NOT NULL REFERENCES council_runs(id) ON DELETE CASCADE,
  agent      text NOT NULL,                          -- technical|macro|news|risk|...
  stance     text NOT NULL,                          -- bullish|bearish|neutral|abstain
  confidence numeric(4,3) NOT NULL CHECK (confidence BETWEEN 0 AND 1),
  evidence   jsonb NOT NULL,                         -- [{tool, args, value, ts, source}]
  rationale  text NOT NULL,
  veto       boolean NOT NULL DEFAULT false,         -- حق النقض لوكيل المخاطر
  tokens_in  int, tokens_out int, latency_ms int,
  PRIMARY KEY (run_id, agent)
);

CREATE TABLE decisions (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  run_id      uuid NOT NULL UNIQUE REFERENCES council_runs(id) ON DELETE CASCADE,
  action      text NOT NULL,                         -- buy|sell|no_trade|wait
  conviction  numeric(4,3) NOT NULL,                 -- إجماع مرجّح 0..1
  calibrated_p numeric(4,3),                         -- احتمال مُعايَر
  ci_low      numeric(4,3), ci_high numeric(4,3),
  sample_n    int,
  dissent     jsonb NOT NULL DEFAULT '[]'::jsonb,    -- من خالف ولماذا
  invalid_if  text[] NOT NULL DEFAULT '{}',          -- شروط الإبطال
  published_at timestamptz,                          -- يُكتب قبل حدوث السوق
  outcome     text,                                  -- win|loss|breakeven|ambiguous
  outcome_at  timestamptz
);
CREATE RULE decisions_no_update AS ON UPDATE TO decisions WHERE old.published_at IS NOT NULL AND new.outcome IS NULL DO INSTEAD NOTHING;

قاعدة النزاهة: بعد النشر، لا يُعدَّل القرار. التقييم يُكتب في حقول outcome فقط. أي تعديل آخر يُرفض على مستوى قاعدة البيانات (ليس التطبيق).


4. الأوامر والمراكز (Financial Integrity)

CREATE TABLE orders (
  id              uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id         uuid NOT NULL REFERENCES users(id),
  account_id      uuid NOT NULL,
  decision_id     uuid REFERENCES decisions(id),
  client_order_id text NOT NULL,                 -- idempotency key (UUID من العميل)
  auid            text NOT NULL,
  side            text NOT NULL CHECK (side IN ('buy','sell')),
  type            text NOT NULL CHECK (type IN ('market','limit','stop','stop_limit','trailing','oco')),
  qty             numeric(20,8) NOT NULL CHECK (qty > 0),
  limit_price     numeric(20,8),
  stop_price      numeric(20,8),
  tif             text NOT NULL DEFAULT 'GTC',
  state           text NOT NULL,                 -- draft|risk_rejected|sent|acked|partial|filled|cancelled|rejected
  reject_reason   text,
  risk_snapshot   jsonb NOT NULL,                -- حدود وقت الإرسال (إثبات الامتثال)
  approved_by     uuid NOT NULL,                 -- هوية المستخدم الذي وافق
  approved_at     timestamptz NOT NULL,
  broker_order_id text,
  created_at      timestamptz NOT NULL DEFAULT now(),
  UNIQUE (account_id, client_order_id)
);

CREATE TABLE fills (
  id         bigserial PRIMARY KEY,
  order_id   uuid NOT NULL REFERENCES orders(id),
  qty        numeric(20,8) NOT NULL,
  price      numeric(20,8) NOT NULL,
  fee        numeric(20,8) NOT NULL DEFAULT 0,
  slippage_bps numeric(8,2),
  filled_at  timestamptz NOT NULL,
  broker_fill_id text UNIQUE
);

CREATE TABLE positions (
  account_id uuid NOT NULL, auid text NOT NULL,
  qty numeric(20,8) NOT NULL, avg_price numeric(20,8) NOT NULL,
  stop_price numeric(20,8), tp_prices numeric(20,8)[],
  opened_at timestamptz, updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, auid)
) PARTITION BY HASH (account_id);

التطابق (Reconciliation): وظيفة كل 5 ثوانٍ تقارن positions بكشف الوسيط؛ أي فرق > 0 يُنشئ سجل recon_breaks ويظهر للمستخدم كتنبيه أحمر. لا يُسمح بالتنفيذ التالي حتى يُحلّ أو يُتجاهل صراحةً.


5. ClickHouse — طبقة السلاسل الزمنية

CREATE TABLE md_ticks (
  auid LowCardinality(String),
  venue LowCardinality(String),
  ts DateTime64(6, 'UTC'),
  bid Decimal(18,8), ask Decimal(18,8), last Decimal(18,8),
  bid_sz UInt32, ask_sz UInt32, trade_sz UInt32
) ENGINE = ReplicatedReplacingMergeTree
PARTITION BY toYYYYMMDD(ts)
ORDER BY (auid, ts)
TTL ts + INTERVAL 90 DAY TO VOLUME 'cold';

CREATE TABLE ohlcv (
  auid LowCardinality(String),
  tf LowCardinality(String),          -- 1s,1m,5m,15m,1h,4h,1d,1w
  ts DateTime('UTC'),
  open Decimal(18,8), high Decimal(18,8), low Decimal(18,8), close Decimal(18,8),
  volume Decimal(28,8), trades UInt32,
  vwap Decimal(18,8), buy_vol Decimal(28,8), sell_vol Decimal(28,8)
) ENGINE = ReplicatedAggregatingMergeTree
PARTITION BY (tf, toYYYYMM(ts)) ORDER BY (auid, tf, ts);

CREATE TABLE orderbook_snapshots (
  auid LowCardinality(String), ts DateTime64(3,'UTC'),
  bids Array(Tuple(Decimal(18,8), UInt32)),
  asks Array(Tuple(Decimal(18,8), UInt32))
) ENGINE = MergeTree PARTITION BY toYYYYMMDD(ts) ORDER BY (auid, ts)
TTL ts + INTERVAL 30 DAY;

CREATE TABLE audit_events (
  ts DateTime64(3,'UTC'), actor_id String, actor_role LowCardinality(String),
  action LowCardinality(String), resource String, ip String, ua String,
  result LowCardinality(String), meta String
) ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (ts, actor_id)
TTL ts + INTERVAL 7 YEAR;   -- التزام تنظيمي

الاحتفاظ والحجم التقديري: 10,000 رمز × 50 تيك/ثانية × 6.5 ساعة ≈ 11.7 مليار صف/يوم في السيناريو الأقصى — لذلك في الواقع نُخزّن تيكات مُدمجة بذكاء: تسعير كامل للرموز الساخنة (500 رمز)، وتجميع 1s للبقية. هذا يخفّض الحجم > 90%.


6. Redis / Valkey — مفاتيح التشغيل

المفتاح النوع TTL الاستخدام
px:{auid} hash 5s آخر سعر/سبريد للعرض
ob:{auid} string(zstd) 2s آخر عمق سوق
candle:{auid}:{tf} string 0 آخر شمعة قيد التكوين
rsk:{account} hash 0 العدادات اليومية (الخسارة، عدد الصفقات)
rl:{ip}:{route} counter 60s Rate limiting
sess:{sid} hash 30m الجلسة (مع دوران)
lock:order:{client_order_id} string NX 60s قفل idempotency
q:council stream 0 طابور طلبات التحليل

7. Kafka/Redpanda — مواضيع الأحداث

Topic Partitions احتفاظ المُنتِج → المستهلك
md.ticks.<class> 32 6h atlas-ingest → aggregator, risk
md.bars.1m 16 24h aggregator → atlas-query, scanner
council.requested 8 24h bff → oracle-council
council.opinion 8 24h oracle-council → supervisor
council.decision 8 30d supervisor → bff, journal, eval
risk.check 8 24h council/execution → aegis-risk
exec.order 8 30d execution → ledger, audit
exec.fill 8 30d execution → ledger, notify
alerts.triggered 8 7d scanners → notify
billing.events 2 30d billing → analytics

قاعدة: كل حدث يحمل event_id (UUIDv7)، occurred_at، schema_version، وtrace_id. المخططات في Schema Registry بوضع BACKWARD_TRANSITIVE.


8. حوكمة البيانات

AURIGA Blueprint · إفصاح: هذا المستند ليس نصيحة استثمارية ولا رأيًا قانونيًا.