more trader refactoring

This commit is contained in:
c9s 2020-07-12 22:52:37 +08:00
parent c329f6dc86
commit f6a1c20cfe
6 changed files with 223 additions and 117 deletions

View File

@ -1,10 +1,12 @@
package bbgo
import "github.com/c9s/bbgo/pkg/bbgo/types"
type TradingContext struct {
Symbol string
// Market is the market configuration of a symbol
Market Market
Market types.Market
AverageBidPrice float64
CurrentPrice float64

View File

@ -1,61 +1,2 @@
package bbgo
import (
"math"
"strconv"
)
type Market struct {
Symbol string
PricePrecision int
VolumePrecision int
QuoteCurrency string
BaseCurrency string
MinQuantity float64
MinAmount float64
}
func (m Market) FormatPrice(val float64) string {
return strconv.FormatFloat(val, 'f', m.PricePrecision, 64)
}
func (m Market) FormatVolume(val float64) string {
return strconv.FormatFloat(val, 'f', m.VolumePrecision, 64)
}
func (m Market) CanonicalizeVolume(val float64) float64 {
p := math.Pow10(m.VolumePrecision)
return math.Trunc(p * val) / p
}
// Binance Markets, this should be defined per exchange
var MarketBTCUSDT = Market{
Symbol: "BTCUSDT",
BaseCurrency: "BTC",
QuoteCurrency: "USDT",
PricePrecision: 2,
VolumePrecision: 6,
MinQuantity: 0.00000100,
MinAmount: 10.0,
}
var MarketBNBUSDT = Market{
Symbol: "BNBUSDT",
BaseCurrency: "BNB",
QuoteCurrency: "USDT",
PricePrecision: 4,
VolumePrecision: 2,
MinQuantity: 0.01,
MinAmount: 10.0,
}
var Markets = map[string]Market{
"BNBUSDT": MarketBNBUSDT,
"BTCUSDT": MarketBTCUSDT,
}
func FindMarket(symbol string) (m Market, ok bool) {
m, ok = Markets[symbol]
return m, ok
}

View File

@ -1,8 +1,11 @@
package bbgo
import (
types2 "github.com/c9s/bbgo/pkg/bbgo/types"
"github.com/c9s/bbgo/pkg/bbgo/types"
"github.com/c9s/bbgo/pkg/slack/slackstyle"
log "github.com/sirupsen/logrus"
"github.com/slack-go/slack"
"strconv"
"strings"
"time"
)
@ -11,12 +14,12 @@ type ProfitAndLossCalculator struct {
Symbol string
StartTime time.Time
CurrentPrice float64
Trades []types2.Trade
Trades []types.Trade
CurrencyPrice map[string]float64
}
func (c *ProfitAndLossCalculator) AddTrade(trade types2.Trade) {
func (c *ProfitAndLossCalculator) AddTrade(trade types.Trade) {
c.Trades = append(c.Trades, trade)
}
@ -129,3 +132,33 @@ func (report ProfitAndLossReport) Print() {
log.Infof("overall profit: %s", USD.FormatMoneyFloat64(report.Profit))
}
func (report ProfitAndLossReport) SlackAttachment() slack.Attachment {
var color = ""
if report.Profit > 0 {
color = slackstyle.Green
} else {
color = slackstyle.Red
}
market, ok := types.FindMarket(report.Symbol)
if !ok {
return slack.Attachment{}
}
return slack.Attachment{
Title: "Profit and Loss report of " + report.Symbol,
Color: color,
// Pretext: "",
// Text: "",
Fields: []slack.AttachmentField{
{Title: "Symbol", Value: report.Symbol, Short: true,},
{Title: "Profit", Value: USD.FormatMoney(report.Profit), Short: true,},
{Title: "Current Price", Value: USD.FormatMoney(report.CurrentPrice), Short: true,},
{Title: "Average Bid Price", Value: USD.FormatMoney(report.AverageBidPrice), Short: true,},
{Title: "Current Stock", Value: market.FormatVolume(report.Stock), Short: true,},
{Title: "Number of Trades", Value: strconv.Itoa(report.NumTrades), Short: true,},
},
Footer: report.StartTime.Format(time.RFC822),
FooterIcon: "",
}
}

View File

@ -3,7 +3,6 @@ package bbgo
import (
"context"
"fmt"
"strconv"
"time"
"github.com/leekchan/accounting"
@ -19,6 +18,88 @@ import (
var USD = accounting.Accounting{Symbol: "$ ", Precision: 2}
var BTC = accounting.Accounting{Symbol: "BTC ", Precision: 8}
type SlackReporter struct {
Slack *slack.Client
TradingChannel string
ErrorChannel string
InfoChannel string
}
func (t *SlackReporter) Infof(format string, args ...interface{}) {
var slackAttachments []slack.Attachment = nil
var slackArgsStartIdx = -1
for idx, arg := range args {
switch a := arg.(type) {
// concrete type assert first
case slack.Attachment:
if slackArgsStartIdx == -1 {
slackArgsStartIdx = idx
}
slackAttachments = append(slackAttachments, a)
case slackstyle.SlackAttachmentCreator:
if slackArgsStartIdx == -1 {
slackArgsStartIdx = idx
}
slackAttachments = append(slackAttachments, a.SlackAttachment())
}
}
var nonSlackArgs = []interface{}{}
if slackArgsStartIdx > 0 {
nonSlackArgs = args[:slackArgsStartIdx]
}
log.Infof(format, nonSlackArgs...)
_, _, err := t.Slack.PostMessageContext(context.Background(), t.InfoChannel,
slack.MsgOptionText(fmt.Sprintf(format, nonSlackArgs...), true),
slack.MsgOptionAttachments(slackAttachments...))
if err != nil {
log.WithError(err).Errorf("slack error: %s", err.Error())
}
}
func (t *SlackReporter) Errorf(err error, format string, args ...interface{}) {
log.WithError(err).Errorf(format, args...)
_, _, err2 := t.Slack.PostMessageContext(context.Background(), t.ErrorChannel,
slack.MsgOptionText("ERROR: "+err.Error()+" "+fmt.Sprintf(format, args...), true))
if err2 != nil {
log.WithError(err2).Error("slack error:", err2)
}
}
func (t *SlackReporter) ReportTrade(trade *types.Trade) {
_, _, err := t.Slack.PostMessageContext(context.Background(), t.TradingChannel,
slack.MsgOptionText(util.Render(`:handshake: trade execution @ {{ .Price }}`, trade), true),
slack.MsgOptionAttachments(trade.SlackAttachment()))
if err != nil {
t.Errorf(err, "slack send error")
}
}
func (t *SlackReporter) ReportPnL(report *ProfitAndLossReport) {
attachment := report.SlackAttachment()
_, _, err := t.Slack.PostMessageContext(context.Background(), t.TradingChannel,
slack.MsgOptionText(util.Render(
`:heavy_dollar_sign: Here is your *{{ .symbol }}* PnL report collected since *{{ .startTime }}*`,
map[string]interface{}{
"symbol": report.Symbol,
"startTime": report.StartTime.Format(time.RFC822),
}), true),
slack.MsgOptionAttachments(attachment))
if err != nil {
t.Errorf(err, "slack send error")
}
}
type Trader struct {
// Context is trading Context
Context *TradingContext
@ -87,7 +168,7 @@ func (t *Trader) ReportTrade(trade *types.Trade) {
}
_, _, err := t.Slack.PostMessageContext(context.Background(), t.TradingChannel,
slack.MsgOptionText(util.Render(`:handshake: trade execution`, trade), true),
slack.MsgOptionText(util.Render(`:handshake: Trade execution @ {{ .Price }}`, trade), true),
slack.MsgOptionAttachments(slack.Attachment{
Title: "New Trade",
Color: color,
@ -104,72 +185,27 @@ func (t *Trader) ReportTrade(trade *types.Trade) {
}))
if err != nil {
t.Errorf(err, "Slack send error")
t.Errorf(err, "slack send error")
}
}
func (t *Trader) ReportPnL() {
tradingCtx := t.Context
report := tradingCtx.ProfitAndLossCalculator.Calculate()
report := t.Context.ProfitAndLossCalculator.Calculate()
report.Print()
var color = ""
if report.Profit > 0 {
color = slackstyle.Green
} else {
color = slackstyle.Red
}
attachment := report.SlackAttachment()
_, _, err := t.Slack.PostMessageContext(context.Background(), t.TradingChannel,
slack.MsgOptionText(util.Render(
`:heavy_dollar_sign: Here is your *{{ .symbol }}* PnL report collected since *{{ .startTime }}*`,
map[string]interface{}{
"symbol": tradingCtx.Symbol,
"symbol": report.Symbol,
"startTime": report.StartTime.Format(time.RFC822),
}), true),
slack.MsgOptionAttachments(slack.Attachment{
Title: "Profit and Loss report",
Color: color,
// Pretext: "",
// Text: "",
Fields: []slack.AttachmentField{
{
Title: "Symbol",
Value: tradingCtx.Symbol,
Short: true,
},
{
Title: "Profit",
Value: USD.FormatMoney(report.Profit),
Short: true,
},
{
Title: "Current Price",
Value: USD.FormatMoney(report.CurrentPrice),
Short: true,
},
{
Title: "Average Bid Price",
Value: USD.FormatMoney(report.AverageBidPrice),
Short: true,
},
{
Title: "Current Stock",
Value: tradingCtx.Market.FormatVolume(report.Stock),
Short: true,
},
{
Title: "Number of Trades",
Value: strconv.Itoa(report.NumTrades),
Short: true,
},
},
Footer: report.StartTime.Format(time.RFC822),
FooterIcon: "",
}))
slack.MsgOptionAttachments(attachment))
if err != nil {
t.Errorf(err, "Slack send error")
t.Errorf(err, "slack send error")
}
}

59
bbgo/types/market.go Normal file
View File

@ -0,0 +1,59 @@
package types
import (
"math"
"strconv"
)
type Market struct {
Symbol string
PricePrecision int
VolumePrecision int
QuoteCurrency string
BaseCurrency string
MinQuantity float64
MinAmount float64
}
func (m Market) FormatPrice(val float64) string {
return strconv.FormatFloat(val, 'f', m.PricePrecision, 64)
}
func (m Market) FormatVolume(val float64) string {
return strconv.FormatFloat(val, 'f', m.VolumePrecision, 64)
}
func (m Market) CanonicalizeVolume(val float64) float64 {
p := math.Pow10(m.VolumePrecision)
return math.Trunc(p*val) / p
}
var MarketBTCUSDT = Market{
Symbol: "BTCUSDT",
BaseCurrency: "BTC",
QuoteCurrency: "USDT",
PricePrecision: 2,
VolumePrecision: 6,
MinQuantity: 0.00000100,
MinAmount: 10.0,
}
var MarketBNBUSDT = Market{
Symbol: "BNBUSDT",
BaseCurrency: "BNB",
QuoteCurrency: "USDT",
PricePrecision: 4,
VolumePrecision: 2,
MinQuantity: 0.01,
MinAmount: 10.0,
}
var Markets = map[string]Market{
"BNBUSDT": MarketBNBUSDT,
"BTCUSDT": MarketBTCUSDT,
}
func FindMarket(symbol string) (m Market, ok bool) {
m, ok = Markets[symbol]
return m, ok
}

View File

@ -1,6 +1,9 @@
package types
import "time"
import (
"github.com/slack-go/slack"
"time"
)
type Trade struct {
ID int64
@ -14,3 +17,35 @@ type Trade struct {
Fee float64
FeeCurrency string
}
func (trade Trade) SlackAttachment() slack.Attachment {
var color = ""
if trade.IsBuyer {
color = "#228B22"
} else {
color = "#DC143C"
}
market, ok := FindMarket(trade.Symbol)
if !ok {
return slack.Attachment{
Title: "New Trade",
Color: color,
}
}
return slack.Attachment{
Title: "New Trade",
Color: color,
// Pretext: "",
// Text: "",
Fields: []slack.AttachmentField{
{Title: "Symbol", Value: trade.Symbol, Short: true,},
{Title: "Side", Value: trade.Side, Short: true,},
{Title: "Price", Value: market.FormatPrice(trade.Price), Short: true,},
{Title: "Volume", Value: market.FormatVolume(trade.Volume), Short: true,},
},
// Footer: tradingCtx.TradeStartTime.Format(time.RFC822),
// FooterIcon: "",
}
}