-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathprice.rs
2253 lines (2054 loc) · 74.2 KB
/
price.rs
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use borsh::{
BorshDeserialize,
BorshSerialize,
};
use std::convert::TryFrom;
use schemars::JsonSchema;
use crate::{
utils,
UnixTimestamp,
};
// Constants for working with pyth's number representation
const PD_EXPO: i32 = -9;
const PD_SCALE: u64 = 1_000_000_000;
const MAX_PD_V_U64: u64 = (1 << 28) - 1;
/// A price with a degree of uncertainty at a certain time, represented as a price +- a confidence
/// interval.
///
/// Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for
/// using this price safely.
///
/// The confidence interval roughly corresponds to the standard error of a normal distribution.
/// Both the price and confidence are stored in a fixed-point numeric representation, `x *
/// 10^expo`, where `expo` is the exponent. For example:
///
/// ```
/// use pyth_sdk::Price;
/// Price { price: 12345, conf: 267, expo: -2, publish_time: 100 }; // represents 123.45 +- 2.67 published at UnixTimestamp 100
/// Price { price: 123, conf: 1, expo: 2, publish_time: 100 }; // represents 12300 +- 100 published at UnixTimestamp 100
/// ```
///
/// `Price` supports a limited set of mathematical operations. All of these operations will
/// propagate any uncertainty in the arguments into the result. However, the uncertainty in the
/// result may overestimate the true uncertainty (by at most a factor of `sqrt(2)`) due to
/// computational limitations. Furthermore, all of these operations may return `None` if their
/// result cannot be represented within the numeric representation (e.g., the exponent is so
/// small that the price does not fit into an i64). Users of these methods should (1) select
/// their exponents to avoid this problem, and (2) handle the `None` case gracefully.
#[derive(
Clone,
Copy,
Default,
Debug,
PartialEq,
Eq,
BorshSerialize,
BorshDeserialize,
serde::Serialize,
serde::Deserialize,
JsonSchema,
)]
pub struct Price {
/// Price.
#[serde(with = "utils::as_string")] // To ensure accuracy on conversion to json.
#[schemars(with = "String")]
pub price: i64,
/// Confidence interval.
#[serde(with = "utils::as_string")]
#[schemars(with = "String")]
pub conf: u64,
/// Exponent.
pub expo: i32,
/// Publish time.
pub publish_time: UnixTimestamp,
}
impl Price {
/// Get the current price of this account in a different quote currency.
///
/// If this account represents the price of the product X/Z, and `quote` represents the price
/// of the product Y/Z, this method returns the price of X/Y. Use this method to get the
/// price of e.g., mSOL/SOL from the mSOL/USD and SOL/USD accounts.
///
/// `result_expo` determines the exponent of the result, i.e., the number of digits below the
/// decimal point. This method returns `None` if either the price or confidence are too
/// large to be represented with the requested exponent.
///
/// Example:
/// ```ignore
/// let btc_usd: Price = ...;
/// let eth_usd: Price = ...;
/// // -8 is the desired exponent for the result
/// let btc_eth: Price = btc_usd.get_price_in_quote(ð_usd, -8);
/// println!("BTC/ETH price: ({} +- {}) x 10^{}", price.price, price.conf, price.expo);
/// ```
pub fn get_price_in_quote(&self, quote: &Price, result_expo: i32) -> Option<Price> {
self.div(quote)?.scale_to_exponent(result_expo)
}
/// Get the valuation of a collateral position according to:
/// 1. the net amount currently deposited (across the protocol)
/// 2. the deposits endpoint for the affine combination (across the protocol)
/// 3. the initial (at 0 deposits) and final (at the deposits endpoint) valuation discount rates
///
/// We use a linear interpolation between the the initial and final discount rates,
/// scaled by the proportion of the deposits endpoint that has been deposited.
/// This essentially assumes a linear liquidity cumulative density function,
/// which has been shown to be a reasonable assumption for many crypto tokens in literature.
/// For more detail on this: https://pythnetwork.medium.com/improving-lending-protocols-with-liquidity-oracles-fd1ea4f96f37
///
/// If the assumptions of the liquidity curve hold true, we are obtaining a lower bound for the
/// net price at which one can sell the quantity of token specified by deposits in the open
/// markets. We value collateral according to the total deposits in the protocol due to the
/// present intractability of assessing collateral at risk by price range.
///
/// Args
/// deposits: u64, quantity of token deposited in the protocol
/// deposits_endpoint: u64, deposits right endpoint for the affine combination
/// rate_discount_initial: u64, initial discounted rate at 0 deposits (units given by
/// discount_exponent) rate_discount_final: u64, final discounted rate at deposits_endpoint
/// deposits (units given by discount_exponent) discount_exponent: u64, the exponent to
/// apply to the discounts above (e.g. if discount_final is 10 but meant to express 0.1/10%,
/// exponent would be -2) note that if discount_initial is bigger than 100% per the discount
/// exponent scale, then the initial valuation of the collateral will be higher than the oracle
/// price
pub fn get_collateral_valuation_price(
&self,
deposits: u64,
deposits_endpoint: u64,
rate_discount_initial: u64,
rate_discount_final: u64,
discount_exponent: i32,
) -> Option<Price> {
// valuation price should not increase as amount of collateral grows, so
// rate_discount_initial should >= rate_discount_final
if rate_discount_initial < rate_discount_final {
return None;
}
// get price versions of discounts
let initial_percentage = Price {
price: i64::try_from(rate_discount_initial).ok()?,
conf: 0,
expo: discount_exponent,
publish_time: 0,
};
let final_percentage = Price {
price: i64::try_from(rate_discount_final).ok()?,
conf: 0,
expo: discount_exponent,
publish_time: 0,
};
// get the interpolated discount as a price
let discount_interpolated = Price::affine_combination(
0,
initial_percentage,
i64::try_from(deposits_endpoint).ok()?,
final_percentage,
i64::try_from(deposits).ok()?,
-9,
)?;
let conf_orig = self.conf;
let expo_orig = self.expo;
// get price discounted, convert back to the original exponents we received the price in
let price_discounted = self
.mul(&discount_interpolated)?
.scale_to_exponent(expo_orig)?;
Some(Price {
price: price_discounted.price,
conf: conf_orig,
expo: price_discounted.expo,
publish_time: self.publish_time,
})
}
/// Get the valuation of a borrow position according to:
/// 1. the net amount currently borrowed (across the protocol)
/// 2. the borrowed endpoint for the affine combination (across the protocol)
/// 3. the initial (at 0 borrows) and final (at the borrow endpoint) valuation premiums
///
/// We use a linear interpolation between the the initial and final premiums,
/// scaled by the proportion of the borrows endpoint that has been borrowed out.
/// This essentially assumes a linear liquidity cumulative density function,
/// which has been shown to be a reasonable assumption for many crypto tokens in literature.
/// For more detail on this: https://pythnetwork.medium.com/improving-lending-protocols-with-liquidity-oracles-fd1ea4f96f37
///
/// If the assumptions of the liquidity curve hold true, we are obtaining an upper bound for the
/// net price at which one can buy the quantity of token specified by borrows in the open
/// markets. We value the borrows according to the total borrows out of the protocol due to
/// the present intractability of assessing collateral at risk and repayment likelihood by
/// price range.
///
/// Args
/// borrows: u64, quantity of token borrowed from the protocol
/// borrows_endpoint: u64, borrows right endpoint for the affine combination
/// rate_premium_initial: u64, initial premium at 0 borrows (units given by premium_exponent)
/// rate_premium_final: u64, final premium at borrows_endpoint borrows (units given by
/// premium_exponent) premium_exponent: u64, the exponent to apply to the premiums above
/// (e.g. if premium_final is 50 but meant to express 0.05/5%, exponent would be -3)
/// note that if premium_initial is less than 100% per the premium exponent scale, then the
/// initial valuation of the borrow will be lower than the oracle price
pub fn get_borrow_valuation_price(
&self,
borrows: u64,
borrows_endpoint: u64,
rate_premium_initial: u64,
rate_premium_final: u64,
premium_exponent: i32,
) -> Option<Price> {
// valuation price should not decrease as amount of borrow grows, so rate_premium_initial
// should <= rate_premium_final
if rate_premium_initial > rate_premium_final {
return None;
}
// get price versions of premiums
let initial_percentage = Price {
price: i64::try_from(rate_premium_initial).ok()?,
conf: 0,
expo: premium_exponent,
publish_time: 0,
};
let final_percentage = Price {
price: i64::try_from(rate_premium_final).ok()?,
conf: 0,
expo: premium_exponent,
publish_time: 0,
};
// get the interpolated premium as a price
let premium_interpolated = Price::affine_combination(
0,
initial_percentage,
i64::try_from(borrows_endpoint).ok()?,
final_percentage,
i64::try_from(borrows).ok()?,
-9,
)?;
let conf_orig = self.conf;
let expo_orig = self.expo;
// get price premium, convert back to the original exponents we received the price in
let price_premium = self
.mul(&premium_interpolated)?
.scale_to_exponent(expo_orig)?;
Some(Price {
price: price_premium.price,
conf: conf_orig,
expo: price_premium.expo,
publish_time: self.publish_time,
})
}
/// affine_combination performs an affine combination of two prices located at x coordinates x1
/// and x2, for query x coordinate x_query Takes in 2 points and a 3rd "query" x coordinate,
/// to compute the value at x_query Effectively draws a line between the 2 points and then
/// proceeds to interpolate/extrapolate to find the value at the query coordinate according
/// to that line
///
/// affine_combination gives you the Price, scaled to a specified exponent, closest to y2 *
/// ((xq-x1)/(x2-x1)) + y1 * ((x2-x3)/(x2-x1)) If the numerators and denominators of the
/// fractions there are both representable within 8 digits of precision and the fraction
/// itself is also representable within 8 digits of precision, there is no loss due to taking
/// the fractions. If the prices are normalized, then there is no loss in taking the
/// products via mul. Otherwise, the prices will be converted to a form representable within
/// 8 digits of precision. The scaling to the specified expo pre_add_expo introduces a max
/// error of 2*10^pre_add_expo. If pre_add_expo is small enough relative to the products,
/// then there is no loss due to scaling. If the fractions are expressable within 8 digits
/// of precision, the ys are normalized, and the exponent is sufficiently small,
/// then you get an exact result. Otherwise, your error is bounded as given below.
///
/// Args
/// x1: i64, the x coordinate of the first point
/// y1: Price, the y coordinate of the first point, represented as a Price struct
/// x2: i64, the x coordinate of the second point, must be greater than x1
/// y2: Price, the y coordinate of the second point, represented as a Price struct
/// x_query: i64, the query x coordinate, at which we wish to impute a y value
/// pre_add_expo: i32, the exponent to scale to, before final addition; essentially the final
/// precision you want
///
/// Logic
/// imputed y value = y2 * ((xq-x1)/(x2-x1)) + y1 * ((x2-x3)/(x2-x1))
/// 1. compute A = xq-x1
/// 2. compute B = x2-xq
/// 3. compute C = x2-x1
/// 4. compute D = A/C
/// 5. compute E = B/C
/// 6. compute F = y2 * D
/// 7. compute G = y1 * E
/// 8. compute H = F + G
///
/// Bounds due to precision loss
/// x = 10^(PD_EXPO+2)
/// fraction (due to normalization & division) incurs max loss of x
/// Thus, max loss here: Err(D), Err(E) <= x
/// If y1, y2 already normalized, no additional error. O/w, Err(y1), Err(y2) with normalization
/// <= x Err(F), Err(G) <= (1+x)^2 - 1 (in fractional terms) ~= 2x
/// Err(H) <= 2*2x = 4x, when PD_EXPO = -9 ==> Err(H) <= 4*10^-7
///
/// Scaling this back has error bounded by the expo (10^pre_add_expo).
/// This is because reverting a potentially finer expo to a coarser grid has the potential to be
/// off by the order of the atomic unit of the coarser grid.
/// This scaling error combines with the previous error additively: Err <= 4x +
/// 2*10^pre_add_expo But if pre_add_expo is reasonably small (<= -9), then other term will
/// dominate
///
/// Note that if the ys are unnormalized due to the confidence but not the price, the
/// normalization could zero out the price fields. Based on this, it is recommended that
/// input prices are normalized, or at least do not contain huge discrepancies between price and
/// confidence.
pub fn affine_combination(
x1: i64,
y1: Price,
x2: i64,
y2: Price,
x_query: i64,
pre_add_expo: i32,
) -> Option<Price> {
if x2 <= x1 {
return None;
}
// get the deltas for the x coordinates
// 1. compute A = xq-x1
let delta_q1 = x_query.checked_sub(x1)?;
// 2. compute B = x2-xq
let delta_2q = x2.checked_sub(x_query)?;
// 3. compute C = x2-x1
let delta_21 = x2.checked_sub(x1)?;
// get the relevant fractions of the deltas, with scaling
// 4. compute D = A/C, Err(D) <= x
let frac_q1 = Price::fraction(delta_q1, delta_21)?;
// 5. compute E = B/C, Err(E) <= x
let frac_2q = Price::fraction(delta_2q, delta_21)?;
// calculate products for left and right
// 6. compute F = y2 * D, Err(F) <= (1+x)^2 - 1 ~= 2x
let mut left = y2.mul(&frac_q1)?;
// 7. compute G = y1 * E, Err(G) <= (1+x)^2 - 1 ~= 2x
let mut right = y1.mul(&frac_2q)?;
// Err(scaling) += 2*10^pre_add_expo
left = left.scale_to_exponent(pre_add_expo)?;
right = right.scale_to_exponent(pre_add_expo)?;
// 8. compute H = F + G, Err(H) ~= 4x + 2*10^pre_add_expo
left.add(&right)
}
/// Get the price of a basket of currencies.
///
/// Each entry in `amounts` is of the form `(price, qty, qty_expo)`, and the result is the sum
/// of `price * qty * 10^qty_expo`. The result is returned with exponent `result_expo`.
///
/// An example use case for this function is to get the value of an LP token.
///
/// Example:
/// ```ignore
/// let btc_usd: Price = ...;
/// let eth_usd: Price = ...;
/// // Quantity of each asset in fixed-point a * 10^e.
/// // This represents 0.1 BTC and .05 ETH.
/// // -8 is desired exponent for result
/// let basket_price: Price = Price::price_basket(&[
/// (btc_usd, 10, -2),
/// (eth_usd, 5, -2)
/// ], -8);
/// println!("0.1 BTC and 0.05 ETH are worth: ({} +- {}) x 10^{} USD",
/// basket_price.price, basket_price.conf, basket_price.expo);
/// ```
pub fn price_basket(amounts: &[(Price, i64, i32)], result_expo: i32) -> Option<Price> {
if amounts.is_empty() {
return None;
}
let mut res = Price {
price: 0,
conf: 0,
expo: result_expo,
publish_time: amounts[0].0.publish_time,
};
for amount in amounts {
res = res.add(
&amount
.0
.cmul(amount.1, amount.2)?
.scale_to_exponent(result_expo)?,
)?
}
Some(res)
}
/// Divide this price by `other` while propagating the uncertainty in both prices into the
/// result.
///
/// This method will automatically select a reasonable exponent for the result. If both
/// `self` and `other` are normalized, the exponent is `self.expo + PD_EXPO - other.expo`
/// (i.e., the fraction has `PD_EXPO` digits of additional precision). If they are not
/// normalized, this method will normalize them, resulting in an unpredictable result
/// exponent. If the result is used in a context that requires a specific exponent,
/// please call `scale_to_exponent` on it.
pub fn div(&self, other: &Price) -> Option<Price> {
// Price is not guaranteed to store its price/confidence in normalized form.
// Normalize them here to bound the range of price/conf, which is required to perform
// arithmetic operations.
let base = self.normalize()?;
let other = other.normalize()?;
if other.price == 0 {
return None;
}
// These use at most 27 bits each
let (base_price, base_sign) = Price::to_unsigned(base.price);
let (other_price, other_sign) = Price::to_unsigned(other.price);
// Compute the midprice, base in terms of other.
// Uses at most 57 bits
let midprice = base_price.checked_mul(PD_SCALE)?.checked_div(other_price)?;
let midprice_expo = base.expo.checked_sub(other.expo)?.checked_add(PD_EXPO)?;
// Compute the confidence interval.
// This code uses the 1-norm instead of the 2-norm for computational reasons.
// Let p +- a and q +- b be the two arguments to this method. The correct
// formula is p/q * sqrt( (a/p)^2 + (b/q)^2 ). This quantity
// is difficult to compute due to the sqrt and overflow/underflow considerations.
//
// This code instead computes p/q * (a/p + b/q) = a/q + pb/q^2 .
// This quantity is at most a factor of sqrt(2) greater than the correct result, which
// shouldn't matter considering that confidence intervals are typically ~0.1% of the price.
// This uses 57 bits and has an exponent of PD_EXPO.
let other_confidence_pct: u64 =
other.conf.checked_mul(PD_SCALE)?.checked_div(other_price)?;
// first term is 57 bits, second term is 57 + 58 - 29 = 86 bits. Same exponent as the
// midprice. Note: the computation of the 2nd term consumes about 3k ops. We may
// want to optimize this.
let conf = (base.conf.checked_mul(PD_SCALE)?.checked_div(other_price)? as u128)
.checked_add(
(other_confidence_pct as u128)
.checked_mul(midprice as u128)?
.checked_div(PD_SCALE as u128)?,
)?;
// Note that this check only fails if an argument's confidence interval was >> its price,
// in which case None is a reasonable result, as we have essentially 0 information about the
// price.
if conf < (u64::MAX as u128) {
Some(Price {
price: (midprice as i64)
.checked_mul(base_sign)?
.checked_mul(other_sign)?,
conf: conf as u64,
expo: midprice_expo,
publish_time: self.publish_time.min(other.publish_time),
})
} else {
None
}
}
/// Add `other` to this, propagating uncertainty in both prices.
///
/// Requires both `Price`s to have the same exponent -- use `scale_to_exponent` on
/// the arguments if necessary.
///
/// TODO: could generalize this method to support different exponents.
pub fn add(&self, other: &Price) -> Option<Price> {
assert_eq!(self.expo, other.expo);
let price = self.price.checked_add(other.price)?;
// The conf should technically be sqrt(a^2 + b^2), but that's harder to compute.
let conf = self.conf.checked_add(other.conf)?;
Some(Price {
price,
conf,
expo: self.expo,
publish_time: self.publish_time.min(other.publish_time),
})
}
/// Multiply this `Price` by a constant `c * 10^e`.
pub fn cmul(&self, c: i64, e: i32) -> Option<Price> {
self.mul(&Price {
price: c,
conf: 0,
expo: e,
publish_time: self.publish_time,
})
}
/// Multiply this `Price` by `other`, propagating any uncertainty.
pub fn mul(&self, other: &Price) -> Option<Price> {
// Price is not guaranteed to store its price/confidence in normalized form.
// Normalize them here to bound the range of price/conf, which is required to perform
// arithmetic operations.
let base = self.normalize()?;
let other = other.normalize()?;
// These use at most 27 bits each
let (base_price, base_sign) = Price::to_unsigned(base.price);
let (other_price, other_sign) = Price::to_unsigned(other.price);
// Uses at most 27*2 = 54 bits
let midprice = base_price.checked_mul(other_price)?;
let midprice_expo = base.expo.checked_add(other.expo)?;
// Compute the confidence interval.
// This code uses the 1-norm instead of the 2-norm for computational reasons.
// Note that this simplifies: pq * (a/p + b/q) = qa + pb
// 27*2 + 1 bits
let conf = base
.conf
.checked_mul(other_price)?
.checked_add(other.conf.checked_mul(base_price)?)?;
Some(Price {
price: (midprice as i64)
.checked_mul(base_sign)?
.checked_mul(other_sign)?,
conf,
expo: midprice_expo,
publish_time: self.publish_time.min(other.publish_time),
})
}
/// Get a copy of this struct where the price and confidence
/// have been normalized to be between `MIN_PD_V_I64` and `MAX_PD_V_I64`.
pub fn normalize(&self) -> Option<Price> {
// signed division is very expensive in op count
let (mut p, s) = Price::to_unsigned(self.price);
let mut c = self.conf;
let mut e = self.expo;
while p > MAX_PD_V_U64 || c > MAX_PD_V_U64 {
p = p.checked_div(10)?;
c = c.checked_div(10)?;
e = e.checked_add(1)?;
}
Some(Price {
price: (p as i64).checked_mul(s)?,
conf: c,
expo: e,
publish_time: self.publish_time,
})
}
/// Scale this price/confidence so that its exponent is `target_expo`.
///
/// Return `None` if this number is outside the range of numbers representable in `target_expo`,
/// which will happen if `target_expo` is too small.
///
/// Warning: if `target_expo` is significantly larger than the current exponent, this
/// function will return 0 +- 0.
pub fn scale_to_exponent(&self, target_expo: i32) -> Option<Price> {
let mut delta = target_expo.checked_sub(self.expo)?;
if delta >= 0 {
let mut p = self.price;
let mut c = self.conf;
// 2nd term is a short-circuit to bound op consumption
while delta > 0 && (p != 0 || c != 0) {
p = p.checked_div(10)?;
c = c.checked_div(10)?;
delta = delta.checked_sub(1)?;
}
Some(Price {
price: p,
conf: c,
expo: target_expo,
publish_time: self.publish_time,
})
} else {
let mut p = self.price;
let mut c = self.conf;
// Either p or c == None will short-circuit to bound op consumption
while delta < 0 {
p = p.checked_mul(10)?;
c = c.checked_mul(10)?;
delta = delta.checked_add(1)?;
}
Some(Price {
price: p,
conf: c,
expo: target_expo,
publish_time: self.publish_time,
})
}
}
/// Helper function to convert signed integers to unsigned and a sign bit, which simplifies
/// some of the computations above.
fn to_unsigned(x: i64) -> (u64, i64) {
if x == i64::MIN {
// special case because i64::MIN == -i64::MIN
(i64::MAX as u64 + 1, -1)
} else if x < 0 {
(-x as u64, -1)
} else {
(x as u64, 1)
}
}
/// Helper function to create fraction
///
/// fraction(x, y) gives you the unnormalized Price closest to x/y.
/// This output could have arbitrary exponent due to the div, so you may need to call
/// scale_to_exponent to scale to your desired expo. If you cannot represent x/y exactly
/// within 8 digits of precision, it may zero out the remainder. In particular, if x and/or
/// y cannot be represented within 8 digits of precision, potential for precision error.
/// If x and y can both be represented within 8 digits of precision AND x/y can be represented
/// within 8 digits, no precision loss.
///
/// Error of normalizing x, y <= 10^(PD_EXPO+2) = 10^-7
/// Inherits any bounded errors from normalization and div
fn fraction(x: i64, y: i64) -> Option<Price> {
// convert x and y to Prices
let x_as_price = Price {
price: x,
conf: 0,
expo: 0,
publish_time: 0,
};
let y_as_price = Price {
price: y,
conf: 0,
expo: 0,
publish_time: 0,
};
// get the relevant fraction
let frac = x_as_price.div(&y_as_price)?;
Some(frac)
}
}
#[cfg(test)]
mod test {
use quickcheck::TestResult;
use quickcheck_macros::quickcheck;
use crate::price::{
Price,
MAX_PD_V_U64,
PD_EXPO,
PD_SCALE,
};
const MAX_PD_V_I64: i64 = MAX_PD_V_U64 as i64;
const MIN_PD_V_I64: i64 = -MAX_PD_V_I64;
fn pc(price: i64, conf: u64, expo: i32) -> Price {
Price {
price,
conf,
expo,
publish_time: 0,
}
}
fn pc_scaled(price: i64, conf: u64, cur_expo: i32, expo: i32) -> Price {
Price {
price,
conf,
expo: cur_expo,
publish_time: 0,
}
.scale_to_exponent(expo)
.unwrap()
}
#[test]
fn test_normalize() {
fn succeeds(price1: Price, expected: Price) {
assert_eq!(price1.normalize().unwrap(), expected);
}
fn fails(price1: Price) {
assert_eq!(price1.normalize(), None);
}
succeeds(
pc(2 * (PD_SCALE as i64), 3 * PD_SCALE, 0),
pc(2 * (PD_SCALE as i64) / 100, 3 * PD_SCALE / 100, 2),
);
succeeds(
pc(-2 * (PD_SCALE as i64), 3 * PD_SCALE, 0),
pc(-2 * (PD_SCALE as i64) / 100, 3 * PD_SCALE / 100, 2),
);
// the i64 / u64 max values are a factor of 10^11 larger than MAX_PD_V
let expo = -(PD_EXPO - 2);
let scale_i64 = (PD_SCALE as i64) * 100;
let scale_u64 = scale_i64 as u64;
succeeds(pc(i64::MAX, 1, 0), pc(i64::MAX / scale_i64, 0, expo));
succeeds(pc(i64::MIN, 1, 0), pc(i64::MIN / scale_i64, 0, expo));
succeeds(pc(1, u64::MAX, 0), pc(0, u64::MAX / scale_u64, expo));
// exponent overflows
succeeds(
pc(i64::MAX, 1, i32::MAX - expo),
pc(i64::MAX / scale_i64, 0, i32::MAX),
);
fails(pc(i64::MAX, 1, i32::MAX - expo + 1));
succeeds(
pc(i64::MAX, 1, i32::MIN),
pc(i64::MAX / scale_i64, 0, i32::MIN + expo),
);
succeeds(
pc(1, u64::MAX, i32::MAX - expo),
pc(0, u64::MAX / scale_u64, i32::MAX),
);
fails(pc(1, u64::MAX, i32::MAX - expo + 1));
// Check timestamp won't change after normalize
let p = Price {
publish_time: 100,
..Default::default()
};
assert_eq!(p.normalize().unwrap().publish_time, 100);
}
#[test]
fn test_scale_to_exponent() {
fn succeeds(price1: Price, target: i32, expected: Price) {
assert_eq!(price1.scale_to_exponent(target).unwrap(), expected);
}
fn fails(price1: Price, target: i32) {
assert_eq!(price1.scale_to_exponent(target), None);
}
succeeds(pc(1234, 1234, 0), 0, pc(1234, 1234, 0));
succeeds(pc(1234, 1234, 0), 1, pc(123, 123, 1));
succeeds(pc(1234, 1234, 0), 2, pc(12, 12, 2));
succeeds(pc(-1234, 1234, 0), 2, pc(-12, 12, 2));
succeeds(pc(1234, 1234, 0), 4, pc(0, 0, 4));
succeeds(pc(1234, 1234, 0), -1, pc(12340, 12340, -1));
succeeds(pc(1234, 1234, 0), -2, pc(123400, 123400, -2));
succeeds(pc(1234, 1234, 0), -8, pc(123400000000, 123400000000, -8));
// insufficient precision to represent the result in this exponent
fails(pc(1234, 1234, 0), -20);
fails(pc(1234, 0, 0), -20);
fails(pc(0, 1234, 0), -20);
// fails because exponent delta overflows
fails(pc(1, 1, i32::MIN), i32::MAX);
// Check timestamp won't change after scale to exponent
let p = Price {
publish_time: 100,
..pc(1234, 1234, 0)
};
assert_eq!(p.scale_to_exponent(2).unwrap().publish_time, 100);
}
#[test]
fn test_div() {
fn succeeds(price1: Price, price2: Price, expected: Price) {
assert_eq!(price1.div(&price2).unwrap(), expected);
}
fn fails(price1: Price, price2: Price) {
let result = price1.div(&price2);
assert_eq!(result, None);
}
succeeds(pc(1, 1, 0), pc(1, 1, 0), pc_scaled(1, 2, 0, PD_EXPO));
succeeds(pc(1, 1, -8), pc(1, 1, -8), pc_scaled(1, 2, 0, PD_EXPO));
succeeds(pc(10, 1, 0), pc(1, 1, 0), pc_scaled(10, 11, 0, PD_EXPO));
succeeds(pc(1, 1, 1), pc(1, 1, 0), pc_scaled(10, 20, 0, PD_EXPO + 1));
succeeds(pc(1, 1, 0), pc(5, 1, 0), pc_scaled(20, 24, -2, PD_EXPO));
// Negative numbers
succeeds(pc(-1, 1, 0), pc(1, 1, 0), pc_scaled(-1, 2, 0, PD_EXPO));
succeeds(pc(1, 1, 0), pc(-1, 1, 0), pc_scaled(-1, 2, 0, PD_EXPO));
succeeds(pc(-1, 1, 0), pc(-1, 1, 0), pc_scaled(1, 2, 0, PD_EXPO));
// Different exponents in the two inputs
succeeds(
pc(100, 10, -8),
pc(2, 1, -7),
pc_scaled(500_000_000, 300_000_000, -8, PD_EXPO - 1),
);
succeeds(
pc(100, 10, -4),
pc(2, 1, 0),
pc_scaled(500_000, 300_000, -8, PD_EXPO + -4),
);
// Test with end range of possible inputs where the output should not lose precision.
succeeds(
pc(MAX_PD_V_I64, MAX_PD_V_U64, 0),
pc(MAX_PD_V_I64, MAX_PD_V_U64, 0),
pc_scaled(1, 2, 0, PD_EXPO),
);
succeeds(
pc(MAX_PD_V_I64, MAX_PD_V_U64, 0),
pc(1, 1, 0),
pc_scaled(MAX_PD_V_I64, 2 * MAX_PD_V_U64, 0, PD_EXPO),
);
succeeds(
pc(1, 1, 0),
pc(MAX_PD_V_I64, MAX_PD_V_U64, 0),
pc(
(PD_SCALE as i64) / MAX_PD_V_I64,
2 * (PD_SCALE / MAX_PD_V_U64),
PD_EXPO,
),
);
succeeds(
pc(MIN_PD_V_I64, MAX_PD_V_U64, 0),
pc(MIN_PD_V_I64, MAX_PD_V_U64, 0),
pc_scaled(1, 2, 0, PD_EXPO),
);
succeeds(
pc(MIN_PD_V_I64, MAX_PD_V_U64, 0),
pc(1, 1, 0),
pc_scaled(MIN_PD_V_I64, 2 * MAX_PD_V_U64, 0, PD_EXPO),
);
succeeds(
pc(1, 1, 0),
pc(MIN_PD_V_I64, MAX_PD_V_U64, 0),
pc(
(PD_SCALE as i64) / MIN_PD_V_I64,
2 * (PD_SCALE / MAX_PD_V_U64),
PD_EXPO,
),
);
succeeds(
pc(1, MAX_PD_V_U64, 0),
pc(1, MAX_PD_V_U64, 0),
pc_scaled(1, 2 * MAX_PD_V_U64, 0, PD_EXPO),
);
// This fails because the confidence interval is too large to be represented in PD_EXPO
fails(pc(MAX_PD_V_I64, MAX_PD_V_U64, 0), pc(1, MAX_PD_V_U64, 0));
// Unnormalized tests below here
// More realistic inputs (get BTC price in ETH)
let ten_e7: i64 = 10000000;
let uten_e7: u64 = 10000000;
succeeds(
pc(520010 * ten_e7, 310 * uten_e7, -8),
pc(38591 * ten_e7, 18 * uten_e7, -8),
pc(1347490347, 1431804, -8),
);
// Test with end range of possible inputs to identify overflow
// These inputs will lose precision due to the initial normalization.
// Get the rounded versions of these inputs in order to compute the expected results.
let normed = pc(i64::MAX, u64::MAX, 0).normalize().unwrap();
succeeds(
pc(i64::MAX, u64::MAX, 0),
pc(i64::MAX, u64::MAX, 0),
pc_scaled(1, 4, 0, PD_EXPO),
);
succeeds(
pc(i64::MAX, u64::MAX, 0),
pc(1, 1, 0),
pc_scaled(
normed.price,
3 * (normed.price as u64),
normed.expo,
normed.expo + PD_EXPO,
),
);
succeeds(
pc(1, 1, 0),
pc(i64::MAX, u64::MAX, 0),
pc(
(PD_SCALE as i64) / normed.price,
3 * (PD_SCALE / (normed.price as u64)),
PD_EXPO - normed.expo,
),
);
succeeds(
pc(i64::MAX, 1, 0),
pc(i64::MAX, 1, 0),
pc_scaled(1, 0, 0, PD_EXPO),
);
succeeds(
pc(i64::MAX, 1, 0),
pc(1, 1, 0),
pc_scaled(
normed.price,
normed.price as u64,
normed.expo,
normed.expo + PD_EXPO,
),
);
succeeds(
pc(1, 1, 0),
pc(i64::MAX, 1, 0),
pc(
(PD_SCALE as i64) / normed.price,
PD_SCALE / (normed.price as u64),
PD_EXPO - normed.expo,
),
);
let normed = pc(i64::MIN, u64::MAX, 0).normalize().unwrap();
let normed_c = (-normed.price) as u64;
succeeds(
pc(i64::MIN, u64::MAX, 0),
pc(i64::MIN, u64::MAX, 0),
pc_scaled(1, 4, 0, PD_EXPO),
);
succeeds(
pc(i64::MIN, u64::MAX, 0),
pc(i64::MAX, u64::MAX, 0),
pc_scaled(-1, 4, 0, PD_EXPO),
);
succeeds(
pc(i64::MIN, u64::MAX, 0),
pc(1, 1, 0),
pc_scaled(
normed.price,
3 * normed_c,
normed.expo,
normed.expo + PD_EXPO,
),
);
succeeds(
pc(1, 1, 0),
pc(i64::MIN, u64::MAX, 0),
pc(
(PD_SCALE as i64) / normed.price,
3 * (PD_SCALE / normed_c),
PD_EXPO - normed.expo,
),
);
succeeds(
pc(i64::MIN, 1, 0),
pc(i64::MIN, 1, 0),
pc_scaled(1, 0, 0, PD_EXPO),
);
succeeds(
pc(i64::MIN, 1, 0),
pc(1, 1, 0),
pc_scaled(normed.price, normed_c, normed.expo, normed.expo + PD_EXPO),
);
succeeds(
pc(1, 1, 0),
pc(i64::MIN, 1, 0),
pc(
(PD_SCALE as i64) / normed.price,
PD_SCALE / (normed_c),
PD_EXPO - normed.expo,
),
);
// Price is zero pre-normalization
succeeds(pc(0, 1, 0), pc(1, 1, 0), pc_scaled(0, 1, 0, PD_EXPO));
succeeds(pc(0, 1, 0), pc(100, 1, 0), pc_scaled(0, 1, -2, PD_EXPO));
fails(pc(1, 1, 0), pc(0, 1, 0));
// Normalizing the input when the confidence is >> price produces a price of 0.
fails(pc(1, 1, 0), pc(1, u64::MAX, 0));
succeeds(
pc(1, u64::MAX, 0),
pc(1, 1, 0),
pc_scaled(0, normed.conf, normed.expo, normed.expo + PD_EXPO),
);
// Exponent under/overflow.
succeeds(
pc(1, 1, i32::MAX),
pc(1, 1, 0),
pc(PD_SCALE as i64, 2 * PD_SCALE, i32::MAX + PD_EXPO),
);
fails(pc(1, 1, i32::MAX), pc(1, 1, -1));
succeeds(
pc(1, 1, i32::MIN - PD_EXPO),
pc(1, 1, 0),
pc(PD_SCALE as i64, 2 * PD_SCALE, i32::MIN),
);
succeeds(
pc(1, 1, i32::MIN),
pc(1, 1, PD_EXPO),
pc(PD_SCALE as i64, 2 * PD_SCALE, i32::MIN),