Issue #23254:fix gain/loss calculation

cloned https://github.com/xtuple/xtuple/pull/1739 for the 4.7 line