2
0

order.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package util
  2. import (
  3. "errors"
  4. "git.beejay.kim/Gshopper/sentio"
  5. "math"
  6. )
  7. func CreateOrder(
  8. m sentio.Market,
  9. s sentio.Strategy,
  10. t sentio.Side,
  11. probability *sentio.Probability,
  12. q map[string]sentio.Quote,
  13. sl map[string]float64,
  14. ) error {
  15. var (
  16. symbol string
  17. account sentio.MarketAccount
  18. threshold float32
  19. size uint
  20. ok bool
  21. err error
  22. )
  23. if symbol, ok = s.PositionSymbols()[t]; !ok {
  24. return errors.New("`CreateOrder`: unknown Side for the current strategy")
  25. }
  26. // define threshold
  27. if threshold, ok = s.PositionProbabilities()[t]; !ok {
  28. return nil
  29. }
  30. // Prevent cases when order will be closed ASAP they were opened.
  31. // Also, Alpaca requires at least 0.01 gap against base_price
  32. if sentio.ToFixed(sl[symbol], 2) > sentio.ToFixed(q[symbol].BidPrice, 2)-0.01 {
  33. return sentio.ErrHighStoploss
  34. }
  35. if account, err = m.Account(); err != nil {
  36. return err
  37. }
  38. if account.GetCash() < q[symbol].BidPrice {
  39. return sentio.ErrTooSmallOrder
  40. }
  41. var (
  42. stamp *sentio.Probability_Stamp
  43. next *sentio.Probability_Stamp
  44. )
  45. if stamp, ok = probability.First(); !ok {
  46. return nil
  47. }
  48. if next, ok = probability.Next(1); !ok {
  49. return nil
  50. }
  51. if (sentio.LONG == t && stamp.Value > threshold && next.Value > threshold) ||
  52. (sentio.SHORT == t && stamp.Value < threshold && next.Value < threshold) {
  53. // create a new order
  54. if size = uint(math.Floor(account.GetCash() * .8 / q[symbol].BidPrice)); size < 1 {
  55. return sentio.ErrTooSmallOrder
  56. }
  57. _, err = m.CreateOrder(symbol, size, sl[symbol])
  58. return err
  59. }
  60. return nil
  61. }
  62. func CloseAllOrders(m sentio.Market, s sentio.Strategy) error {
  63. var (
  64. symbols = Symbols(s)
  65. orders []sentio.Order
  66. err error
  67. )
  68. if orders, err = m.Orders(sentio.OrderListCriteria{
  69. Status: "open",
  70. Symbols: symbols,
  71. }); err != nil {
  72. return err
  73. }
  74. for i := range orders {
  75. if _, err = m.CloseOrder(orders[i]); err != nil {
  76. return err
  77. }
  78. }
  79. return nil
  80. }