Skip to content
This repository has been archived by the owner on Feb 1, 2024. It is now read-only.

Commit

Permalink
Use clients/horizonclient (#204)
Browse files Browse the repository at this point in the history
* use horizonclient

* change more instances to horizonclient

* fix loadaccount function

* remove duplicate AppName and AppVersion headers
  • Loading branch information
poliha authored and nikhilsaraf committed Jul 25, 2019
1 parent 4af564d commit 585080c
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 64 deletions.
12 changes: 7 additions & 5 deletions accounting/pnl/pnl.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import (
"strconv"
"strings"

"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/plugins"
)
Expand Down Expand Up @@ -51,7 +52,7 @@ func main() {
}

func getTotalNativeValue(address string, cmcRef string) float64 {
client := horizon.DefaultPublicNetClient
client := horizonclient.DefaultPublicNetClient
account := loadAccount(client, address)

nativeBal := 0.0
Expand Down Expand Up @@ -95,11 +96,12 @@ func getTotalNativeValue(address string, cmcRef string) float64 {
return totalNativeValue
}

func loadAccount(client *horizon.Client, address string) horizon.Account {
account, e := client.LoadAccount(address)
func loadAccount(client *horizonclient.Client, address string) hProtocol.Account {
acctReq := horizonclient.AccountRequest{AccountID: address}
account, e := client.AccountDetail(acctReq)
if e != nil {
switch t := e.(type) {
case *horizon.Error:
case *horizonclient.Error:
log.Fatal(t.Problem)
default:
log.Fatal(e)
Expand Down
6 changes: 3 additions & 3 deletions cmd/terminate.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

"github.com/nikhilsaraf/go-tools/multithreading"
"github.com/spf13/cobra"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/support/config"
"github.com/stellar/kelp/model"
Expand Down Expand Up @@ -38,8 +38,8 @@ func init() {
log.Println("Started Terminator for account: ", *configFile.TradingAccount)

// --- start initialization of objects ----
client := &horizon.Client{
URL: configFile.HorizonURL,
client := &horizonclient.Client{
HorizonURL: configFile.HorizonURL,
HTTP: http.DefaultClient,
AppName: "kelp",
AppVersion: version,
Expand Down
33 changes: 12 additions & 21 deletions cmd/trade.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/nikhilsaraf/go-tools/multithreading"
"github.com/spf13/cobra"
"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/support/config"
Expand Down Expand Up @@ -195,8 +194,7 @@ func makeExchangeShimSdex(
l logger.Logger,
botConfig trader.BotConfig,
options inputs,
client *horizon.Client,
newClient *horizonclient.Client,
client *horizonclient.Client,
ieif *plugins.IEIF,
network build.Network,
threadTracker *multithreading.ThreadTracker,
Expand Down Expand Up @@ -263,7 +261,7 @@ func makeExchangeShimSdex(
tradingPair.Base: botConfig.AssetBase(),
tradingPair.Quote: botConfig.AssetQuote(),
}
feeFn := makeFeeFn(l, botConfig, newClient)
feeFn := makeFeeFn(l, botConfig, client)
sdex := plugins.MakeSDEX(
client,
ieif,
Expand Down Expand Up @@ -292,7 +290,7 @@ func makeStrategy(
l logger.Logger,
network build.Network,
botConfig trader.BotConfig,
client *horizon.Client,
client *horizonclient.Client,
sdex *plugins.SDEX,
exchangeShim api.ExchangeShim,
assetBase hProtocol.Asset,
Expand Down Expand Up @@ -324,7 +322,7 @@ func makeStrategy(
func makeBot(
l logger.Logger,
botConfig trader.BotConfig,
client *horizon.Client,
client *horizonclient.Client,
sdex *plugins.SDEX,
exchangeShim api.ExchangeShim,
ieif *plugins.IEIF,
Expand Down Expand Up @@ -397,20 +395,13 @@ func runTradeCmd(options inputs) {
Quote: model.Asset(utils.Asset2CodeString(assetQuote)),
}

client := &horizon.Client{
URL: botConfig.HorizonURL,
HTTP: http.DefaultClient,
}
newClient := &horizonclient.Client{
// TODO horizonclient.Client has a bug in it where it does not use "/" to separate the horizonURL from the fee_stats endpoint
HorizonURL: botConfig.HorizonURL + "/",
client := &horizonclient.Client{
HorizonURL: botConfig.HorizonURL,
HTTP: http.DefaultClient,
}
if !*options.noHeaders {
client.AppName = "kelp"
client.AppVersion = version
newClient.AppName = "kelp"
newClient.AppVersion = version

p := prefs.Make(prefsFilename)
if p.FirstTime() {
Expand Down Expand Up @@ -439,7 +430,6 @@ func runTradeCmd(options inputs) {
botConfig,
options,
client,
newClient,
ieif,
network,
threadTracker,
Expand Down Expand Up @@ -560,7 +550,7 @@ func startFillTracking(
l logger.Logger,
strategy api.Strategy,
botConfig trader.BotConfig,
client *horizon.Client,
client *horizonclient.Client,
sdex *plugins.SDEX,
exchangeShim api.ExchangeShim,
tradingPair *model.TradingPair,
Expand Down Expand Up @@ -607,7 +597,7 @@ func startQueryServer(
strategyName string,
strategy api.Strategy,
botConfig trader.BotConfig,
client *horizon.Client,
client *horizonclient.Client,
sdex *plugins.SDEX,
exchangeShim api.ExchangeShim,
tradingPair *model.TradingPair,
Expand Down Expand Up @@ -643,14 +633,15 @@ func startQueryServer(
}()
}

func validateTrustlines(l logger.Logger, client *horizon.Client, botConfig *trader.BotConfig) {
func validateTrustlines(l logger.Logger, client *horizonclient.Client, botConfig *trader.BotConfig) {
if !botConfig.IsTradingSdex() {
l.Info("no need to validate trustlines because we're not using SDEX as the trading exchange")
return
}

log.Printf("validating trustlines...\n")
account, e := client.LoadAccount(botConfig.TradingAccount())
acctReq := horizonclient.AccountRequest{AccountID: botConfig.TradingAccount()}
account, e := client.AccountDetail(acctReq)
if e != nil {
logger.Fatal(l, e)
}
Expand Down Expand Up @@ -679,7 +670,7 @@ func validateTrustlines(l logger.Logger, client *horizon.Client, botConfig *trad
func deleteAllOffersAndExit(
l logger.Logger,
botConfig trader.BotConfig,
client *horizon.Client,
client *horizonclient.Client,
sdex *plugins.SDEX,
exchangeShim api.ExchangeShim,
threadTracker *multithreading.ThreadTracker,
Expand Down
2 changes: 1 addition & 1 deletion gui/backend/get_bot_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func (s *APIServer) runGetBotInfoDirect(w http.ResponseWriter, botName string) {
}
}

offers, e := utils.LoadAllOffers(account.AccountID, horizon.DefaultTestNetClient)
offers, e := utils.LoadAllOffers(account.AccountID, horizonclient.DefaultTestNetClient)
if e != nil {
s.writeErrorJson(w, fmt.Sprintf("error getting offers for account '%s' for botName '%s': %s\n", botConfig.TradingAccount(), botName, e))
return
Expand Down
6 changes: 3 additions & 3 deletions plugins/priceFeed.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import (
"strings"

"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/model"
)

// privateSdexHack is a temporary hack struct for SDEX price feeds pending refactor
type privateSdexHack struct {
API *horizon.Client
API *horizonclient.Client
Ieif *IEIF
Network build.Network
}
Expand All @@ -21,7 +21,7 @@ type privateSdexHack struct {
var privateSdexHackVar *privateSdexHack

// SetPrivateSdexHack sets the privateSdexHack variable which is temporary until the pending SDEX price feed refactor
func SetPrivateSdexHack(api *horizon.Client, ieif *IEIF, network build.Network) error {
func SetPrivateSdexHack(api *horizonclient.Client, ieif *IEIF, network build.Network) error {
if privateSdexHackVar != nil {
return fmt.Errorf("privateSdexHack is already set: %+v", privateSdexHackVar)
}
Expand Down
63 changes: 51 additions & 12 deletions plugins/sdex.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/nikhilsaraf/go-tools/multithreading"
"github.com/pkg/errors"
"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/model"
Expand All @@ -33,7 +33,7 @@ const fetchTradesResolution = 300000

// SDEX helps with building and submitting transactions to the Stellar network
type SDEX struct {
API *horizon.Client
API *horizonclient.Client
SourceAccount string
TradingAccount string
SourceSeed string
Expand Down Expand Up @@ -70,7 +70,7 @@ type Balance struct {

// MakeSDEX is a factory method for SDEX
func MakeSDEX(
api *horizon.Client,
api *horizonclient.Client,
ieif *IEIF,
exchangeShim api.ExchangeShim,
sourceSeed string,
Expand Down Expand Up @@ -157,7 +157,13 @@ func (sdex *SDEX) GetAssetConverter() *model.AssetConverter {
func (sdex *SDEX) incrementSeqNum() {
if sdex.reloadSeqNum {
log.Println("reloading sequence number")
seqNum, err := sdex.API.SequenceForAccount(sdex.SourceAccount)
acctReq := horizonclient.AccountRequest{AccountID: sdex.SourceAccount}
accountDetail, err := sdex.API.AccountDetail(acctReq)
if err != nil {
log.Printf("error loading account detail: %s\n", err)
return
}
seqNum, err := accountDetail.GetSequenceNumber()
if err != nil {
log.Printf("error getting seq num: %s\n", err)
return
Expand Down Expand Up @@ -223,7 +229,8 @@ func (sdex *SDEX) minReserve(subentries int32) float64 {

// assetBalance returns asset balance, asset trust limit, reserve balance (zero for non-XLM), error
func (sdex *SDEX) _assetBalance(asset hProtocol.Asset) (*api.Balance, error) {
account, err := sdex.API.LoadAccount(sdex.TradingAccount)
acctReq := horizonclient.AccountRequest{AccountID: sdex.TradingAccount}
account, err := sdex.API.AccountDetail(acctReq)
if err != nil {
return nil, fmt.Errorf("error: unable to load account to fetch balance: %s", err)
}
Expand Down Expand Up @@ -433,10 +440,10 @@ func (sdex *SDEX) sign(tx *build.TransactionBuilder) (string, error) {
}

func (sdex *SDEX) submit(txeB64 string, asyncCallback func(hash string, e error), asyncMode bool) {
resp, err := sdex.API.SubmitTransaction(txeB64)
resp, err := sdex.API.SubmitTransactionXDR(txeB64)
if err != nil {
if herr, ok := errors.Cause(err).(*horizon.Error); ok {
var rcs *horizon.TransactionResultCodes
if herr, ok := errors.Cause(err).(*horizonclient.Error); ok {
var rcs *hProtocol.TransactionResultCodes
rcs, err = herr.ResultCodes()
if err != nil {
log.Printf("(async) error: no result codes from horizon: %s\n", err)
Expand Down Expand Up @@ -530,7 +537,19 @@ func (sdex *SDEX) GetTradeHistory(pair model.TradingPair, maybeCursorStart inter

trades := []model.Trade{}
for {
tradesPage, e := sdex.API.LoadTrades(baseAsset, quoteAsset, 0, fetchTradesResolution, horizon.Cursor(cursorStart), horizon.Order(horizon.OrderAsc), horizon.Limit(maxPageLimit))
tradeReq := horizonclient.TradeRequest{
BaseAssetType: horizonclient.AssetType(baseAsset.Type),
BaseAssetCode: baseAsset.Code,
BaseAssetIssuer: baseAsset.Issuer,
CounterAssetType: horizonclient.AssetType(quoteAsset.Type),
CounterAssetCode: quoteAsset.Code,
CounterAssetIssuer: quoteAsset.Issuer,
Order: horizonclient.OrderAsc,
Cursor: cursorStart,
Limit: uint(maxPageLimit),
}

tradesPage, e := sdex.API.Trades(tradeReq)
if e != nil {
if strings.Contains(e.Error(), "Rate limit exceeded") {
// return normally, we will continue loading trades in the next call from where we left off
Expand Down Expand Up @@ -631,7 +650,7 @@ func (sdex *SDEX) getOrderAction(baseAsset hProtocol.Asset, quoteAsset hProtocol
}

// returns tradeHistoryResult, hitCursorEnd, and any error
func (sdex *SDEX) tradesPage2TradeHistoryResult(baseAsset hProtocol.Asset, quoteAsset hProtocol.Asset, tradesPage horizon.TradesPage, cursorEnd string) (*api.TradeHistoryResult, bool, error) {
func (sdex *SDEX) tradesPage2TradeHistoryResult(baseAsset hProtocol.Asset, quoteAsset hProtocol.Asset, tradesPage hProtocol.TradesPage, cursorEnd string) (*api.TradeHistoryResult, bool, error) {
var cursor string
trades := []model.Trade{}

Expand Down Expand Up @@ -688,7 +707,18 @@ func (sdex *SDEX) GetLatestTradeCursor() (interface{}, error) {
return nil, fmt.Errorf("error while convertig pair to base and quote asset: %s", e)
}

tradesPage, e := sdex.API.LoadTrades(baseAsset, quoteAsset, 0, fetchTradesResolution, horizon.Order(horizon.OrderDesc), horizon.Limit(1))
tradeReq := horizonclient.TradeRequest{
BaseAssetType: horizonclient.AssetType(baseAsset.Type),
BaseAssetCode: baseAsset.Code,
BaseAssetIssuer: baseAsset.Issuer,
CounterAssetType: horizonclient.AssetType(quoteAsset.Type),
CounterAssetCode: quoteAsset.Code,
CounterAssetIssuer: quoteAsset.Issuer,
Order: horizonclient.OrderDesc,
Limit: uint(1),
}

tradesPage, e := sdex.API.Trades(tradeReq)
if e != nil {
return nil, fmt.Errorf("error while fetching latest trade cursor in SDEX: %s", e)
}
Expand All @@ -713,7 +743,16 @@ func (sdex *SDEX) GetOrderBook(pair *model.TradingPair, maxCount int32) (*model.
return nil, fmt.Errorf("cannot get SDEX orderbook: %s", e)
}

ob, e := sdex.API.LoadOrderBook(baseAsset, quoteAsset)
obReq := horizonclient.OrderBookRequest{
SellingAssetType: horizonclient.AssetType(baseAsset.Type),
SellingAssetCode: baseAsset.Code,
SellingAssetIssuer: baseAsset.Issuer,
BuyingAssetType: horizonclient.AssetType(quoteAsset.Type),
BuyingAssetCode: quoteAsset.Code,
BuyingAssetIssuer: quoteAsset.Issuer,
}

ob, e := sdex.API.OrderBook(obReq)
if e != nil {
return nil, fmt.Errorf("cannot get SDEX orderbook: %s", e)
}
Expand Down
6 changes: 3 additions & 3 deletions plugins/sdexFeed.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"strings"

"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/model"
Expand Down Expand Up @@ -44,7 +44,7 @@ func makeSDEXFeed(url string) (*sdexFeed, error) {
tradingPair.Quote: *quoteAsset,
}

var api *horizon.Client
var api *horizonclient.Client
var ieif *IEIF
var network build.Network
if privateSdexHackVar != nil {
Expand All @@ -53,7 +53,7 @@ func makeSDEXFeed(url string) (*sdexFeed, error) {
network = privateSdexHackVar.Network
} else {
// use production network by default
api = horizon.DefaultPublicNetClient
api = horizonclient.DefaultPublicNetClient
ieif = MakeIEIF(true)
network = build.PublicNetwork
}
Expand Down
6 changes: 3 additions & 3 deletions query/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

"github.com/stellar/kelp/support/utils"

"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/model"
"github.com/stellar/kelp/plugins"
Expand All @@ -23,7 +23,7 @@ type Server struct {
strategyName string
strategy api.Strategy
botConfig trader.BotConfig
client *horizon.Client
client *horizonclient.Client
sdex *plugins.SDEX
exchangeShim api.ExchangeShim
tradingPair *model.TradingPair
Expand All @@ -35,7 +35,7 @@ func MakeServer(
strategyName string,
strategy api.Strategy,
botConfig trader.BotConfig,
client *horizon.Client,
client *horizonclient.Client,
sdex *plugins.SDEX,
exchangeShim api.ExchangeShim,
tradingPair *model.TradingPair,
Expand Down
Loading

0 comments on commit 585080c

Please sign in to comment.