crex

package module
v1.2.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 7, 2020 License: MIT Imports: 10 Imported by: 3

README

GitHub go.mod Go version license build status

CREX

中文 | English

CREX 是一个用Golang语言开发的量化交易库。支持tick级别数字币期货平台的回测和实盘。实盘与回测无缝切换,无需更改代码。

回测

示例 @backtest

交易结果

开源策略

https://github.com/coinrust/trading-strategies

主要特性

  • 使用简单
  • Tick级别回测
  • 实盘、回测公用策略代码
  • 支持 WebSocket 共有和私有订阅
  • 支持期货、现货回测
  • 支持期货双向合约,正反向合约

支持交易所

CREX库当前支持以下8个加密货币交易市场和交易API

logo id name ver ws doc
binance binancefutures Binance Futures 1 N API
bitmex bitmex BitMEX 1 Y API
deribit deribit Deribit 2 Y API
bybit bybit Bybit 2 Y API
huobi hbdm Huobi DM 1 Y API
huobi hbdmswap Huobi Swap 1 Y API
okex okexfutures OKEX Futures 3 Y API
okex okexswap OKEX Swap 3 Y API

示例

package main

import (
	. "github.com/coinrust/crex"
	"github.com/coinrust/crex/exchanges"
	"log"
	"time"
)

type BasicStrategy struct {
	StrategyBase
}

func (s *BasicStrategy) OnInit() error {
	return nil
}

func (s *BasicStrategy) OnTick() error {
	currency := "BTC"
	symbol := "BTC-PERPETUAL"

	balance, err := s.Exchange.GetBalance(currency)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("balance: %#v", balance)

	s.Exchange.GetOrderBook(symbol, 10)

	s.Exchange.OpenLong(symbol, OrderTypeLimit, 5000, 10)
	s.Exchange.CloseLong(symbol, OrderTypeLimit, 6000, 10)

	s.Exchange.PlaceOrder(symbol,
		Buy, OrderTypeLimit, 1000.0, 10, OrderPostOnlyOption(true))

	s.Exchange.GetOpenOrders(symbol)
	s.Exchange.GetPositions(symbol)
	return nil
}

func (s *BasicStrategy) Run() error {
	// run loop
	for {
		s.OnTick()
		time.Sleep(1 * time.Second)
	}
	return nil
}

func (s *BasicStrategy) OnExit() error {
	return nil
}

func main() {
	exchange := exchanges.NewExchange(exchanges.Deribit,
		ApiProxyURLOption("socks5://127.0.0.1:1080"), // 使用代理
		//ApiAccessKeyOption("[accessKey]"),
		//ApiSecretKeyOption("[secretKey]"),
		ApiTestnetOption(true))

	s := &BasicStrategy{}

	s.Setup(TradeModeLiveTrading, exchange)

	s.OnInit()
	s.Run()
	s.OnExit()
}

WebSocket 示例

package main

import (
	. "github.com/coinrust/crex"
	"github.com/coinrust/crex/exchanges"
	"log"
)

func main() {
	ws := exchanges.NewExchange(exchanges.OkexFutures,
		ApiProxyURLOption("socks5://127.0.0.1:1080"), // 使用代理
		//ApiAccessKeyOption("[accessKey]"),
		//ApiSecretKeyOption("[secretKey]"),
		//ApiPassPhraseOption("[passphrase]"),
		ApiWebSocketOption(true)) // 开启 WebSocket

	market := Market{
		Symbol: "BTC-USD-200626",
	}
	// 订阅订单薄
	ws.SubscribeLevel2Snapshots(market, func(ob *OrderBook) {
		log.Printf("%#v", ob)
	})
	// 订阅成交记录
	ws.SubscribeTrades(market, func(trades []*Trade) {
		log.Printf("%#v", trades)
	})
	// 订阅订单成交信息
	ws.SubscribeOrders(market, func(orders []*Order) {
		log.Printf("%#v", orders)
	})
	// 订阅持仓信息
	ws.SubscribePositions(market, func(positions []*Position) {
		log.Printf("%#v", positions)
	})

	select {}
}

回测数据

1. 标准 CSV 数据格式
  • 列定界符: , (逗号)
  • 换行标记: \n (LF)
  • 日期时间格式: Unix 时间戳 (ms)
