Skip to content

Commit

Permalink
Market performance optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
CRBl69 committed Nov 22, 2024
1 parent c36f3e7 commit 76f15fc
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 19 deletions.
43 changes: 43 additions & 0 deletions src/typescript/frontend/src/app/chats/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { fetchChatEvents } from "@/queries/market";
import type { NextRequest } from "next/server";
import { stringifyJSON } from "utils";

type ChatSearchParams = {
marketID: string | null;
fromMarketNonce: string | null;
};

export type ValidChatSearchParams = {
marketID: string;
fromMarketNonce: string;
};

const isNumber = (s: string) => !isNaN(parseInt(s));

const isValidChatSearchParams = (params: ChatSearchParams): params is ValidChatSearchParams => {
const { marketID, fromMarketNonce } = params;
// prettier-ignore
return (
marketID !== null && isNumber(marketID) &&
fromMarketNonce !== null && isNumber(fromMarketNonce)
);
};

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const params: ChatSearchParams = {
marketID: searchParams.get("marketID"),
fromMarketNonce: searchParams.get("fromMarketNonce"),
};

if (!isValidChatSearchParams(params)) {
return new Response("Invalid chat search params.", { status: 400 });
}

const marketID = Number(params.marketID);
const fromMarketNonce = Number(params.fromMarketNonce);

const res = await fetchChatEvents({ marketID, fromMarketNonce });

return new Response(stringifyJSON(res));
}
43 changes: 43 additions & 0 deletions src/typescript/frontend/src/app/trades/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { fetchSwapEvents } from "@/queries/market";
import type { NextRequest } from "next/server";
import { stringifyJSON } from "utils";

type SwapSearchParams = {
marketID: string | null;
fromMarketNonce: string | null;
};

export type ValidSwapSearchParams = {
marketID: string;
fromMarketNonce: string;
};

const isNumber = (s: string) => !isNaN(parseInt(s));

const isValidSwapSearchParams = (params: SwapSearchParams): params is ValidSwapSearchParams => {
const { marketID, fromMarketNonce } = params;
// prettier-ignore
return (
marketID !== null && isNumber(marketID) &&
fromMarketNonce !== null && isNumber(fromMarketNonce)
);
};

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const params: SwapSearchParams = {
marketID: searchParams.get("marketID"),
fromMarketNonce: searchParams.get("fromMarketNonce"),
};

if (!isValidSwapSearchParams(params)) {
return new Response("Invalid chat search params.", { status: 400 });
}

const marketID = Number(params.marketID);
const fromMarketNonce = Number(params.fromMarketNonce);

const res = await fetchSwapEvents({ marketID, fromMarketNonce });

