Spaces:
Sleeping
Sleeping
File size: 5,960 Bytes
1192bae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | # database/database_setup.py
import sqlite3
from sqlite3 import Error
import os
# Database configuration
DB_DIR = "database"
DB_PATH = os.path.join(DB_DIR, "kryptrix.db")
def create_connection(db_path=DB_PATH):
"""
Create a database connection to SQLite and enable foreign key constraints.
Ensures the database directory exists.
"""
try:
os.makedirs(os.path.dirname(db_path), exist_ok=True)
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA foreign_keys = ON;") # Enable foreign keys
print(f"SQLite DB connected at {db_path}")
return conn
except Error as e:
print(f"Error connecting to database: {e}")
return None
def create_tables(conn):
"""
Create all tables required for Kryptrix.
"""
tables = {}
try:
cursor = conn.cursor()
# Tokens table
tables['tokens'] = """
CREATE TABLE IF NOT EXISTS tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
symbol TEXT UNIQUE NOT NULL,
name TEXT,
source TEXT NOT NULL
)
"""
cursor.execute(tables['tokens'])
# Prices table - CORRECTED
tables['prices'] = """
CREATE TABLE IF NOT EXISTS prices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_id INTEGER NOT NULL,
source TEXT NOT NULL,
timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
price_usd REAL,
volume_24h REAL,
raw_data TEXT,
FOREIGN KEY(token_id) REFERENCES tokens(id) ON DELETE CASCADE
)
"""
cursor.execute(tables['prices'])
cursor.execute("CREATE INDEX IF NOT EXISTS idx_prices_token_time ON prices(token_id, timestamp)")
# Indicators table
tables['indicators'] = """
CREATE TABLE IF NOT EXISTS indicators (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_id INTEGER NOT NULL,
timestamp DATETIME NOT NULL,
sma10 REAL,
sma30 REAL,
ema REAL,
rsi14 REAL,
vwap24h REAL,
realized_vol REAL,
raw_data TEXT,
FOREIGN KEY(token_id) REFERENCES tokens(id) ON DELETE CASCADE
)
"""
cursor.execute(tables['indicators'])
cursor.execute("CREATE INDEX IF NOT EXISTS idx_indicators_token_time ON indicators(token_id, timestamp)")
# Arbitrage table
tables['arbitrage'] = """
CREATE TABLE IF NOT EXISTS arbitrage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_id INTEGER NOT NULL,
timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
source_a TEXT,
source_b TEXT,
price_diff REAL,
percent_diff REAL,
raw_data TEXT,
FOREIGN KEY(token_id) REFERENCES tokens(id) ON DELETE CASCADE
)
"""
cursor.execute(tables['arbitrage'])
cursor.execute("CREATE INDEX IF NOT EXISTS idx_arbitrage_token_time ON arbitrage(token_id, timestamp)")
# Anomalies table
tables['anomalies'] = """
CREATE TABLE IF NOT EXISTS anomalies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_id INTEGER NOT NULL,
timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
anomaly_type TEXT,
value REAL,
description TEXT,
raw_data TEXT,
FOREIGN KEY(token_id) REFERENCES tokens(id) ON DELETE CASCADE
)
"""
cursor.execute(tables['anomalies'])
cursor.execute("CREATE INDEX IF NOT EXISTS idx_anomalies_token_time ON anomalies(token_id, timestamp)")
# API Health / Logs table
tables['api_health'] = """
CREATE TABLE IF NOT EXISTS api_health (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source TEXT NOT NULL,
timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
status TEXT,
response_time_ms REAL,
error_message TEXT,
raw_data TEXT
)
"""
cursor.execute(tables['api_health'])
cursor.execute("CREATE INDEX IF NOT EXISTS idx_api_health_source_time ON api_health(source, timestamp)")
# Feature Simulations (A/B testing) table
tables['simulations'] = """
CREATE TABLE IF NOT EXISTS simulations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_id INTEGER NOT NULL,
timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
scenario TEXT,
baseline REAL,
simulated REAL,
delta REAL,
recommendation TEXT,
raw_data TEXT,
FOREIGN KEY(token_id) REFERENCES tokens(id) ON DELETE CASCADE
)
"""
cursor.execute(tables['simulations'])
cursor.execute("CREATE INDEX IF NOT EXISTS idx_simulations_token_time ON simulations(token_id, timestamp)")
# Stakeholder Requests table
tables['stakeholder_requests'] = """
CREATE TABLE IF NOT EXISTS stakeholder_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
request TEXT NOT NULL,
submitted_at DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
processed INTEGER DEFAULT 0,
response TEXT
)
"""
cursor.execute(tables['stakeholder_requests'])
conn.commit()
print("All tables created successfully.")
except Error as e:
print(f"Error creating tables: {e}")
def initialize_db():
"""
Initialize the database: create connection and tables.
"""
conn = create_connection()
if conn:
create_tables(conn)
conn.close()
print("Database setup complete.")
if __name__ == "__main__":
initialize_db() |