时间格式
列名 描述
t Unix 时间戳 (ms)
asks[0-X].price 卖单价(升序)
asks[0-X].amount 卖单量
bids[0-X].price 买单价(降序)
bids[0-X].amount 买单量
样本数据示例
t,asks[0].price,asks[0].amount,asks[1].price,asks[1].amount,asks[2].price,asks[2].amount,asks[3].price,asks[3].amount,asks[4].price,asks[4].amount,asks[5].price,asks[5].amount,asks[6].price,asks[6].amount,asks[7].price,asks[7].amount,asks[8].price,asks[8].amount,asks[9].price,asks[9].amount,bids[0].price,bids[0].amount,bids[1].price,bids[1].amount,bids[2].price,bids[2].amount,bids[3].price,bids[3].amount,bids[4].price,bids[4].amount,bids[5].price,bids[5].amount,bids[6].price,bids[6].amount,bids[7].price,bids[7].amount,bids[8].price,bids[8].amount,bids[9].price,bids[9].amount
1569888000143,8304.5,7010,8305,60,8305.5,1220,8306,80,8307,200,8307.5,1650,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,90,8300,71320,8299.5,310
1569888000285,8304.5,7010,8305,60,8305.5,1220,8306,80,8307,200,8307.5,1650,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
1569888000307,8304.5,7010,8305,60,8305.5,1220,8306,80,8307,200,8307.5,11010,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
1569888000309,8304.5,7010,8305,60,8305.5,1220,8306,80,8307,200,8307.5,20370,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
1569888000406,8304.5,7010,8305,60,8305.5,1220,8306,80,8307,8960,8307.5,11010,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
1569888000500,8304.5,7010,8305,60,8305.5,1220,8306,80,8307,200,8307.5,20370,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
1569888000522,8304.5,10270,8305,60,8305.5,1220,8306,80,8307,200,8307.5,20370,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185750,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
1569888000527,8304.5,10270,8305,60,8305.5,1220,8306,80,8307,200,8307.5,20370,8308,68260,8308.5,120000,8309,38400,8309.5,8400,8304,185010,8303.5,52200,8303,20600,8302.5,4500,8302,2000,8301.5,18200,8301,18000,8300.5,5090,8300,71320,8299.5,310
2. MongoDB (推荐)
  • Database. for example: tick_db
  • Collection. for example: deribit:BTC-PERPETUAL
  • Document: t: timestamp (ms) a: asks Array [[ask_price_0,ask_amount_0],[ask_price_1,ask_amount_1],...] b: bids Array [[bid_price_0,ask_amount_0],[bid_price_1,bid_amount_1],...]
{"_id":{"$oid":"5eb946d88316c7a9c541705c"},"t":{"$numberLong":"1569888000143"},"a":[[8304.5,7010],[8305,60],[8305.5,1220],[8306,80],[8307,200],[8307.5,1650],[8308,68260],[8308.5,120000],[8309,38400],[8309.5,8400]],"b":[[8304,185750],[8303.5,52200],[8303,20600],[8302.5,4500],[8302,2000],[8301.5,18200],[8301,18000],[8300.5,90],[8300,71320],[8299.5,310]]}
数据处理示例

Example of importing data into a database:

cd ./cmd/deribit-data-to-db
go build
./deribit-data-to-db

TODO

  • Paper trading.

QQ群

QQ群: 932289088

捐赠

METHOD ADDRESS
BTC 1Nk4AsGj5HEJ5csRenTUPab1sjUySCZ3Pq
ETH 0xa74eade7ea08a8c48d7de4d582fac145afc86e3d

LICENSE

MIT ©coinrust

Documentation

Index

Constants

View Source
const (
	SimEventKey   = "event"
	SimEventOrder = "order" // 委托
	SimEventDeal  = "deal"  // 成交
)

回测交易撮合事件类型

View Source
const (
	ContractTypeNone = ""   // Non-delivery contract 非交割合约
	ContractTypeW1   = "W1" // week 当周合约
	ContractTypeW2   = "W2" // two week 次周合约
	ContractTypeM1   = "M1" // month 月合约
	ContractTypeQ1   = "Q1" // quarter 季度合约
	ContractTypeQ2   = "Q2" // two quarter 次季度合约
)

ContractType 合约类型

