Skip to content

Commit

Permalink
Quotes (#22)
Browse files Browse the repository at this point in the history
* add Quotes

* add Quotes

* add QuotesChan

* add QuotesChan

* fix deprecated grpc connection

* fix quotes struct

---------

Co-authored-by: whitefox <whitefox@mayflower.work>
  • Loading branch information
kmlebedev and whitefox authored Dec 8, 2024
1 parent c20fafc commit 0906159
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
33 changes: 28 additions & 5 deletions client/commands/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bytes"
"encoding/xml"
"fmt"
log "github.com/sirupsen/logrus"
"time"
)

type ServerStatus struct {
Expand Down Expand Up @@ -446,7 +448,7 @@ type Quotation struct {
Board string `xml:"board,omitempty"` // Идентификатор режима торгов
SecCode string `xml:"seccode,omitempty"` // Код инструмента
Open float64 `xml:"open,omitempty"` // Цена первой сделки
WapPice float64 `xml:"waprice,omitempty"` // Средневзвешенная цена
WapPrice float64 `xml:"waprice,omitempty"` // Средневзвешенная цена
Last float64 `xml:"last,omitempty"` // Цена последней сделки
Quantity int `xml:"quantity,omitempty"` // Объем последней сделки, в лотах
Time string `xml:"time,omitempty"` // Время заключения последней сделки
Expand Down Expand Up @@ -484,14 +486,14 @@ type Quotation struct {
LCurrentPrice float64 `xml:"lcurrentprice,omitempty"` // Официальная текущая цена Биржи
}

type trade struct {
type Trade struct {
XMLName xml.Name `xml:"trade"`
SecId int `xml:"secid,attr"` // внутренний код
SecCode string `xml:"seccode,omitempty"` // Код инструмента
TradeNo int64 `xml:"tradeno,omitempty"` // Биржевой номер сделки
Time string `xml:"time,omitempty"` // Время сделки :date
Board string `xml:"board,omitempty"` // Идентификатор режима торгов
Pice float64 `xml:"price,omitempty"` // Цена сделки
Price float64 `xml:"price,omitempty"` // Цена сделки
Quantity int `xml:"quantity,omitempty"` // Объем сделки, в лотах
BuySell string `xml:"buysell,omitempty"` // покупка (B) / продажа (S)
OpenInterest int `xml:"openinterest,omitempty"` // Открытый интерес
Expand All @@ -500,7 +502,7 @@ type trade struct {

type AllTrades struct {
XMLName xml.Name `xml:"alltrades"`
Items []trade `xml:"trade"`
Items []Trade `xml:"trade"`
}

type SecInfo struct {
Expand Down Expand Up @@ -535,10 +537,31 @@ type SecInfo struct {
CurrencyId string `xml:"currencyid,omitempty"` // Валюта расчетов режима торгов по умолчанию
}

type Quotes struct {
XMLName xml.Name `xml:"quotes"`
Items []Quote `xml:"quote"`
Time time.Time
}

// Значение «-1» одновременно и в поле sell и в поле buy означает, что строка с данной ценой (или с данным значением пары price + source) удалена из «стакана».
type Quote struct {
XMLName xml.Name `xml:"quote"`
SecId int `xml:"secid,attr"` // внутренний код
SecCode string `xml:"seccode,omitempty"` // Код инструмента
Board string `xml:"board,omitempty"` // Идентификатор режима торгов
Price float64 `xml:"price,omitempty"` // Цена
Source string `xml:"source,omitempty"` // Источник котировки (маркетмейкер)
Yield int `xml:"yield,omitempty"` // Доходность (актуально только для облигаций)
Buy int `xml:"buy,omitempty"` // Количество бумаг к покупке, значение «-1» - больше нет заявок на покупку
Sell int `xml:"sell,omitempty"` // Количество бумаг к продаже, значение «-1» - больше нет заявок на покупку
}

// Encodes the request into XML format.
func EncodeRequest(request interface{}) string {
var bytesBuffer bytes.Buffer
e := xml.NewEncoder(&bytesBuffer)
e.Encode(request)
if err := e.Encode(request); err != nil {
log.Errorf("encode request %+v: %v", request, err)
}
return bytesBuffer.String()
}
23 changes: 18 additions & 5 deletions client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"os"
"strings"
"time"

. "github.com/kmlebedev/txmlconnector/client/commands"
pb "github.com/kmlebedev/txmlconnector/proto"
Expand Down Expand Up @@ -39,10 +40,15 @@ type TCClient struct {
ResponseChannel chan string
ShutdownChannel chan bool
AllTradesChan chan AllTrades
QuotesChan chan Quotes
grpcConn *grpc.ClientConn
ctx context.Context
}

var (
timeNowLocation, _ = time.LoadLocation("Europe/Moscow")
)

func init() {
ll := log.InfoLevel
if lvl, ok := os.LookupEnv("TC_LOG_LEVEL"); ok {
Expand Down Expand Up @@ -80,10 +86,8 @@ func NewTCClientWithConn(client pb.ConnectServiceClient, conn *grpc.ClientConn)

func NewTCClient() (*TCClient, error) {
log.Infoln("gRPC client running ...")
conn, err := grpc.Dial(
conn, err := grpc.NewClient(
os.Getenv("TC_TARGET"),
grpc.WithInsecure(),
grpc.WithBlock(),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
)
if err != nil {
Expand Down Expand Up @@ -123,7 +127,7 @@ func (tc *TCClient) Connect() error {
}
if result.Success != "true" {
log.Error("Result: ", result.Message)
fmt.Errorf("Result not success: %s", result.Message)
return fmt.Errorf("Result not success: %s", result.Message)
} else {
log.Debugf("Result: %+v", result)
}
Expand All @@ -136,7 +140,7 @@ func (tc *TCClient) Disconnect() error {
}

func (tc *TCClient) Close() {
tc.grpcConn.Close()
_ = tc.grpcConn.Close()
}

func (tc *TCClient) SendCommand(cmd Command) error {
Expand Down Expand Up @@ -185,6 +189,15 @@ func (tc *TCClient) LoopReadingFromStream(stream *pb.ConnectService_FetchRespons
} else {
tc.AllTradesChan <- allTrades
}
case "quotes":
quotes := Quotes{}
now := time.Now().In(timeNowLocation)
if err := xml.Unmarshal(msgData, &quotes); err != nil {
log.Error(err)
} else {
quotes.Time = now
tc.QuotesChan <- quotes
}
case "sec_info_upd":
secInfoUpd := SecInfoUpd{}
if err := xml.Unmarshal(msgData, &secInfoUpd); err != nil {
Expand Down

0 comments on commit 0906159

Please sign in to comment.