bbgo_origin/pkg/service/profit.go

111 lines
1.8 KiB
Go
Raw Normal View History

package service
import (
"context"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/c9s/bbgo/pkg/types"
)
type ProfitService struct {
DB *sqlx.DB
}
func NewProfitService(db *sqlx.DB) *ProfitService {
return &ProfitService{db}
}
func (s *ProfitService) Load(ctx context.Context, id int64) (*types.Trade, error) {
var trade types.Trade
rows, err := s.DB.NamedQuery("SELECT * FROM trades WHERE id = :id", map[string]interface{}{
"id": id,
})
if err != nil {
return nil, err
}
defer rows.Close()
if rows.Next() {
err = rows.StructScan(&trade)
return &trade, err
}
return nil, errors.Wrapf(ErrTradeNotFound, "trade id:%d not found", id)
}
2022-03-04 11:24:40 +00:00
func (s *ProfitService) scanRows(rows *sqlx.Rows) (profits []types.Profit, err error) {
for rows.Next() {
2022-03-04 11:24:40 +00:00
var profit types.Profit
if err := rows.StructScan(&profit); err != nil {
return profits, err
}
2022-03-04 11:24:40 +00:00
profits = append(profits, profit)
}
2022-03-04 11:24:40 +00:00
return profits, rows.Err()
}
2022-03-04 11:24:40 +00:00
func (s *ProfitService) Insert(profit types.Profit) error {
_, err := s.DB.NamedExec(`
2022-03-04 11:24:40 +00:00
INSERT INTO profits (
strategy,
2022-03-04 16:27:44 +00:00
strategy_instance_id,
2022-03-04 11:24:40 +00:00
symbol,
2022-03-04 16:27:44 +00:00
quote_currency,
base_currency,
2022-03-04 11:24:40 +00:00
average_cost,
profit,
2022-03-04 16:27:44 +00:00
net_profit,
profit_margin,
net_profit_margin,
2022-03-04 11:24:40 +00:00
trade_id,
price,
quantity,
quote_quantity,
side,
2022-03-04 16:27:44 +00:00
is_buyer,
is_maker,
fee,
fee_currency,
fee_in_usd,
2022-03-04 11:24:40 +00:00
traded_at,
exchange,
is_margin,
is_futures,
is_isolated
) VALUES (
2022-03-04 16:27:44 +00:00
:strategy,
2022-03-04 11:24:40 +00:00
:strategy_instance_id,
:symbol,
2022-03-04 16:27:44 +00:00
:quote_currency,
:base_currency,
2022-03-04 11:24:40 +00:00
:average_cost,
2022-03-04 16:27:44 +00:00
:profit,
:net_profit,
:profit_margin,
:net_profit_margin,
2022-03-04 11:24:40 +00:00
:trade_id,
:price,
:quantity,
:quote_quantity,
:side,
:is_buyer,
:is_maker,
:fee,
:fee_currency,
2022-03-04 16:27:44 +00:00
:fee_in_usd,
2022-03-04 11:24:40 +00:00
:traded_at,
:exchange,
:is_margin,
:is_futures,
:is_isolated
)`,
profit)
return err
}