View Source
const (
	PERIOD_1MIN   = "1m"
	PERIOD_3MIN   = "3m"
	PERIOD_5MIN   = "5m"
	PERIOD_15MIN  = "15m"
	PERIOD_30MIN  = "30m"
	PERIOD_60MIN  = "60m"
	PERIOD_1H     = "1h"
	PERIOD_2H     = "2h"
	PERIOD_3H     = "3h"
	PERIOD_4H     = "4h"
	PERIOD_6H     = "6h"
	PERIOD_8H     = "8h"
	PERIOD_12H    = "12h"
	PERIOD_1DAY   = "1d"
	PERIOD_3DAY   = "3d"
	PERIOD_1WEEK  = "1w"
	PERIOD_1MONTH = "1M"
	PERIOD_1YEAR  = "1y"
)

K线周期

View Source
const (
	// StrategyOptionTag 选项Tag
	StrategyOptionTag = "opt"
)

Variables

View Source
var (
	ErrNotImplemented    = errors.New("not implement")
	ErrWebSocketDisabled = errors.New("websocket disabled")
	ErrApiKeysRequired   = errors.New("api keys required")

	ErrInvalidAmount = errors.New("amount is not valid")
)

Functions

func GenOrderId added in v1.2.0

func GenOrderId() string

func SetIdGenerate added in v1.2.0

func SetIdGenerate(g *utils.IdGenerate)

Types

type ApiOption added in v1.1.1

type ApiOption func(p *Parameters)

func ApiAccessKeyOption added in v1.1.1

func ApiAccessKeyOption(accessKey string) ApiOption

func ApiApiURLOption added in v1.1.4

func ApiApiURLOption(apiURL string) ApiOption

func ApiDebugModeOption added in v1.1.1

func ApiDebugModeOption(debugMode bool) ApiOption

func ApiHttpClientOption added in v1.1.1

func ApiHttpClientOption(httpClient *http.Client) ApiOption

func ApiPassPhraseOption added in v1.1.1

func ApiPassPhraseOption(passPhrase string) ApiOption

func ApiProxyURLOption added in v1.1.1

func ApiProxyURLOption(proxyURL string) ApiOption

func ApiSecretKeyOption added in v1.1.1

func ApiSecretKeyOption(secretKey string) ApiOption

func ApiTestnetOption added in v1.1.1

func ApiTestnetOption(testnet bool) ApiOption

func ApiWebSocketOption added in v1.1.2

func ApiWebSocketOption(enabled bool) ApiOption

func ApiWsURLOption added in v1.1.4

func ApiWsURLOption(wsURL string) ApiOption

type Balance added in v1.1.1

type Balance struct {
	Equity        float64 // 净值
	Available     float64 // 可用余额
	Margin        float64 // 已用保证金
	RealizedPnl   float64
	UnrealisedPnl float64
}

type Direction

type Direction int

Direction 委托/持仓方向

const (
	Buy       Direction = iota // 做多
	Sell                       // 做空
	CloseBuy                   // 平多
	CloseSell                  // 平空
)

func (Direction) String

func (d Direction) String() string

type EmptyExchangeLogger added in v1.2.1

type EmptyExchangeLogger struct {
}

EmptyExchangeLogger 交易所撮合日志

func (*EmptyExchangeLogger) Debug added in v1.2.1

func (l *EmptyExchangeLogger) Debug(args ...interface{})

func (*EmptyExchangeLogger) Debugf added in v1.2.1

func (l *EmptyExchangeLogger) Debugf(template string, args ...interface{})

func (*EmptyExchangeLogger) Debugw added in v1.2.1

func (l *EmptyExchangeLogger) Debugw(msg string, keysAndValues ...interface{})

func (*EmptyExchangeLogger) Error added in v1.2.1

func (l *EmptyExchangeLogger) Error(args ...interface{})

func (*EmptyExchangeLogger) Errorf added in v1.2.1

func (l *EmptyExchangeLogger) Errorf(template string, args ...interface{})

func (*EmptyExchangeLogger) Errorw added in v1.2.1

func (l *EmptyExchangeLogger) Errorw(msg string, keysAndValues ...interface{})

func (*EmptyExchangeLogger) Info added in v1.2.1

func (l *EmptyExchangeLogger) Info(args ...interface{})

func (*EmptyExchangeLogger) Infof added in v1.2.1

func (l *EmptyExchangeLogger) Infof(template string, args ...interface{})

func (*EmptyExchangeLogger) Infow added in v1.2.1

func (l *EmptyExchangeLogger) Infow(msg string, keysAndValues ...interface{})

func (*EmptyExchangeLogger) Sync added in v1.2.1

