From 1176147000a860cee3cee99e4feb621deadfaae1 Mon Sep 17 00:00:00 2001 From: xiaolinny Date: Fri, 16 Jan 2026 08:47:41 +0800 Subject: [PATCH] backtester: Refactor sortByMFI to use slices.SortFunc (#2122) * 2122: slices funcs * Update backtester/eventhandlers/strategies/top2bottom2/top2bottom2.go Co-authored-by: Gareth Kirwan --------- Co-authored-by: Gareth Kirwan Co-authored-by: Adrian Gallagher --- .../strategies/top2bottom2/top2bottom2.go | 22 +++---------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/backtester/eventhandlers/strategies/top2bottom2/top2bottom2.go b/backtester/eventhandlers/strategies/top2bottom2/top2bottom2.go index f69e0bcc..243af752 100644 --- a/backtester/eventhandlers/strategies/top2bottom2/top2bottom2.go +++ b/backtester/eventhandlers/strategies/top2bottom2/top2bottom2.go @@ -3,7 +3,7 @@ package top2bottom2 import ( "errors" "fmt" - "sort" + "slices" "time" "github.com/shopspring/decimal" @@ -69,22 +69,6 @@ type mfiFundEvent struct { funds funding.IFundReader } -// ByPrice used for sorting orders by order date -type byMFI []mfiFundEvent - -func (b byMFI) Len() int { return len(b) } -func (b byMFI) Less(i, j int) bool { return b[i].mfi.LessThan(b[j].mfi) } -func (b byMFI) Swap(i, j int) { b[i], b[j] = b[j], b[i] } - -// sortOrdersByPrice the caller function to sort orders -func sortByMFI(o *[]mfiFundEvent, reverse bool) { - if reverse { - sort.Sort(sort.Reverse(byMFI(*o))) - } else { - sort.Sort(byMFI(*o)) - } -} - // OnSimultaneousSignals analyses multiple data points simultaneously, allowing flexibility // in allowing a strategy to only place an order for X currency if Y currency's price is Z func (s *Strategy) OnSimultaneousSignals(d []data.Handler, f funding.IFundingTransferer, _ portfolio.Handler) ([]signal.Event, error) { @@ -181,7 +165,7 @@ func (s *Strategy) selectTopAndBottomPerformers(mfiFundEvents []mfiFundEvent, re if len(mfiFundEvents) == 0 { return resp, nil } - sortByMFI(&mfiFundEvents, true) + slices.SortFunc(mfiFundEvents, func(a, b mfiFundEvent) int { return b.mfi.Compare(a.mfi) }) buyingOrSelling := false for i := range mfiFundEvents { if i < 2 && mfiFundEvents[i].mfi.GreaterThanOrEqual(s.mfiHigh) { @@ -191,7 +175,7 @@ func (s *Strategy) selectTopAndBottomPerformers(mfiFundEvents []mfiFundEvent, re break } } - sortByMFI(&mfiFundEvents, false) + slices.Reverse(mfiFundEvents) for i := range mfiFundEvents { if i < 2 && mfiFundEvents[i].mfi.LessThanOrEqual(s.mfiLow) { mfiFundEvents[i].event.SetDirection(order.Buy)