forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
order_book_request.go
73 lines (61 loc) · 2.46 KB
/
order_book_request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package horizonclient
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/support/errors"
)
// BuildURL creates the endpoint to be queried based on the data in the OrderBookRequest struct.
func (obr OrderBookRequest) BuildURL() (endpoint string, err error) {
endpoint = "order_book"
// add the parameters to a map here so it is easier for addQueryParams to populate the parameter list
// We can't use assetCode and assetIssuer types here because the paremeter names are different
paramMap := make(map[string]string)
paramMap["selling_asset_type"] = string(obr.SellingAssetType)
paramMap["selling_asset_code"] = obr.SellingAssetCode
paramMap["selling_asset_issuer"] = obr.SellingAssetIssuer
paramMap["buying_asset_type"] = string(obr.BuyingAssetType)
paramMap["buying_asset_code"] = obr.BuyingAssetCode
paramMap["buying_asset_issuer"] = obr.BuyingAssetIssuer
queryParams := addQueryParams(paramMap, limit(obr.Limit))
if queryParams != "" {
endpoint = fmt.Sprintf("%s?%s", endpoint, queryParams)
}
_, err = url.Parse(endpoint)
if err != nil {
err = errors.Wrap(err, "failed to parse endpoint")
}
return endpoint, err
}
// HTTPRequest returns the http request for the order book endpoint
func (obr OrderBookRequest) HTTPRequest(horizonURL string) (*http.Request, error) {
endpoint, err := obr.BuildURL()
if err != nil {
return nil, err
}
return http.NewRequest("GET", horizonURL+endpoint, nil)
}
// OrderBookHandler is a function that is called when a new order summary is received
type OrderBookHandler func(hProtocol.OrderBookSummary)
// StreamOrderBooks streams the orderbook for a given asset pair. Use context.WithCancel
// to stop streaming or context.Background() if you want to stream indefinitely.
// OrderBookHandler is a user-supplied function that is executed for each streamed order received.
func (obr OrderBookRequest) StreamOrderBooks(ctx context.Context, client *Client, handler OrderBookHandler) error {
endpoint, err := obr.BuildURL()
if err != nil {
return errors.Wrap(err, "unable to build endpoint for orderbook request")
}
url := fmt.Sprintf("%s%s", client.fixHorizonURL(), endpoint)
return client.stream(ctx, url, func(data []byte) error {
var orderbook hProtocol.OrderBookSummary
err = json.Unmarshal(data, &orderbook)
if err != nil {
return errors.Wrap(err, "error unmarshaling data for orderbook request")
}
handler(orderbook)
return nil
})
}