func (l *EmptyExchangeLogger) Sync()

func (*EmptyExchangeLogger) Warn added in v1.2.1

func (l *EmptyExchangeLogger) Warn(args ...interface{})

func (*EmptyExchangeLogger) Warnf added in v1.2.1

func (l *EmptyExchangeLogger) Warnf(template string, args ...interface{})

func (*EmptyExchangeLogger) Warnw added in v1.2.1

func (l *EmptyExchangeLogger) Warnw(msg string, keysAndValues ...interface{})

type Event

type Event struct {
	// contains filtered or unexported fields
}

func (*Event) SetSymbol

func (e *Event) SetSymbol(s string)

SetSymbol returns the symbol string of the event

func (*Event) SetTime

func (e *Event) SetTime(t time.Time)

SetTime returns the timestamp of an event

func (Event) Symbol

func (e Event) Symbol() string

Symbol returns the symbol string of the event

func (Event) Time

func (e Event) Time() time.Time

Time returns the timestamp of an event

type Exchange added in v1.1.2

type Exchange interface {

	// 获取 Exchange 名称
	GetName() (name string)

	// 获取交易所时间(ms)
	GetTime() (tm int64, err error)

	// 获取账号余额
	GetBalance(currency string) (result *Balance, err error)

	// 获取订单薄(OrderBook)
	GetOrderBook(symbol string, depth int) (result *OrderBook, err error)

	// 获取K线数据
	// period: 数据周期. 分钟或者关键字1m(minute) 1h 1d 1w 1M(month) 1y 枚举值:1 3 5 15 30 60 120 240 360 720 "5m" "4h" "1d" ...
	GetRecords(symbol string, period string, from int64, end int64, limit int) (records []*Record, err error)

	// 设置合约类型
	// currencyPair: 交易对,如: BTC-USD(OKEX) BTC(HBDM)
	// contractType: W1,W2,Q1,Q2
	SetContractType(currencyPair string, contractType string) (err error)

	// 获取当前设置的合约ID
	GetContractID() (symbol string, err error)

	// 设置杠杆大小
	SetLeverRate(value float64) (err error)

	// 开多
	OpenLong(symbol string, orderType OrderType, price float64, size float64) (result *Order, err error)

	// 开空
	OpenShort(symbol string, orderType OrderType, price float64, size float64) (result *Order, err error)

	// 平多
	CloseLong(symbol string, orderType OrderType, price float64, size float64) (result *Order, err error)

	// 平空
	CloseShort(symbol string, orderType OrderType, price float64, size float64) (result *Order, err error)

	// 下单
	PlaceOrder(symbol string, direction Direction, orderType OrderType, price float64, size float64,
		opts ...PlaceOrderOption) (result *Order, err error)

	// 获取活跃委托单列表
	GetOpenOrders(symbol string, opts ...OrderOption) (result []*Order, err error)

	// 获取委托信息
	GetOrder(symbol string, id string, opts ...OrderOption) (result *Order, err error)

	// 撤销全部委托单
	CancelAllOrders(symbol string, opts ...OrderOption) (err error)

	// 撤销单个委托单
	CancelOrder(symbol string, id string, opts ...OrderOption) (result *Order, err error)

	// 修改委托
	AmendOrder(symbol string, id string, price float64, size float64, opts ...OrderOption) (result *Order, err error)

	// 获取持仓
	GetPositions(symbol string) (result []*Position, err error)

	// 订阅成交记录
	SubscribeTrades(market Market, callback func(trades []*Trade)) error

	// 订阅L2 OrderBook
	SubscribeLevel2Snapshots(market Market, callback func(ob *OrderBook)) error

	// 订阅委托
	SubscribeOrders(market Market, callback func(orders []*Order)) error

	// 订阅持仓
	SubscribePositions(market Market, callback func(positions []*Position)) error
}

Exchange 交易所接口

type ExchangeLogger added in v1.1.13

type ExchangeLogger interface {
	// Debug Using:log.Debug("test")
	Debug(args ...interface{})

	// Debugf Using:log.Debugf("test:%s", err)
	Debugf(template string, args ...interface{})

	// Debugw Using:log.Debugw("test", "field1", "value1", "field2", "value2")
	Debugw(msg string, keysAndValues ...interface{})

	Info(args ...interface{})

	Infof(template string, args ...interface{})

	Infow(msg string, keysAndValues ...interface{})

	Warn(args ...interface{})

	Warnf(template string, args ...interface{})

	Warnw(msg string, keysAndValues ...interface{})

	Error(args ...interface{})

	Errorf(template string, args ...interface{})

	Errorw(msg string, keysAndValues ...interface{})

	// 同步,确保日志写入
	Sync()
}