return new Response(stringifyJSON(res));
}
Original file line number Diff line number Diff line change
Expand Up @@ -335,16 +335,13 @@ export const Chart = (props: ChartContainerProps) => {
tvWidget.current.onChartReady(() => {
const chart = tvWidget.current!.activeChart();
const now = new Date();
const startDaysAgo = 1;
const endDaysAgo = 0;
const startMilliseconds = now.getTime() - startDaysAgo * MS_IN_ONE_DAY;
const endMilliseconds = now.getTime() - endDaysAgo * MS_IN_ONE_DAY;
const startTimestamp = Math.floor(new Date(startMilliseconds).getTime()) / 1000;
const endTimestamp = Math.floor(new Date(endMilliseconds).getTime()) / 1000;

chart
.setVisibleRange({
from: startTimestamp,
from: endTimestamp - (24 * 60 * 60) / 6,
to: endTimestamp,
})
.catch((error) => {
Expand Down
2 changes: 1 addition & 1 deletion src/typescript/frontend/src/components/charts/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const MS_IN_ONE_DAY = 24 * 60 * 60 * 1000;
export const EXCHANGE_NAME = "emojicoin.fun";

export const WIDGET_OPTIONS: Omit<ChartingLibraryWidgetOptions, "datafeed" | "container"> = {
interval: "5" as ResolutionString,
interval: "1" as ResolutionString,
library_path: "/static/charting_library/",
theme: "Dark" as ThemeName,
locale: "en" as LanguageCode,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type Types } from "@sdk-types";
import { type Period, periodEnumToRawDuration, rawPeriodToEnum } from "@sdk/const";
import { ONE_APT, type Period, periodEnumToRawDuration, rawPeriodToEnum } from "@sdk/const";
import { type SwapEventModel, type PeriodicStateEventModel } from "@sdk/indexer-v2/types";
import { getPeriodStartTimeFromTime } from "@sdk/utils";
import { q64ToBig } from "@sdk/utils/nominal-price";
Expand Down Expand Up @@ -59,7 +59,7 @@ export const toBar = (event: PeriodicStateEventModel): Bar => ({
high: q64ToBig(event.periodicState.highPriceQ64).toNumber(),
low: q64ToBig(event.periodicState.lowPriceQ64).toNumber(),
close: q64ToBig(event.periodicState.closePriceQ64).toNumber(),
volume: Number(event.periodicState.volumeBase),
volume: Number(event.periodicState.volumeQuote) / ONE_APT,
});

export const toBars = (events: PeriodicStateEventModel | PeriodicStateEventModel[]) =>
Expand Down
52 changes: 40 additions & 12 deletions src/typescript/sdk/src/indexer-v2/queries/app/market.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ if (process.env.NODE_ENV !== "test") {
require("server-only");
}

import { LIMIT, ORDER_BY } from "../../../queries";
import { ORDER_BY } from "../../../queries";
import { type AnyNumberString } from "../../../types";
import { TableName } from "../../types/json-types";
import { postgrest, toQueryArray } from "../client";
Expand All @@ -14,32 +14,60 @@ import {
toPeriodicStateEventModel,
toSwapEventModel,
} from "../../types";
import { type PeriodicStateEventQueryArgs, type MarketStateQueryArgs } from "../../types/common";
import { type PeriodicStateEventQueryArgs } from "../../types/common";
import { type SymbolEmoji } from "../../../emoji_data/types";

const selectSwapsByMarketID = ({
marketID,
page = 1,
pageSize = LIMIT,
}: { marketID: AnyNumberString } & MarketStateQueryArgs) =>
postgrest
fromMarketNonce = null,
amount = 20,
}: {
marketID: AnyNumberString;
fromMarketNonce?: number | null;
amount?: number;
}) => {
if (fromMarketNonce !== null) {
return postgrest
.from(TableName.SwapEvents)
.select("*")
.eq("market_id", marketID)
.lte("market_nonce", fromMarketNonce)
.order("market_nonce", ORDER_BY.DESC)
.limit(amount);
}
return postgrest
.from(TableName.SwapEvents)
.select("*")
.eq("market_id", marketID)
.order("market_nonce", ORDER_BY.DESC)
.range((page - 1) * pageSize, page * pageSize - 1);
.limit(amount);
};

const selectChatsByMarketID = ({
marketID,
page = 1,
pageSize = LIMIT,
}: { marketID: AnyNumberString } & MarketStateQueryArgs) =>
postgrest
fromMarketNonce = null,
amount = 20,
}: {
marketID: AnyNumberString;
fromMarketNonce?: number | null;
amount?: number;
}) => {
if (fromMarketNonce !== null) {
return postgrest
.from(TableName.ChatEvents)
.select("*")
.eq("market_id", marketID)
.lte("market_nonce", fromMarketNonce)
.order("market_nonce", ORDER_BY.DESC)
.limit(amount);
}
return postgrest
.from(TableName.ChatEvents)
.select("*")
.eq("market_id", marketID)
.order("market_nonce", ORDER_BY.DESC)
.range((page - 1) * pageSize, page * pageSize - 1);
.limit(amount);
};

// This query uses `offset` instead of `page` because the periodic state events query requires
// more granular pagination due to the requirements of the private TradingView charting library.
Expand Down

0 comments on commit 76f15fc

Please sign in to comment.