2
0

order.go 2.0 KB

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