ExchangeLogger 交易所撮合日志

type ExchangeSim added in v1.1.10

type ExchangeSim interface {

	// 设置回测组件
	SetBacktest(backtest IBacktest)

	// 设置交易撮合日志组件
	SetExchangeLogger(l ExchangeLogger)

	// 运行一次(回测系统调用)
	RunEventLoopOnce() (err error) // Run sim match for backtest only
}

ExchangeSim 模拟交易所接口

type IBacktest added in v1.2.3

type IBacktest interface {
	// 获取当前时间
	GetTime() time.Time
}

IBacktest 回测的接口

type Item

type Item struct {
	Price  float64
	Amount float64
}

type LogItem

type LogItem struct {
	Time    time.Time `json:"time"`
	RawTime time.Time `json:"raw_time"`
	Prices  []float64 `json:"prices"`
	//Ask     float64    `json:"ask"`
	//Bid     float64    `json:"bid"`
	Stats []LogStats `json:"stats"`
}

func (*LogItem) TotalEquity

func (i *LogItem) TotalEquity() float64

type LogItems

type LogItems []*LogItem

type LogStats

type LogStats struct {
	Balance float64 `json:"balance"`
	Equity  float64 `json:"equity"`
}

type Market added in v0.9.9

type Market struct {
	Symbol string // BTCUSDT(OKEX)/XBTUSD(BitMEX)/...
}

Market 市场信息

type Order

type Order struct {
	ID           string      `json:"id"`            // ID
	ClientOId    string      `json:"client_oid"`    // 客户端订单ID
	Symbol       string      `json:"symbol"`        // 标
	Time         time.Time   `json:"time"`          // 订单时间
	Price        float64     `json:"price"`         // 价格
	StopPx       float64     `json:"stop_px"`       // 触发价
	Amount       float64     `json:"amount"`        // 委托数量
	AvgPrice     float64     `json:"avg_price"`     // 平均成交价
	FilledAmount float64     `json:"filled_amount"` // 成交数量
	Direction    Direction   `json:"direction"`     // 委托方向
	Type         OrderType   `json:"type"`          // 委托类型
	PostOnly     bool        `json:"post_only"`     // 只做Maker选项
	ReduceOnly   bool        `json:"reduce_only"`   // 只减仓选项
	Commission   float64     `json:"commission"`    // 支付的佣金
	Pnl          float64     `json:"pnl"`           // 盈亏
	UpdateTime   time.Time   `json:"update_time"`   // 更新时间
	Status       OrderStatus `json:"status"`        // 委托状态
}

Order 委托

func (*Order) IsOpen

func (o *Order) IsOpen() bool

IsOpen 是否活跃委托

type OrderBook

type OrderBook struct {
	Symbol string
	Time   time.Time
	Asks   []Item
	Bids   []Item
}

func (*OrderBook) Ask

func (o *OrderBook) Ask() (result Item)

Ask 卖一

func (*OrderBook) AskAvePrice added in v1.1.9

func (o *OrderBook) AskAvePrice(size float64) float64

func (*OrderBook) AskPrice

func (o *OrderBook) AskPrice() (result float64)

AskPrice 卖一价

func (*OrderBook) Bid

func (o *OrderBook) Bid() (result Item)

Bid 买一

func (*OrderBook) BidAvePrice added in v1.1.9

func (o *OrderBook) BidAvePrice(size float64) float64

func (*OrderBook) BidPrice

func (o *OrderBook) BidPrice() (result float64)

BidPrice 买一价

func (*OrderBook) MatchAsks added in v1.2.3

func (o *OrderBook) MatchAsks(size float64) (filledSize float64, avgPrice float64)

func (*OrderBook) MatchBids added in v1.2.3

func (o *OrderBook) MatchBids(size float64) (filledSize float64, avgPrice float64)

func (*OrderBook) MatchOrderbook added in v1.2.3

func (o *OrderBook) MatchOrderbook(size float64, ob []Item) (filledSize float64, avgPrice float64)

func (*OrderBook) Price

func (o *OrderBook) Price() float64

