-
Notifications
You must be signed in to change notification settings - Fork 327
Ondo price smoothing #4465
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Ondo price smoothing #4465
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@chainlink/ondo-calculated-adapter': minor | ||
| --- | ||
|
|
||
| Price smoothing |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { TZDate } from '@date-fns/tz' | ||
|
|
||
| // Seconds relative to session boundary (-ve before, +ve after) | ||
| export const calculateSecondsFromTransition = ( | ||
| sessionBoundaries: string[], | ||
| sessionBoundariesTimeZone: string, | ||
| ) => { | ||
| const now = new TZDate(new Date().getTime(), sessionBoundariesTimeZone) | ||
| // Handle cases where we're close to midnight | ||
| const offsets = [-1, 0, 1] | ||
|
|
||
| return offsets.reduce((minDiff, offset) => { | ||
| const diff = calculateWithDayOffset(sessionBoundaries, sessionBoundariesTimeZone, now, offset) | ||
|
|
||
| return Math.abs(diff) < Math.abs(minDiff) ? diff : minDiff | ||
| }, Number.MAX_SAFE_INTEGER) | ||
| } | ||
|
|
||
| const calculateWithDayOffset = ( | ||
| sessionBoundaries: string[], | ||
| sessionBoundariesTimeZone: string, | ||
| now: TZDate, | ||
| offset: number, | ||
| ) => | ||
| sessionBoundaries.reduce((minDiff, b) => { | ||
| const [hour, minute] = b.split(':') | ||
| const session = new TZDate( | ||
| now.getFullYear(), | ||
| now.getMonth(), | ||
| now.getDate() + offset, | ||
| Number(hour), | ||
| Number(minute), | ||
| 0, | ||
| 0, | ||
| sessionBoundariesTimeZone, | ||
| ) | ||
|
|
||
| const diff = (now.getTime() - session.getTime()) / 1000 | ||
|
|
||
| return Math.abs(diff) < Math.abs(minDiff) ? diff : minDiff | ||
| }, Number.MAX_SAFE_INTEGER) | ||
mxiao-cll marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,101 @@ | ||
| // Algorithm by @kalanyuz and @eshaqiri | ||
| import { parseUnits } from 'ethers' | ||
|
|
||
| const PRECISION = 18 // Keep 18 decimals when converting number to bigint | ||
|
|
||
| const CONFIG = { | ||
| KALMAN: { | ||
| Q: parseUnits('0.000075107026567861', PRECISION), // Process noise | ||
| ALPHA: parseUnits('0.9996386263245117', PRECISION), // Spread-to-noise multiplier | ||
| INITIAL_P: parseUnits('1.5', PRECISION), // initial covariance | ||
| MIN_R: parseUnits('0.002545840040746239', PRECISION), // Measurement noise floor | ||
| DECAY_FACTOR: parseUnits('0.99', PRECISION), //Covariance decay | ||
| }, | ||
| TRANSITION: { | ||
| WINDOW_BEFORE: 10, // seconds | ||
| WINDOW_AFTER: 60, // seconds | ||
| }, | ||
| } | ||
|
|
||
| // 1D Kalman filter for price with measurement noise based on spread | ||
| class KalmanFilter { | ||
| private x = -1n | ||
| private p = CONFIG.KALMAN.INITIAL_P | ||
|
|
||
| public smooth(price: bigint, spread: bigint) { | ||
| const prevX = this.x | ||
| const prevP = this.p | ||
|
|
||
| if (this.x < 0n) { | ||
| this.x = price | ||
| return { price: this.x, x: prevX, p: prevP } | ||
| } | ||
|
|
||
| // Predict | ||
| const x_pred = this.x | ||
| const p_pred = deScale(this.p * CONFIG.KALMAN.DECAY_FACTOR) + CONFIG.KALMAN.Q | ||
|
|
||
| // Measurement noise from spread (handle None / <=0) | ||
| const eff_spread = spread > CONFIG.KALMAN.MIN_R ? spread : CONFIG.KALMAN.MIN_R | ||
| const r = deScale(CONFIG.KALMAN.ALPHA * eff_spread) | ||
| // Update | ||
| const k = (p_pred * scale(1)) / (p_pred + r) | ||
| this.x = x_pred + deScale(k * (price - x_pred)) | ||
| this.p = deScale((scale(1) - k) * p_pred) | ||
|
|
||
| return { price: this.x, x: prevX, p: prevP } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Session Aware Smoother | ||
| * | ||
| * Manages the transition state and applies the weighted blending | ||
| * between raw and smoothed prices. | ||
| */ | ||
| export class SessionAwareSmoother { | ||
| // TODO: Implement this in a seperaate PR | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| public processUpdate = (rawPrice: bigint, _secondsFromTransition: number) => { | ||
| return rawPrice | ||
| private filter: KalmanFilter = new KalmanFilter() | ||
|
|
||
| /** | ||
| * Process a new price update | ||
| * @param rawPrice The current raw median price | ||
| * @param spread The current spread between ask and bid prices | ||
| * @param secondsFromTransition Seconds relative to session boundary (-ve before, +ve after) | ||
| */ | ||
| public processUpdate(rawPrice: bigint, spread: bigint, secondsFromTransition: number) { | ||
| // Calculate blending weight | ||
| const w = this.calculateTransitionWeight(secondsFromTransition) | ||
|
|
||
| // Calculate smoothed price | ||
| const smoothedPrice = this.filter.smooth(rawPrice, spread) | ||
|
|
||
| // Apply blending: price_output = smoothed * w + raw * (1 - w) | ||
| return { | ||
| price: deScale(smoothedPrice.price * scale(w) + rawPrice * (scale(1) - scale(w))), | ||
| x: smoothedPrice.x, | ||
| p: smoothedPrice.p, | ||
| } | ||
| } | ||
|
|
||
| // Calculates the raised cosine decay weight | ||
| private calculateTransitionWeight(t: number): number { | ||
| const { WINDOW_BEFORE, WINDOW_AFTER } = CONFIG.TRANSITION | ||
|
|
||
| // Outside window | ||
| if (t < -WINDOW_BEFORE || t > WINDOW_AFTER) { | ||
| return 0.0 | ||
| } | ||
|
|
||
| // Select window side | ||
| const window = t < 0 ? WINDOW_BEFORE : WINDOW_AFTER | ||
|
|
||
| // Raised cosine function: 0.5 * (1 + cos(pi * t / window)) | ||
| // At t=0, cos(0)=1 -> w=1.0 (Fully smoothed) | ||
| // At t=window, cos(pi)=-1 -> w=0.0 (Fully raw) | ||
mxiao-cll marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // At t=-window, cos(-pi)=-1 -> w=0.0 | ||
| return 0.5 * (1 + Math.cos((Math.PI * t) / window)) | ||
mxiao-cll marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| const scale = (number: number) => parseUnits(number.toFixed(PRECISION), PRECISION) | ||
| const deScale = (bigint: bigint) => bigint / 10n ** BigInt(PRECISION) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
packages/composites/ondo-calculated/test/integration/__snapshots__/adapter.test.ts.snap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.