This commit is contained in:
2026-04-30 10:50:37 +02:00
parent 523bbe0860
commit 37d54887d6
16 changed files with 1495 additions and 9 deletions

View File

@@ -19,6 +19,7 @@ mod liquidity_event;
mod observed_token;
mod onchain_observation;
mod pair;
mod pair_candle;
mod pair_metric;
mod pool;
mod pool_listing;
@@ -50,6 +51,7 @@ pub use liquidity_event::KbLiquidityEventDto;
pub use observed_token::KbObservedTokenDto;
pub use onchain_observation::KbOnchainObservationDto;
pub use pair::KbPairDto;
pub use pair_candle::KbPairCandleDto;
pub use pair_metric::KbPairMetricDto;
pub use pool::KbPoolDto;
pub use pool_listing::KbPoolListingDto;

View File

@@ -0,0 +1,135 @@
// file: kb_lib/src/db/dtos/pair_candle.rs
//! Pair-candle DTO.
/// Application-facing pair-candle DTO.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct KbPairCandleDto {
/// Optional numeric primary key.
pub id: std::option::Option<i64>,
/// Related pair id.
pub pair_id: i64,
/// Candle timeframe in seconds.
pub timeframe_seconds: i64,
/// Inclusive bucket start in unix seconds.
pub bucket_start_unix: i64,
/// Exclusive bucket end in unix seconds.
pub bucket_end_unix: i64,
/// Open price in quote-per-base units.
pub open_price_quote_per_base: f64,
/// High price in quote-per-base units.
pub high_price_quote_per_base: f64,
/// Low price in quote-per-base units.
pub low_price_quote_per_base: f64,
/// Close price in quote-per-base units.
pub close_price_quote_per_base: f64,
/// Trade count inside the candle.
pub trade_count: i64,
/// Buy count inside the candle.
pub buy_count: i64,
/// Sell count inside the candle.
pub sell_count: i64,
/// Aggregated base volume as decimal text when available.
pub base_volume_raw: std::option::Option<std::string::String>,
/// Aggregated quote volume as decimal text when available.
pub quote_volume_raw: std::option::Option<std::string::String>,
/// Optional first trade signature inside the candle.
pub first_trade_signature: std::option::Option<std::string::String>,
/// Optional last trade signature inside the candle.
pub last_trade_signature: std::option::Option<std::string::String>,
/// Creation timestamp.
pub created_at: chrono::DateTime<chrono::Utc>,
/// Update timestamp.
pub updated_at: chrono::DateTime<chrono::Utc>,
}
impl KbPairCandleDto {
/// Creates a new pair-candle DTO.
#[allow(clippy::too_many_arguments)]
pub fn new(
pair_id: i64,
timeframe_seconds: i64,
bucket_start_unix: i64,
bucket_end_unix: i64,
open_price_quote_per_base: f64,
high_price_quote_per_base: f64,
low_price_quote_per_base: f64,
close_price_quote_per_base: f64,
trade_count: i64,
buy_count: i64,
sell_count: i64,
base_volume_raw: std::option::Option<std::string::String>,
quote_volume_raw: std::option::Option<std::string::String>,
first_trade_signature: std::option::Option<std::string::String>,
last_trade_signature: std::option::Option<std::string::String>,
) -> Self {
let now = chrono::Utc::now();
Self {
id: None,
pair_id,
timeframe_seconds,
bucket_start_unix,
bucket_end_unix,
open_price_quote_per_base,
high_price_quote_per_base,
low_price_quote_per_base,
close_price_quote_per_base,
trade_count,
buy_count,
sell_count,
base_volume_raw,
quote_volume_raw,
first_trade_signature,
last_trade_signature,
created_at: now,
updated_at: now,
}
}
}
impl TryFrom<crate::KbPairCandleEntity> for KbPairCandleDto {
type Error = crate::KbError;
fn try_from(entity: crate::KbPairCandleEntity) -> Result<Self, Self::Error> {
let created_at_result = chrono::DateTime::parse_from_rfc3339(&entity.created_at);
let created_at = match created_at_result {
Ok(created_at) => created_at.with_timezone(&chrono::Utc),
Err(error) => {
return Err(crate::KbError::Db(format!(
"cannot parse pair_candle created_at '{}': {}",
entity.created_at, error
)));
}
};
let updated_at_result = chrono::DateTime::parse_from_rfc3339(&entity.updated_at);
let updated_at = match updated_at_result {
Ok(updated_at) => updated_at.with_timezone(&chrono::Utc),
Err(error) => {
return Err(crate::KbError::Db(format!(
"cannot parse pair_candle updated_at '{}': {}",
entity.updated_at, error
)));
}
};
Ok(Self {
id: Some(entity.id),
pair_id: entity.pair_id,
timeframe_seconds: entity.timeframe_seconds,
bucket_start_unix: entity.bucket_start_unix,
bucket_end_unix: entity.bucket_end_unix,
open_price_quote_per_base: entity.open_price_quote_per_base,
high_price_quote_per_base: entity.high_price_quote_per_base,
low_price_quote_per_base: entity.low_price_quote_per_base,
close_price_quote_per_base: entity.close_price_quote_per_base,
trade_count: entity.trade_count,
buy_count: entity.buy_count,
sell_count: entity.sell_count,
base_volume_raw: entity.base_volume_raw,
quote_volume_raw: entity.quote_volume_raw,
first_trade_signature: entity.first_trade_signature,
last_trade_signature: entity.last_trade_signature,
created_at,
updated_at,
})
}
}

