Giter VIP home page Giter VIP logo

go-ftx's Introduction

go-ftx

FTX exchange API version2, renew at 2020/04.

Description

go-ftx is a go client library for FTX API Document.

Supported

  • Public & Private
  • Orders
  • Leveraged tokens
  • Options
  • Websocket
  • SubAccounts

Not Supported

  • FIX API

Installation

$ go get -u github.com/go-numb/go-ftx

Usage

package main

import (
	"fmt"
	"github.com/dustin/go-humanize"
	"github.com/go-numb/go-ftx/auth"
	"github.com/go-numb/go-ftx/rest"
	"github.com/go-numb/go-ftx/rest/private/orders"
	//"log"
	"github.com/go-numb/go-ftx/rest/private/account"
	"github.com/go-numb/go-ftx/rest/public/futures"
	"github.com/go-numb/go-ftx/rest/public/markets"
	"github.com/go-numb/go-ftx/types"
	"github.com/labstack/gommon/log"
	"sort"
	"strings"
)

func main() {
	// Only main account
	client := rest.New(auth.New("<key>", "<secret>"))

	// or
	// UseSubAccounts
	clientWithSubAccounts := rest.New(
		auth.New(
			"<key>",
			"<secret>",
			auth.SubAccount{
				UUID:     1,
				Nickname: "subaccount_1",
			},
			auth.SubAccount{
				UUID:     2,
				Nickname: "subaccount_2",
			},
			// many....
		))
	// switch subaccount
	clientWithSubAccounts.Auth.UseSubAccountID(1) // or 2... this number is key in map[int]SubAccount

	// account informations
	// client or clientWithSubAccounts in this time.
	c := client // or clientWithSubAccounts
	info, err := c.Information(&account.RequestForInformation{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%v\n", info)

	// lev, err := c.Leverage(5)
	lev, err := c.Leverage(&account.RequestForLeverage{
		Leverage: 3,
	})

	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%v\n", lev)

	market, err := c.Markets(&markets.RequestForMarkets{
		ProductCode: "XRPBULL/USDT",
	})

	if err != nil {
		log.Fatal(err)
	}

	// products List
	fmt.Printf("%+v\n", strings.Join(market.List(), "\n"))
	// product ranking by USD
	fmt.Printf("%+v\n", strings.Join(market.Ranking(markets.ALL), "\n"))

	// FundingRate
	rates, err := c.Rates(&futures.RequestForRates{})
	if err != nil {
		log.Fatal(err)
	}
	// Sort by FundingRate & Print
	// Custom sort
	sort.Sort(sort.Reverse(rates))
	for _, v := range *rates {
		fmt.Printf("%s			%s		%s\n", humanize.Commaf(v.Rate), v.Future, v.Time.String())
	}

	order, err := c.PlaceOrder(&orders.RequestForPlaceOrder{
		Type:   types.LIMIT,
		Market: "BTC-PERP",
		Side:   types.BUY,
		Price:  6200,
		Size:   0.01,
		// Optionals
		ClientID:   "use_original_client_id",
		Ioc:        false,
		ReduceOnly: false,
		PostOnly:   false,
	})
	if err != nil {
		// client.Logger.Error(err) // Logger does not seem to exist @tuanito
	}

	fmt.Printf("%+v\n", order)

	ok, err := c.CancelByID(&orders.RequestForCancelByID{
		OrderID: 1,
		// either... , prioritize clientID
		ClientID:       "",
		TriggerOrderID: "",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(ok)
	// ok is status comment

}

Websocket

package main

import (
	"context"
	"fmt"
	"github.com/go-numb/go-ftx/realtime"
	"github.com/go-numb/go-ftx/auth"

	"github.com/labstack/gommon/log"
)


func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ch := make(chan realtime.Response)
	go realtime.Connect(ctx, ch, []string{"ticker"}, []string{"BTC-PERP", "ETH-PERP"}, nil)
	go realtime.ConnectForPrivate(ctx, ch, "<key>", "<secret>", []string{"orders", "fills"}, nil)

	for {
		select {
		case v := <-ch:
			switch v.Type {
			case realtime.TICKER:
				fmt.Printf("%s	%+v\n", v.Symbol, v.Ticker)

			case realtime.TRADES:
				fmt.Printf("%s	%+v\n", v.Symbol, v.Trades)
				for i := range v.Trades {
					if v.Trades[i].Liquidation {
						fmt.Printf("-----------------------------%+v\n", v.Trades[i])
					}
				}

			case realtime.ORDERBOOK:
				fmt.Printf("%s	%+v\n", v.Symbol, v.Orderbook)

			case realtime.ORDERS:
				fmt.Printf("%d	%+v\n", v.Type, v.Orders)

			case realtime.FILLS:
				fmt.Printf("%d	%+v\n", v.Type, v.Fills)

			case realtime.UNDEFINED:
				fmt.Printf("UNDEFINED %s	%s\n", v.Symbol, v.Results.Error())
			}
		}
	}
}

Author

@_numbP

License

MIT

go-ftx's People

Contributors

0cv avatar ambiguo avatar byroncoetsee avatar deluan avatar dependabot[bot] avatar dr497 avatar emstlk avatar go-numb avatar gonumb avatar guotie avatar howjmay avatar jswanglab avatar koioannis avatar krisa avatar moxis avatar pccr10001 avatar qct avatar sc4recoin avatar spiderpowa avatar tuanito avatar zenpoet avatar zmxv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-ftx's Issues

modifyOrder api cannot modify size

Hello,
I use the modify Order API, and send correct params of size and price to it, the server just returned:

APIError: status=400, message=Must modify either price or size

Seems like the size is never sent to the ftx server. can you look into that?

The code is not functional

First of all, thanks for your great works. I tried go-ftx package with placing an order on ftx. And i got {
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x2c pc=0x12b5a49] }

See if you can give me some advices. Thanks a lot.

Websocket - Server restarting, please reconnect

Hello, i often have this error

ftx websocket/go/pkg/mod/github.com/go-numb/[email protected]/realtime/websocket.go:179: [ERROR]: channel error: {"type": "info", "code": 20001, "msg": "Server restarting, please reconnect"}

And once the error occurs, It's never reconnect, i have to re-start the application, Do you have any idea ?

json Unmarshal issue on int type json fields in realtime structs

I have recently noticed a bunch of warning messages of the form:

2022/03/10 03:21:40 [WARN]: cant unmarshal orderbook json: cannot unmarshal number 3018249120 into Go struct field Orderbook.checksum of type int

And

2022/03/10 03:21:17 [WARN]: cant unmarshal trades json: cannot unmarshal number 3495842160 into Go struct field Trade.id of type int

These numbers aren't too big to be ints so not sure what's going on here

Bug with realtime.FILLS in websocket

Just found a bug with websocket fill, it does not actually respond with any data in realtime.FILLS, all data fields are empty, see below:

(string) (len=5) "fill:"
(fills.Fill) {
Future: (string) "",
Market: (string) "",
Type: (string) "",
Liquidity: (string) "",
BaseCurrency: (string) "",
QuoteCurrency: (string) "",
Side: (string) "",
Price: (float64) 0,
Size: (float64) 0,
Fee: (float64) 0,
FeeRate: (float64) 0,
Time: (time.Time) 0001-01-01 00:00:00 +0000 UTC,
ID: (int) 0,
OrderID: (int) 0,
TradeID: (int) 0
}

I am using a version of: acc9d92 and seeing changes made accordingly to commit comments

Can someone confirm that this is actually fixed already?

Thanks

Invalid authenticator code in requesting Withdraw

Hi I am using this awesome package for withdrawing money from ftx, but I am always meeting the following error.
APIError: status=400, message=Invalid authenticator code

Do you have idea how can I solve this problem. I have provided both password and 2fa code, but it doesn't work at all

Unmarshalling issue when calling c.MyOpQuoteRequest

Here is the error:

WARN[0002] [FTX] options scraper error: rest.Response.Result: readObjectStart: expect { or n, but found [, error found in #10 byte of ...|"result":[],"success|..., bigger context ...|{"result":[],"success":true}
|...

I will attempt to fix it now

TriggerHistory struct type mismatch

Hello There,

Thanks for the amazing library.

Is there any specific reason to use int instead of float64 for Size and FilledSize under TriggerHistory struct.

image

JSON decoding is failing since its not a float with below error

rest.Response.Error: Result: orders.ResponseForOrderTriggerHistories: orders.TriggerHistory.Size: assertInteger: can not decode float as int, error found in #10 byte of ...|0,"size":1.0,"status|..., bigger context ...|t","orderPrice":null,"triggerPrice":100.0,"size":1.0,"status":"cancelled","createdAt":"2021-08-17T01|...

Example of recovery of the connection

By any chance that an example of re-connect to the web socket server could be provided?

I am getting below exception very offten due to various of reasons:

github.com/go-numb/[email protected]/realtime/websocket.go:161: [ERROR]: msg error: read tcp 192.168.1.101:61155->104.18.27.153:443: read: operation timed out

Is this recoverable ? how ?

Thanks

Further maintenance of this project

Hi,

I would like to use your project and extend it. Would you prefer that we work in the same project or would you prefer me to fork a new project from yours ?

Kind regards.

Tuan.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.