strategy: add ktrade

This commit is contained in:
austin362667 2022-08-30 09:16:53 +08:00 committed by Austin Liu
parent 889318ddcb
commit 42d7117464
3 changed files with 250 additions and 0 deletions

View File

@ -16,6 +16,7 @@ import (
_ "github.com/c9s/bbgo/pkg/strategy/funding"
_ "github.com/c9s/bbgo/pkg/strategy/grid"
_ "github.com/c9s/bbgo/pkg/strategy/kline"
_ "github.com/c9s/bbgo/pkg/strategy/ktrade"
_ "github.com/c9s/bbgo/pkg/strategy/marketcap"
_ "github.com/c9s/bbgo/pkg/strategy/pivotshort"
_ "github.com/c9s/bbgo/pkg/strategy/pricealert"

View File

@ -0,0 +1,115 @@
package ktrade
import (
"context"
"github.com/c9s/bbgo/pkg/util"
"time"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
type Minute struct {
Symbol string
Market types.Market `json:"-"`
types.IntervalWindow
// MarketOrder is the option to enable market order short.
MarketOrder bool `json:"marketOrder"`
Quantity fixedpoint.Value `json:"quantity"`
orderExecutor *bbgo.GeneralOrderExecutor
session *bbgo.ExchangeSession
activeOrders *bbgo.ActiveOrderBook
StreamBook *types.StreamOrderBook
midPrice fixedpoint.Value
bbgo.QuantityOrAmount
}
func (s *Minute) updateOrder(ctx context.Context, symbol string) {
bestBid, bestAsk, _ := s.StreamBook.BestBidAndAsk()
s.midPrice = bestBid.Price.Add(bestAsk.Price).Div(fixedpoint.NewFromInt(2))
log.Info(s.midPrice)
}
func (s *Minute) Bind(session *bbgo.ExchangeSession, orderExecutor *bbgo.GeneralOrderExecutor) {
s.session = session
s.orderExecutor = orderExecutor
position := orderExecutor.Position()
symbol := position.Symbol
s.StreamBook = types.NewStreamBook(symbol)
s.StreamBook.BindStream(session.MarketDataStream)
//store, _ := session.MarketDataStore(symbol)
session.MarketDataStream.OnMarketTrade(func(trade types.Trade) {
log.Infof("%s trade @ %f", trade.Side, trade.Price.Float64())
bestAsk, _ := s.StreamBook.BestAsk()
bestBid, _ := s.StreamBook.BestBid()
if trade.Side == types.SideTypeBuy && trade.Price.Compare(s.midPrice) > 0 && trade.Price.Compare(bestAsk.Price) <= 0 {
_ = s.orderExecutor.GracefulCancel(context.Background())
// update ask price
newAskPrice := s.midPrice.Mul(fixedpoint.NewFromFloat(0.25)).Add(trade.Price.Mul(fixedpoint.NewFromFloat(0.75)))
log.Infof("short @ %f", newAskPrice.Float64())
s.placeOrder(context.Background(), types.SideTypeSell, s.Quantity, newAskPrice.Ceil(), symbol)
} else if trade.Side == types.SideTypeSell && trade.Price.Compare(s.midPrice) < 0 && trade.Price.Compare(bestBid.Price) >= 0 {
_ = s.orderExecutor.GracefulCancel(context.Background())
// update bid price
newBidPrice := s.midPrice.Mul(fixedpoint.NewFromFloat(0.25)).Add(trade.Price.Mul(fixedpoint.NewFromFloat(0.75)))
log.Infof("long @ %f", newBidPrice.Float64())
s.placeOrder(context.Background(), types.SideTypeBuy, s.Quantity, newBidPrice.Floor(), symbol)
}
})
session.MarketDataStream.OnKLineClosed(types.KLineWith(symbol, s.Interval, func(kline types.KLine) {
log.Info(kline.NumberOfTrades)
}))
go func() {
quoteTicker := time.NewTicker(util.MillisecondsJitter(time.Millisecond*10, 200))
defer quoteTicker.Stop()
for {
select {
case <-quoteTicker.C:
s.updateOrder(context.Background(), symbol)
}
}
}()
if !bbgo.IsBackTesting {
session.MarketDataStream.OnMarketTrade(func(trade types.Trade) {
})
}
}
func (s *Minute) placeOrder(ctx context.Context, side types.SideType, quantity fixedpoint.Value, price fixedpoint.Value, symbol string) {
market, _ := s.session.Market(symbol)
_, err := s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: symbol,
Market: market,
Side: side,
Type: types.OrderTypeLimitMaker,
Quantity: quantity,
Price: price,
//TimeInForce: types.TimeInForceGTC,
Tag: "ktrade",
})
if err != nil {
log.WithError(err).Errorf("can not place order")
}
}

View File

@ -0,0 +1,134 @@
package ktrade
import (
"context"
"fmt"
"os"
"sync"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/sirupsen/logrus"
)
const ID = "ktrade"
var one = fixedpoint.One
var zero = fixedpoint.Zero
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type IntervalWindowSetting struct {
types.IntervalWindow
}
type Strategy struct {
Environment *bbgo.Environment
Symbol string `json:"symbol"`
Market types.Market
types.IntervalWindow
// persistence fields
Position *types.Position `persistence:"position"`
ProfitStats *types.ProfitStats `persistence:"profit_stats"`
TradeStats *types.TradeStats `persistence:"trade_stats"`
activeOrders *bbgo.ActiveOrderBook
Minute *Minute `json:"minute"`
ExitMethods bbgo.ExitMethodSet `json:"exits"`
session *bbgo.ExchangeSession
orderExecutor *bbgo.GeneralOrderExecutor
// StrategyController
bbgo.StrategyController
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{})
session.Subscribe(types.MarketTradeChannel, s.Symbol, types.SubscribeOptions{})
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Minute.Interval})
if !bbgo.IsBackTesting {
session.Subscribe(types.MarketTradeChannel, s.Symbol, types.SubscribeOptions{})
}
s.ExitMethods.SetAndSubscribe(session, s)
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
var instanceID = s.InstanceID()
if s.Position == nil {
s.Position = types.NewPositionFromMarket(s.Market)
}
if s.ProfitStats == nil {
s.ProfitStats = types.NewProfitStats(s.Market)
}
if s.TradeStats == nil {
s.TradeStats = types.NewTradeStats(s.Symbol)
}
// StrategyController
s.Status = types.StrategyStatusRunning
s.OnSuspend(func() {
// Cancel active orders
_ = s.orderExecutor.GracefulCancel(ctx)
})
s.OnEmergencyStop(func() {
// Cancel active orders
_ = s.orderExecutor.GracefulCancel(ctx)
// Close 100% position
//_ = s.ClosePosition(ctx, fixedpoint.One)
})
// initial required information
s.session = session
s.orderExecutor = bbgo.NewGeneralOrderExecutor(session, s.Symbol, ID, instanceID, s.Position)
s.orderExecutor.BindEnvironment(s.Environment)
s.orderExecutor.BindProfitStats(s.ProfitStats)
s.orderExecutor.BindTradeStats(s.TradeStats)
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
bbgo.Sync(s)
})
s.orderExecutor.Bind()
s.activeOrders = bbgo.NewActiveOrderBook(s.Symbol)
for _, method := range s.ExitMethods {
method.Bind(session, s.orderExecutor)
}
if s.Minute != nil {
s.Minute.Bind(session, s.orderExecutor)
}
bbgo.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
_, _ = fmt.Fprintln(os.Stderr, s.TradeStats.String())
_ = s.orderExecutor.GracefulCancel(ctx)
})
return nil
}