123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- package util
- import (
- "errors"
- "git.beejay.kim/Gshopper/sentio"
- "math"
- )
- func CreateOrder(
- m sentio.Market,
- s sentio.Strategy,
- t sentio.Side,
- probability *sentio.Probability,
- q map[string]sentio.Quote,
- sl map[string]float64,
- tp map[string]float64,
- ) error {
- var (
- symbol string
- account sentio.MarketAccount
- threshold float32
- stamp *sentio.Probability_Stamp
- size uint
- ok bool
- err error
- )
- if symbol, ok = s.PositionSymbols()[t]; !ok {
- return errors.New("`CreateOrder`: unknown Side for the current strategy")
- }
- // define threshold
- if threshold, ok = s.PositionProbabilities()[t]; !ok {
- return nil
- }
- // Prevent orders those have too small expected profit
- if sentio.ToFixed(tp[symbol], 2)/sentio.ToFixed(q[symbol].BidPrice, 2) < 1.0009 {
- return sentio.ErrLowTakeProfit
- }
- // Prevent cases when order will be closed ASAP they were opened.
- // Also, Alpaca requires at least 0.01 gap against base_price
- if sentio.ToFixed(sl[symbol], 2) > sentio.ToFixed(q[symbol].BidPrice, 2)-0.01 {
- return sentio.ErrHighStoploss
- }
- if account, err = m.Account(); err != nil {
- return err
- }
- if account.GetCash() < q[symbol].BidPrice {
- return sentio.ErrTooSmallOrder
- }
- if stamp, ok = probability.First(); !ok {
- return nil
- }
- if sentio.LONG == t && stamp.Value > threshold ||
- sentio.SHORT == t && stamp.Value < threshold {
- // create a new order
- if size = uint(math.Floor(account.GetCash() * .8 / q[symbol].BidPrice)); size < 1 {
- return sentio.ErrTooSmallOrder
- }
- _, err = m.CreateOrder(symbol, size, sl[symbol], tp[symbol])
- return err
- }
- return nil
- }
- func CloseAllOrders(m sentio.Market, s sentio.Strategy) error {
- var (
- symbols = Symbols(s)
- orders []sentio.Order
- err error
- )
- if orders, err = m.Orders(sentio.OrderListCriteria{
- Status: "open",
- Symbols: symbols,
- }); err != nil {
- return err
- }
- for i := range orders {
- if _, err = m.CloseOrder(orders[i]); err != nil {
- return err
- }
- }
- return nil
- }
|