Merge pull request #1079 from c9s/fix/grid2/write-context

fix: grid2: add write context for submitting orders
This commit is contained in:
Yo-An Lin 2023-03-03 19:26:47 +08:00 committed by GitHub
commit 45da0bd4c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -181,6 +181,9 @@ type Strategy struct {
// mu is used for locking the grid object field, avoid double grid opening
mu sync.Mutex
tradingCtx, writeCtx context.Context
cancelWrite context.CancelFunc
}
func (s *Strategy) ID() string {
@ -477,7 +480,8 @@ func (s *Strategy) processFilledOrder(o types.Order) {
s.logger.Infof("SUBMIT GRID REVERSE ORDER: %s", orderForm.String())
createdOrders, err := s.orderExecutor.SubmitOrders(context.Background(), orderForm)
writeCtx := s.getWriteContext()
createdOrders, err := s.orderExecutor.SubmitOrders(writeCtx, orderForm)
if err != nil {
s.logger.WithError(err).Errorf("GRID REVERSE ORDER SUBMISSION ERROR: order: %s", orderForm.String())
return
@ -1047,13 +1051,11 @@ func (s *Strategy) openGrid(ctx context.Context, session *bbgo.ExchangeSession)
s.debugGridOrders(submitOrders, lastPrice)
var createdOrders []types.Order
for _, submitOrder := range submitOrders {
ret, err2 := s.orderExecutor.SubmitOrders(ctx, submitOrder)
if err2 != nil {
return err2
}
createdOrders = append(createdOrders, ret...)
writeCtx := s.getWriteContext(ctx)
createdOrders, err2 := s.orderExecutor.SubmitOrders(writeCtx, submitOrders...)
if err2 != nil {
return err2
}
// try to always emit grid ready
@ -1604,9 +1606,32 @@ func (s *Strategy) CleanUp(ctx context.Context) error {
return s.cancelAll(ctx)
}
func (s *Strategy) getWriteContext(fallbackCtxList ...context.Context) context.Context {
if s.writeCtx != nil {
return s.writeCtx
}
for _, c := range fallbackCtxList {
if c != nil {
return c
}
}
if s.tradingCtx != nil {
return s.tradingCtx
}
// final fallback to context background
return context.Background()
}
func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
instanceID := s.InstanceID()
// allocate a context for write operation (submitting orders)
s.tradingCtx = ctx
s.writeCtx, s.cancelWrite = context.WithCancel(ctx)
s.session = session
if service, ok := session.Exchange.(types.ExchangeOrderQueryService); ok {
@ -1704,6 +1729,10 @@ func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.
return
}
if s.cancelWrite != nil {
s.cancelWrite()
}
if err := s.CloseGrid(ctx); err != nil {
s.logger.WithError(err).Errorf("grid graceful order cancel error")
}