Price returns the middle of Bid and Ask.

func (*OrderBook) Table added in v1.2.4

func (o *OrderBook) Table() string

type OrderOption added in v1.1.3

type OrderOption func(p *OrderParameter)

订单选项

func OrderStopOption added in v1.1.6

func OrderStopOption(stop bool) OrderOption

触发委托选项

type OrderParameter added in v1.1.3

type OrderParameter struct {
	Stop bool // 是否是触发委托
}

func ParseOrderParameter added in v1.1.3

func ParseOrderParameter(opts ...OrderOption) *OrderParameter

type OrderStatus

type OrderStatus int

OrderStatus 委托状态

const (
	OrderStatusCreated         OrderStatus = iota // 创建委托
	OrderStatusRejected                           // 委托被拒绝
	OrderStatusNew                                // 委托待成交
	OrderStatusPartiallyFilled                    // 委托部分成交
	OrderStatusFilled                             // 委托完全成交
	OrderStatusCancelPending                      // 委托取消
	OrderStatusCancelled                          // 委托被取消
	OrderStatusUntriggered                        // 等待触发条件委托单
	OrderStatusTriggered                          // 已触发条件单
)

func (OrderStatus) String

func (s OrderStatus) String() string

type OrderType

type OrderType int

OrderType 委托类型

const (
	OrderTypeMarket     OrderType = iota // 市价单
	OrderTypeLimit                       // 限价单
	OrderTypeStopMarket                  // 市价止损单
	OrderTypeStopLimit                   // 限价止损单
)

func (OrderType) String

func (t OrderType) String() string

type Parameters added in v1.1.1

type Parameters struct {
	DebugMode  bool
	HttpClient *http.Client
	ProxyURL   string // example: socks5://127.0.0.1:1080 | http://127.0.0.1:1080
	ApiURL     string
	WsURL      string
	Testnet    bool
	AccessKey  string
	SecretKey  string
	Passphrase string
	WebSocket  bool // Enable websocket option
}

type PlaceOrderOption added in v1.1.6

type PlaceOrderOption func(p *PlaceOrderParameter)

订单选项

func OrderBasePriceOption added in v1.1.6

func OrderBasePriceOption(basePrice float64) PlaceOrderOption

基础价格选项(如: bybit 需要提供此参数)

func OrderClientOIdOption added in v1.2.6

func OrderClientOIdOption(clientOId string) PlaceOrderOption

func OrderPostOnlyOption added in v1.1.3

func OrderPostOnlyOption(postOnly bool) PlaceOrderOption

被动委托选项

func OrderPriceTypeOption added in v1.1.3

func OrderPriceTypeOption(priceType string) PlaceOrderOption

OrderPriceType 选项

func OrderReduceOnlyOption added in v1.1.3

func OrderReduceOnlyOption(reduceOnly bool) PlaceOrderOption

只减仓选项

func OrderStopPxOption added in v1.1.3

func OrderStopPxOption(stopPx float64) PlaceOrderOption

触发价格选项

type PlaceOrderParameter added in v1.1.6

type PlaceOrderParameter struct {
	BasePrice  float64
	StopPx     float64
	PostOnly   bool
	ReduceOnly bool
	PriceType  string
	ClientOId  string
}

func ParsePlaceOrderParameter added in v1.1.6

func ParsePlaceOrderParameter(opts ...PlaceOrderOption) *PlaceOrderParameter

type Position

type Position struct {
	Symbol    string    `json:"symbol"`     // 标
	OpenTime  time.Time `json:"open_time"`  // 开仓时间
	OpenPrice float64   `json:"open_price"` // 开仓价
	Size      float64   `json:"size"`       // 仓位大小
	AvgPrice  float64   `json:"avg_price"`  // 平均价
	Profit    float64   `json:"profit"`     //浮动盈亏
}

Position 持仓

func (*Position) IsLong

func (p *Position) IsLong() bool

IsLong 是否多仓

func (*Position) IsOpen

func (p *Position) IsOpen() bool

IsOpen 是否持仓

func (*Position) IsShort

func (p *Position) IsShort() bool

IsShort 是否空仓

func (*Position) Side

func (p *Position) Side() Direction

type Record added in v0.9.8

type Record struct {
	Symbol    string    `json:"symbol"`    // 标
	Timestamp time.Time `json:"timestamp"` // 时间
	Open      float64   `json:"open"`      // 开盘价
	High      float64   `json:"high"`      // 最高价
	Low       float64   `json:"low"`       // 最低价
	Close     float64   `json:"close"`     // 收盘价
	Volume    float64   `json:"volume"`    // 量
}

