1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- 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,
- ) error {
- var (
- symbol string
- account sentio.MarketAccount
- threshold float32
- 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 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
- }
- var (
- stamp *sentio.Probability_Stamp
- next *sentio.Probability_Stamp
- )
- if stamp, ok = probability.First(); !ok {
- return nil
- }
- if next, ok = probability.Next(1); !ok {
- return nil
- }
- if (sentio.LONG == t && stamp.Value > threshold && next.Value > threshold) ||
- (sentio.SHORT == t && stamp.Value < threshold && next.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])
- 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
- }
|