Skip to content

Commit

Permalink
Switch to Std SignedDecimal (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
Art3miX authored Jun 28, 2024
1 parent 61338b6 commit 18fefff
Show file tree
Hide file tree
Showing 15 changed files with 90 additions and 591 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
- auctions manager = `1404`
- auction = `1408`
- oracle = `1446`
- rebalancer = `1442`
- rebalancer = `1462`
- services manager = `1405`
- account = `1403`

Expand Down
3 changes: 1 addition & 2 deletions contracts/services/rebalancer/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use auction_package::Pair;
use cosmwasm_std::entry_point;
use cosmwasm_std::{
to_json_binary, Addr, Binary, Coin, Decimal, Deps, DepsMut, Env, Event, MessageInfo, Reply,
Response, StdError, StdResult, Uint128,
Response, SignedDecimal, StdError, StdResult, Uint128,
};
use cw2::set_contract_version;
use cw_storage_plus::Bound;
Expand All @@ -16,7 +16,6 @@ use valence_package::helpers::{approve_admin_change, verify_services_manager, Op
use valence_package::services::rebalancer::{
PauseData, RebalancerExecuteMsg, SystemRebalanceStatus,
};
use valence_package::signed_decimal::SignedDecimal;
use valence_package::states::{QueryFeeAction, ADMIN, SERVICES_MANAGER, SERVICE_FEE_CONFIG};

use crate::error::ContractError;
Expand Down
8 changes: 7 additions & 1 deletion contracts/services/rebalancer/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use cosmwasm_std::{CheckedFromRatioError, DecimalRangeExceeded, OverflowError, StdError};
use cosmwasm_std::{
CheckedFromRatioError, DecimalRangeExceeded, OverflowError, SignedDecimalRangeExceeded,
StdError,
};
use cw_utils::PaymentError;
use thiserror::Error;
use valence_package::error::ValenceError;
Expand All @@ -14,6 +17,9 @@ pub enum ContractError {
#[error(transparent)]
OverflowError(#[from] OverflowError),

#[error(transparent)]
SignedDecimalRangeExceeded(#[from] SignedDecimalRangeExceeded),

#[error(transparent)]
CheckedFromRatioError(#[from] CheckedFromRatioError),

Expand Down
43 changes: 20 additions & 23 deletions contracts/services/rebalancer/src/rebalance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use auction_package::{
};
use cosmwasm_std::{
coins, to_json_binary, Addr, CosmosMsg, Decimal, Deps, DepsMut, Empty, Env, Event, Order,
Response, StdError, SubMsg, Uint128, WasmMsg,
Response, SignedDecimal, StdError, SubMsg, Uint128, WasmMsg,
};
use cw_storage_plus::Bound;
use valence_package::{
Expand All @@ -17,7 +17,6 @@ use valence_package::{
ParsedPID, PauseData, RebalanceTrade, RebalancerConfig, SystemRebalanceStatus,
TargetOverrideStrategy,
},
signed_decimal::SignedDecimal,
CLOSEST_TO_ONE_POSSIBLE,
};

Expand Down Expand Up @@ -262,7 +261,12 @@ pub fn do_rebalance(
.min(Decimal::from_atomics(MAX_PID_DT_VALUE, 0)?)
};

let (mut to_sell, to_buy) = do_pid(total_value, &mut target_helpers, config.pid.clone(), dt)?;
let (mut to_sell, to_buy) = do_pid(
total_value,
&mut target_helpers,
config.pid.clone(),
dt.try_into()?,
)?;

// Update targets in config only the last data we need for the next rebalance calculation
for target in config.targets.iter_mut() {
Expand Down Expand Up @@ -449,55 +453,48 @@ fn do_pid(
total_value: Decimal,
targets: &mut [TargetHelper],
pid: ParsedPID,
dt: Decimal,
dt: SignedDecimal,
) -> Result<TradesTuple, ContractError> {
let mut to_sell: Vec<TargetHelper> = vec![];
let mut to_buy: Vec<TargetHelper> = vec![];

// turn values into signed decimals
let signed_p: SignedDecimal = pid.p.into();
let signed_i: SignedDecimal = pid.i.into();
let signed_d: SignedDecimal = pid.d.into();

let signed_dt: SignedDecimal = dt.into();

targets.iter_mut().for_each(|target| {
let signed_input: SignedDecimal = target.balance_value.into();
for target in targets.iter_mut() {
let signed_input: SignedDecimal = target.balance_value.try_into()?;

// Reset to trade value
target.value_to_trade = Decimal::zero();

let target_value = SignedDecimal::from(total_value * target.target.percentage);
let target_value: SignedDecimal = (total_value * target.target.percentage).try_into()?;

let error = target_value - signed_input;

let p = error * signed_p;
let i = target.target.last_i + (error * signed_i * signed_dt);
let p = error * pid.p;
let i = target.target.last_i + (error * pid.i * dt);
let mut d = match target.target.last_input {
Some(last_input) => signed_input - last_input.into(),
Some(last_input) => signed_input - last_input,
None => SignedDecimal::zero(),
};

d = d * signed_d / signed_dt;
d = d * pid.d / dt;

let output = p + i - d;

target.value_to_trade = output.value();
target.value_to_trade = output.abs_diff(SignedDecimal::zero());

target.target.last_input = Some(target.balance_value);
target.target.last_input = Some(target.balance_value.try_into()?);
target.target.last_i = i;

if output.is_zero() {
return;
continue;
}

match output.sign() {
match !output.is_negative() {
// output is negative, we need to sell
false => to_sell.push(target.clone()),
// output is positive, we need to buy
true => to_buy.push(target.clone()),
}
});
}

Ok((to_sell, to_buy))
}
Expand Down
3 changes: 3 additions & 0 deletions packages/valence-package/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ pub enum ValenceError {
#[error("PID values cannot be more then 1")]
PIDErrorOver,

#[error("PID values cannot be negative")]
PIDErrorNegative,

#[error("max_limit_bps must be between 1-10000")]
InvalidMaxLimitRange,

Expand Down
1 change: 0 additions & 1 deletion packages/valence-package/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ pub mod event_indexing;
pub mod helpers;
pub mod msgs;
pub mod services;
pub mod signed_decimal;
pub mod states;

pub const CLOSEST_TO_ONE_POSSIBLE: &str = "0.9999";
25 changes: 15 additions & 10 deletions packages/valence-package/src/services/rebalancer.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use auction_package::Pair;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
coins, Addr, Api, BankMsg, CosmosMsg, Decimal, Env, MessageInfo, Timestamp, Uint128,
coins, Addr, Api, BankMsg, CosmosMsg, Decimal, Env, MessageInfo, SignedDecimal, Timestamp,
Uint128,
};
use cw_utils::{must_pay, Expiration};
use std::borrow::Borrow;
use std::hash::Hash;
use std::{collections::HashSet, hash::Hasher, str::FromStr};
use valence_macros::valence_service_execute_msgs;

use crate::{error::ValenceError, helpers::OptionalField, signed_decimal::SignedDecimal};
use crate::{error::ValenceError, helpers::OptionalField};

/// Rebalancer execute msgs.
#[valence_service_execute_msgs]
Expand Down Expand Up @@ -239,7 +240,7 @@ pub struct ParsedTarget {
/// Can only be a single one for an account
pub min_balance: Option<Uint128>,
/// The input we got from the last rebalance.
pub last_input: Option<Decimal>,
pub last_input: Option<SignedDecimal>,
/// The last I value we got from the last rebalance PID calculation.
pub last_i: SignedDecimal,
}
Expand Down Expand Up @@ -275,27 +276,31 @@ pub struct PID {
impl PID {
pub fn into_parsed(self) -> Result<ParsedPID, ValenceError> {
ParsedPID {
p: Decimal::from_str(&self.p)?,
i: Decimal::from_str(&self.i)?,
d: Decimal::from_str(&self.d)?,
p: SignedDecimal::from_str(&self.p)?,
i: SignedDecimal::from_str(&self.i)?,
d: SignedDecimal::from_str(&self.d)?,
}
.verify()
}
}

#[cw_serde]
pub struct ParsedPID {
pub p: Decimal,
pub i: Decimal,
pub d: Decimal,
pub p: SignedDecimal,
pub i: SignedDecimal,
pub d: SignedDecimal,
}

impl ParsedPID {
pub fn verify(self) -> Result<Self, ValenceError> {
if self.p > Decimal::one() || self.i > Decimal::one() {
if self.p > SignedDecimal::one() || self.i > SignedDecimal::one() {
return Err(ValenceError::PIDErrorOver);
}

if self.p.is_negative() || self.i.is_negative() || self.d.is_negative() {
return Err(ValenceError::PIDErrorNegative);
}

Ok(self)
}
}
Expand Down
Loading

0 comments on commit 18fefff

Please sign in to comment.