Record 表示K线数据

type SpotAsset added in v1.2.3

type SpotAsset struct {
	Name      string  // BTC
	Available float64 // 可用
	Frozen    float64 // 冻结
	Borrow    float64 // 借币
}

现货资产

type SpotBalance added in v1.2.3

type SpotBalance struct {
	Base  SpotAsset // 基础货币
	Quote SpotAsset // 交易的资产
}

SpotBalance 现货账号资产

type SpotExchange added in v1.2.3

type SpotExchange interface {

	// 获取 Exchange 名称
	GetName() (name string)

	// 获取交易所时间(ms)
	GetTime() (tm int64, err error)

	// 获取账号余额
	GetBalance(currency string) (result *SpotBalance, err error)

	// 获取订单薄(OrderBook)
	GetOrderBook(symbol string, depth int) (result *OrderBook, err error)

	// 获取K线数据
	// period: 数据周期. 分钟或者关键字1m(minute) 1h 1d 1w 1M(month) 1y 枚举值:1 3 5 15 30 60 120 240 360 720 "5m" "4h" "1d" ...
	GetRecords(symbol string, period string, from int64, end int64, limit int) (records []*Record, err error)

	// 买
	Buy(symbol string, orderType OrderType, price float64, size float64) (result *Order, err error)

	// 卖
	Sell(symbol string, orderType OrderType, price float64, size float64) (result *Order, err error)

	// 下单
	PlaceOrder(symbol string, direction Direction, orderType OrderType, price float64, size float64,
		opts ...PlaceOrderOption) (result *Order, err error)

	// 获取活跃委托单列表
	GetOpenOrders(symbol string, opts ...OrderOption) (result []*Order, err error)

	// 获取历史委托列表
	GetHistoryOrders(symbol string, opts ...OrderOption) (result []*Order, err error)

	// 获取委托信息
	GetOrder(symbol string, id string, opts ...OrderOption) (result *Order, err error)

	// 撤销全部委托单
	CancelAllOrders(symbol string, opts ...OrderOption) (err error)

	// 撤销单个委托单
	CancelOrder(symbol string, id string, opts ...OrderOption) (result *Order, err error)
}

SpotExchange 现货交易所接口

type SpotExchangeSim added in v1.2.3

type SpotExchangeSim interface {
	SpotExchange

	// 设置交易撮合日志组件
	SetExchangeLogger(l ExchangeLogger)

	// 运行一次(回测系统调用)
	RunEventLoopOnce() (err error) // Run sim match for backtest only
}

SpotExchangeSim 模拟交易所接口

type SpotStrategyBase added in v1.2.4

type SpotStrategyBase struct {
	Exchanges []SpotExchange
	Exchange  SpotExchange
	// contains filtered or unexported fields
}

SpotStrategyBase Strategy base class

func (*SpotStrategyBase) GetOptions added in v1.2.4

func (s *SpotStrategyBase) GetOptions() (optionMap map[string]*StrategyOption)

GetOptions Returns the options of strategy

func (*SpotStrategyBase) Name added in v1.2.4

func (s *SpotStrategyBase) Name() string

func (*SpotStrategyBase) SetName added in v1.2.4

func (s *SpotStrategyBase) SetName(name string)

func (*SpotStrategyBase) SetOptions added in v1.2.4

func (s *SpotStrategyBase) SetOptions(options map[string]interface{}) error

SetOptions Sets the options for the strategy

func (*SpotStrategyBase) SetSelf added in v1.2.4

func (s *SpotStrategyBase) SetSelf(self Strategy) error

SetSelf 设置 self 对象

func (*SpotStrategyBase) Setup added in v1.2.4

func (s *SpotStrategyBase) Setup(mode TradeMode, exchanges ...interface{}) error

Setup Setups the exchanges

func (*SpotStrategyBase) TradeMode added in v1.2.4

func (s *SpotStrategyBase) TradeMode() TradeMode

type Stats

