2022-04-14 11:01:13 +00:00
|
|
|
package ewoDgtrd
|
2022-04-07 10:25:02 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-05-24 13:55:43 +00:00
|
|
|
"errors"
|
2022-04-14 10:58:05 +00:00
|
|
|
"fmt"
|
2022-05-31 12:36:37 +00:00
|
|
|
"math"
|
2022-06-13 03:08:08 +00:00
|
|
|
"os"
|
2022-06-06 10:10:46 +00:00
|
|
|
"sync"
|
2022-04-07 10:25:02 +00:00
|
|
|
|
2022-05-25 07:11:19 +00:00
|
|
|
"github.com/fatih/color"
|
2022-04-07 10:25:02 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2022-04-11 08:07:52 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2022-04-07 10:25:02 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/indicator"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
const ID = "ewo_dgtrd"
|
2022-05-30 03:45:52 +00:00
|
|
|
|
2022-04-07 10:25:02 +00:00
|
|
|
var log = logrus.WithField("strategy", ID)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
|
|
|
type Strategy struct {
|
2022-05-24 07:19:00 +00:00
|
|
|
Position *types.Position `json:"position,omitempty" persistence:"position"`
|
|
|
|
ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
|
2022-05-13 13:58:35 +00:00
|
|
|
|
2022-06-09 10:31:02 +00:00
|
|
|
Market types.Market
|
|
|
|
Session *bbgo.ExchangeSession
|
|
|
|
UseHeikinAshi bool `json:"useHeikinAshi"` // use heikinashi kline
|
|
|
|
Stoploss fixedpoint.Value `json:"stoploss"`
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
Interval types.Interval `json:"interval"`
|
2022-06-13 03:08:08 +00:00
|
|
|
UseEma bool `json:"useEma"` // use exponential ma or not
|
|
|
|
UseSma bool `json:"useSma"` // if UseEma == false, use simple ma or not
|
|
|
|
SignalWindow int `json:"sigWin"` // signal window
|
|
|
|
DisableShortStop bool `json:"disableShortStop"` // disable SL on short
|
|
|
|
DisableLongStop bool `json:"disableLongStop"` // disable SL on long
|
|
|
|
FilterHigh float64 `json:"cciStochFilterHigh"` // high filter for CCI Stochastic indicator
|
|
|
|
FilterLow float64 `json:"cciStochFilterLow"` // low filter for CCI Stochastic indicator
|
|
|
|
EwoChangeFilterHigh float64 `json:"ewoChangeFilterHigh"` // high filter for ewo histogram
|
|
|
|
EwoChangeFilterLow float64 `json:"ewoChangeFilterLow"` // low filter for ewo histogram
|
2022-04-14 10:58:05 +00:00
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
Record bool `json:"record"` // print record messages on position exit point
|
|
|
|
|
2022-05-13 13:58:35 +00:00
|
|
|
KLineStartTime types.Time
|
|
|
|
KLineEndTime types.Time
|
|
|
|
|
|
|
|
*bbgo.Environment
|
2022-04-13 01:43:31 +00:00
|
|
|
*bbgo.Graceful
|
2022-05-13 13:58:35 +00:00
|
|
|
bbgo.StrategyController
|
|
|
|
|
2022-06-05 21:43:38 +00:00
|
|
|
activeMakerOrders *bbgo.ActiveOrderBook
|
2022-05-13 13:58:35 +00:00
|
|
|
orderStore *bbgo.OrderStore
|
|
|
|
tradeCollector *bbgo.TradeCollector
|
2022-05-30 03:45:52 +00:00
|
|
|
entryPrice fixedpoint.Value
|
|
|
|
waitForTrade bool
|
2022-05-13 13:58:35 +00:00
|
|
|
|
2022-06-06 10:10:46 +00:00
|
|
|
atr *indicator.ATR
|
|
|
|
emv *indicator.EMV
|
|
|
|
ccis *CCISTOCH
|
|
|
|
ma5 types.Series
|
|
|
|
ma34 types.Series
|
|
|
|
ewo types.Series
|
|
|
|
ewoSignal types.Series
|
|
|
|
ewoHistogram types.Series
|
2022-05-31 12:36:37 +00:00
|
|
|
ewoChangeRate float64
|
2022-06-06 10:10:46 +00:00
|
|
|
heikinAshi *HeikinAshi
|
|
|
|
peakPrice fixedpoint.Value
|
|
|
|
bottomPrice fixedpoint.Value
|
|
|
|
midPrice fixedpoint.Value
|
|
|
|
lock sync.RWMutex
|
2022-05-13 13:58:35 +00:00
|
|
|
|
|
|
|
buyPrice fixedpoint.Value
|
|
|
|
sellPrice fixedpoint.Value
|
2022-04-07 10:25:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
2022-05-12 11:02:34 +00:00
|
|
|
func (s *Strategy) InstanceID() string {
|
|
|
|
return fmt.Sprintf("%s:%s", ID, s.Symbol)
|
|
|
|
}
|
|
|
|
|
2022-04-13 01:43:31 +00:00
|
|
|
func (s *Strategy) Initialize() error {
|
2022-05-24 07:19:00 +00:00
|
|
|
return nil
|
2022-04-13 01:43:31 +00:00
|
|
|
}
|
|
|
|
|
2022-04-07 10:25:02 +00:00
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
|
|
|
log.Infof("subscribe %s", s.Symbol)
|
2022-05-19 01:48:36 +00:00
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1m})
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
|
2022-05-12 10:40:48 +00:00
|
|
|
|
2022-05-13 13:58:35 +00:00
|
|
|
session.Subscribe(types.BookTickerChannel, s.Symbol, types.SubscribeOptions{})
|
2022-04-07 10:25:02 +00:00
|
|
|
}
|
|
|
|
|
2022-04-14 10:58:05 +00:00
|
|
|
type UpdatableSeries interface {
|
2022-04-07 10:25:02 +00:00
|
|
|
types.Series
|
|
|
|
Update(value float64)
|
|
|
|
}
|
|
|
|
|
2022-05-13 13:58:35 +00:00
|
|
|
// Refer: https://tw.tradingview.com/script/XZyG5SOx-CCI-Stochastic-and-a-quick-lesson-on-Scalping-Trading-Systems/
|
|
|
|
type CCISTOCH struct {
|
2022-05-24 07:19:00 +00:00
|
|
|
cci *indicator.CCI
|
|
|
|
stoch *indicator.STOCH
|
|
|
|
ma *indicator.SMA
|
|
|
|
filterHigh float64
|
|
|
|
filterLow float64
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
2022-05-24 07:19:00 +00:00
|
|
|
func NewCCISTOCH(i types.Interval, filterHigh, filterLow float64) *CCISTOCH {
|
|
|
|
cci := &indicator.CCI{IntervalWindow: types.IntervalWindow{Interval: i, Window: 28}}
|
|
|
|
stoch := &indicator.STOCH{IntervalWindow: types.IntervalWindow{Interval: i, Window: 28}}
|
|
|
|
ma := &indicator.SMA{IntervalWindow: types.IntervalWindow{Interval: i, Window: 3}}
|
2022-05-13 13:58:35 +00:00
|
|
|
return &CCISTOCH{
|
2022-05-24 07:19:00 +00:00
|
|
|
cci: cci,
|
|
|
|
stoch: stoch,
|
|
|
|
ma: ma,
|
|
|
|
filterHigh: filterHigh,
|
|
|
|
filterLow: filterLow,
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CCISTOCH) Update(cloze float64) {
|
|
|
|
inc.cci.Update(cloze)
|
|
|
|
inc.stoch.Update(inc.cci.Last(), inc.cci.Last(), inc.cci.Last())
|
|
|
|
inc.ma.Update(inc.stoch.LastD())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CCISTOCH) BuySignal() bool {
|
|
|
|
hasGrey := false
|
|
|
|
for i := 0; i < len(inc.ma.Values); i++ {
|
|
|
|
v := inc.ma.Index(i)
|
2022-05-24 07:19:00 +00:00
|
|
|
if v > inc.filterHigh {
|
2022-05-13 13:58:35 +00:00
|
|
|
return false
|
2022-05-25 07:11:19 +00:00
|
|
|
} else if v >= inc.filterLow && v <= inc.filterHigh {
|
2022-05-13 13:58:35 +00:00
|
|
|
hasGrey = true
|
|
|
|
continue
|
2022-05-25 07:11:19 +00:00
|
|
|
} else if v < inc.filterLow {
|
2022-05-13 13:58:35 +00:00
|
|
|
return hasGrey
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CCISTOCH) SellSignal() bool {
|
|
|
|
hasGrey := false
|
|
|
|
for i := 0; i < len(inc.ma.Values); i++ {
|
|
|
|
v := inc.ma.Index(i)
|
2022-05-24 07:19:00 +00:00
|
|
|
if v < inc.filterLow {
|
2022-05-13 13:58:35 +00:00
|
|
|
return false
|
2022-05-25 07:11:19 +00:00
|
|
|
} else if v >= inc.filterLow && v <= inc.filterHigh {
|
2022-05-13 13:58:35 +00:00
|
|
|
hasGrey = true
|
|
|
|
continue
|
2022-05-25 07:11:19 +00:00
|
|
|
} else if v > inc.filterHigh {
|
2022-05-13 13:58:35 +00:00
|
|
|
return hasGrey
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-04-15 10:12:11 +00:00
|
|
|
type VWEMA struct {
|
2022-04-14 10:58:05 +00:00
|
|
|
PV UpdatableSeries
|
|
|
|
V UpdatableSeries
|
|
|
|
}
|
|
|
|
|
2022-04-15 10:12:11 +00:00
|
|
|
func (inc *VWEMA) Last() float64 {
|
2022-04-14 10:58:05 +00:00
|
|
|
return inc.PV.Last() / inc.V.Last()
|
|
|
|
}
|
|
|
|
|
2022-04-15 10:12:11 +00:00
|
|
|
func (inc *VWEMA) Index(i int) float64 {
|
2022-04-14 10:58:05 +00:00
|
|
|
if i >= inc.PV.Length() {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
vi := inc.V.Index(i)
|
|
|
|
if vi == 0 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return inc.PV.Index(i) / vi
|
|
|
|
}
|
|
|
|
|
2022-04-15 10:12:11 +00:00
|
|
|
func (inc *VWEMA) Length() int {
|
2022-04-14 10:58:05 +00:00
|
|
|
pvl := inc.PV.Length()
|
|
|
|
vl := inc.V.Length()
|
|
|
|
if pvl < vl {
|
|
|
|
return pvl
|
|
|
|
}
|
|
|
|
return vl
|
|
|
|
}
|
|
|
|
|
2022-04-15 10:12:11 +00:00
|
|
|
func (inc *VWEMA) Update(kline types.KLine) {
|
2022-04-14 10:58:05 +00:00
|
|
|
inc.PV.Update(kline.Close.Mul(kline.Volume).Float64())
|
|
|
|
inc.V.Update(kline.Volume.Float64())
|
|
|
|
}
|
|
|
|
|
2022-04-15 10:12:11 +00:00
|
|
|
func (inc *VWEMA) UpdateVal(price float64, vol float64) {
|
2022-04-14 10:58:05 +00:00
|
|
|
inc.PV.Update(price * vol)
|
|
|
|
inc.V.Update(vol)
|
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
// Setup the Indicators going to be used
|
2022-06-06 10:10:46 +00:00
|
|
|
func (s *Strategy) SetupIndicators(store *bbgo.MarketDataStore) {
|
2022-05-24 07:19:00 +00:00
|
|
|
window5 := types.IntervalWindow{Interval: s.Interval, Window: 5}
|
|
|
|
window34 := types.IntervalWindow{Interval: s.Interval, Window: 34}
|
|
|
|
s.atr = &indicator.ATR{IntervalWindow: window34}
|
2022-05-31 12:36:37 +00:00
|
|
|
s.emv = &indicator.EMV{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: 14}}
|
2022-05-24 07:19:00 +00:00
|
|
|
s.ccis = NewCCISTOCH(s.Interval, s.FilterHigh, s.FilterLow)
|
2022-04-28 11:09:15 +00:00
|
|
|
|
2022-06-06 10:10:46 +00:00
|
|
|
getSource := func(window types.KLineWindow) types.Series {
|
|
|
|
if s.UseHeikinAshi {
|
|
|
|
return s.heikinAshi.Close
|
|
|
|
}
|
|
|
|
return window.Close()
|
|
|
|
}
|
|
|
|
getVol := func(window types.KLineWindow) types.Series {
|
|
|
|
if s.UseHeikinAshi {
|
|
|
|
return s.heikinAshi.Volume
|
|
|
|
}
|
|
|
|
return window.Volume()
|
|
|
|
}
|
|
|
|
s.heikinAshi = NewHeikinAshi(500)
|
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if interval == s.atr.Interval {
|
|
|
|
if s.atr.RMA == nil {
|
|
|
|
for _, kline := range window {
|
2022-05-31 12:36:37 +00:00
|
|
|
high := kline.High.Float64()
|
|
|
|
low := kline.Low.Float64()
|
|
|
|
cloze := kline.Close.Float64()
|
|
|
|
vol := kline.Volume.Float64()
|
|
|
|
s.atr.Update(high, low, cloze)
|
|
|
|
s.emv.Update(high, low, vol)
|
2022-05-11 11:56:56 +00:00
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
} else {
|
|
|
|
kline := window[len(window)-1]
|
|
|
|
high := kline.High.Float64()
|
|
|
|
low := kline.Low.Float64()
|
|
|
|
cloze := kline.Close.Float64()
|
|
|
|
vol := kline.Volume.Float64()
|
|
|
|
s.atr.Update(high, low, cloze)
|
|
|
|
s.emv.Update(high, low, vol)
|
2022-05-11 11:56:56 +00:00
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
}
|
|
|
|
if s.Interval != interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.heikinAshi.Close.Length() == 0 {
|
|
|
|
for _, kline := range window {
|
|
|
|
s.heikinAshi.Update(kline)
|
|
|
|
s.ccis.Update(getSource(window).Last())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
s.heikinAshi.Update(window[len(window)-1])
|
|
|
|
s.ccis.Update(getSource(window).Last())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
if s.UseEma {
|
|
|
|
ema5 := &indicator.EWMA{IntervalWindow: window5}
|
|
|
|
ema34 := &indicator.EWMA{IntervalWindow: window34}
|
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
2022-04-14 10:58:05 +00:00
|
|
|
if s.Interval != interval {
|
|
|
|
return
|
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
if ema5.Length() == 0 {
|
2022-06-29 02:13:43 +00:00
|
|
|
closes := types.Reverse(getSource(window))
|
2022-06-06 10:10:46 +00:00
|
|
|
for _, cloze := range closes {
|
|
|
|
ema5.Update(cloze)
|
|
|
|
ema34.Update(cloze)
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
|
|
|
} else {
|
2022-06-06 10:10:46 +00:00
|
|
|
cloze := getSource(window).Last()
|
|
|
|
ema5.Update(cloze)
|
|
|
|
ema34.Update(cloze)
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
|
2022-04-14 10:58:05 +00:00
|
|
|
})
|
2022-06-06 10:10:46 +00:00
|
|
|
|
|
|
|
s.ma5 = ema5
|
|
|
|
s.ma34 = ema34
|
|
|
|
} else if s.UseSma {
|
|
|
|
sma5 := &indicator.SMA{IntervalWindow: window5}
|
|
|
|
sma34 := &indicator.SMA{IntervalWindow: window34}
|
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if s.Interval != interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if sma5.Length() == 0 {
|
2022-06-29 02:13:43 +00:00
|
|
|
closes := types.Reverse(getSource(window))
|
2022-06-06 10:10:46 +00:00
|
|
|
for _, cloze := range closes {
|
2022-04-14 10:58:05 +00:00
|
|
|
sma5.Update(cloze)
|
|
|
|
sma34.Update(cloze)
|
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
} else {
|
|
|
|
cloze := getSource(window).Last()
|
|
|
|
sma5.Update(cloze)
|
|
|
|
sma34.Update(cloze)
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
})
|
|
|
|
s.ma5 = sma5
|
|
|
|
s.ma34 = sma34
|
2022-04-14 10:58:05 +00:00
|
|
|
} else {
|
2022-06-06 10:10:46 +00:00
|
|
|
evwma5 := &VWEMA{
|
|
|
|
PV: &indicator.EWMA{IntervalWindow: window5},
|
|
|
|
V: &indicator.EWMA{IntervalWindow: window5},
|
|
|
|
}
|
|
|
|
evwma34 := &VWEMA{
|
|
|
|
PV: &indicator.EWMA{IntervalWindow: window34},
|
|
|
|
V: &indicator.EWMA{IntervalWindow: window34},
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
2022-05-13 13:58:35 +00:00
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if s.Interval != interval {
|
|
|
|
return
|
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
clozes := getSource(window)
|
|
|
|
vols := getVol(window)
|
|
|
|
if evwma5.PV.Length() == 0 {
|
|
|
|
for i := clozes.Length() - 1; i >= 0; i-- {
|
|
|
|
price := clozes.Index(i)
|
|
|
|
vol := vols.Index(i)
|
|
|
|
evwma5.UpdateVal(price, vol)
|
|
|
|
evwma34.UpdateVal(price, vol)
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
} else {
|
2022-06-06 10:10:46 +00:00
|
|
|
price := clozes.Last()
|
|
|
|
vol := vols.Last()
|
|
|
|
evwma5.UpdateVal(price, vol)
|
|
|
|
evwma34.UpdateVal(price, vol)
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
})
|
2022-06-06 10:10:46 +00:00
|
|
|
s.ma5 = evwma5
|
|
|
|
s.ma34 = evwma34
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s.ewo = types.Mul(types.Minus(types.Div(s.ma5, s.ma34), 1.0), 100.)
|
2022-05-31 12:36:37 +00:00
|
|
|
s.ewoHistogram = types.Minus(s.ma5, s.ma34)
|
2022-05-24 07:19:00 +00:00
|
|
|
windowSignal := types.IntervalWindow{Interval: s.Interval, Window: s.SignalWindow}
|
2022-04-14 10:58:05 +00:00
|
|
|
if s.UseEma {
|
2022-05-24 07:19:00 +00:00
|
|
|
sig := &indicator.EWMA{IntervalWindow: windowSignal}
|
2022-04-14 10:58:05 +00:00
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, _ types.KLineWindow) {
|
|
|
|
if interval != s.Interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if sig.Length() == 0 {
|
|
|
|
// lazy init
|
2022-06-29 02:13:43 +00:00
|
|
|
ewoVals := types.Reverse(s.ewo)
|
2022-04-14 10:58:05 +00:00
|
|
|
for _, ewoValue := range ewoVals {
|
|
|
|
sig.Update(ewoValue)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
sig.Update(s.ewo.Last())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
s.ewoSignal = sig
|
|
|
|
} else if s.UseSma {
|
2022-05-24 07:19:00 +00:00
|
|
|
sig := &indicator.SMA{IntervalWindow: windowSignal}
|
2022-04-14 10:58:05 +00:00
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, _ types.KLineWindow) {
|
|
|
|
if interval != s.Interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if sig.Length() == 0 {
|
|
|
|
// lazy init
|
2022-06-29 02:13:43 +00:00
|
|
|
ewoVals := types.Reverse(s.ewo)
|
2022-04-14 10:58:05 +00:00
|
|
|
for _, ewoValue := range ewoVals {
|
|
|
|
sig.Update(ewoValue)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
sig.Update(s.ewo.Last())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
s.ewoSignal = sig
|
|
|
|
} else {
|
2022-04-15 10:12:11 +00:00
|
|
|
sig := &VWEMA{
|
2022-05-24 07:19:00 +00:00
|
|
|
PV: &indicator.EWMA{IntervalWindow: windowSignal},
|
|
|
|
V: &indicator.EWMA{IntervalWindow: windowSignal},
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if interval != s.Interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if sig.Length() == 0 {
|
|
|
|
// lazy init
|
2022-06-29 02:13:43 +00:00
|
|
|
ewoVals := types.Reverse(s.ewo)
|
2022-04-14 10:58:05 +00:00
|
|
|
for i, ewoValue := range ewoVals {
|
2022-06-06 10:10:46 +00:00
|
|
|
vol := window.Volume().Index(i)
|
2022-04-14 10:58:05 +00:00
|
|
|
sig.PV.Update(ewoValue * vol)
|
|
|
|
sig.V.Update(vol)
|
|
|
|
}
|
|
|
|
} else {
|
2022-06-06 10:10:46 +00:00
|
|
|
vol := window.Volume().Last()
|
2022-04-14 10:58:05 +00:00
|
|
|
sig.PV.Update(s.ewo.Last() * vol)
|
|
|
|
sig.V.Update(vol)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
s.ewoSignal = sig
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
// Utility to evaluate if the order is valid or not to send to the exchange
|
2022-05-24 13:55:43 +00:00
|
|
|
func (s *Strategy) validateOrder(order *types.SubmitOrder) error {
|
2022-04-13 12:08:59 +00:00
|
|
|
if order.Type == types.OrderTypeMarket && order.TimeInForce != "" {
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("wrong field: market vs TimeInForce")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
if order.Side == types.SideTypeSell {
|
2022-04-23 07:43:11 +00:00
|
|
|
baseBalance, ok := s.Session.GetAccount().Balance(s.Market.BaseCurrency)
|
2022-04-13 12:08:59 +00:00
|
|
|
if !ok {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Error("cannot get account")
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("cannot get account")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
if order.Quantity.Compare(baseBalance.Available) > 0 {
|
2022-05-30 03:45:52 +00:00
|
|
|
log.Errorf("qty %v > avail %v", order.Quantity, baseBalance.Available)
|
|
|
|
return errors.New("qty > avail")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
price := order.Price
|
|
|
|
if price.IsZero() {
|
2022-04-14 10:58:05 +00:00
|
|
|
price, ok = s.Session.LastPrice(s.Symbol)
|
2022-04-13 12:08:59 +00:00
|
|
|
if !ok {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Error("no price")
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("no price")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
orderAmount := order.Quantity.Mul(price)
|
|
|
|
if order.Quantity.Sign() <= 0 ||
|
2022-04-14 10:58:05 +00:00
|
|
|
order.Quantity.Compare(s.Market.MinQuantity) < 0 ||
|
|
|
|
orderAmount.Compare(s.Market.MinNotional) < 0 {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Debug("amount fail")
|
2022-06-17 11:19:51 +00:00
|
|
|
return fmt.Errorf("amount fail: quantity: %v, amount: %v", order.Quantity, orderAmount)
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
return nil
|
2022-04-13 12:08:59 +00:00
|
|
|
} else if order.Side == types.SideTypeBuy {
|
2022-04-23 07:43:11 +00:00
|
|
|
quoteBalance, ok := s.Session.GetAccount().Balance(s.Market.QuoteCurrency)
|
2022-04-13 12:08:59 +00:00
|
|
|
if !ok {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Error("cannot get account")
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("cannot get account")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
price := order.Price
|
|
|
|
if price.IsZero() {
|
2022-04-14 10:58:05 +00:00
|
|
|
price, ok = s.Session.LastPrice(s.Symbol)
|
2022-04-13 12:08:59 +00:00
|
|
|
if !ok {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Error("no price")
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("no price")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
totalQuantity := quoteBalance.Available.Div(price)
|
|
|
|
if order.Quantity.Compare(totalQuantity) > 0 {
|
2022-05-30 03:45:52 +00:00
|
|
|
log.Errorf("qty %v > avail %v", order.Quantity, totalQuantity)
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("qty > avail")
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
|
|
|
orderAmount := order.Quantity.Mul(price)
|
|
|
|
if order.Quantity.Sign() <= 0 ||
|
2022-04-14 10:58:05 +00:00
|
|
|
orderAmount.Compare(s.Market.MinNotional) < 0 ||
|
|
|
|
order.Quantity.Compare(s.Market.MinQuantity) < 0 {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Debug("amount fail")
|
2022-06-17 11:19:51 +00:00
|
|
|
return fmt.Errorf("amount fail: quantity: %v, amount: %v", order.Quantity, orderAmount)
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
return nil
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Error("side error")
|
2022-05-24 13:55:43 +00:00
|
|
|
return errors.New("side error")
|
2022-04-13 12:08:59 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
func (s *Strategy) PlaceBuyOrder(ctx context.Context, price fixedpoint.Value) (*types.Order, *types.Order) {
|
|
|
|
var closeOrder *types.Order
|
|
|
|
var ok bool
|
|
|
|
waitForTrade := false
|
|
|
|
base := s.Position.GetBase()
|
|
|
|
if base.Abs().Compare(s.Market.MinQuantity) >= 0 && base.Mul(s.GetLastPrice()).Abs().Compare(s.Market.MinNotional) >= 0 && base.Sign() < 0 {
|
|
|
|
if closeOrder, ok = s.ClosePosition(ctx); !ok {
|
|
|
|
log.Errorf("sell position %v remained not closed, skip placing order", base)
|
|
|
|
return closeOrder, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if s.Position.GetBase().Sign() < 0 {
|
|
|
|
// we are not able to make close trade at this moment,
|
|
|
|
// will close the rest of the position by normal limit order
|
|
|
|
// s.entryPrice is set in the last trade
|
|
|
|
waitForTrade = true
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
quoteBalance, ok := s.Session.GetAccount().Balance(s.Market.QuoteCurrency)
|
|
|
|
if !ok {
|
|
|
|
log.Infof("buy order at price %v failed", price)
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, nil
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
quantityAmount := quoteBalance.Available
|
|
|
|
totalQuantity := quantityAmount.Div(price)
|
|
|
|
order := types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeBuy,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Price: price,
|
|
|
|
Quantity: totalQuantity,
|
|
|
|
Market: s.Market,
|
|
|
|
TimeInForce: types.TimeInForceGTC,
|
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
if err := s.validateOrder(&order); err != nil {
|
|
|
|
log.Infof("validation failed %v: %v", order, err)
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, nil
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
log.Warnf("long at %v, position %v, closeOrder %v, timestamp: %s", price, s.Position.GetBase(), closeOrder, s.KLineStartTime)
|
2022-05-13 13:58:35 +00:00
|
|
|
createdOrders, err := s.Session.Exchange.SubmitOrders(ctx, order)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("cannot place order")
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, nil
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
|
|
|
|
log.Infof("post order c: %v, entryPrice: %v o: %v", waitForTrade, s.entryPrice, createdOrders)
|
|
|
|
s.waitForTrade = waitForTrade
|
2022-05-13 13:58:35 +00:00
|
|
|
s.orderStore.Add(createdOrders...)
|
|
|
|
s.activeMakerOrders.Add(createdOrders...)
|
|
|
|
s.tradeCollector.Process()
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, &createdOrders[0]
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
func (s *Strategy) PlaceSellOrder(ctx context.Context, price fixedpoint.Value) (*types.Order, *types.Order) {
|
|
|
|
var closeOrder *types.Order
|
|
|
|
var ok bool
|
|
|
|
waitForTrade := false
|
|
|
|
base := s.Position.GetBase()
|
|
|
|
if base.Abs().Compare(s.Market.MinQuantity) >= 0 && base.Abs().Mul(s.GetLastPrice()).Compare(s.Market.MinNotional) >= 0 && base.Sign() > 0 {
|
|
|
|
if closeOrder, ok = s.ClosePosition(ctx); !ok {
|
|
|
|
log.Errorf("buy position %v remained not closed, skip placing order", base)
|
|
|
|
return closeOrder, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if s.Position.GetBase().Sign() > 0 {
|
|
|
|
// we are not able to make close trade at this moment,
|
|
|
|
// will close the rest of the position by normal limit order
|
|
|
|
// s.entryPrice is set in the last trade
|
|
|
|
waitForTrade = true
|
|
|
|
}
|
|
|
|
baseBalance, ok := s.Session.GetAccount().Balance(s.Market.BaseCurrency)
|
|
|
|
if !ok {
|
|
|
|
return closeOrder, nil
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
order := types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeSell,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Market: s.Market,
|
2022-05-30 03:45:52 +00:00
|
|
|
Quantity: baseBalance.Available,
|
2022-05-13 13:58:35 +00:00
|
|
|
Price: price,
|
|
|
|
TimeInForce: types.TimeInForceGTC,
|
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
if err := s.validateOrder(&order); err != nil {
|
|
|
|
log.Infof("validation failed %v: %v", order, err)
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, nil
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
log.Warnf("short at %v, position %v closeOrder %v, timestamp: %s", price, s.Position.GetBase(), closeOrder, s.KLineStartTime)
|
2022-05-13 13:58:35 +00:00
|
|
|
createdOrders, err := s.Session.Exchange.SubmitOrders(ctx, order)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("cannot place order")
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, nil
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
log.Infof("post order, c: %v, entryPrice: %v o: %v", waitForTrade, s.entryPrice, createdOrders)
|
|
|
|
s.waitForTrade = waitForTrade
|
2022-05-13 13:58:35 +00:00
|
|
|
s.orderStore.Add(createdOrders...)
|
|
|
|
s.activeMakerOrders.Add(createdOrders...)
|
|
|
|
s.tradeCollector.Process()
|
2022-05-30 03:45:52 +00:00
|
|
|
return closeOrder, &createdOrders[0]
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
// ClosePosition(context.Context) -> (closeOrder *types.Order, ok bool)
|
2022-06-09 09:36:22 +00:00
|
|
|
// this will decorate the generated order from NewMarketCloseOrder
|
2022-05-30 03:45:52 +00:00
|
|
|
// add do necessary checks
|
|
|
|
// if available quantity is zero, will return (nil, true)
|
|
|
|
// if any of the checks failed, will return (nil, false)
|
|
|
|
// otherwise, return the created close order and true
|
|
|
|
func (s *Strategy) ClosePosition(ctx context.Context) (*types.Order, bool) {
|
2022-06-09 09:36:22 +00:00
|
|
|
order := s.Position.NewMarketCloseOrder(fixedpoint.One)
|
2022-05-30 03:45:52 +00:00
|
|
|
// no position exists
|
2022-05-13 13:58:35 +00:00
|
|
|
if order == nil {
|
|
|
|
// no base
|
|
|
|
s.sellPrice = fixedpoint.Zero
|
|
|
|
s.buyPrice = fixedpoint.Zero
|
2022-05-30 03:45:52 +00:00
|
|
|
return nil, true
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
order.TimeInForce = ""
|
2022-05-30 03:45:52 +00:00
|
|
|
// If there's any order not yet been traded in the orderbook,
|
|
|
|
// we need this additional check to make sure we have enough balance to post a close order
|
|
|
|
balances := s.Session.GetAccount().Balances()
|
|
|
|
baseBalance := balances[s.Market.BaseCurrency].Available
|
|
|
|
if order.Side == types.SideTypeBuy {
|
|
|
|
price := s.GetLastPrice()
|
|
|
|
quoteAmount := balances[s.Market.QuoteCurrency].Available.Div(price)
|
|
|
|
if order.Quantity.Compare(quoteAmount) > 0 {
|
|
|
|
order.Quantity = quoteAmount
|
|
|
|
}
|
|
|
|
} else if order.Side == types.SideTypeSell && order.Quantity.Compare(baseBalance) > 0 {
|
|
|
|
order.Quantity = baseBalance
|
|
|
|
}
|
|
|
|
// if no available balance...
|
|
|
|
if order.Quantity.IsZero() {
|
|
|
|
return nil, true
|
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
if err := s.validateOrder(order); err != nil {
|
|
|
|
log.Errorf("cannot place close order %v: %v", order, err)
|
2022-05-30 03:45:52 +00:00
|
|
|
return nil, false
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
createdOrders, err := s.Session.Exchange.SubmitOrders(ctx, *order)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("cannot place close order")
|
2022-05-30 03:45:52 +00:00
|
|
|
return nil, false
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
log.Infof("close order %v", createdOrders)
|
|
|
|
s.orderStore.Add(createdOrders...)
|
|
|
|
s.activeMakerOrders.Add(createdOrders...)
|
|
|
|
s.tradeCollector.Process()
|
2022-05-30 03:45:52 +00:00
|
|
|
return &createdOrders[0], true
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
func (s *Strategy) CancelAll(ctx context.Context) {
|
2022-05-13 13:58:35 +00:00
|
|
|
var toCancel []types.Order
|
|
|
|
for _, order := range s.orderStore.Orders() {
|
2022-05-30 03:45:52 +00:00
|
|
|
if order.Status == types.OrderStatusNew || order.Status == types.OrderStatusPartiallyFilled {
|
2022-05-13 13:58:35 +00:00
|
|
|
toCancel = append(toCancel, order)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(toCancel) > 0 {
|
|
|
|
if err := s.Session.Exchange.CancelOrders(ctx, toCancel...); err != nil {
|
|
|
|
log.WithError(err).Errorf("cancel order error")
|
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
s.waitForTrade = false
|
|
|
|
}
|
|
|
|
}
|
2022-05-13 13:58:35 +00:00
|
|
|
|
2022-05-30 03:45:52 +00:00
|
|
|
func (s *Strategy) GetLastPrice() fixedpoint.Value {
|
|
|
|
var lastPrice fixedpoint.Value
|
|
|
|
var ok bool
|
|
|
|
if s.Environment.IsBackTesting() {
|
|
|
|
lastPrice, ok = s.Session.LastPrice(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("cannot get last price")
|
|
|
|
return lastPrice
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
s.lock.RLock()
|
|
|
|
if s.midPrice.IsZero() {
|
|
|
|
lastPrice, ok = s.Session.LastPrice(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("cannot get last price")
|
|
|
|
return lastPrice
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
lastPrice = s.midPrice
|
|
|
|
}
|
|
|
|
s.lock.RUnlock()
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
return lastPrice
|
2022-05-13 13:58:35 +00:00
|
|
|
}
|
|
|
|
|
2022-04-28 11:09:15 +00:00
|
|
|
// Trading Rules:
|
|
|
|
// - buy / sell the whole asset
|
2022-06-09 10:31:02 +00:00
|
|
|
// - SL by atr (lastprice < buyprice - atr) || (lastprice > sellprice + atr)
|
|
|
|
// - TP by detecting if there's a ewo pivotHigh(1,1) -> close long, or pivotLow(1,1) -> close short
|
|
|
|
// - TP by ma34 +- atr * 2
|
|
|
|
// - TP by (lastprice < peak price - atr) || (lastprice > bottom price + atr)
|
2022-04-28 11:09:15 +00:00
|
|
|
// - SL by s.Stoploss (Abs(price_diff / price) > s.Stoploss)
|
|
|
|
// - entry condition on ewo(Elliott wave oscillator) Crosses ewoSignal(ma on ewo, signalWindow)
|
2022-06-09 10:31:02 +00:00
|
|
|
// * buy signal on (crossover on previous K bar and no crossunder on latest K bar)
|
|
|
|
// * sell signal on (crossunder on previous K bar and no crossunder on latest K bar)
|
2022-04-28 11:09:15 +00:00
|
|
|
// - and filtered by the following rules:
|
2022-06-09 10:31:02 +00:00
|
|
|
// * buy: buy signal ON, kline Close > Open, Close > ma5, Close > ma34, CCI Stochastic Buy signal
|
|
|
|
// * sell: sell signal ON, kline Close < Open, Close < ma5, Close < ma34, CCI Stochastic Sell signal
|
|
|
|
// - or entry when ma34 +- atr * 3 gets touched
|
|
|
|
// - entry price: latestPrice +- atr / 2 (short,long), close at market price
|
|
|
|
// Cancel non-fully filled orders on new signal (either in same direction or not)
|
2022-04-28 11:09:15 +00:00
|
|
|
//
|
|
|
|
// ps: kline might refer to heikinashi or normal ohlc
|
2022-04-07 10:25:02 +00:00
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
2022-05-13 13:58:35 +00:00
|
|
|
s.buyPrice = fixedpoint.Zero
|
|
|
|
s.sellPrice = fixedpoint.Zero
|
2022-04-14 10:58:05 +00:00
|
|
|
s.peakPrice = fixedpoint.Zero
|
|
|
|
s.bottomPrice = fixedpoint.Zero
|
2022-04-13 01:43:31 +00:00
|
|
|
|
2022-05-25 07:11:19 +00:00
|
|
|
counterTPfromPeak := 0
|
|
|
|
percentAvgTPfromPeak := 0.0
|
|
|
|
counterTPfromCCI := 0
|
|
|
|
percentAvgTPfromCCI := 0.0
|
|
|
|
counterTPfromLongShort := 0
|
|
|
|
percentAvgTPfromLongShort := 0.0
|
|
|
|
counterTPfromAtr := 0
|
|
|
|
percentAvgTPfromAtr := 0.0
|
|
|
|
counterTPfromOrder := 0
|
|
|
|
percentAvgTPfromOrder := 0.0
|
|
|
|
counterSLfromSL := 0
|
|
|
|
percentAvgSLfromSL := 0.0
|
|
|
|
counterSLfromOrder := 0
|
|
|
|
percentAvgSLfromOrder := 0.0
|
|
|
|
|
2022-06-05 22:57:25 +00:00
|
|
|
s.activeMakerOrders = bbgo.NewActiveOrderBook(s.Symbol)
|
2022-05-13 13:58:35 +00:00
|
|
|
s.activeMakerOrders.BindStream(session.UserDataStream)
|
|
|
|
|
|
|
|
s.orderStore = bbgo.NewOrderStore(s.Symbol)
|
|
|
|
s.orderStore.BindStream(session.UserDataStream)
|
|
|
|
|
|
|
|
if s.Position == nil {
|
|
|
|
s.Position = types.NewPositionFromMarket(s.Market)
|
2022-04-11 10:55:34 +00:00
|
|
|
}
|
2022-05-13 13:58:35 +00:00
|
|
|
if s.ProfitStats == nil {
|
|
|
|
s.ProfitStats = types.NewProfitStats(s.Market)
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
2022-05-13 13:58:35 +00:00
|
|
|
s.tradeCollector = bbgo.NewTradeCollector(s.Symbol, s.Position, s.orderStore)
|
2022-04-13 01:43:31 +00:00
|
|
|
s.tradeCollector.OnTrade(func(trade types.Trade, profit, netprofit fixedpoint.Value) {
|
2022-05-13 13:58:35 +00:00
|
|
|
if s.Symbol != trade.Symbol {
|
|
|
|
return
|
|
|
|
}
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify(trade)
|
2022-05-13 13:58:35 +00:00
|
|
|
s.ProfitStats.AddTrade(trade)
|
|
|
|
|
2022-04-13 01:43:31 +00:00
|
|
|
if !profit.IsZero() {
|
2022-04-13 12:08:59 +00:00
|
|
|
log.Warnf("generate profit: %v, netprofit: %v, trade: %v", profit, netprofit, trade)
|
2022-05-13 13:58:35 +00:00
|
|
|
p := s.Position.NewProfit(trade, profit, netprofit)
|
|
|
|
p.Strategy = ID
|
|
|
|
p.StrategyInstanceID = s.InstanceID()
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify(&p)
|
2022-05-13 13:58:35 +00:00
|
|
|
|
|
|
|
s.ProfitStats.AddProfit(p)
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify(&s.ProfitStats)
|
2022-05-13 13:58:35 +00:00
|
|
|
s.Environment.RecordPosition(s.Position, trade, &p)
|
|
|
|
} else {
|
|
|
|
s.Environment.RecordPosition(s.Position, trade, nil)
|
2022-04-13 01:43:31 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
// calculate report for the position that cannot be closed by close order (amount too small)
|
|
|
|
if s.waitForTrade {
|
|
|
|
price := s.entryPrice
|
|
|
|
if price.IsZero() {
|
|
|
|
panic("no price found")
|
|
|
|
}
|
|
|
|
pnlRate := trade.Price.Sub(price).Abs().Div(trade.Price).Float64()
|
|
|
|
if s.Record {
|
|
|
|
log.Errorf("record avg %v trade %v", price, trade)
|
|
|
|
}
|
|
|
|
if trade.Side == types.SideTypeBuy {
|
|
|
|
if trade.Price.Compare(price) < 0 {
|
|
|
|
percentAvgTPfromOrder = percentAvgTPfromOrder*float64(counterTPfromOrder) + pnlRate
|
|
|
|
counterTPfromOrder += 1
|
|
|
|
percentAvgTPfromOrder /= float64(counterTPfromOrder)
|
|
|
|
} else {
|
|
|
|
percentAvgSLfromOrder = percentAvgSLfromOrder*float64(counterSLfromOrder) + pnlRate
|
|
|
|
counterSLfromOrder += 1
|
|
|
|
percentAvgSLfromOrder /= float64(counterSLfromOrder)
|
|
|
|
}
|
|
|
|
} else if trade.Side == types.SideTypeSell {
|
|
|
|
if trade.Price.Compare(price) > 0 {
|
|
|
|
percentAvgTPfromOrder = percentAvgTPfromOrder*float64(counterTPfromOrder) + pnlRate
|
|
|
|
counterTPfromOrder += 1
|
|
|
|
percentAvgTPfromOrder /= float64(counterTPfromOrder)
|
|
|
|
} else {
|
|
|
|
percentAvgSLfromOrder = percentAvgSLfromOrder*float64(counterSLfromOrder) + pnlRate
|
|
|
|
counterSLfromOrder += 1
|
|
|
|
percentAvgSLfromOrder /= float64(counterSLfromOrder)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
panic(fmt.Sprintf("no sell(%v) or buy price(%v), %v", s.sellPrice, s.buyPrice, trade))
|
|
|
|
}
|
|
|
|
s.waitForTrade = false
|
|
|
|
}
|
|
|
|
if s.Position.GetBase().Abs().Compare(s.Market.MinQuantity) >= 0 && s.Position.GetBase().Abs().Mul(trade.Price).Compare(s.Market.MinNotional) >= 0 {
|
2022-05-13 13:58:35 +00:00
|
|
|
sign := s.Position.GetBase().Sign()
|
|
|
|
if sign > 0 {
|
|
|
|
log.Infof("base become positive, %v", trade)
|
2022-05-24 13:55:43 +00:00
|
|
|
s.buyPrice = s.Position.AverageCost
|
|
|
|
s.sellPrice = fixedpoint.Zero
|
|
|
|
s.peakPrice = s.Position.AverageCost
|
2022-05-13 13:58:35 +00:00
|
|
|
} else if sign == 0 {
|
2022-05-30 03:45:52 +00:00
|
|
|
panic("not going to happen")
|
2022-05-13 13:58:35 +00:00
|
|
|
} else {
|
|
|
|
log.Infof("base become negative, %v", trade)
|
2022-05-24 13:55:43 +00:00
|
|
|
s.buyPrice = fixedpoint.Zero
|
|
|
|
s.sellPrice = s.Position.AverageCost
|
|
|
|
s.bottomPrice = s.Position.AverageCost
|
2022-04-28 11:09:15 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
s.entryPrice = trade.Price
|
2022-05-13 13:58:35 +00:00
|
|
|
} else {
|
2022-05-30 03:45:52 +00:00
|
|
|
log.Infof("base become zero, rest of base: %v", s.Position.GetBase())
|
|
|
|
if s.Position.GetBase().IsZero() {
|
|
|
|
s.entryPrice = fixedpoint.Zero
|
|
|
|
}
|
2022-05-13 13:58:35 +00:00
|
|
|
s.buyPrice = fixedpoint.Zero
|
|
|
|
s.sellPrice = fixedpoint.Zero
|
2022-05-30 03:45:52 +00:00
|
|
|
s.peakPrice = fixedpoint.Zero
|
|
|
|
s.bottomPrice = fixedpoint.Zero
|
2022-04-14 10:58:05 +00:00
|
|
|
}
|
2022-04-13 01:43:31 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
s.tradeCollector.OnPositionUpdate(func(position *types.Position) {
|
|
|
|
log.Infof("position changed: %s", position)
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify(s.Position)
|
2022-04-13 01:43:31 +00:00
|
|
|
})
|
|
|
|
s.tradeCollector.BindStream(session.UserDataStream)
|
|
|
|
|
2022-06-06 10:10:46 +00:00
|
|
|
store, ok := s.Session.MarketDataStore(s.Symbol)
|
|
|
|
if !ok {
|
2022-06-17 11:19:51 +00:00
|
|
|
return fmt.Errorf("cannot get marketdatastore of %s", s.Symbol)
|
2022-06-06 10:10:46 +00:00
|
|
|
}
|
|
|
|
s.SetupIndicators(store)
|
2022-04-13 01:43:31 +00:00
|
|
|
|
2022-06-06 10:10:46 +00:00
|
|
|
// local peak of ewo
|
|
|
|
shortSig := s.ewo.Last() < s.ewo.Index(1) && s.ewo.Index(1) > s.ewo.Index(2)
|
|
|
|
longSig := s.ewo.Last() > s.ewo.Index(1) && s.ewo.Index(1) < s.ewo.Index(2)
|
|
|
|
|
2022-05-12 10:40:48 +00:00
|
|
|
sellOrderTPSL := func(price fixedpoint.Value) {
|
2022-05-30 03:45:52 +00:00
|
|
|
lastPrice := s.GetLastPrice()
|
|
|
|
base := s.Position.GetBase().Abs()
|
|
|
|
if base.Mul(lastPrice).Compare(s.Market.MinNotional) < 0 || base.Compare(s.Market.MinQuantity) < 0 {
|
2022-05-24 13:55:43 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.sellPrice.IsZero() {
|
|
|
|
return
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
balances := session.GetAccount().Balances()
|
|
|
|
quoteBalance := balances[s.Market.QuoteCurrency].Available
|
2022-05-25 07:11:19 +00:00
|
|
|
atr := fixedpoint.NewFromFloat(s.atr.Last())
|
2022-05-24 13:55:43 +00:00
|
|
|
atrx2 := fixedpoint.NewFromFloat(s.atr.Last() * 2)
|
2022-05-12 10:40:48 +00:00
|
|
|
buyall := false
|
2022-05-24 13:55:43 +00:00
|
|
|
if s.bottomPrice.IsZero() || s.bottomPrice.Compare(price) > 0 {
|
|
|
|
s.bottomPrice = price
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
takeProfit := false
|
|
|
|
bottomBack := s.bottomPrice
|
2022-05-13 13:58:35 +00:00
|
|
|
spBack := s.sellPrice
|
2022-05-30 03:45:52 +00:00
|
|
|
reason := -1
|
|
|
|
if quoteBalance.Div(lastPrice).Compare(s.Market.MinQuantity) >= 0 && quoteBalance.Compare(s.Market.MinNotional) >= 0 {
|
2022-05-25 07:11:19 +00:00
|
|
|
base := fixedpoint.NewFromFloat(s.ma34.Last())
|
2022-05-12 10:40:48 +00:00
|
|
|
// TP
|
2022-06-06 10:10:46 +00:00
|
|
|
if lastPrice.Compare(s.sellPrice) < 0 && (longSig ||
|
2022-05-31 12:36:37 +00:00
|
|
|
(!atrx2.IsZero() && base.Sub(atrx2).Compare(lastPrice) >= 0)) {
|
2022-05-13 13:58:35 +00:00
|
|
|
buyall = true
|
|
|
|
takeProfit = true
|
2022-05-25 07:11:19 +00:00
|
|
|
|
|
|
|
// calculate report
|
2022-06-06 10:10:46 +00:00
|
|
|
if longSig {
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 1
|
2022-05-25 07:11:19 +00:00
|
|
|
} else {
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 2
|
2022-05-25 07:11:19 +00:00
|
|
|
}
|
|
|
|
|
2022-05-24 07:19:00 +00:00
|
|
|
}
|
2022-05-25 07:11:19 +00:00
|
|
|
if !atr.IsZero() && s.bottomPrice.Add(atr).Compare(lastPrice) <= 0 &&
|
2022-05-13 13:58:35 +00:00
|
|
|
lastPrice.Compare(s.sellPrice) < 0 {
|
2022-05-12 10:40:48 +00:00
|
|
|
buyall = true
|
|
|
|
takeProfit = true
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 3
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SL
|
2022-05-24 13:55:43 +00:00
|
|
|
/*if (!atrx2.IsZero() && s.bottomPrice.Add(atrx2).Compare(lastPrice) <= 0) ||
|
2022-05-13 13:58:35 +00:00
|
|
|
lastPrice.Sub(s.bottomPrice).Div(lastPrice).Compare(s.Stoploss) > 0 {
|
|
|
|
if lastPrice.Compare(s.sellPrice) < 0 {
|
|
|
|
takeProfit = true
|
|
|
|
}
|
|
|
|
buyall = true
|
|
|
|
s.bottomPrice = fixedpoint.Zero
|
|
|
|
}*/
|
2022-05-25 07:11:19 +00:00
|
|
|
if !s.DisableShortStop && ((!atr.IsZero() && s.sellPrice.Sub(atr).Compare(lastPrice) >= 0) ||
|
2022-05-24 13:55:43 +00:00
|
|
|
lastPrice.Sub(s.sellPrice).Div(s.sellPrice).Compare(s.Stoploss) > 0) {
|
2022-05-12 10:40:48 +00:00
|
|
|
buyall = true
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 4
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if buyall {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Warnf("buyall TPSL %v %v", s.Position.GetBase(), quoteBalance)
|
2022-05-30 03:45:52 +00:00
|
|
|
p := s.sellPrice
|
|
|
|
if order, ok := s.ClosePosition(ctx); order != nil && ok {
|
2022-05-12 10:40:48 +00:00
|
|
|
if takeProfit {
|
2022-05-24 13:55:43 +00:00
|
|
|
log.Errorf("takeprofit buy at %v, avg %v, l: %v, atrx2: %v", lastPrice, spBack, bottomBack, atrx2)
|
2022-05-12 10:40:48 +00:00
|
|
|
} else {
|
2022-05-24 13:55:43 +00:00
|
|
|
log.Errorf("stoploss buy at %v, avg %v, l: %v, atrx2: %v", lastPrice, spBack, bottomBack, atrx2)
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
|
|
|
|
// calculate report
|
|
|
|
if s.Record {
|
|
|
|
log.Error("record ba")
|
|
|
|
}
|
|
|
|
var pnlRate float64
|
|
|
|
if takeProfit {
|
|
|
|
pnlRate = p.Sub(lastPrice).Div(lastPrice).Float64()
|
|
|
|
} else {
|
|
|
|
pnlRate = lastPrice.Sub(p).Div(lastPrice).Float64()
|
|
|
|
}
|
|
|
|
switch reason {
|
|
|
|
case 0:
|
|
|
|
percentAvgTPfromCCI = percentAvgTPfromCCI*float64(counterTPfromCCI) + pnlRate
|
|
|
|
counterTPfromCCI += 1
|
|
|
|
percentAvgTPfromCCI /= float64(counterTPfromCCI)
|
|
|
|
case 1:
|
|
|
|
percentAvgTPfromLongShort = percentAvgTPfromLongShort*float64(counterTPfromLongShort) + pnlRate
|
|
|
|
counterTPfromLongShort += 1
|
|
|
|
percentAvgTPfromLongShort /= float64(counterTPfromLongShort)
|
|
|
|
case 2:
|
|
|
|
percentAvgTPfromAtr = percentAvgTPfromAtr*float64(counterTPfromAtr) + pnlRate
|
|
|
|
counterTPfromAtr += 1
|
|
|
|
percentAvgTPfromAtr /= float64(counterTPfromAtr)
|
|
|
|
case 3:
|
|
|
|
percentAvgTPfromPeak = percentAvgTPfromPeak*float64(counterTPfromPeak) + pnlRate
|
|
|
|
counterTPfromPeak += 1
|
|
|
|
percentAvgTPfromPeak /= float64(counterTPfromPeak)
|
|
|
|
case 4:
|
|
|
|
percentAvgSLfromSL = percentAvgSLfromSL*float64(counterSLfromSL) + pnlRate
|
|
|
|
counterSLfromSL += 1
|
|
|
|
percentAvgSLfromSL /= float64(counterSLfromSL)
|
|
|
|
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
buyOrderTPSL := func(price fixedpoint.Value) {
|
2022-05-30 03:45:52 +00:00
|
|
|
lastPrice := s.GetLastPrice()
|
|
|
|
base := s.Position.GetBase().Abs()
|
|
|
|
if base.Mul(lastPrice).Compare(s.Market.MinNotional) < 0 || base.Compare(s.Market.MinQuantity) < 0 {
|
2022-05-24 13:55:43 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if s.buyPrice.IsZero() {
|
|
|
|
return
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
balances := session.GetAccount().Balances()
|
|
|
|
baseBalance := balances[s.Market.BaseCurrency].Available
|
2022-05-25 07:11:19 +00:00
|
|
|
atr := fixedpoint.NewFromFloat(s.atr.Last())
|
2022-05-24 13:55:43 +00:00
|
|
|
atrx2 := fixedpoint.NewFromFloat(s.atr.Last() * 2)
|
2022-05-12 10:40:48 +00:00
|
|
|
sellall := false
|
2022-05-24 13:55:43 +00:00
|
|
|
if s.peakPrice.IsZero() || s.peakPrice.Compare(price) < 0 {
|
|
|
|
s.peakPrice = price
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
takeProfit := false
|
|
|
|
peakBack := s.peakPrice
|
2022-05-13 13:58:35 +00:00
|
|
|
bpBack := s.buyPrice
|
2022-05-30 03:45:52 +00:00
|
|
|
reason := -1
|
|
|
|
if baseBalance.Compare(s.Market.MinQuantity) >= 0 && baseBalance.Mul(lastPrice).Compare(s.Market.MinNotional) >= 0 {
|
2022-05-12 10:40:48 +00:00
|
|
|
// TP
|
2022-05-25 07:11:19 +00:00
|
|
|
base := fixedpoint.NewFromFloat(s.ma34.Last())
|
2022-06-06 10:10:46 +00:00
|
|
|
if lastPrice.Compare(s.buyPrice) > 0 && (shortSig ||
|
2022-05-31 12:36:37 +00:00
|
|
|
(!atrx2.IsZero() && base.Add(atrx2).Compare(lastPrice) <= 0)) {
|
2022-05-12 10:40:48 +00:00
|
|
|
sellall = true
|
|
|
|
takeProfit = true
|
2022-05-25 07:11:19 +00:00
|
|
|
|
|
|
|
// calculate report
|
2022-06-06 10:10:46 +00:00
|
|
|
if shortSig {
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 1
|
2022-05-25 07:11:19 +00:00
|
|
|
} else {
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 2
|
2022-05-25 07:11:19 +00:00
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
if !atr.IsZero() && s.peakPrice.Sub(atr).Compare(lastPrice) >= 0 &&
|
|
|
|
lastPrice.Compare(s.buyPrice) > 0 {
|
|
|
|
sellall = true
|
|
|
|
takeProfit = true
|
|
|
|
reason = 3
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
|
|
|
|
// SL
|
2022-05-13 13:58:35 +00:00
|
|
|
/*if s.peakPrice.Sub(lastPrice).Div(s.peakPrice).Compare(s.Stoploss) > 0 ||
|
2022-05-24 13:55:43 +00:00
|
|
|
(!atrx2.IsZero() && s.peakPrice.Sub(atrx2).Compare(lastPrice) >= 0) {
|
2022-05-13 13:58:35 +00:00
|
|
|
if lastPrice.Compare(s.buyPrice) > 0 {
|
|
|
|
takeProfit = true
|
|
|
|
}
|
|
|
|
sellall = true
|
|
|
|
s.peakPrice = fixedpoint.Zero
|
|
|
|
}*/
|
2022-05-24 13:55:43 +00:00
|
|
|
if !s.DisableLongStop && (s.buyPrice.Sub(lastPrice).Div(s.buyPrice).Compare(s.Stoploss) > 0 ||
|
2022-05-25 07:11:19 +00:00
|
|
|
(!atr.IsZero() && s.buyPrice.Sub(atr).Compare(lastPrice) >= 0)) {
|
2022-05-12 10:40:48 +00:00
|
|
|
sellall = true
|
2022-05-30 03:45:52 +00:00
|
|
|
reason = 4
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if sellall {
|
2022-05-13 13:58:35 +00:00
|
|
|
log.Warnf("sellall TPSL %v", s.Position.GetBase())
|
2022-05-30 03:45:52 +00:00
|
|
|
p := s.buyPrice
|
|
|
|
if order, ok := s.ClosePosition(ctx); order != nil && ok {
|
2022-05-12 10:40:48 +00:00
|
|
|
if takeProfit {
|
2022-05-24 13:55:43 +00:00
|
|
|
log.Errorf("takeprofit sell at %v, avg %v, h: %v, atrx2: %v", lastPrice, bpBack, peakBack, atrx2)
|
2022-05-12 10:40:48 +00:00
|
|
|
} else {
|
2022-05-24 13:55:43 +00:00
|
|
|
log.Errorf("stoploss sell at %v, avg %v, h: %v, atrx2: %v", lastPrice, bpBack, peakBack, atrx2)
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
2022-05-30 03:45:52 +00:00
|
|
|
// calculate report
|
|
|
|
if s.Record {
|
|
|
|
log.Error("record sa")
|
|
|
|
}
|
|
|
|
var pnlRate float64
|
|
|
|
if takeProfit {
|
|
|
|
pnlRate = lastPrice.Sub(p).Div(p).Float64()
|
|
|
|
} else {
|
|
|
|
pnlRate = p.Sub(lastPrice).Div(p).Float64()
|
|
|
|
}
|
|
|
|
switch reason {
|
|
|
|
case 0:
|
|
|
|
percentAvgTPfromCCI = percentAvgTPfromCCI*float64(counterTPfromCCI) + pnlRate
|
|
|
|
counterTPfromCCI += 1
|
|
|
|
percentAvgTPfromCCI /= float64(counterTPfromCCI)
|
|
|
|
case 1:
|
|
|
|
percentAvgTPfromLongShort = percentAvgTPfromLongShort*float64(counterTPfromLongShort) + pnlRate
|
|
|
|
counterTPfromLongShort += 1
|
|
|
|
percentAvgTPfromLongShort /= float64(counterTPfromLongShort)
|
|
|
|
case 2:
|
|
|
|
percentAvgTPfromAtr = percentAvgTPfromAtr*float64(counterTPfromAtr) + pnlRate
|
|
|
|
counterTPfromAtr += 1
|
|
|
|
percentAvgTPfromAtr /= float64(counterTPfromAtr)
|
|
|
|
case 3:
|
|
|
|
percentAvgTPfromPeak = percentAvgTPfromPeak*float64(counterTPfromPeak) + pnlRate
|
|
|
|
counterTPfromPeak += 1
|
|
|
|
percentAvgTPfromPeak /= float64(counterTPfromPeak)
|
|
|
|
case 4:
|
|
|
|
percentAvgSLfromSL = percentAvgSLfromSL*float64(counterSLfromSL) + pnlRate
|
|
|
|
counterSLfromSL += 1
|
|
|
|
percentAvgSLfromSL /= float64(counterSLfromSL)
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// set last price by realtime book ticker update
|
|
|
|
// to trigger TP/SL
|
|
|
|
session.MarketDataStream.OnBookTickerUpdate(func(ticker types.BookTicker) {
|
|
|
|
if s.Environment.IsBackTesting() {
|
2022-04-07 10:25:02 +00:00
|
|
|
return
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
bestBid := ticker.Buy
|
|
|
|
bestAsk := ticker.Sell
|
|
|
|
var midPrice fixedpoint.Value
|
2022-05-16 17:32:51 +00:00
|
|
|
|
|
|
|
if tryLock(&s.lock) {
|
2022-05-12 10:40:48 +00:00
|
|
|
if !bestAsk.IsZero() && !bestBid.IsZero() {
|
|
|
|
s.midPrice = bestAsk.Add(bestBid).Div(types.Two)
|
|
|
|
} else if !bestAsk.IsZero() {
|
|
|
|
s.midPrice = bestAsk
|
|
|
|
} else {
|
|
|
|
s.midPrice = bestBid
|
|
|
|
}
|
|
|
|
midPrice = s.midPrice
|
|
|
|
s.lock.Unlock()
|
|
|
|
}
|
2022-05-16 17:32:51 +00:00
|
|
|
|
2022-05-12 10:40:48 +00:00
|
|
|
if !midPrice.IsZero() {
|
|
|
|
buyOrderTPSL(midPrice)
|
|
|
|
sellOrderTPSL(midPrice)
|
2022-05-16 17:32:51 +00:00
|
|
|
// log.Debugf("best bid %v, best ask %v, mid %v", bestBid, bestAsk, midPrice)
|
2022-05-12 10:40:48 +00:00
|
|
|
}
|
|
|
|
})
|
2022-04-11 08:07:52 +00:00
|
|
|
|
2022-06-06 10:10:46 +00:00
|
|
|
getHigh := func(window types.KLineWindow) types.Series {
|
|
|
|
if s.UseHeikinAshi {
|
|
|
|
return s.heikinAshi.High
|
|
|
|
}
|
|
|
|
return window.High()
|
|
|
|
}
|
|
|
|
getLow := func(window types.KLineWindow) types.Series {
|
|
|
|
if s.UseHeikinAshi {
|
|
|
|
return s.heikinAshi.Low
|
|
|
|
}
|
|
|
|
return window.Low()
|
|
|
|
}
|
|
|
|
getClose := func(window types.KLineWindow) types.Series {
|
|
|
|
if s.UseHeikinAshi {
|
|
|
|
return s.heikinAshi.Close
|
2022-04-13 12:08:59 +00:00
|
|
|
}
|
2022-06-06 10:10:46 +00:00
|
|
|
return window.Close()
|
|
|
|
}
|
|
|
|
getOpen := func(window types.KLineWindow) types.Series {
|
|
|
|
if s.UseHeikinAshi {
|
|
|
|
return s.heikinAshi.Open
|
|
|
|
}
|
|
|
|
return window.Open()
|
|
|
|
}
|
|
|
|
|
|
|
|
store.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
|
|
|
kline := window[len(window)-1]
|
2022-05-13 13:58:35 +00:00
|
|
|
s.KLineStartTime = kline.StartTime
|
|
|
|
s.KLineEndTime = kline.EndTime
|
|
|
|
|
|
|
|
// well, only track prices on 1m
|
2022-06-06 10:10:46 +00:00
|
|
|
if interval == types.Interval1m {
|
2022-05-13 13:58:35 +00:00
|
|
|
|
|
|
|
if s.Environment.IsBackTesting() {
|
|
|
|
buyOrderTPSL(kline.High)
|
|
|
|
sellOrderTPSL(kline.Low)
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-12 10:40:48 +00:00
|
|
|
var lastPrice fixedpoint.Value
|
|
|
|
var ok bool
|
|
|
|
if s.Environment.IsBackTesting() {
|
|
|
|
lastPrice, ok = session.LastPrice(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("cannot get last price")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
s.lock.RLock()
|
2022-05-24 13:55:43 +00:00
|
|
|
if s.midPrice.IsZero() {
|
|
|
|
lastPrice, ok = session.LastPrice(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("cannot get last price")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
lastPrice = s.midPrice
|
|
|
|
}
|
2022-05-12 10:40:48 +00:00
|
|
|
s.lock.RUnlock()
|
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
balances := session.GetAccount().Balances()
|
2022-05-25 07:11:19 +00:00
|
|
|
baseBalance := balances[s.Market.BaseCurrency].Total()
|
|
|
|
quoteBalance := balances[s.Market.QuoteCurrency].Total()
|
2022-05-24 13:55:43 +00:00
|
|
|
atr := fixedpoint.NewFromFloat(s.atr.Last())
|
2022-05-12 10:40:48 +00:00
|
|
|
if !s.Environment.IsBackTesting() {
|
2022-05-24 07:19:00 +00:00
|
|
|
log.Infof("Get last price: %v, ewo %f, ewoSig %f, ccis: %f, atr %v, kline: %v, balance[base]: %v balance[quote]: %v",
|
|
|
|
lastPrice, s.ewo.Last(), s.ewoSignal.Last(), s.ccis.ma.Last(), atr, kline, baseBalance, quoteBalance)
|
2022-04-11 08:07:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if kline.Interval != s.Interval {
|
|
|
|
return
|
|
|
|
}
|
2022-04-13 01:43:31 +00:00
|
|
|
|
2022-06-06 10:10:46 +00:00
|
|
|
priceHighest := types.Highest(getHigh(window), 233)
|
|
|
|
priceLowest := types.Lowest(getLow(window), 233)
|
2022-05-31 12:36:37 +00:00
|
|
|
priceChangeRate := (priceHighest - priceLowest) / priceHighest / 14
|
|
|
|
ewoHighest := types.Highest(s.ewoHistogram, 233)
|
|
|
|
|
|
|
|
s.ewoChangeRate = math.Abs(s.ewoHistogram.Last() / ewoHighest * priceChangeRate)
|
|
|
|
|
2022-04-14 10:58:05 +00:00
|
|
|
longSignal := types.CrossOver(s.ewo, s.ewoSignal)
|
|
|
|
shortSignal := types.CrossUnder(s.ewo, s.ewoSignal)
|
2022-06-06 10:10:46 +00:00
|
|
|
|
2022-05-31 12:36:37 +00:00
|
|
|
base := s.ma34.Last()
|
2022-06-06 10:10:46 +00:00
|
|
|
sellLine := base + s.atr.Last()*3
|
|
|
|
buyLine := base - s.atr.Last()*3
|
|
|
|
clozes := getClose(window)
|
|
|
|
opens := getOpen(window)
|
|
|
|
|
|
|
|
// get trend flags
|
|
|
|
bull := clozes.Last() > opens.Last()
|
|
|
|
breakThrough := clozes.Last() > s.ma5.Last() && clozes.Last() > s.ma34.Last()
|
|
|
|
breakDown := clozes.Last() < s.ma5.Last() && clozes.Last() < s.ma34.Last()
|
2022-05-24 13:55:43 +00:00
|
|
|
|
|
|
|
// kline breakthrough ma5, ma34 trend up, and cci Stochastic bull
|
2022-06-09 10:31:02 +00:00
|
|
|
IsBull := bull && breakThrough && s.ccis.BuySignal() && s.ewoChangeRate < s.EwoChangeFilterHigh && s.ewoChangeRate > s.EwoChangeFilterLow
|
2022-05-24 13:55:43 +00:00
|
|
|
// kline downthrough ma5, ma34 trend down, and cci Stochastic bear
|
2022-06-09 10:31:02 +00:00
|
|
|
IsBear := !bull && breakDown && s.ccis.SellSignal() && s.ewoChangeRate < s.EwoChangeFilterHigh && s.ewoChangeRate > s.EwoChangeFilterLow
|
2022-04-08 10:05:28 +00:00
|
|
|
|
2022-05-12 10:40:48 +00:00
|
|
|
if !s.Environment.IsBackTesting() {
|
2022-05-24 13:55:43 +00:00
|
|
|
log.Infof("IsBull: %v, bull: %v, longSignal[1]: %v, shortSignal: %v, lastPrice: %v",
|
|
|
|
IsBull, bull, longSignal.Index(1), shortSignal.Last(), lastPrice)
|
|
|
|
log.Infof("IsBear: %v, bear: %v, shortSignal[1]: %v, longSignal: %v, lastPrice: %v",
|
|
|
|
IsBear, !bull, shortSignal.Index(1), longSignal.Last(), lastPrice)
|
|
|
|
}
|
|
|
|
|
2022-05-31 12:36:37 +00:00
|
|
|
if (longSignal.Index(1) && !shortSignal.Last() && IsBull) || lastPrice.Float64() <= buyLine {
|
2022-06-06 10:10:46 +00:00
|
|
|
price := lastPrice.Sub(atr.Div(types.Two))
|
2022-05-25 07:11:19 +00:00
|
|
|
// if total asset (including locked) could be used to buy
|
|
|
|
if quoteBalance.Div(price).Compare(s.Market.MinQuantity) >= 0 && quoteBalance.Compare(s.Market.MinNotional) >= 0 {
|
2022-05-30 03:45:52 +00:00
|
|
|
// cancel all orders to release lock
|
|
|
|
s.CancelAll(ctx)
|
|
|
|
|
|
|
|
// backup, since the s.sellPrice will be cleared when doing ClosePosition
|
|
|
|
sellPrice := s.sellPrice
|
2022-05-31 12:36:37 +00:00
|
|
|
log.Errorf("ewoChangeRate %v, emv %v", s.ewoChangeRate, s.emv.Last())
|
2022-05-25 07:11:19 +00:00
|
|
|
|
|
|
|
// calculate report
|
2022-05-30 03:45:52 +00:00
|
|
|
if closeOrder, _ := s.PlaceBuyOrder(ctx, price); closeOrder != nil {
|
|
|
|
if s.Record {
|
|
|
|
log.Error("record l")
|
|
|
|
}
|
|
|
|
if !sellPrice.IsZero() {
|
|
|
|
if lastPrice.Compare(sellPrice) > 0 {
|
|
|
|
pnlRate := lastPrice.Sub(sellPrice).Div(lastPrice).Float64()
|
|
|
|
percentAvgTPfromOrder = percentAvgTPfromOrder*float64(counterTPfromOrder) + pnlRate
|
|
|
|
counterTPfromOrder += 1
|
|
|
|
percentAvgTPfromOrder /= float64(counterTPfromOrder)
|
|
|
|
} else {
|
|
|
|
pnlRate := sellPrice.Sub(lastPrice).Div(lastPrice).Float64()
|
|
|
|
percentAvgSLfromOrder = percentAvgSLfromOrder*float64(counterSLfromOrder) + pnlRate
|
|
|
|
counterSLfromOrder += 1
|
|
|
|
percentAvgSLfromOrder /= float64(counterSLfromOrder)
|
|
|
|
}
|
2022-05-25 07:11:19 +00:00
|
|
|
} else {
|
2022-05-30 03:45:52 +00:00
|
|
|
panic("no sell price")
|
2022-05-25 07:11:19 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-31 12:36:37 +00:00
|
|
|
if (shortSignal.Index(1) && !longSignal.Last() && IsBear) || lastPrice.Float64() >= sellLine {
|
2022-06-06 10:10:46 +00:00
|
|
|
price := lastPrice.Add(atr.Div(types.Two))
|
2022-05-25 07:11:19 +00:00
|
|
|
// if total asset (including locked) could be used to sell
|
|
|
|
if baseBalance.Mul(price).Compare(s.Market.MinNotional) >= 0 && baseBalance.Compare(s.Market.MinQuantity) >= 0 {
|
2022-05-30 03:45:52 +00:00
|
|
|
// cancel all orders to release lock
|
|
|
|
s.CancelAll(ctx)
|
|
|
|
|
|
|
|
// backup, since the s.buyPrice will be cleared when doing ClosePosition
|
|
|
|
buyPrice := s.buyPrice
|
2022-05-31 12:36:37 +00:00
|
|
|
log.Errorf("ewoChangeRate: %v, emv %v", s.ewoChangeRate, s.emv.Last())
|
2022-05-25 07:11:19 +00:00
|
|
|
|
|
|
|
// calculate report
|
2022-05-30 03:45:52 +00:00
|
|
|
if closeOrder, _ := s.PlaceSellOrder(ctx, price); closeOrder != nil {
|
|
|
|
if s.Record {
|
|
|
|
log.Error("record s")
|
|
|
|
}
|
|
|
|
if !buyPrice.IsZero() {
|
|
|
|
if lastPrice.Compare(buyPrice) > 0 {
|
|
|
|
pnlRate := lastPrice.Sub(buyPrice).Div(buyPrice).Float64()
|
|
|
|
percentAvgTPfromOrder = percentAvgTPfromOrder*float64(counterTPfromOrder) + pnlRate
|
|
|
|
counterTPfromOrder += 1
|
|
|
|
percentAvgTPfromOrder /= float64(counterTPfromOrder)
|
|
|
|
} else {
|
|
|
|
pnlRate := buyPrice.Sub(lastPrice).Div(buyPrice).Float64()
|
|
|
|
percentAvgSLfromOrder = percentAvgSLfromOrder*float64(counterSLfromOrder) + pnlRate
|
|
|
|
counterSLfromOrder += 1
|
|
|
|
percentAvgSLfromOrder /= float64(counterSLfromOrder)
|
|
|
|
}
|
2022-05-25 07:11:19 +00:00
|
|
|
} else {
|
2022-05-30 03:45:52 +00:00
|
|
|
panic("no buy price")
|
2022-05-25 07:11:19 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-24 13:55:43 +00:00
|
|
|
}
|
2022-04-13 01:43:31 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
log.Infof("canceling active orders...")
|
2022-05-30 03:45:52 +00:00
|
|
|
s.CancelAll(ctx)
|
2022-04-13 01:43:31 +00:00
|
|
|
|
|
|
|
s.tradeCollector.Process()
|
2022-06-13 03:08:08 +00:00
|
|
|
hiblue := color.New(color.FgHiBlue).FprintfFunc()
|
|
|
|
blue := color.New(color.FgBlue).FprintfFunc()
|
|
|
|
hiyellow := color.New(color.FgHiYellow).FprintfFunc()
|
|
|
|
hiblue(os.Stderr, "---- Trade Report (Without Fee) ----\n")
|
|
|
|
hiblue(os.Stderr, "TP:\n")
|
|
|
|
blue(os.Stderr, "\tpeak / bottom with atr: %d, avg pnl rate: %f\n", counterTPfromPeak, percentAvgTPfromPeak)
|
|
|
|
blue(os.Stderr, "\tCCI Stochastic: %d, avg pnl rate: %f\n", counterTPfromCCI, percentAvgTPfromCCI)
|
|
|
|
blue(os.Stderr, "\tLongSignal/ShortSignal: %d, avg pnl rate: %f\n", counterTPfromLongShort, percentAvgTPfromLongShort)
|
|
|
|
blue(os.Stderr, "\tma34 and Atrx2: %d, avg pnl rate: %f\n", counterTPfromAtr, percentAvgTPfromAtr)
|
|
|
|
blue(os.Stderr, "\tActive Order: %d, avg pnl rate: %f\n", counterTPfromOrder, percentAvgTPfromOrder)
|
2022-05-25 07:11:19 +00:00
|
|
|
|
|
|
|
totalTP := counterTPfromPeak + counterTPfromCCI + counterTPfromLongShort + counterTPfromAtr + counterTPfromOrder
|
|
|
|
avgProfit := (float64(counterTPfromPeak)*percentAvgTPfromPeak +
|
|
|
|
float64(counterTPfromCCI)*percentAvgTPfromCCI +
|
|
|
|
float64(counterTPfromLongShort)*percentAvgTPfromLongShort +
|
|
|
|
float64(counterTPfromAtr)*percentAvgTPfromAtr +
|
|
|
|
float64(counterTPfromOrder)*percentAvgTPfromOrder) / float64(totalTP)
|
2022-06-13 03:08:08 +00:00
|
|
|
hiblue(os.Stderr, "\tSum: %d, avg pnl rate: %f\n", totalTP, avgProfit)
|
2022-05-25 07:11:19 +00:00
|
|
|
|
2022-06-13 03:08:08 +00:00
|
|
|
hiblue(os.Stderr, "SL:\n")
|
|
|
|
blue(os.Stderr, "\tentry SL: %d, avg pnl rate: -%f\n", counterSLfromSL, percentAvgSLfromSL)
|
|
|
|
blue(os.Stderr, "\tActive Order: %d, avg pnl rate: -%f\n", counterSLfromOrder, percentAvgSLfromOrder)
|
2022-05-25 07:11:19 +00:00
|
|
|
|
|
|
|
totalSL := counterSLfromSL + counterSLfromOrder
|
|
|
|
avgLoss := (float64(counterSLfromSL)*percentAvgSLfromSL + float64(counterSLfromOrder)*percentAvgSLfromOrder) / float64(totalSL)
|
2022-06-13 03:08:08 +00:00
|
|
|
hiblue(os.Stderr, "\tSum: %d, avg pnl rate: -%f\n", totalSL, avgLoss)
|
2022-05-25 07:11:19 +00:00
|
|
|
|
2022-06-13 03:08:08 +00:00
|
|
|
hiblue(os.Stderr, "WinRate: %f\n", float64(totalTP)/float64(totalTP+totalSL))
|
2022-05-25 07:11:19 +00:00
|
|
|
|
2022-06-09 10:31:02 +00:00
|
|
|
maString := "vwema"
|
|
|
|
if s.UseSma {
|
|
|
|
maString = "sma"
|
|
|
|
}
|
|
|
|
if s.UseEma {
|
|
|
|
maString = "ema"
|
|
|
|
}
|
|
|
|
|
2022-06-13 03:08:08 +00:00
|
|
|
hiyellow(os.Stderr, "----- EWO Settings -------\n")
|
|
|
|
hiyellow(os.Stderr, "General:\n")
|
|
|
|
hiyellow(os.Stderr, "\tuseHeikinAshi: %v\n", s.UseHeikinAshi)
|
|
|
|
hiyellow(os.Stderr, "\tstoploss: %v\n", s.Stoploss)
|
|
|
|
hiyellow(os.Stderr, "\tsymbol: %s\n", s.Symbol)
|
|
|
|
hiyellow(os.Stderr, "\tinterval: %s\n", s.Interval)
|
|
|
|
hiyellow(os.Stderr, "\tMA type: %s\n", maString)
|
|
|
|
hiyellow(os.Stderr, "\tdisableShortStop: %v\n", s.DisableShortStop)
|
|
|
|
hiyellow(os.Stderr, "\tdisableLongStop: %v\n", s.DisableLongStop)
|
|
|
|
hiyellow(os.Stderr, "\trecord: %v\n", s.Record)
|
|
|
|
hiyellow(os.Stderr, "CCI Stochastic:\n")
|
|
|
|
hiyellow(os.Stderr, "\tccistochFilterHigh: %f\n", s.FilterHigh)
|
|
|
|
hiyellow(os.Stderr, "\tccistochFilterLow: %f\n", s.FilterLow)
|
|
|
|
hiyellow(os.Stderr, "Ewo && Ewo Histogram:\n")
|
|
|
|
hiyellow(os.Stderr, "\tsigWin: %d\n", s.SignalWindow)
|
|
|
|
hiyellow(os.Stderr, "\tewoChngFilterHigh: %f\n", s.EwoChangeFilterHigh)
|
|
|
|
hiyellow(os.Stderr, "\tewoChngFilterLow: %f\n", s.EwoChangeFilterLow)
|
2022-04-07 10:25:02 +00:00
|
|
|
})
|
|
|
|
return nil
|
|
|
|
}
|