fix stream issue and pnl issues

This commit is contained in:
c9s 2020-07-11 12:07:24 +08:00
parent 19b225737f
commit 0e9bd1547d
2 changed files with 22 additions and 18 deletions

View File

@ -7,6 +7,7 @@ import (
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"strconv"
"strings"
"time"
)
@ -30,11 +31,12 @@ type Subscription struct {
}
func (s *Subscription) String() string {
return fmt.Sprintf("%s@%s_%s", s.Symbol, s.Channel, s.Options.String())
return fmt.Sprintf("%s@%s_%s", strings.ToLower(s.Symbol), s.Channel, s.Options.String())
}
type StreamCommand struct {
ID int `json:"id,omitempty"`
type StreamRequest struct {
// request ID is required
ID int `json:"id"`
Method string `json:"method"`
Params []string `json:"params"`
}
@ -70,16 +72,13 @@ func (s *PrivateStream) Connect(ctx context.Context) error {
}
log.Infof("[binance] subscribing channels: %+v", params)
err = conn.WriteJSON(StreamCommand{
err = conn.WriteJSON(StreamRequest{
Method: "SUBSCRIBE",
Params: params,
ID: 1,
})
if err != nil {
return err
}
return nil
return err
}
func (s *PrivateStream) Read(ctx context.Context, eventC chan interface{}) {
@ -101,16 +100,21 @@ func (s *PrivateStream) Read(ctx context.Context, eventC chan interface{}) {
}
default:
if err := s.Conn.SetReadDeadline(time.Now().Add(time.Minute)); err != nil {
log.WithError(err).Errorf("set read deadline error", err)
if err := s.Conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil {
log.WithError(err).Errorf("set read deadline error: %s", err.Error())
}
_, message, err := s.Conn.ReadMessage()
mt, message, err := s.Conn.ReadMessage()
if err != nil {
log.WithError(err).Errorf("read error", err)
log.WithError(err).Errorf("read error: %s", err.Error())
return
}
// skip non-text messages
if mt != websocket.TextMessage {
continue
}
log.Debugf("[binance] recv: %s", message)
e, err := parseEvent(string(message))

View File

@ -99,8 +99,9 @@ func (c *ProfitAndLossCalculator) Calculate() *ProfitAndLossReport {
fee := bidFee + askFee + futureFee
return &ProfitAndLossReport{
CurrentPrice: c.CurrentPrice,
Symbol: c.Symbol,
StartTime: c.StartTime,
CurrentPrice: c.CurrentPrice,
NumTrades: len(trades),
Profit: profit,
@ -113,6 +114,7 @@ func (c *ProfitAndLossCalculator) Calculate() *ProfitAndLossReport {
type ProfitAndLossReport struct {
CurrentPrice float64
StartTime time.Time
Symbol string
NumTrades int
Profit float64
@ -124,10 +126,8 @@ type ProfitAndLossReport struct {
func (report ProfitAndLossReport) Print() {
log.Infof("trades since: %v", report.StartTime)
log.Infof("average bid price: %s", USD.FormatMoneyFloat64(report.AverageBidPrice))
log.Infof("Stock volume: %f", report.Stock)
log.Infof("stock volume: %f", report.Stock)
log.Infof("current price: %s", USD.FormatMoneyFloat64(report.CurrentPrice))
log.Infof("overall profit: %s", USD.FormatMoneyFloat64(report.Profit))
}
func CalculateCostAndProfit(trades []Trade, currentPrice float64, startTime time.Time) (report *ProfitAndLossReport) {
}