decred.org/dcrdex@v1.0.3/client/mm/libxc/orderbook_test.go (about) 1 // This code is available on the terms of the project LICENSE.md file, 2 // also available online at https://blueoakcouncil.org/license/1.0.0. 3 4 package libxc 5 6 import "testing" 7 8 func TestOrderbook(t *testing.T) { 9 ob := newOrderBook() 10 11 // Test vwap on empty books 12 _, _, filled := ob.vwap(true, 1) 13 if filled { 14 t.Fatalf("empty book should not be filled") 15 } 16 _, _, filled = ob.vwap(false, 1) 17 if filled { 18 t.Fatalf("empty book should not be filled") 19 } 20 21 // Populate the book with some bids and asks. They both 22 // have the same values, but VWAP for asks should be 23 // calculate from the lower values first. 24 ob.update([]*obEntry{ 25 {qty: 30, rate: 4000}, 26 {qty: 30, rate: 5000}, 27 {qty: 80, rate: 400}, 28 {qty: 10, rate: 3000}, 29 }, []*obEntry{ 30 {qty: 30, rate: 4000}, 31 {qty: 30, rate: 5000}, 32 {qty: 80, rate: 400}, 33 {qty: 10, rate: 3000}, 34 }) 35 vwap, extrema, filled := ob.vwap(true, 65) 36 if !filled { 37 t.Fatalf("should be filled") 38 } 39 expectedVWAP := uint64((30*5000 + 30*4000 + 5*3000) / 65) 40 if vwap != expectedVWAP { 41 t.Fatalf("wrong vwap. expected %d got %d", expectedVWAP, vwap) 42 } 43 if extrema != 3000 { 44 t.Fatalf("wrong extrema") 45 } 46 47 vwap, extrema, filled = ob.vwap(false, 65) 48 if !filled { 49 t.Fatalf("should be filled") 50 } 51 expectedVWAP = uint64(400) 52 if vwap != expectedVWAP { 53 t.Fatalf("wrong vwap. expected %d got %d", expectedVWAP, vwap) 54 } 55 if extrema != 400 { 56 t.Fatalf("wrong extrema") 57 } 58 59 // Tests querying more quantity than on books 60 _, _, filled = ob.vwap(true, 161) 61 if filled { 62 t.Fatalf("should not be filled") 63 } 64 _, _, filled = ob.vwap(false, 161) 65 if filled { 66 t.Fatalf("should not be filled") 67 } 68 69 // Update quantities. Setting qty to 0 should delete. 70 ob.update([]*obEntry{ 71 {qty: 0, rate: 5000}, 72 {qty: 50, rate: 4000}, 73 }, []*obEntry{ 74 {qty: 0, rate: 400}, 75 {qty: 35, rate: 4000}, 76 }) 77 78 vwap, extrema, filled = ob.vwap(true, 65) 79 if !filled { 80 t.Fatalf("should be filled") 81 } 82 expectedVWAP = uint64((50*4000 + 10*3000 + 5*400) / 65) 83 if vwap != expectedVWAP { 84 t.Fatalf("wrong vwap. expected %d got %d", expectedVWAP, vwap) 85 } 86 if extrema != 400 { 87 t.Fatalf("wrong extrema") 88 } 89 90 vwap, extrema, filled = ob.vwap(false, 65) 91 if !filled { 92 t.Fatalf("should be filled") 93 } 94 expectedVWAP = uint64((20*5000 + 35*4000 + 10*3000) / 65) 95 if vwap != expectedVWAP { 96 t.Fatalf("wrong vwap. expected %d got %d", expectedVWAP, vwap) 97 } 98 if extrema != 5000 { 99 t.Fatalf("wrong extrema") 100 } 101 }