diff --git a/common.go b/common.go index 33f32374..cb231f0d 100644 --- a/common.go +++ b/common.go @@ -175,8 +175,12 @@ func CalculateFee(amount, fee float64) float64 { return amount * (fee / 100) } +func CalculatePercentageGainOrLoss(priceNow, priceThen float64) float64 { + return (priceNow - priceThen) / priceThen * 100 +} + func CalculatePercentageDifference(amount, secondAmount float64) float64 { - return (secondAmount - amount) / amount * 100 + return (amount - secondAmount) / ((amount + secondAmount) / 2) * 100 } func CalculateNetProfit(amount, priceThen, priceNow, costs float64) float64 { diff --git a/common_test.go b/common_test.go index 4f9781cc..653e2ffb 100644 --- a/common_test.go +++ b/common_test.go @@ -183,11 +183,22 @@ func TestCalculateAmountWithFee(t *testing.T) { } } +func TestCalculatePercentageGainOrLoss(t *testing.T) { + t.Parallel() + originalInput := float64(9300) + secondInput := float64(9000) + expectedOutput := 3.3333333333333335 + actualResult := CalculatePercentageGainOrLoss(originalInput, secondInput) + if expectedOutput != actualResult { + t.Error(fmt.Sprintf("Test failed. Expected '%f'. Actual '%f'.", expectedOutput, actualResult)) + } +} + func TestCalculatePercentageDifference(t *testing.T) { t.Parallel() - originalInput := float64(5) - secondAmount := float64(10) - expectedOutput := float64(100) + originalInput := float64(10) + secondAmount := float64(5) + expectedOutput := 66.66666666666666 actualResult := CalculatePercentageDifference(originalInput, secondAmount) if expectedOutput != actualResult { t.Error(fmt.Sprintf("Test failed. Expected '%f'. Actual '%f'.", expectedOutput, actualResult))