Skip to content

Commit 1744281

Browse files
authored
Merge pull request #986 from andycheng123/fix/protective-stop
fix: general order executor: ClosePosition() works on futures position
2 parents 34866ce + 5ad247c commit 1744281

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

pkg/bbgo/order_executor_general.go

+29-12
Original file line numberDiff line numberDiff line change
@@ -407,22 +407,39 @@ func (e *GeneralOrderExecutor) ClosePosition(ctx context.Context, percentage fix
407407
atomic.AddInt64(&e.closing, 1)
408408
defer atomic.StoreInt64(&e.closing, 0)
409409

410-
// check base balance and adjust the close position order
411-
if e.position.IsLong() {
412-
if baseBalance, ok := e.session.Account.Balance(e.position.Market.BaseCurrency); ok {
413-
submitOrder.Quantity = fixedpoint.Min(submitOrder.Quantity, baseBalance.Available)
410+
if e.session.Futures { // Futures: Use base qty in e.position
411+
submitOrder.Quantity = e.position.GetBase().Abs()
412+
submitOrder.ReduceOnly = true
413+
if e.position.IsLong() {
414+
submitOrder.Side = types.SideTypeSell
415+
} else if e.position.IsShort() {
416+
submitOrder.Side = types.SideTypeBuy
417+
} else {
418+
submitOrder.Side = types.SideTypeSelf
419+
submitOrder.Quantity = fixedpoint.Zero
414420
}
421+
415422
if submitOrder.Quantity.IsZero() {
416-
return fmt.Errorf("insufficient base balance, can not sell: %+v", submitOrder)
423+
return fmt.Errorf("no position to close: %+v", submitOrder)
417424
}
418-
} else if e.position.IsShort() {
419-
// TODO: check quote balance here, we also need the current price to validate, need to design.
420-
/*
421-
if quoteBalance, ok := e.session.Account.Balance(e.position.Market.QuoteCurrency); ok {
422-
// AdjustQuantityByMaxAmount(submitOrder.Quantity, quoteBalance.Available)
423-
// submitOrder.Quantity = fixedpoint.Min(submitOrder.Quantity,)
425+
} else { // Spot and spot margin
426+
// check base balance and adjust the close position order
427+
if e.position.IsLong() {
428+
if baseBalance, ok := e.session.Account.Balance(e.position.Market.BaseCurrency); ok {
429+
submitOrder.Quantity = fixedpoint.Min(submitOrder.Quantity, baseBalance.Available)
424430
}
425-
*/
431+
if submitOrder.Quantity.IsZero() {
432+
return fmt.Errorf("insufficient base balance, can not sell: %+v", submitOrder)
433+
}
434+
} else if e.position.IsShort() {
435+
// TODO: check quote balance here, we also need the current price to validate, need to design.
436+
/*
437+
if quoteBalance, ok := e.session.Account.Balance(e.position.Market.QuoteCurrency); ok {
438+
// AdjustQuantityByMaxAmount(submitOrder.Quantity, quoteBalance.Available)
439+
// submitOrder.Quantity = fixedpoint.Min(submitOrder.Quantity,)
440+
}
441+
*/
442+
}
426443
}
427444

428445
tagStr := strings.Join(tags, ",")

0 commit comments

Comments
 (0)