View File

@@ -21,6 +21,7 @@ mod liquidity_event;
mod observed_token;
mod onchain_observation;
mod pair;
mod pair_candle;
mod pair_metric;
mod pool;
mod pool_listing;
@@ -52,6 +53,7 @@ pub use liquidity_event::KbLiquidityEventEntity;
pub use observed_token::KbObservedTokenEntity;
pub use onchain_observation::KbOnchainObservationEntity;
pub use pair::KbPairEntity;
pub use pair_candle::KbPairCandleEntity;
pub use pair_metric::KbPairMetricEntity;
pub use pool::KbPoolEntity;
pub use pool_listing::KbPoolListingEntity;

View File

@@ -0,0 +1,44 @@
// file: kb_lib/src/db/entities/pair_candle.rs
//! Pair-candle entity.
/// Persisted pair-candle row.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
pub struct KbPairCandleEntity {
/// Numeric primary key.
pub id: i64,
/// Related pair id.
pub pair_id: i64,
/// Candle timeframe in seconds.
pub timeframe_seconds: i64,
/// Inclusive bucket start in unix seconds.
pub bucket_start_unix: i64,
/// Exclusive bucket end in unix seconds.
pub bucket_end_unix: i64,
/// Open price in quote-per-base units.
pub open_price_quote_per_base: f64,
/// High price in quote-per-base units.
pub high_price_quote_per_base: f64,
/// Low price in quote-per-base units.
pub low_price_quote_per_base: f64,
/// Close price in quote-per-base units.
pub close_price_quote_per_base: f64,
/// Trade count inside the candle.
pub trade_count: i64,
/// Buy count inside the candle.
pub buy_count: i64,
/// Sell count inside the candle.
pub sell_count: i64,
/// Aggregated base volume as decimal text when available.
pub base_volume_raw: std::option::Option<std::string::String>,
/// Aggregated quote volume as decimal text when available.
pub quote_volume_raw: std::option::Option<std::string::String>,
/// Optional first trade signature inside the candle.
pub first_trade_signature: std::option::Option<std::string::String>,
/// Optional last trade signature inside the candle.
pub last_trade_signature: std::option::Option<std::string::String>,
/// Creation timestamp encoded as RFC3339 UTC text.
pub created_at: std::string::String,
/// Update timestamp encoded as RFC3339 UTC text.
pub updated_at: std::string::String,
}

View File

