backtest: fix fee calculation

This commit is contained in:
c9s 2022-06-12 03:45:47 +08:00
parent ce70bbbc4a
commit 2e8f9c3ad8
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54

View File

@ -201,11 +201,15 @@ func (m *SimplePriceMatching) executeTrade(trade types.Trade) {
var err error var err error
// execute trade, update account balances // execute trade, update account balances
if trade.IsBuyer { if trade.IsBuyer {
err = m.Account.UseLockedBalance(m.Market.QuoteCurrency, trade.Price.Mul(trade.Quantity)) err = m.Account.UseLockedBalance(m.Market.QuoteCurrency, trade.QuoteQuantity)
m.Account.AddBalance(m.Market.BaseCurrency, trade.Quantity.Sub(trade.Fee.Div(trade.Price)))
// here the fee currency is the base currency
m.Account.AddBalance(m.Market.BaseCurrency, trade.Quantity.Sub(trade.Fee))
} else { } else {
err = m.Account.UseLockedBalance(m.Market.BaseCurrency, trade.Quantity) err = m.Account.UseLockedBalance(m.Market.BaseCurrency, trade.Quantity)
m.Account.AddBalance(m.Market.QuoteCurrency, trade.Quantity.Mul(trade.Price).Sub(trade.Fee))
// here the fee currency is the quote currency
m.Account.AddBalance(m.Market.QuoteCurrency, trade.QuoteQuantity.Sub(trade.Fee))
} }
if err != nil { if err != nil {
@ -237,6 +241,7 @@ func (m *SimplePriceMatching) newTradeFromOrder(order *types.Order, isMaker bool
price = m.LastPrice price = m.LastPrice
} }
var quoteQuantity = order.Quantity.Mul(price)
var fee fixedpoint.Value var fee fixedpoint.Value
var feeCurrency string var feeCurrency string
@ -247,7 +252,7 @@ func (m *SimplePriceMatching) newTradeFromOrder(order *types.Order, isMaker bool
feeCurrency = m.Market.BaseCurrency feeCurrency = m.Market.BaseCurrency
case types.SideTypeSell: case types.SideTypeSell:
fee = order.Quantity.Mul(price).Mul(feeRate) fee = quoteQuantity.Mul(feeRate)
feeCurrency = m.Market.QuoteCurrency feeCurrency = m.Market.QuoteCurrency
} }
@ -262,7 +267,7 @@ func (m *SimplePriceMatching) newTradeFromOrder(order *types.Order, isMaker bool
Exchange: "backtest", Exchange: "backtest",
Price: price, Price: price,
Quantity: order.Quantity, Quantity: order.Quantity,
QuoteQuantity: order.Quantity.Mul(price), QuoteQuantity: quoteQuantity,
Symbol: order.Symbol, Symbol: order.Symbol,
Side: order.Side, Side: order.Side,
IsBuyer: order.Side == types.SideTypeBuy, IsBuyer: order.Side == types.SideTypeBuy,