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
//! # Equilibrium Volatility Pallet
//!
//! Equilibrium's Volatility Pallet is a Substrate module that calculates and
//! stores prices volatility and prices correlation for all system currencies.
//! This data is used for fees and other system parameters calculation

#![cfg_attr(not(feature = "std"), no_std)]

mod mock;
mod tests;

use core::slice::Iter;
use eq_oracle::OnNewPrice;
use eq_primitives::currency::Currency;
use eq_utils::math::*;
use frame_support::{
    codec::{Decode, Encode},
    debug, decl_error, decl_event, decl_module, decl_storage, ensure,
    traits::{Get, UnixTime},
};
use sp_arithmetic::{traits::Saturating, FixedI64, FixedPointNumber};
use sp_runtime::traits::CheckedAdd;
use sp_runtime::RuntimeDebug;
use sp_std::prelude::*;

/// A time period for which price is aggregated
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug)]
pub enum PricePeriod {
    Min,
    TenMin,
    Hour,
    FourHour,
    Day,
}

impl PricePeriod {
    pub fn iterator() -> Iter<'static, PricePeriod> {
        static PRICE_PERIOD: [PricePeriod; 5] = [
            PricePeriod::Min,
            PricePeriod::TenMin,
            PricePeriod::Hour,
            PricePeriod::FourHour,
            PricePeriod::Day,
        ];
        PRICE_PERIOD.iter()
    }
    /// `PricePeriod` representation in seconds
    fn as_secs(&self) -> u64 {
        match self {
            PricePeriod::Min => 60,
            PricePeriod::TenMin => 600,
            PricePeriod::Hour => 3600, // todo тут лишний ноль был // todel
            PricePeriod::FourHour => 14_400, // todo тут лишний ноль был // todel
            PricePeriod::Day => 86_400,
        }
    }
}

/// Substrate pallet configuration trait
pub trait Trait: system::Trait {
    // todel
    // type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;

    /// Timestamp provider
    type UnixTime: UnixTime;
    /// Amount of maximum stored price points
    type MaxPricePoints: Get<usize>;
    /// Time between two data points
    type PeriodTypeForAggregates: Get<PricePeriod>;
}

decl_storage! {
    trait Store for Module<T: Trait> as EqVolatility {
        /// Pallet storage - vectors of prices for every `Currency` for each `PricePeriod`
        pub Prices get(fn prices): double_map hasher(blake2_128_concat) Currency, hasher(blake2_128_concat) PricePeriod => Vec<FixedI64>;
        /// Pallet storage - timestamps of updates for every `Currency` in each `PricePeriod`
        pub LastUpdate get(fn last_update): double_map hasher(blake2_128_concat) Currency, hasher(blake2_128_concat) PricePeriod => u64;
        /// Pallet storage - volatilities for every `Currency`
        pub Volatility get(fn volatility): map hasher(blake2_128_concat) Currency => FixedI64;
        /// Pallet storage - price correlations for every pair of currencies
        pub Corellation get(fn corellation): double_map hasher(blake2_128_concat) Currency, hasher(blake2_128_concat) Currency => FixedI64;
    }
    add_extra_genesis {
        config(volatilities): Vec<(u8, u64, u64)>;
        config(corellations): Vec<(u8, u8, u64, u64)>;
        config(prices): Vec<(u8, u64, u64)>;
        config(update_date): u64;

        build(|config: &GenesisConfig| {
            for &(currency, nom, denom) in config.volatilities.iter() {
                let currency_typed: Currency = currency.into();
                let value: FixedI64 = FixedI64::saturating_from_rational(nom, denom);
                <Volatility>::insert(currency_typed, value);
            }
            for &(currency1, currency2, nom, denom) in config.corellations.iter() {
                let c1_typed: Currency = currency1.into();
                let c2_typed: Currency = currency2.into();
                let value: FixedI64 = FixedI64::saturating_from_rational(nom, denom);
                <Corellation>::insert(c1_typed, c2_typed, value);
                if currency1 != currency2 {
                    <Corellation>::insert(c2_typed, c1_typed, value);
                }
            }

            let mut currency_cached = 0;
            for &(currency, nom, denom) in config.prices.iter() {
                let currency_typed: Currency = currency.into();
                let period = PricePeriod::Day;

                if currency != currency_cached
                {
                    let vec: Vec<FixedI64> = Vec::new();
                    <Prices>::insert(currency_typed, period.clone(), vec);
                    <LastUpdate>::insert(currency_typed, period.clone(), config.update_date);
                    currency_cached = currency;
                }
                let price: FixedI64 = FixedI64::saturating_from_rational(nom, denom);
                <Prices>::mutate(currency_typed, period, |curr_vec| {
                    curr_vec.push(price);
                });
            }
        });
    }
}

// todel
// decl_event!(
//     pub enum Event<T>
//     where
//         AccountId = <T as system::Trait>::AccountId,
//     {
//         /// TODO - unused
//         AEvent(AccountId),
//     }
// );
// decl_error! {
//     pub enum Error for Module<T: Trait> {
//         /// TODO - no errors
//         AError,  // in future add custom errors for processors
//     }
// }

decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {}
        // type Error = Error<T>;
        // fn deposit_event() = default;
    // }
}