@@ -23,6 +23,7 @@ mod liquidity_event;
mod observed_token;
mod onchain_observation;
mod pair;
mod pair_candle;
mod pair_metric;
mod pool;
mod pool_listing;
@@ -84,6 +85,9 @@ pub use onchain_observation::list_recent_onchain_observations;
pub use pair::get_pair_by_pool_id;
pub use pair::list_pairs;
pub use pair::upsert_pair;
pub use pair_candle::get_pair_candle_by_key;
pub use pair_candle::list_pair_candles_by_pair_and_timeframe;
pub use pair_candle::upsert_pair_candle;
pub use pair_metric::get_pair_metric_by_pair_id;
pub use pair_metric::list_pair_metrics;
pub use pair_metric::upsert_pair_metric;
@@ -108,6 +112,7 @@ pub use token_mint_event::list_recent_token_mint_events;
pub use token_mint_event::upsert_token_mint_event;
pub use trade_event::get_trade_event_by_decoded_event_id;
pub use trade_event::list_trade_events_by_pair_id;
pub use trade_event::list_trade_events_by_transaction_id;
pub use trade_event::upsert_trade_event;
pub use wallet::get_wallet_by_address;
pub use wallet::list_wallets;

View File

@@ -0,0 +1,216 @@
// file: kb_lib/src/db/queries/pair_candle.rs
//! Queries for `kb_pair_candles`.
/// Inserts or updates one pair-candle row and returns its stable internal id.
pub async fn upsert_pair_candle(
database: &crate::KbDatabase,
dto: &crate::KbPairCandleDto,
) -> Result<i64, crate::KbError> {
match database.connection() {
crate::KbDatabaseConnection::Sqlite(pool) => {
let query_result = sqlx::query(
r#"
INSERT INTO kb_pair_candles (
pair_id,
timeframe_seconds,
bucket_start_unix,
bucket_end_unix,
open_price_quote_per_base,
high_price_quote_per_base,
low_price_quote_per_base,
close_price_quote_per_base,
trade_count,
buy_count,
sell_count,
base_volume_raw,
quote_volume_raw,
first_trade_signature,
last_trade_signature,
created_at,
updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(pair_id, timeframe_seconds, bucket_start_unix) DO UPDATE SET
bucket_end_unix = excluded.bucket_end_unix,
open_price_quote_per_base = excluded.open_price_quote_per_base,
high_price_quote_per_base = excluded.high_price_quote_per_base,
low_price_quote_per_base = excluded.low_price_quote_per_base,
close_price_quote_per_base = excluded.close_price_quote_per_base,
trade_count = excluded.trade_count,
buy_count = excluded.buy_count,
sell_count = excluded.sell_count,
base_volume_raw = excluded.base_volume_raw,
quote_volume_raw = excluded.quote_volume_raw,
first_trade_signature = excluded.first_trade_signature,
last_trade_signature = excluded.last_trade_signature,
updated_at = excluded.updated_at
"#,
)
.bind(dto.pair_id)
.bind(dto.timeframe_seconds)
.bind(dto.bucket_start_unix)
.bind(dto.bucket_end_unix)
.bind(dto.open_price_quote_per_base)
.bind(dto.high_price_quote_per_base)
.bind(dto.low_price_quote_per_base)
.bind(dto.close_price_quote_per_base)
.bind(dto.trade_count)
.bind(dto.buy_count)
.bind(dto.sell_count)
.bind(dto.base_volume_raw.clone())
.bind(dto.quote_volume_raw.clone())
.bind(dto.first_trade_signature.clone())
.bind(dto.last_trade_signature.clone())
.bind(dto.created_at.to_rfc3339())
.bind(dto.updated_at.to_rfc3339())
.execute(pool)
.await;
if let Err(error) = query_result {
return Err(crate::KbError::Db(format!(
"cannot upsert kb_pair_candles on sqlite: {}",
error
)));
}
let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
r#"
SELECT id
FROM kb_pair_candles
WHERE pair_id = ? AND timeframe_seconds = ? AND bucket_start_unix = ?
LIMIT 1
"#,
)
.bind(dto.pair_id)
.bind(dto.timeframe_seconds)
.bind(dto.bucket_start_unix)
.fetch_one(pool)
.await;
match id_result {
Ok(id) => Ok(id),
Err(error) => Err(crate::KbError::Db(format!(
"cannot fetch kb_pair_candles id for pair_id '{}' timeframe '{}' bucket '{}' on sqlite: {}",
dto.pair_id, dto.timeframe_seconds, dto.bucket_start_unix, error
))),
}
}
}
}
/// Returns one pair-candle row identified by `(pair_id, timeframe_seconds, bucket_start_unix)`.
pub async fn get_pair_candle_by_key(
database: &crate::KbDatabase,
pair_id: i64,
timeframe_seconds: i64,
bucket_start_unix: i64,
) -> Result<std::option::Option<crate::KbPairCandleDto>, crate::KbError> {
match database.connection() {
crate::KbDatabaseConnection::Sqlite(pool) => {
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbPairCandleEntity>(
r#"
SELECT
id,
pair_id,
timeframe_seconds,
bucket_start_unix,
bucket_end_unix,
open_price_quote_per_base,
high_price_quote_per_base,
low_price_quote_per_base,
close_price_quote_per_base,
trade_count,
buy_count,
sell_count,
base_volume_raw,
quote_volume_raw,
first_trade_signature,
last_trade_signature,
created_at,
updated_at
FROM kb_pair_candles
WHERE pair_id = ? AND timeframe_seconds = ? AND bucket_start_unix = ?
LIMIT 1
"#,
)
.bind(pair_id)
.bind(timeframe_seconds)
.bind(bucket_start_unix)
.fetch_optional(pool)
.await;
let entity_option = match query_result {
Ok(entity_option) => entity_option,
Err(error) => {
return Err(crate::KbError::Db(format!(
"cannot read kb_pair_candles by key on sqlite: {}",
error
)));
}
};
match entity_option {
Some(entity) => crate::KbPairCandleDto::try_from(entity).map(Some),
None => Ok(None),
}
}
}
}
/// Lists candles for one pair and one timeframe ordered by bucket start.
pub async fn list_pair_candles_by_pair_and_timeframe(
database: &crate::KbDatabase,
pair_id: i64,
timeframe_seconds: i64,
) -> Result<std::vec::Vec<crate::KbPairCandleDto>, crate::KbError> {
match database.connection() {
crate::KbDatabaseConnection::Sqlite(pool) => {
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbPairCandleEntity>(
r#"
SELECT
id,
pair_id,
timeframe_seconds,
bucket_start_unix,
bucket_end_unix,
open_price_quote_per_base,
high_price_quote_per_base,
low_price_quote_per_base,
close_price_quote_per_base,
trade_count,
buy_count,
sell_count,
base_volume_raw,
quote_volume_raw,
first_trade_signature,
last_trade_signature,
created_at,
updated_at
FROM kb_pair_candles
WHERE pair_id = ? AND timeframe_seconds = ?
ORDER BY bucket_start_unix ASC, id ASC
"#,
)
.bind(pair_id)
.bind(timeframe_seconds)
.fetch_all(pool)
.await;
let entities = match query_result {
Ok(entities) => entities,
Err(error) => {
return Err(crate::KbError::Db(format!(
"cannot list kb_pair_candles by pair_id '{}' timeframe '{}' on sqlite: {}",
pair_id, timeframe_seconds, error
)));
}
};
let mut dtos = std::vec::Vec::new();
for entity in entities {
let dto_result = crate::KbPairCandleDto::try_from(entity);
let dto = match dto_result {
Ok(dto) => dto,
Err(error) => return Err(error),
};
dtos.push(dto);
}
Ok(dtos)
}
}
}

View File

@@ -199,6 +199,66 @@ ORDER BY created_at ASC, id ASC
}
}
/// Lists trade-event rows for one transaction id ordered by id.
pub async fn list_trade_events_by_transaction_id(
database: &crate::KbDatabase,
transaction_id: i64,
) -> Result<std::vec::Vec<crate::KbTradeEventDto>, crate::KbError> {
match database.connection() {
crate::KbDatabaseConnection::Sqlite(pool) => {
let query_result = sqlx::query_as::<sqlx::Sqlite, crate::KbTradeEventEntity>(
r#"
SELECT
id,
dex_id,
pool_id,
pair_id,
transaction_id,
decoded_event_id,
signature,
slot,
trade_side,
base_token_id,
quote_token_id,
base_amount_raw,
quote_amount_raw,
price_quote_per_base,
source_kind,
source_endpoint_name,
payload_json,
created_at,
updated_at
FROM kb_trade_events
WHERE transaction_id = ?
ORDER BY id ASC
"#,
)
.bind(transaction_id)
.fetch_all(pool)
.await;
let entities = match query_result {
Ok(entities) => entities,
Err(error) => {
return Err(crate::KbError::Db(format!(
"cannot list kb_trade_events by transaction_id '{}' on sqlite: {}",
transaction_id, error
)));
}
};
let mut dtos = std::vec::Vec::new();
for entity in entities {
let dto_result = crate::KbTradeEventDto::try_from(entity);
let dto = match dto_result {
Ok(dto) => dto,
Err(error) => return Err(error),
};
dtos.push(dto);
}
Ok(dtos)
}
}
}
fn kb_trade_side_to_string(value: crate::KbSwapTradeSide) -> &'static str {
match value {
crate::KbSwapTradeSide::BuyBase => "BuyBase",

View File

@@ -322,6 +322,18 @@ pub(crate) async fn ensure_schema(database: &crate::KbDatabase) -> Result<(), cr
if let Err(error) = result {
return Err(error);
}
let result = create_kb_pair_candles_table(pool).await;
if let Err(error) = result {
return Err(error);
}
let result = create_kb_idx_pair_candles_pair_timeframe(pool).await;
if let Err(error) = result {
return Err(error);
}
let result = create_kb_idx_pair_candles_bucket(pool).await;
if let Err(error) = result {
return Err(error);
}
Ok(())
}
}
@@ -1788,3 +1800,61 @@ ON kb_wallet_holdings(token_id)
)
.await
}
async fn create_kb_pair_candles_table(pool: &sqlx::SqlitePool) -> Result<(), crate::KbError> {
execute_sqlite_schema_statement(
pool,
"create_kb_pair_candles_table",
r#"
CREATE TABLE IF NOT EXISTS kb_pair_candles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
pair_id INTEGER NOT NULL,
timeframe_seconds INTEGER NOT NULL,
bucket_start_unix INTEGER NOT NULL,
bucket_end_unix INTEGER NOT NULL,
open_price_quote_per_base REAL NOT NULL,
high_price_quote_per_base REAL NOT NULL,
low_price_quote_per_base REAL NOT NULL,
close_price_quote_per_base REAL NOT NULL,
trade_count INTEGER NOT NULL,
buy_count INTEGER NOT NULL,
sell_count INTEGER NOT NULL,
base_volume_raw TEXT NULL,
quote_volume_raw TEXT NULL,
first_trade_signature TEXT NULL,
last_trade_signature TEXT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(pair_id, timeframe_seconds, bucket_start_unix),
FOREIGN KEY(pair_id) REFERENCES kb_pairs(id) ON DELETE CASCADE
)
"#,
)
.await
}
async fn create_kb_idx_pair_candles_pair_timeframe(
pool: &sqlx::SqlitePool,
) -> Result<(), crate::KbError> {
execute_sqlite_schema_statement(
pool,
"create_kb_idx_pair_candles_pair_timeframe",
r#"
CREATE INDEX IF NOT EXISTS kb_idx_pair_candles_pair_timeframe
ON kb_pair_candles(pair_id, timeframe_seconds)
"#,
)
.await
}
async fn create_kb_idx_pair_candles_bucket(pool: &sqlx::SqlitePool) -> Result<(), crate::KbError> {
execute_sqlite_schema_statement(
pool,
"create_kb_idx_pair_candles_bucket",
r#"
CREATE INDEX IF NOT EXISTS kb_idx_pair_candles_bucket
ON kb_pair_candles(bucket_start_unix)
"#,
)
.await
}