Skip to content

Commit

Permalink
backtester: Fix ensureOrderFitsWithinHLV (thrasher-corp#1338)
Browse files Browse the repository at this point in the history
Co-authored-by: xiaoniu <[email protected]>
  • Loading branch information
yangrq1018 and yangrq1018 authored Sep 11, 2023
1 parent c9040a8 commit bc26c53
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 9 deletions.
10 changes: 3 additions & 7 deletions backtester/eventhandlers/exchange/exchange.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,20 +439,16 @@ func ensureOrderFitsWithinHLV(price, amount, high, low, volume decimal.Decimal)
if adjustedPrice.GreaterThan(high) {
adjustedPrice = high
}
orderVolume := amount.Mul(adjustedPrice)
if volume.LessThanOrEqual(decimal.Zero) || orderVolume.LessThanOrEqual(volume) {
if volume.LessThanOrEqual(decimal.Zero) || amount.LessThanOrEqual(volume) {
return adjustedPrice, amount
}
if orderVolume.GreaterThan(volume) {
if amount.GreaterThan(volume) {
// reduce the volume to not exceed the total volume of the candle
// it is slightly less than the total to still allow for the illusion
// that open high low close values are valid with the remaining volume
// this is very opinionated
orderVolume = volume.Mul(decimal.NewFromFloat(0.99999999))
adjustedAmount = volume.Mul(decimal.NewFromFloat(0.99999999))
}
// extract the amount from the adjusted volume
adjustedAmount = orderVolume.Div(adjustedPrice)

return adjustedPrice, adjustedAmount
}

Expand Down
4 changes: 2 additions & 2 deletions backtester/eventhandlers/exchange/exchange_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ func TestSetCurrency(t *testing.T) {

func TestEnsureOrderFitsWithinHLV(t *testing.T) {
t.Parallel()
adjustedPrice, adjustedAmount := ensureOrderFitsWithinHLV(decimal.NewFromInt(123), decimal.NewFromInt(1), decimal.NewFromInt(100), decimal.NewFromInt(99), decimal.NewFromInt(100))
adjustedPrice, adjustedAmount := ensureOrderFitsWithinHLV(decimal.NewFromInt(123), decimal.NewFromInt(1), decimal.NewFromInt(100), decimal.NewFromInt(99), decimal.NewFromInt(10))
if !adjustedAmount.Equal(decimal.NewFromInt(1)) {
t.Error("expected 1")
}
if !adjustedPrice.Equal(decimal.NewFromInt(100)) {
t.Error("expected 100")
}

adjustedPrice, adjustedAmount = ensureOrderFitsWithinHLV(decimal.NewFromInt(123), decimal.NewFromInt(1), decimal.NewFromInt(100), decimal.NewFromInt(99), decimal.NewFromInt(80))
adjustedPrice, adjustedAmount = ensureOrderFitsWithinHLV(decimal.NewFromInt(123), decimal.NewFromInt(1), decimal.NewFromInt(100), decimal.NewFromInt(99), decimal.NewFromFloat(0.8))
if !adjustedAmount.Equal(decimal.NewFromFloat(0.799999992)) {
t.Errorf("received: %v, expected: %v", adjustedAmount, decimal.NewFromFloat(0.799999992))
}
Expand Down

0 comments on commit bc26c53

Please sign in to comment.