impl<T: Trait> Module<T> {
    /// Private function for pallet calculations
    fn calv_log_return_diff_mid(currency: &Currency) -> Option<Vec<FixedI64>> {
        let prices = <Prices>::get(currency, T::PeriodTypeForAggregates::get());

        if prices.len() != T::MaxPricePoints::get() {
            return None;
        }

        let log_returns: Result<Vec<FixedI64>, ()> = (0..prices.len() - 1)
            .enumerate()
            .map(|(index, _)| -> Result<FixedI64, ()> {
                ensure!(prices[index].into_inner() != 0, ());
                let diff = prices[index + 1] / prices[index];
                diff.ln()
            })
            .collect();
        if log_returns.is_err() {
            // panic or error?
            debug::error!("{}:{}. log_returns.is_err()", file!(), line!());
            return None;
        }

        let log_returns_unwrapped = log_returns.unwrap();

        let log_returns_sum_option = log_returns_unwrapped
            .iter()
            .try_fold(FixedI64::saturating_from_integer(0), |acc, x| {
                acc.checked_add(x)
            }); // log_returns.len() as f64;

        if log_returns_sum_option.is_none() {
            // panic or error?
            debug::error!("{}:{}. log_returns_average.is_none()", file!(), line!());
            return None;
        }

        let log_returns_average = log_returns_sum_option.unwrap()
            / FixedI64::saturating_from_integer(log_returns_unwrapped.len() as i64);

        let result: Vec<FixedI64> = log_returns_unwrapped
            .iter()
            .map(|&x| (x - log_returns_average))
            .collect();
        Some(result)
    }

    /// Recalculates price-related aggregates for `currency` in given `price_period`
    fn recalc_aggregates(currency: &Currency, price_period: &PricePeriod) {
        if *price_period != T::PeriodTypeForAggregates::get() {
            return;
        }

        let prices = <Prices>::get(currency, price_period);

        if prices.len() != T::MaxPricePoints::get() {
            return;
        }

        if let Some(log_returns_diff) = Self::calv_log_return_diff_mid(currency) {
            // TODO add option to check overflow
            let volatility =
                FixedI64::saturating_from_rational(1, log_returns_diff.len() as u64 - 1)
                    .saturating_mul(
                        log_returns_diff
                            .iter()
                            .map(|&x| x.sqr())
                            .fold(FixedI64::saturating_from_integer(0), |acc, x| acc + x),
                    )
                    .sqrt();
            <Volatility>::insert(currency, volatility.unwrap());

            // corr

            for acurrency in Currency::iterator() {
                if acurrency == currency {
                    continue;
                }

                if let Some(log_returns_diff_another) = Self::calv_log_return_diff_mid(acurrency) {
                    let another_volatility = <Volatility>::get(&acurrency);

                    if another_volatility.into_inner() == 0 {
                        continue;
                    }

                    let corr =
                        (FixedI64::saturating_from_rational(1, log_returns_diff.len() as u64 - 1)
                            / volatility.unwrap()
                            / another_volatility)
                            .saturating_mul(
                                log_returns_diff
                                    .iter()
                                    .enumerate()
                                    .map(|(index, item)| {
                                        item.saturating_mul(log_returns_diff_another[index])
                                    })
                                    .fold(FixedI64::saturating_from_integer(0), |acc, x| acc + x),
                            );

                    <Corellation>::insert(currency, acurrency, corr);
                    <Corellation>::insert(acurrency, currency, corr);
                }
            }
        } else {
            // Err?
            return;
        }
    }
}

/// Implemented aggregates recalculation on each new price
impl<T: Trait> OnNewPrice for Module<T> {
    fn on_new_price(currency: &Currency, price: FixedI64) {
        let current_time = T::UnixTime::now().as_secs();

        for aperiod in PricePeriod::iterator() {
            let period_ms = aperiod.as_secs();
            let last_update = <LastUpdate>::get(currency, aperiod);
            let mut ms_passed = current_time - last_update;

            if ms_passed == 0 {
                <Prices>::mutate(currency, aperiod, |curr_vec| {
                    let len = curr_vec.len();
                    curr_vec[len - 1] = price;
                });
                Self::recalc_aggregates(&currency, &aperiod);
            } else if last_update == 0 {
                <Prices>::mutate(currency, aperiod, |curr_vec| {
                    curr_vec.push(price);
                });
                <LastUpdate>::insert(currency, aperiod, current_time);
                Self::recalc_aggregates(&currency, &aperiod);
            } else if ms_passed >= period_ms {
                <Prices>::mutate(currency, aperiod, |curr_vec| {
                    let last_price: FixedI64;
                    {
                        last_price = *curr_vec.last().unwrap();
                    }
                    while ms_passed >= period_ms * 2 {
                        curr_vec.push(last_price);
                        ms_passed -= period_ms;
                    }
                    curr_vec.push(price);

                    if curr_vec.len() > T::MaxPricePoints::get() {
                        curr_vec.drain(..(curr_vec.len() - T::MaxPricePoints::get()));
                    }
                });
                <LastUpdate>::insert(currency, aperiod, current_time);
                Self::recalc_aggregates(&currency, &aperiod);
            }
        }
    }
}

/// Volatility, correlation and covariance storage adapter
pub trait VolatilityGetter {
    /// Returns volatility indicator for a given `currency`
    fn get_volatility(currency: &Currency) -> FixedI64;
    /// Returns prices correlation for `Currency` `c1` and `c2`
    fn get_correlation(c1: &Currency, c2: &Currency) -> FixedI64;
    /// Returns prices covariance for `Currency` `c1` and `c2`
    fn get_covariance(c1: &Currency, c2: &Currency) -> FixedI64 {
        // todo: is it correct for usd?
        let v1 = Self::get_volatility(c1);
        let v2 = Self::get_volatility(c2);
        let covariance = v1 * v2 * Self::get_correlation(c1, c2);

        covariance
    }
}

impl<T: Trait> VolatilityGetter for Module<T> {
    fn get_volatility(currency: &Currency) -> FixedI64 {
        Self::volatility(currency)
    }

    fn get_correlation(c1: &Currency, c2: &Currency) -> FixedI64 {
        Self::corellation(c1, c2)
    }
}