2
0

order_intent.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package sentio
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "unicode/utf8"
  8. )
  9. type OrderIntent int8
  10. const (
  11. BuyToOpen OrderIntent = iota
  12. BuyToClose
  13. SellToOpen
  14. SellToClose
  15. )
  16. var intents = map[OrderIntent]string{
  17. BuyToOpen: "buy_to_open",
  18. BuyToClose: "buy_to_close",
  19. SellToOpen: "sell_to_open",
  20. SellToClose: "sell_to_close",
  21. }
  22. func (s OrderIntent) String() string {
  23. if intent, ok := intents[s]; ok {
  24. return intent
  25. }
  26. return "undefined"
  27. }
  28. func (s OrderIntent) MarshalJSON() ([]byte, error) {
  29. intent := s.String()
  30. return []byte(`"` + intent + `"`), nil
  31. }
  32. func (s *OrderIntent) UnmarshalJSON(data []byte) error {
  33. var (
  34. intent OrderIntent
  35. runes = bytes.Runes(data)
  36. err error
  37. )
  38. if l := utf8.RuneCount(data); runes != nil && runes[0] == 34 && runes[l-1] == 34 {
  39. data = data[1 : l-1]
  40. intent, err = ParseOrderIntent(string(data))
  41. } else {
  42. n, err := strconv.Atoi(string(data))
  43. if err == nil {
  44. intent = OrderIntent(n)
  45. }
  46. }
  47. if err != nil {
  48. return err
  49. }
  50. if _, ok := intents[intent]; !ok {
  51. return fmt.Errorf("unknown `OrderIntent`: %s", data)
  52. }
  53. *s = intent
  54. return nil
  55. }
  56. func ParseOrderIntent(s string) (OrderIntent, error) {
  57. s = strings.TrimSpace(s)
  58. s = strings.ToLower(s)
  59. for intent, s2 := range intents {
  60. if s == s2 {
  61. return intent, nil
  62. }
  63. }
  64. return -1, fmt.Errorf("`sentio.ParseOrderIntent`: undefined OrderIntent `%s`", s)
  65. }