type Stats struct {
	Start           time.Time     `json:"start"`
	End             time.Time     `json:"end"`
	Duration        time.Duration `json:"duration"`
	RunDuration     time.Duration `json:"run_duration"`
	EntryPrice      float64       `json:"entry_price"`
	ExitPrice       float64       `json:"exit_price"`
	EntryEquity     float64       `json:"entry_equity"`
	ExitEquity      float64       `json:"exit_equity"`
	BaHReturn       float64       `json:"bah_return"`     // Buy & Hold Return
	BaHReturnPnt    float64       `json:"bah_return_pnt"` // Buy & Hold Return
	EquityReturn    float64       `json:"equity_return"`
	EquityReturnPnt float64       `json:"equity_return_pnt"`
	AnnReturn       float64       `json:"ann_return"`    // 年化收益率
	MaxDrawDown     float64       `json:"max_draw_down"` // 最大回撤
}

Stats Back testing Statistics

func (*Stats) PrintResult

func (s *Stats) PrintResult()

type Strategy

type Strategy interface {
	Name() string
	SetName(name string)
	SetSelf(self Strategy) error
	//Setup(mode TradeMode, exchanges ...Exchange) error
	Setup(mode TradeMode, exchanges ...interface{}) error
	IsStopped() bool
	StopNow()
	TradeMode() TradeMode
	SetOptions(options map[string]interface{}) error
	Run() error
	OnInit() error
	OnTick() error
	OnExit() error
}

Strategy interface

type StrategyBase

type StrategyBase struct {
	Exchanges []Exchange
	Exchange  Exchange
	// contains filtered or unexported fields
}

StrategyBase Strategy base class

func (*StrategyBase) GetOptions added in v1.1.4

func (s *StrategyBase) GetOptions() (optionMap map[string]*StrategyOption)

GetOptions Returns the options of strategy

func (*StrategyBase) IsStopped added in v1.2.7

func (s *StrategyBase) IsStopped() bool

func (*StrategyBase) Name added in v1.1.10

func (s *StrategyBase) Name() string

func (*StrategyBase) SetName added in v1.1.10

func (s *StrategyBase) SetName(name string)

func (*StrategyBase) SetOptions added in v1.1.4

func (s *StrategyBase) SetOptions(options map[string]interface{}) error

SetOptions Sets the options for the strategy

func (*StrategyBase) SetSelf added in v1.1.4

func (s *StrategyBase) SetSelf(self Strategy) error

SetSelf 设置 self 对象

func (*StrategyBase) Setup

func (s *StrategyBase) Setup(mode TradeMode, exchanges ...interface{}) error

Setup Setups the exchanges

func (*StrategyBase) StopNow added in v1.2.7

func (s *StrategyBase) StopNow()

func (*StrategyBase) TradeMode added in v1.1.4

func (s *StrategyBase) TradeMode() TradeMode

type StrategyOption added in v1.1.4

type StrategyOption struct {
	Name         string      `json:"name"`
	Description  string      `json:"description"`
	Type         string      `json:"type"`
	Value        interface{} `json:"value"`
	DefaultValue interface{} `json:"default_value"`
}

StrategyOption 策略参数

type Trade added in v0.9.10

type Trade struct {
	ID        string    `json:"id"`     // ID
	Direction Direction `json:"type"`   // 主动成交方向
	Price     float64   `json:"price"`  // 价格
	Amount    float64   `json:"amount"` // 成交量(张),买卖双边成交量之和
	Ts        int64     `json:"ts"`     // 订单成交时间 unix time (ms)
	Symbol    string    `json:"omitempty"`
}

Trade 成交记录

type TradeMode

type TradeMode int

TradeMode 策略模式

const (
	TradeModeBacktest TradeMode = iota
	TradeModePaperTrading
	TradeModeLiveTrading
)

func (TradeMode) String

func (t TradeMode) String() string

type WSEvent added in v0.9.9

type WSEvent int

WS 事件

const (
	WSEventTrade WSEvent = iota + 1
	WSEventL2Snapshot
	WSEventBalance
	WSEventOrder
	WSEventPosition
	WSEventError
	WSEventDisconnected
	WSEventReconnected
)

WS 事件枚举

type WebSocket added in v0.9.9

type WebSocket interface {
	SubscribeTrades(market Market, callback func(trades []Trade)) error
	SubscribeLevel2Snapshots(market Market, callback func(ob *OrderBook)) error
	//SubscribeBalances(market Market, callback func(balance *Balance)) error
	SubscribeOrders(market Market, callback func(orders []Order)) error
	SubscribePositions(market Market, callback func(positions []Position)) error
}

WebSocket 代表WS连接

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL