refactor: worker uses tokio-postgres instead of sqlx
This commit is contained in:
parent
83e63c0de2
commit
cead78381d
|
@ -1,50 +1,48 @@
|
|||
use crate::structs::{candle::Candle, openbook::PgOpenBookFill, resolution::Resolution};
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::{pool::PoolConnection, Postgres};
|
||||
|
||||
use crate::{
|
||||
structs::{
|
||||
candle::Candle,
|
||||
coingecko::{PgCoinGecko24HighLow, PgCoinGecko24HourVolume},
|
||||
openbook::PgOpenBookFill,
|
||||
resolution::Resolution,
|
||||
trader::PgTrader,
|
||||
},
|
||||
utils::AnyhowWrap,
|
||||
};
|
||||
use deadpool_postgres::{GenericClient, Pool};
|
||||
|
||||
pub async fn fetch_earliest_fill(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
market_address_string: &str,
|
||||
) -> anyhow::Result<Option<PgOpenBookFill>> {
|
||||
sqlx::query_as!(
|
||||
PgOpenBookFill,
|
||||
r#"SELECT
|
||||
time as "time!",
|
||||
bid as "bid!",
|
||||
maker as "maker!",
|
||||
native_qty_paid as "native_qty_paid!",
|
||||
native_qty_received as "native_qty_received!",
|
||||
native_fee_or_rebate as "native_fee_or_rebate!"
|
||||
from fills
|
||||
where market = $1
|
||||
and maker = true
|
||||
ORDER BY time asc LIMIT 1"#,
|
||||
market_address_string
|
||||
)
|
||||
.fetch_optional(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
let client = pool.get().await?;
|
||||
|
||||
let stmt = client
|
||||
.prepare(
|
||||
r#"SELECT
|
||||
time as "time!",
|
||||
bid as "bid!",
|
||||
maker as "maker!",
|
||||
native_qty_paid as "native_qty_paid!",
|
||||
native_qty_received as "native_qty_received!",
|
||||
native_fee_or_rebate as "native_fee_or_rebate!"
|
||||
from fills
|
||||
where market = $1
|
||||
and maker = true
|
||||
ORDER BY time asc LIMIT 1"#,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let row = client.query_opt(&stmt, &[&market_address_string]).await?;
|
||||
|
||||
match row {
|
||||
Some(r) => Ok(Some(PgOpenBookFill::from_row(r))),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn fetch_fills_from(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
market_address_string: &str,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
) -> anyhow::Result<Vec<PgOpenBookFill>> {
|
||||
sqlx::query_as!(
|
||||
PgOpenBookFill,
|
||||
r#"SELECT
|
||||
let client = pool.get().await?;
|
||||
|
||||
let stmt = client
|
||||
.prepare(
|
||||
r#"SELECT
|
||||
time as "time!",
|
||||
bid as "bid!",
|
||||
maker as "maker!",
|
||||
|
@ -53,31 +51,36 @@ pub async fn fetch_fills_from(
|
|||
native_fee_or_rebate as "native_fee_or_rebate!"
|
||||
from fills
|
||||
where market = $1
|
||||
and time >= $2
|
||||
and time < $3
|
||||
and time >= $2::timestamptz
|
||||
and time < $3::timestamptz
|
||||
and maker = true
|
||||
ORDER BY time asc"#,
|
||||
market_address_string,
|
||||
start_time,
|
||||
end_time
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
)
|
||||
.await?;
|
||||
|
||||
let rows = client
|
||||
.query(&stmt, &[&market_address_string, &start_time, &end_time])
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| PgOpenBookFill::from_row(r))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn fetch_latest_finished_candle(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
market_name: &str,
|
||||
resolution: Resolution,
|
||||
) -> anyhow::Result<Option<Candle>> {
|
||||
sqlx::query_as!(
|
||||
Candle,
|
||||
r#"SELECT
|
||||
let client = pool.get().await?;
|
||||
|
||||
let stmt = client
|
||||
.prepare(
|
||||
r#"SELECT
|
||||
market_name as "market_name!",
|
||||
start_time as "start_time!",
|
||||
end_time as "end_time!",
|
||||
resolution as "resolution!",
|
||||
market_name as "market_name!",
|
||||
open as "open!",
|
||||
close as "close!",
|
||||
high as "high!",
|
||||
|
@ -89,26 +92,33 @@ pub async fn fetch_latest_finished_candle(
|
|||
and resolution = $2
|
||||
and complete = true
|
||||
ORDER BY start_time desc LIMIT 1"#,
|
||||
market_name,
|
||||
resolution.to_string()
|
||||
)
|
||||
.fetch_optional(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
)
|
||||
.await?;
|
||||
|
||||
let row = client
|
||||
.query_opt(&stmt, &[&market_name, &resolution.to_string()])
|
||||
.await?;
|
||||
|
||||
match row {
|
||||
Some(r) => Ok(Some(Candle::from_row(r))),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn fetch_earliest_candles(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
market_name: &str,
|
||||
resolution: Resolution,
|
||||
) -> anyhow::Result<Vec<Candle>> {
|
||||
sqlx::query_as!(
|
||||
Candle,
|
||||
r#"SELECT
|
||||
let client = pool.get().await?;
|
||||
|
||||
let stmt = client
|
||||
.prepare(
|
||||
r#"SELECT
|
||||
market_name as "market_name!",
|
||||
start_time as "start_time!",
|
||||
end_time as "end_time!",
|
||||
resolution as "resolution!",
|
||||
market_name as "market_name!",
|
||||
open as "open!",
|
||||
close as "close!",
|
||||
high as "high!",
|
||||
|
@ -119,28 +129,32 @@ pub async fn fetch_earliest_candles(
|
|||
where market_name = $1
|
||||
and resolution = $2
|
||||
ORDER BY start_time asc"#,
|
||||
market_name,
|
||||
resolution.to_string()
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
)
|
||||
.await?;
|
||||
|
||||
let rows = client
|
||||
.query(&stmt, &[&market_name, &resolution.to_string()])
|
||||
.await?;
|
||||
|
||||
Ok(rows.into_iter().map(|r| Candle::from_row(r)).collect())
|
||||
}
|
||||
|
||||
pub async fn fetch_candles_from(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
market_name: &str,
|
||||
resolution: Resolution,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
) -> anyhow::Result<Vec<Candle>> {
|
||||
sqlx::query_as!(
|
||||
Candle,
|
||||
r#"SELECT
|
||||
let client = pool.get().await?;
|
||||
|
||||
let stmt = client
|
||||
.prepare(
|
||||
r#"SELECT
|
||||
market_name as "market_name!",
|
||||
start_time as "start_time!",
|
||||
end_time as "end_time!",
|
||||
resolution as "resolution!",
|
||||
market_name as "market_name!",
|
||||
open as "open!",
|
||||
close as "close!",
|
||||
high as "high!",
|
||||
|
@ -153,173 +167,20 @@ pub async fn fetch_candles_from(
|
|||
and start_time >= $3
|
||||
and end_time <= $4
|
||||
ORDER BY start_time asc"#,
|
||||
market_name,
|
||||
resolution.to_string(),
|
||||
start_time,
|
||||
end_time
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
}
|
||||
)
|
||||
.await?;
|
||||
|
||||
pub async fn fetch_tradingview_candles(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
market_name: &str,
|
||||
resolution: Resolution,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
) -> anyhow::Result<Vec<Candle>> {
|
||||
sqlx::query_as!(
|
||||
Candle,
|
||||
r#"SELECT
|
||||
start_time as "start_time!",
|
||||
end_time as "end_time!",
|
||||
resolution as "resolution!",
|
||||
market_name as "market_name!",
|
||||
open as "open!",
|
||||
close as "close!",
|
||||
high as "high!",
|
||||
low as "low!",
|
||||
volume as "volume!",
|
||||
complete as "complete!"
|
||||
from candles
|
||||
where market_name = $1
|
||||
and resolution = $2
|
||||
and start_time >= $3
|
||||
and end_time <= $4
|
||||
ORDER BY start_time asc"#,
|
||||
market_name,
|
||||
resolution.to_string(),
|
||||
start_time,
|
||||
end_time
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
}
|
||||
let rows = client
|
||||
.query(
|
||||
&stmt,
|
||||
&[
|
||||
&market_name,
|
||||
&resolution.to_string(),
|
||||
&start_time,
|
||||
&end_time,
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
pub async fn fetch_top_traders_by_base_volume_from(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
market_address_string: &str,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
) -> anyhow::Result<Vec<PgTrader>> {
|
||||
sqlx::query_as!(
|
||||
PgTrader,
|
||||
r#"SELECT
|
||||
open_orders_owner,
|
||||
sum(
|
||||
native_qty_paid * CASE bid WHEN true THEN 0 WHEN false THEN 1 END
|
||||
) as "raw_ask_size!",
|
||||
sum(
|
||||
native_qty_received * CASE bid WHEN true THEN 1 WHEN false THEN 0 END
|
||||
) as "raw_bid_size!"
|
||||
FROM fills
|
||||
WHERE market = $1
|
||||
AND time >= $2
|
||||
AND time < $3
|
||||
GROUP BY open_orders_owner
|
||||
ORDER BY
|
||||
sum(native_qty_paid * CASE bid WHEN true THEN 0 WHEN false THEN 1 END)
|
||||
+
|
||||
sum(native_qty_received * CASE bid WHEN true THEN 1 WHEN false THEN 0 END)
|
||||
DESC
|
||||
LIMIT 10000"#,
|
||||
market_address_string,
|
||||
start_time,
|
||||
end_time
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
}
|
||||
|
||||
pub async fn fetch_top_traders_by_quote_volume_from(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
market_address_string: &str,
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
) -> anyhow::Result<Vec<PgTrader>> {
|
||||
sqlx::query_as!(
|
||||
PgTrader,
|
||||
r#"SELECT
|
||||
open_orders_owner,
|
||||
sum(
|
||||
native_qty_received * CASE bid WHEN true THEN 0 WHEN false THEN 1 END
|
||||
) as "raw_ask_size!",
|
||||
sum(
|
||||
native_qty_paid * CASE bid WHEN true THEN 1 WHEN false THEN 0 END
|
||||
) as "raw_bid_size!"
|
||||
FROM fills
|
||||
WHERE market = $1
|
||||
AND time >= $2
|
||||
AND time < $3
|
||||
GROUP BY open_orders_owner
|
||||
ORDER BY
|
||||
sum(native_qty_received * CASE bid WHEN true THEN 0 WHEN false THEN 1 END)
|
||||
+
|
||||
sum(native_qty_paid * CASE bid WHEN true THEN 1 WHEN false THEN 0 END)
|
||||
DESC
|
||||
LIMIT 10000"#,
|
||||
market_address_string,
|
||||
start_time,
|
||||
end_time
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
}
|
||||
|
||||
pub async fn fetch_coingecko_24h_volume(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
) -> anyhow::Result<Vec<PgCoinGecko24HourVolume>> {
|
||||
sqlx::query_as!(
|
||||
PgCoinGecko24HourVolume,
|
||||
r#"select market as "address!",
|
||||
sum(native_qty_paid) as "raw_quote_size!",
|
||||
sum(native_qty_received) as "raw_base_size!"
|
||||
from fills
|
||||
where "time" >= current_timestamp - interval '1 day'
|
||||
and bid = true
|
||||
group by market"#
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
}
|
||||
|
||||
pub async fn fetch_coingecko_24h_high_low(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
) -> anyhow::Result<Vec<PgCoinGecko24HighLow>> {
|
||||
sqlx::query_as!(
|
||||
PgCoinGecko24HighLow,
|
||||
r#"select
|
||||
g.market_name as "market_name!",
|
||||
g.high as "high!",
|
||||
g.low as "low!",
|
||||
c."close" as "close!"
|
||||
from
|
||||
(
|
||||
SELECT
|
||||
market_name,
|
||||
max(start_time) as "start_time",
|
||||
max(high) as "high",
|
||||
min(low) as "low"
|
||||
from
|
||||
candles
|
||||
where
|
||||
"resolution" = '1M'
|
||||
and "start_time" >= current_timestamp - interval '1 day'
|
||||
group by
|
||||
market_name
|
||||
) as g
|
||||
join candles c on g.market_name = c.market_name
|
||||
and g.start_time = c.start_time
|
||||
where
|
||||
c.resolution = '1M'"#
|
||||
)
|
||||
.fetch_all(conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
Ok(rows.into_iter().map(|r| Candle::from_row(r)).collect())
|
||||
}
|
||||
|
|
|
@ -1,24 +1,63 @@
|
|||
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
|
||||
use std::time::Duration;
|
||||
use std::{fs, time::Duration};
|
||||
|
||||
use crate::utils::{AnyhowWrap, Config};
|
||||
use deadpool_postgres::{
|
||||
Config as PgConfig, ManagerConfig, Pool, PoolConfig, RecyclingMethod, Runtime, SslMode,
|
||||
Timeouts,
|
||||
};
|
||||
use native_tls::{Certificate, Identity, TlsConnector};
|
||||
use postgres_native_tls::MakeTlsConnector;
|
||||
|
||||
pub async fn connect_to_database(config: &Config) -> anyhow::Result<Pool<Postgres>> {
|
||||
loop {
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(config.max_pg_pool_connections)
|
||||
.connect(&config.database_url)
|
||||
.await;
|
||||
if pool.is_ok() {
|
||||
println!("Database connected");
|
||||
return pool.map_err_anyhow();
|
||||
use crate::utils::Config;
|
||||
|
||||
pub async fn connect_to_database(config: &Config) -> anyhow::Result<Pool> {
|
||||
let mut x = PgConfig::new();
|
||||
x.dbname = Some("postgres".to_owned());
|
||||
|
||||
x.manager = Some(ManagerConfig {
|
||||
recycling_method: RecyclingMethod::Fast,
|
||||
});
|
||||
x.pool = Some(PoolConfig {
|
||||
max_size: config.max_pg_pool_connections,
|
||||
timeouts: Timeouts::default(),
|
||||
});
|
||||
|
||||
// openssl pkcs12 -export -in client.cer -inkey client-key.cer -out client.pks
|
||||
// base64 -i ca.cer -o ca.cer.b64 && base64 -i client.pks -o client.pks.b64
|
||||
// fly secrets set PG_CA_CERT=- < ./ca.cer.b64 -a mango-fills
|
||||
// fly secrets set PG_CLIENT_KEY=- < ./client.pks.b64 -a mango-fills
|
||||
let tls = if config.use_ssl {
|
||||
x.ssl_mode = Some(SslMode::Require);
|
||||
let ca_cert = fs::read(&config.ca_cert_path).expect("reading client cert from file");
|
||||
let client_key = fs::read(&config.client_key_path).expect("reading client key from file");
|
||||
MakeTlsConnector::new(
|
||||
TlsConnector::builder()
|
||||
.add_root_certificate(Certificate::from_pem(&ca_cert)?)
|
||||
.identity(Identity::from_pkcs12(&client_key, "pass")?)
|
||||
.danger_accept_invalid_certs(false)
|
||||
.build()?,
|
||||
)
|
||||
} else {
|
||||
MakeTlsConnector::new(
|
||||
TlsConnector::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
|
||||
let pool = x.create_pool(Some(Runtime::Tokio1), tls).unwrap();
|
||||
match pool.get().await {
|
||||
Ok(_) => println!("Database connected"),
|
||||
Err(e) => {
|
||||
println!("Failed to connect to database: {}, retrying", e.to_string());
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
println!("Failed to connect to database, retrying");
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub async fn setup_database(pool: &Pool<Postgres>) -> anyhow::Result<()> {
|
||||
pub async fn setup_database(pool: &Pool) -> anyhow::Result<()> {
|
||||
let candles_table_fut = create_candles_table(pool);
|
||||
let fills_table_fut = create_fills_table(pool);
|
||||
let result = tokio::try_join!(candles_table_fut, fills_table_fut);
|
||||
|
@ -34,50 +73,51 @@ pub async fn setup_database(pool: &Pool<Postgres>) -> anyhow::Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
pub async fn create_candles_table(pool: &Pool<Postgres>) -> anyhow::Result<()> {
|
||||
let mut tx = pool.begin().await.map_err_anyhow()?;
|
||||
pub async fn create_candles_table(pool: &Pool) -> anyhow::Result<()> {
|
||||
let client = pool.get().await?;
|
||||
|
||||
sqlx::query!(
|
||||
"CREATE TABLE IF NOT EXISTS candles (
|
||||
client
|
||||
.execute(
|
||||
"CREATE TABLE IF NOT EXISTS candles (
|
||||
id serial,
|
||||
market_name text,
|
||||
start_time timestamptz,
|
||||
end_time timestamptz,
|
||||
resolution text,
|
||||
open numeric,
|
||||
close numeric,
|
||||
high numeric,
|
||||
low numeric,
|
||||
volume numeric,
|
||||
open double precision,
|
||||
close double precision,
|
||||
high double precision,
|
||||
low double precision,
|
||||
volume double precision,
|
||||
complete bool
|
||||
)",
|
||||
)
|
||||
.execute(&mut tx)
|
||||
.await?;
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"CREATE INDEX IF NOT EXISTS idx_market_time_resolution ON candles (market_name, start_time, resolution)"
|
||||
).execute(&mut tx).await?;
|
||||
client.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_market_time_resolution ON candles (market_name, start_time, resolution)",
|
||||
&[]
|
||||
).await?;
|
||||
|
||||
sqlx::query!(
|
||||
client.execute(
|
||||
"DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'unique_candles') THEN
|
||||
ALTER TABLE candles ADD CONSTRAINT unique_candles UNIQUE (market_name, start_time, resolution);
|
||||
END IF;
|
||||
END $$"
|
||||
)
|
||||
.execute(&mut tx)
|
||||
.await?;
|
||||
END $$", &[]
|
||||
).await?;
|
||||
|
||||
tx.commit().await.map_err_anyhow()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create_fills_table(pool: &Pool<Postgres>) -> anyhow::Result<()> {
|
||||
let mut tx = pool.begin().await.map_err_anyhow()?;
|
||||
pub async fn create_fills_table(pool: &Pool) -> anyhow::Result<()> {
|
||||
let client = pool.get().await?;
|
||||
|
||||
sqlx::query!(
|
||||
"CREATE TABLE IF NOT EXISTS fills (
|
||||
client
|
||||
.execute(
|
||||
"CREATE TABLE IF NOT EXISTS fills (
|
||||
id numeric PRIMARY KEY,
|
||||
time timestamptz not null,
|
||||
market text not null,
|
||||
|
@ -85,23 +125,28 @@ pub async fn create_fills_table(pool: &Pool<Postgres>) -> anyhow::Result<()> {
|
|||
open_orders_owner text not null,
|
||||
bid bool not null,
|
||||
maker bool not null,
|
||||
native_qty_paid numeric not null,
|
||||
native_qty_received numeric not null,
|
||||
native_fee_or_rebate numeric not null,
|
||||
native_qty_paid double precision not null,
|
||||
native_qty_received double precision not null,
|
||||
native_fee_or_rebate double precision not null,
|
||||
fee_tier text not null,
|
||||
order_id text not null
|
||||
)",
|
||||
)
|
||||
.execute(&mut tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query!("CREATE INDEX IF NOT EXISTS idx_id_market ON fills (id, market)")
|
||||
.execute(&mut tx)
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
|
||||
sqlx::query!("CREATE INDEX IF NOT EXISTS idx_market_time ON fills (market, time)")
|
||||
.execute(&mut tx)
|
||||
client
|
||||
.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_id_market ON fills (id, market)",
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
|
||||
tx.commit().await.map_err_anyhow()
|
||||
client
|
||||
.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_market_time ON fills (market, time)",
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use chrono::Utc;
|
||||
use sqlx::{Connection, Pool, Postgres};
|
||||
use deadpool_postgres::Pool;
|
||||
use std::{
|
||||
collections::{hash_map::DefaultHasher, HashMap},
|
||||
hash::{Hash, Hasher},
|
||||
|
@ -12,10 +12,10 @@ use crate::{
|
|||
};
|
||||
|
||||
pub async fn persist_fill_events(
|
||||
pool: &Pool<Postgres>,
|
||||
pool: &Pool,
|
||||
fill_receiver: &mut Receiver<OpenBookFillEventLog>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut conn = pool.acquire().await.unwrap();
|
||||
let client = pool.get().await?;
|
||||
loop {
|
||||
let mut write_batch = HashMap::new();
|
||||
while write_batch.len() < 10 {
|
||||
|
@ -41,57 +41,57 @@ pub async fn persist_fill_events(
|
|||
if write_batch.len() > 0 {
|
||||
// print!("writing: {:?} events to DB\n", write_batch.len());
|
||||
|
||||
match conn.ping().await {
|
||||
Ok(_) => {
|
||||
let upsert_statement = build_fills_upsert_statement(write_batch);
|
||||
sqlx::query(&upsert_statement)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
.unwrap();
|
||||
}
|
||||
Err(_) => {
|
||||
println!("Fills ping failed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
// match conn.ping().await {
|
||||
// Ok(_) => {
|
||||
let upsert_statement = build_fills_upsert_statement(write_batch);
|
||||
client
|
||||
.execute(&upsert_statement, &[])
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
.unwrap();
|
||||
// }
|
||||
// Err(_) => {
|
||||
// println!("Fills ping failed");
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn persist_candles(
|
||||
pool: Pool<Postgres>,
|
||||
pool: Pool,
|
||||
candles_receiver: &mut Receiver<Vec<Candle>>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut conn = pool.acquire().await.unwrap();
|
||||
let client = pool.get().await.unwrap();
|
||||
loop {
|
||||
match conn.ping().await {
|
||||
Ok(_) => {
|
||||
match candles_receiver.try_recv() {
|
||||
Ok(candles) => {
|
||||
if candles.len() == 0 {
|
||||
continue;
|
||||
}
|
||||
// print!("writing: {:?} candles to DB\n", candles.len());
|
||||
let upsert_statement = build_candes_upsert_statement(candles);
|
||||
sqlx::query(&upsert_statement)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
.unwrap();
|
||||
}
|
||||
Err(TryRecvError::Empty) => continue,
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
panic!("Candles sender must stay alive")
|
||||
}
|
||||
};
|
||||
// match client.ping().await {
|
||||
// Ok(_) => {
|
||||
match candles_receiver.try_recv() {
|
||||
Ok(candles) => {
|
||||
if candles.len() == 0 {
|
||||
continue;
|
||||
}
|
||||
// print!("writing: {:?} candles to DB\n", candles.len());
|
||||
let upsert_statement = build_candes_upsert_statement(candles);
|
||||
client
|
||||
.execute(&upsert_statement, &[])
|
||||
.await
|
||||
.map_err_anyhow()
|
||||
.unwrap();
|
||||
}
|
||||
Err(_) => {
|
||||
println!("Candle ping failed");
|
||||
break;
|
||||
Err(TryRecvError::Empty) => continue,
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
panic!("Candles sender must stay alive")
|
||||
}
|
||||
};
|
||||
// }
|
||||
// Err(_) => {
|
||||
// println!("Candle ping failed");
|
||||
// break;
|
||||
// }
|
||||
// };
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -58,8 +58,7 @@ pub async fn tickers(context: web::Data<WebContext>) -> Result<HttpResponse, Ser
|
|||
let volume_fut = fetch_coingecko_24h_volume(&mut c1);
|
||||
let high_low_fut = fetch_coingecko_24h_high_low(&mut c2);
|
||||
|
||||
let (volume_query, high_low_quey) =
|
||||
join!(volume_fut, high_low_fut,);
|
||||
let (volume_query, high_low_quey) = join!(volume_fut, high_low_fut,);
|
||||
|
||||
let raw_volumes = match volume_query {
|
||||
Ok(c) => c,
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
use num_traits::Zero;
|
||||
use sqlx::types::Decimal;
|
||||
use tokio_postgres::Row;
|
||||
|
||||
use super::resolution::Resolution;
|
||||
|
||||
|
@ -10,11 +9,11 @@ pub struct Candle {
|
|||
pub start_time: DateTime<Utc>,
|
||||
pub end_time: DateTime<Utc>,
|
||||
pub resolution: String,
|
||||
pub open: Decimal,
|
||||
pub close: Decimal,
|
||||
pub high: Decimal,
|
||||
pub low: Decimal,
|
||||
pub volume: Decimal,
|
||||
pub open: f64,
|
||||
pub close: f64,
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub volume: f64,
|
||||
pub complete: bool,
|
||||
}
|
||||
|
||||
|
@ -25,12 +24,27 @@ impl Candle {
|
|||
start_time: DateTime::from_utc(NaiveDateTime::MIN, Utc),
|
||||
end_time: DateTime::from_utc(NaiveDateTime::MIN, Utc),
|
||||
resolution: resolution.to_string(),
|
||||
open: Decimal::zero(),
|
||||
close: Decimal::zero(),
|
||||
high: Decimal::zero(),
|
||||
low: Decimal::zero(),
|
||||
volume: Decimal::zero(),
|
||||
open: 0.0,
|
||||
close: 0.0,
|
||||
high: 0.0,
|
||||
low: 0.0,
|
||||
volume: 0.0,
|
||||
complete: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_row(row: Row) -> Self {
|
||||
Candle {
|
||||
market_name: row.get(0),
|
||||
start_time: row.get(1),
|
||||
end_time: row.get(2),
|
||||
resolution: row.get(3),
|
||||
open: row.get(4),
|
||||
close: row.get(5),
|
||||
high: row.get(6),
|
||||
low: row.get(7),
|
||||
volume: row.get(8),
|
||||
complete: row.get(9),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
use serde::Serialize;
|
||||
use sqlx::types::Decimal;
|
||||
|
||||
use super::{markets::MarketInfo, openbook::token_factor};
|
||||
|
||||
|
@ -35,8 +34,8 @@ pub struct CoinGeckoTicker {
|
|||
|
||||
pub struct PgCoinGecko24HourVolume {
|
||||
pub address: String,
|
||||
pub raw_base_size: Decimal,
|
||||
pub raw_quote_size: Decimal,
|
||||
pub raw_base_size: f64,
|
||||
pub raw_quote_size: f64,
|
||||
}
|
||||
impl PgCoinGecko24HourVolume {
|
||||
pub fn convert_to_readable(&self, markets: &Vec<MarketInfo>) -> CoinGecko24HourVolume {
|
||||
|
@ -54,14 +53,14 @@ impl PgCoinGecko24HourVolume {
|
|||
#[derive(Debug, Default)]
|
||||
pub struct CoinGecko24HourVolume {
|
||||
pub market_name: String,
|
||||
pub base_volume: Decimal,
|
||||
pub target_volume: Decimal,
|
||||
pub base_volume: f64,
|
||||
pub target_volume: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct PgCoinGecko24HighLow {
|
||||
pub market_name: String,
|
||||
pub high: Decimal,
|
||||
pub low: Decimal,
|
||||
pub close: Decimal,
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub close: f64,
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
use anchor_lang::{event, AnchorDeserialize, AnchorSerialize};
|
||||
use chrono::{DateTime, Utc};
|
||||
use num_traits::FromPrimitive;
|
||||
use num_traits::Pow;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use sqlx::types::Decimal;
|
||||
use tokio_postgres::Row;
|
||||
|
||||
#[event]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
|
@ -27,9 +27,21 @@ pub struct PgOpenBookFill {
|
|||
pub time: DateTime<Utc>,
|
||||
pub bid: bool,
|
||||
pub maker: bool,
|
||||
pub native_qty_paid: Decimal,
|
||||
pub native_qty_received: Decimal,
|
||||
pub native_fee_or_rebate: Decimal,
|
||||
pub native_qty_paid: f64,
|
||||
pub native_qty_received: f64,
|
||||
pub native_fee_or_rebate: f64,
|
||||
}
|
||||
impl PgOpenBookFill {
|
||||
pub fn from_row(row: Row) -> Self {
|
||||
PgOpenBookFill {
|
||||
time: row.get(0),
|
||||
bid: row.get(1),
|
||||
maker: row.get(2),
|
||||
native_qty_paid: row.get(3),
|
||||
native_qty_received: row.get(4),
|
||||
native_fee_or_rebate: row.get(5),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, AnchorDeserialize)]
|
||||
|
@ -91,7 +103,7 @@ pub fn calculate_fill_price_and_size(
|
|||
fill: PgOpenBookFill,
|
||||
base_decimals: u8,
|
||||
quote_decimals: u8,
|
||||
) -> (Decimal, Decimal) {
|
||||
) -> (f64, f64) {
|
||||
if fill.bid {
|
||||
let price_before_fees = if fill.maker {
|
||||
fill.native_qty_paid + fill.native_fee_or_rebate
|
||||
|
@ -115,6 +127,6 @@ pub fn calculate_fill_price_and_size(
|
|||
}
|
||||
}
|
||||
|
||||
pub fn token_factor(decimals: u8) -> Decimal {
|
||||
Decimal::from_u64(10u64.pow(decimals as u32)).unwrap()
|
||||
pub fn token_factor(decimals: u8) -> f64 {
|
||||
10f64.pow(decimals as f64)
|
||||
}
|
||||
|
|
|
@ -20,7 +20,10 @@ impl<T, E: std::fmt::Debug> AnyhowWrap for Result<T, E> {
|
|||
pub struct Config {
|
||||
pub rpc_url: String,
|
||||
pub database_url: String,
|
||||
pub max_pg_pool_connections: u32,
|
||||
pub max_pg_pool_connections: usize,
|
||||
pub use_ssl: bool,
|
||||
pub ca_cert_path: String,
|
||||
pub client_key_path: String,
|
||||
}
|
||||
|
||||
pub struct WebContext {
|
||||
|
@ -33,3 +36,19 @@ pub struct WebContext {
|
|||
pub fn to_timestampz(seconds: u64) -> chrono::DateTime<Utc> {
|
||||
chrono::DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(seconds as i64, 0), Utc)
|
||||
}
|
||||
|
||||
pub(crate) fn f64_max(a: f64, b: f64) -> f64 {
|
||||
if a >= b {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn f64_min(a: f64, b: f64) -> f64 {
|
||||
if a < b {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
use chrono::{DateTime, Duration, DurationRound, Utc};
|
||||
use sqlx::{pool::PoolConnection, Postgres};
|
||||
use std::cmp::{max, min};
|
||||
use deadpool_postgres::Pool;
|
||||
use std::cmp::{max};
|
||||
|
||||
use crate::{
|
||||
database::fetch::{fetch_candles_from, fetch_earliest_candles, fetch_latest_finished_candle},
|
||||
|
@ -8,21 +8,22 @@ use crate::{
|
|||
candle::Candle,
|
||||
resolution::{day, Resolution},
|
||||
},
|
||||
utils::{f64_max, f64_min},
|
||||
};
|
||||
|
||||
pub async fn batch_higher_order_candles(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
market_name: &str,
|
||||
resolution: Resolution,
|
||||
) -> anyhow::Result<Vec<Candle>> {
|
||||
let latest_candle = fetch_latest_finished_candle(conn, market_name, resolution).await?;
|
||||
let latest_candle = fetch_latest_finished_candle(pool, market_name, resolution).await?;
|
||||
|
||||
match latest_candle {
|
||||
Some(candle) => {
|
||||
let start_time = candle.end_time;
|
||||
let end_time = start_time + day();
|
||||
let mut constituent_candles = fetch_candles_from(
|
||||
conn,
|
||||
pool,
|
||||
market_name,
|
||||
resolution.get_constituent_resolution(),
|
||||
start_time,
|
||||
|
@ -42,7 +43,7 @@ pub async fn batch_higher_order_candles(
|
|||
}
|
||||
None => {
|
||||
let mut constituent_candles =
|
||||
fetch_earliest_candles(conn, market_name, resolution.get_constituent_resolution())
|
||||
fetch_earliest_candles(pool, market_name, resolution.get_constituent_resolution())
|
||||
.await?;
|
||||
if constituent_candles.len() == 0 {
|
||||
// println!(
|
||||
|
@ -112,8 +113,8 @@ fn combine_into_higher_order_candles(
|
|||
|
||||
while matches!(con_iter.peek(), Some(c) if c.end_time <= end_time) {
|
||||
let unit_candle = con_iter.next().unwrap();
|
||||
combined_candles[i].high = max(combined_candles[i].high, unit_candle.high);
|
||||
combined_candles[i].low = min(combined_candles[i].low, unit_candle.low);
|
||||
combined_candles[i].high = f64_max(combined_candles[i].high, unit_candle.high);
|
||||
combined_candles[i].low = f64_min(combined_candles[i].low, unit_candle.low);
|
||||
combined_candles[i].close = unit_candle.close;
|
||||
combined_candles[i].volume += unit_candle.volume;
|
||||
combined_candles[i].complete = unit_candle.complete;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::cmp::{max, min};
|
||||
use std::cmp::min;
|
||||
|
||||
use chrono::{DateTime, Duration, DurationRound, Utc};
|
||||
use sqlx::{pool::PoolConnection, types::Decimal, Postgres};
|
||||
use deadpool_postgres::Pool;
|
||||
|
||||
use crate::{
|
||||
database::fetch::{fetch_earliest_fill, fetch_fills_from, fetch_latest_finished_candle},
|
||||
|
@ -11,15 +11,13 @@ use crate::{
|
|||
openbook::{calculate_fill_price_and_size, PgOpenBookFill},
|
||||
resolution::{day, Resolution},
|
||||
},
|
||||
utils::{f64_max, f64_min},
|
||||
};
|
||||
|
||||
pub async fn batch_1m_candles(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
market: &MarketInfo,
|
||||
) -> anyhow::Result<Vec<Candle>> {
|
||||
pub async fn batch_1m_candles(pool: &Pool, market: &MarketInfo) -> anyhow::Result<Vec<Candle>> {
|
||||
let market_name = &market.name;
|
||||
let market_address = &market.address;
|
||||
let latest_candle = fetch_latest_finished_candle(conn, market_name, Resolution::R1m).await?;
|
||||
let latest_candle = fetch_latest_finished_candle(pool, market_name, Resolution::R1m).await?;
|
||||
|
||||
match latest_candle {
|
||||
Some(candle) => {
|
||||
|
@ -28,7 +26,7 @@ pub async fn batch_1m_candles(
|
|||
start_time + day(),
|
||||
Utc::now().duration_trunc(Duration::minutes(1))?,
|
||||
);
|
||||
let mut fills = fetch_fills_from(conn, market_address, start_time, end_time).await?;
|
||||
let mut fills = fetch_fills_from(pool, market_address, start_time, end_time).await?;
|
||||
let candles = combine_fills_into_1m_candles(
|
||||
&mut fills,
|
||||
market,
|
||||
|
@ -39,7 +37,7 @@ pub async fn batch_1m_candles(
|
|||
Ok(candles)
|
||||
}
|
||||
None => {
|
||||
let earliest_fill = fetch_earliest_fill(conn, market_address).await?;
|
||||
let earliest_fill = fetch_earliest_fill(pool, market_address).await?;
|
||||
|
||||
if earliest_fill.is_none() {
|
||||
println!("No fills found for: {:?}", market_name);
|
||||
|
@ -54,7 +52,7 @@ pub async fn batch_1m_candles(
|
|||
start_time + day(),
|
||||
Utc::now().duration_trunc(Duration::minutes(1))?,
|
||||
);
|
||||
let mut fills = fetch_fills_from(conn, market_address, start_time, end_time).await?;
|
||||
let mut fills = fetch_fills_from(pool, market_address, start_time, end_time).await?;
|
||||
if fills.len() > 0 {
|
||||
let candles =
|
||||
combine_fills_into_1m_candles(&mut fills, market, start_time, end_time, None);
|
||||
|
@ -71,7 +69,7 @@ fn combine_fills_into_1m_candles(
|
|||
market: &MarketInfo,
|
||||
st: DateTime<Utc>,
|
||||
et: DateTime<Utc>,
|
||||
maybe_last_price: Option<Decimal>,
|
||||
maybe_last_price: Option<f64>,
|
||||
) -> Vec<Candle> {
|
||||
let empty_candle = Candle::create_empty_candle(market.name.clone(), Resolution::R1m);
|
||||
|
||||
|
@ -105,8 +103,8 @@ fn combine_fills_into_1m_candles(
|
|||
calculate_fill_price_and_size(*fill, market.base_decimals, market.quote_decimals);
|
||||
|
||||
candles[i].close = price;
|
||||
candles[i].low = min(price, candles[i].low);
|
||||
candles[i].high = max(price, candles[i].high);
|
||||
candles[i].low = f64_min(price, candles[i].low);
|
||||
candles[i].high = f64_max(price, candles[i].high);
|
||||
candles[i].volume += volume;
|
||||
|
||||
last_price = price;
|
||||
|
|
|
@ -2,7 +2,7 @@ pub mod higher_order_candles;
|
|||
pub mod minute_candles;
|
||||
|
||||
use chrono::Duration;
|
||||
use sqlx::{pool::PoolConnection, Pool, Postgres};
|
||||
use deadpool_postgres::Pool;
|
||||
use strum::IntoEnumIterator;
|
||||
use tokio::{sync::mpsc::Sender, time::sleep};
|
||||
|
||||
|
@ -14,17 +14,17 @@ use crate::{
|
|||
use self::higher_order_candles::batch_higher_order_candles;
|
||||
|
||||
pub async fn batch_for_market(
|
||||
pool: Pool<Postgres>,
|
||||
pool: &Pool,
|
||||
candles_sender: &Sender<Vec<Candle>>,
|
||||
market: &MarketInfo,
|
||||
) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let sender = candles_sender.clone();
|
||||
let market_clone = market.clone();
|
||||
let mut conn = pool.acquire().await?;
|
||||
// let client = pool.get().await?;
|
||||
loop {
|
||||
sleep(Duration::milliseconds(2000).to_std()?).await;
|
||||
match batch_inner(&mut conn, &sender, &market_clone).await {
|
||||
match batch_inner(pool, &sender, &market_clone).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
println!(
|
||||
|
@ -41,19 +41,19 @@ pub async fn batch_for_market(
|
|||
}
|
||||
|
||||
async fn batch_inner(
|
||||
conn: &mut PoolConnection<Postgres>,
|
||||
pool: &Pool,
|
||||
candles_sender: &Sender<Vec<Candle>>,
|
||||
market: &MarketInfo,
|
||||
) -> anyhow::Result<()> {
|
||||
let market_name = &market.name.clone();
|
||||
let candles = batch_1m_candles(conn, market).await?;
|
||||
let candles = batch_1m_candles(pool, market).await?;
|
||||
send_candles(candles, candles_sender).await;
|
||||
|
||||
for resolution in Resolution::iter() {
|
||||
if resolution == Resolution::R1m {
|
||||
continue;
|
||||
}
|
||||
let candles = batch_higher_order_candles(conn, market_name, resolution).await?;
|
||||
let candles = batch_higher_order_candles(pool, market_name, resolution).await?;
|
||||
send_candles(candles, candles_sender).await;
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
@ -1,14 +1,16 @@
|
|||
use dotenv;
|
||||
use openbook_candles::database::{
|
||||
initialize::{connect_to_database, setup_database},
|
||||
insert::{persist_candles, persist_fill_events},
|
||||
};
|
||||
use openbook_candles::structs::candle::Candle;
|
||||
use openbook_candles::structs::markets::{fetch_market_infos, load_markets};
|
||||
use openbook_candles::structs::openbook::OpenBookFillEventLog;
|
||||
use openbook_candles::utils::Config;
|
||||
use openbook_candles::worker::candle_batching::batch_for_market;
|
||||
use openbook_candles::worker::trade_fetching::scrape::scrape;
|
||||
use openbook_candles::{
|
||||
database::{
|
||||
initialize::{connect_to_database, setup_database},
|
||||
insert::{persist_candles, persist_fill_events},
|
||||
},
|
||||
worker::candle_batching::batch_for_market,
|
||||
};
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use std::env;
|
||||
use std::{collections::HashMap, str::FromStr};
|
||||
|
@ -23,15 +25,21 @@ async fn main() -> anyhow::Result<()> {
|
|||
let path_to_markets_json = &args[1];
|
||||
let rpc_url: String = dotenv::var("RPC_URL").unwrap();
|
||||
let database_url: String = dotenv::var("DATABASE_URL").unwrap();
|
||||
let max_pg_pool_connections: u32 = dotenv::var("MAX_PG_POOL_CONNS_WORKER")
|
||||
let use_ssl: bool = dotenv::var("USE_SSL").unwrap().parse::<bool>().unwrap();
|
||||
let ca_cert_path: String = dotenv::var("CA_CERT_PATH").unwrap();
|
||||
let client_key_path: String = dotenv::var("CLIENT_KEY_PATH").unwrap();
|
||||
let max_pg_pool_connections: usize = dotenv::var("MAX_PG_POOL_CONNS_WORKER")
|
||||
.unwrap()
|
||||
.parse::<u32>()
|
||||
.parse::<usize>()
|
||||
.unwrap();
|
||||
|
||||
let config = Config {
|
||||
rpc_url: rpc_url.clone(),
|
||||
database_url,
|
||||
max_pg_pool_connections,
|
||||
use_ssl,
|
||||
ca_cert_path,
|
||||
client_key_path,
|
||||
};
|
||||
|
||||
let markets = load_markets(&path_to_markets_json);
|
||||
|
@ -49,7 +57,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
let (fill_sender, mut fill_receiver) = mpsc::channel::<OpenBookFillEventLog>(1000);
|
||||
|
||||
handles.push(tokio::spawn(async move {
|
||||
scrape(&config, &fill_sender, &target_markets).await; //TODO: send the vec, it's okay
|
||||
scrape(&config, &fill_sender, &target_markets).await;
|
||||
}));
|
||||
|
||||
let fills_pool = pool.clone();
|
||||
|
@ -67,7 +75,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
let sender = candle_sender.clone();
|
||||
let batch_pool = pool.clone();
|
||||
handles.push(tokio::spawn(async move {
|
||||
batch_for_market(batch_pool, &sender, &market)
|
||||
batch_for_market(&batch_pool, &sender, &market)
|
||||
.await
|
||||
.unwrap();
|
||||
println!("SOMETHING WENT WRONG");
|
||||
|
|
Loading…
Reference in New Issue