Code Monkey home page Code Monkey logo

gatews's Introduction

gatews - Gate.io WebSocket SDK

gatews provides new Gate.io WebSocket V4 implementations. It is intended to work along with gateapi-* series to provide a quick way for developers to integrate Gate.io tradings.

This repository is meant to replace WebSocket-API. The latter will not accept any new feature requirements.

Supported languages are:

Refer to corresponding directory for usage.

gatews's People

Contributors

latesun avatar revilwang avatar sinclair-ni 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gatews's Issues

local_order_book.py out of sync

did you try to run local_order_book.py lately?

i see zombie levels (overlapping ask and bid price) always after the very first update.

is the orderbook of websocket v4 ready to be used in production?

thank you for your time''

现货冻结资产推送

目前现货的资产推送频道 spot.balances 对于资产冻结的动作没有推送。比如下一个订单,该订单没有成交,还在服务器挂着。这时候的资产推送频道并不会推送目前被冻结的资产和可用资产。市面上其他竞品,比如火币、Okex、币安都有类似功能。请问是我什么地方没有做对,还是Gate没有该功能?

Your order size 1 is too small. The minimum is 1 USDT

Hello guys,

I'm trying send GOLD_USDT orders through de API V.4, but some errors have been happening.

If I send a order with amount=2 and price=0.009321, I receive the error message:
'Your order size 2 is too small. The minimum is 1 USDT'
The message don't make sense. Is 2 less than 1?

The data/body is:
{
"text":"",
"currency_pair":"GOLD_USDT",
"type":"limit",
"account":"spot",
"side":"buy",
"amount":"2",
"price":"0.0093210",
"time_in_force":"gtc"
}

But, if I send an order with amount=2 and price 1.009321, this works fine. (Price > 1).
This was only to test, because the price 1.009321 is very expensive.

So, I don't understand what's happening.
Probably, the validation is inverted in the API.

Could someone help me?

Thanks.

json: cannot unmarshal number into Go struct field xxx of type string

This is a common error and happens in many cases, for example:

m.wsService.SetCallBack(gatews.ChannelFutureBalance, func(msg *gatews.UpdateMsg) {
	var accounts []gatews.FuturesAccountBook

	if m.conf.Debug && msg.Event == "update" {
		log.Printf("ChannelFutureBalance: %s\n", string(msg.Result))
	}

	if msg.Error != nil {
		errorHandler(convertWsError(msg.Error, excommon.GlobalMarketTypeFutures, excommon.Unknown))
		return
	}

	if msg.Event != "update" {
		return
	}

	if err := json.Unmarshal(msg.Result, &accounts); err != nil {
		errorHandler(convertWsError(err, excommon.GlobalMarketTypeFutures, excommon.Unknown)) // ①
	}
        // ...

① will show the error: json: cannot unmarshal number into Go struct field FuturesAccountBook.balance of type string. This kind of bug also occurs in the case of GateWsFuturesTrade and GateWsFuturesOrder et al.

It could be a solution to refactor the structs in customized code, but it will be much better if your guys can fix this problem inside this package.

Pairing order & position updates?

Hello there,

I'm wondering whether there's any reasonable way to correlate notifications for order updates (futures.orders) and positions (futures.positions) - are there any guarantees to rely on? That is, assuming a trade happens:

  • Is it always like order update notification is dispatched and then the position update notification is dispatched?
  • Do order and position notifications pertaining to the trade have the same timestamp, or is it guaranteed that position update timestamp will not be older than order update one?

Thanks,
L.

request payload does not follow json schema

Hi,

I am sending the following request through the API v4:

{
"time": "1626964798",
"channel": "spot.trades",
"event": "subscribe",
"payload": [
"LTC_USDT"
]
}

I get the following response:
{
"time": 1626965030,
"channel": "",
"event": "",
"error": {"code": 1, "message": "request payload does not follow json schema" },
"result": null
}

(please ignore timestamps, I may have pulled the message from a different try, but same message each time)

I get the same message if I send a spot.ping with no payload.

Any advice on what I am doing wrong?

Delivery Futures - No mapping possible due to missing information in response

Currently, only the WebSocket servers for Spot and Perpetual Futures return an ID when subscribing to a channel (as stated in the gateio documentation).
Screenshot 2021-12-12 at 11 44 19

However, the Delivery Futures WebSocket server does not send back an ID or the payload in the subscribe response => no mapping possible. This makes it impossible to properly create automated trading tools for the delivery futures on gateio!

Analyzing the code, it looks to me that currently an old implementation is used for the Delivery Futures. Is it planned to be migrated into this codebase in the near future? If not, I would recommend a small update to add the request-id to the response for subscribe and unsubscribe events.

Please let me know if I should open the issue in the old repository as well.

Position WS updates vs. positions from REST

Hello there,

Is there any reliable way to determine whether position notification from futures.positions WS channel represents state newer than information returned from REST API (/futures/{settle}/positions)? From what I saw the timestamp (in ms) is not enough - there can be multiple WS notifications sent with the same time_ms.

Thanks,
L.

Websockets being closed on infrequently traded instruments

I've noticed that on some instruments, the server side closes the websocket after a while.

This is despite:

  1. having the "infrastructure" level ping/pong enabled
  2. explicitly doing the application level ping/pong every 30 seconds.

This mostly happens on the websocket when subscribing to trades, and only on infrequently traded instruments

Is this expected?

Thank you.

Order book WS feed version is way ahead (sometimes >30 seconds) of HTTP

I am maintaining local order book and having problems to init it because even with delay of 30 seconds the version of order book I get from WS subscription is still newer than what I get from regular HTTP REST source, e.g.:

2023-01-16 13:35:10.173 - CWS - INFO - [Gate] Initialising new depth ZBC-USDT < Subscribed to WS Feed
SLEEP OF >30 SECONDS
2023-01-16 13:35:41.213 - CWS - INFO - [Gate] [TRY 1] Got initial depth ZBC_USDT version 172136538 < https://api.gateio.ws/api/v4/spot/order_book?with_id=true&currency=ZBC_USDT&limit=1000
2023-01-16 13:35:41.214 - CWS - WARN - [Gate] Update for ZBC-USDT too new: 172136848-172136849 > 172136538 + 1 (+310)

First buffered WS feed update is still 310 versions newer than what I just got via HTTP

What am I missing?

第一个例子就报错!

asyncio.create_task(self._write(conn), name='write')
asyncio.create_task这个函数官方asyncio库不能带参数吧!我python3.7.1

Order book timestamps semantics

Hello there,

I have a question regarding order book notifications coming from WebSocket API (https://www.gate.io/docs/developers/futures/ws/en/#legacy-order-book-notification, https://www.gate.io/docs/developers/futures/ws/en/#order-book-update-notification). There's a timestamp provided in the notification - "t", comment says it's "Order book generation timestamp in milliseconds". Does this timestamp represent the time when the change occurred "in engine" or does it represent the time when the notification was dispatched from your end? I assume the former but wanted to double-check.

Thanks!

永续合约websocket断开太频繁

我在testnet订阅了futures.orders和futures.usertrades私有channel。 websocket断开重连的频率太高。
这是testnet的问题, 还是正式环境也一样?
这种断开重连期间发生的事件无法收到, 处理起来挺麻烦的。 有什么好的处理方式吗?

subscribe all user data events in one ws connection

Thanks for your hard work! But there are two critical problems that I found in your futures API:

1. Some connections are contract specific which is inconvenient

For example, for User Trades API, the connection is contract specific:

from websocket import create_connection
ws = create_connection("wss://fx-ws-testnet.gateio.ws/v4/ws/btc")
ws.send('{
    "time" : 123456,
    "channel" : "futures.usertrades",
    "event": "subscribe",
    "payload" : ["20011", "BTC_USD"],
    "auth": {
            "method": "api_key",
            "KEY":"xxxx",
            "SIGN": "xxxx"
            }}')
print(ws.recv())

which means that N connections are needed if we want to receive notifications from N contracts.

2. If all user-specific data can be integrated with one connection, it will be much better

As far as I know, Binance provides a single Websocket endpoint User Data Stream to receive all user updates, and that's really awesome.

i have issue with the trade order not being visible in the API( "GET /spot/my_trades" endpoint.)

Hello.
As you see on the attached file below, on the "https://www.gate.io/myaccount/mypurselog" page, you can find "Quick Buy-Bought" and "Quick Sell-Sold" data as the action type. (refer to the screenshot, red squared data)
We assume the data (*red squared data) as the "trade" data.
That's why we predicted the data to search through the "GET /spot/ my_trades" endpoint. But it did not work.
The question is, "searching data, do we need to use different end points? Or is it simply the system error?"

Screen Shot 2022-03-10 at 4 16 02 PM

WebSocket connection can not be established giving compression error

The WebSocket connection can not be established and gives error:

failed to connect to server for the 1 time, try again later: 
Unsupported extension: name = permessage-deflate,
params = [('server_no_context_takeover', None), ('client_no_context_takeover', None)]

Most probably this is due to the new default compression extension since is not specifically specified.
Possible solution is to add "compression=None" argument in client.py (line 189) to be like below:

conn = await websockets.connect(self.cfg.host, ssl=ctx, compression=None)

成交通知不匹配

问题:
永续合约PEOPLE_USDT下单, size为262, websocket的futures.orders channel通知的订单成交为262, 但是futures.usertrades channel发送了两笔交易通知, 一笔成交size为8, 另一笔size为256。 不知道这个是不是bug。 如需详细订单和交易通知, 可以发送到邮箱。

Best bid/ask timestamp semantics

Hello there,

I have a question regarding best bid/ask notifications coming from WebSocket API (https://www.gate.io/docs/developers/futures/ws/en/#best-ask-bid-notification). There's a timestamp provided in the notification - "t", comment says it's "Book ticker generated timestamp in milliseconds". Does this timestamp represent the time when the change occurred "in engine" or does it represent the time when the notification was dispatched from your end? I assume the former but wanted to double-check.

Thanks!

`text` field in account book REST response

Hello there!

There's text field in /futures/{settle}/account_book response (https://www.gate.io/docs/developers/apiv4/en/#query-account-book) which is documented as comment. Per observation the semantics of the field value depends on type of the record, e.g. for pnl records the value is contract:orderId, and for funding payments the value is just contract. Can this behavior be relied upon? That is, is it guaranteed that when the record type is fund the value in text field is contract name?

Thanks,
L.

Websocket connection stability

Hello everyone.

I have noticed many frequent random disconnects from the Gate.io websocket server.
Everything is stable when connecting to the websocket servers of 3 other major exchanges (and the code can run for days) but the connection to Gate.io is unstable.
It disconnects with no apparent reason, it does not seem to close the connection, it seems more like just sitting idle and not sending any updates.
Ping / pong protocol is respected with the connection (even though their documentation is vague about it).

Do you have any specific advice about how to handle Gate.io websocket connections? Maybe something that is not apparent in the docs or anything else?

Thank you in advance.

SpotPublicTradeChannel responses

Hello there!

In **response.result** the 'id' field's order not always in order as same in 'create_time_in_ms' too.
When 'create_time_in_ms' field is equal with the next response time, 'id' fields shows the wrong order of responses.

Maybe my fail, but cant handle this strange behavior
Regards,
Atirra

{'status': 'success'}
{'id': 4616057627, 'create_time': 1669181021, 'create_time_ms': '1669181021177.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.0135', 'price': '16490'}
{'id': 4616057628, 'create_time': 1669181021, 'create_time_ms': '1669181021180.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.024', 'price': '16490'}
{'id': 4616057635, 'create_time': 1669181021, 'create_time_ms': '1669181021197.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.0001', 'price': '16489.5'}
{'id': 4616057634, 'create_time': 1669181021, 'create_time_ms': '1669181021194.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.002', 'price': '16490'}
{'id': 4616057633, 'create_time': 1669181021, 'create_time_ms': '1669181021194.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.002', 'price': '16490'}
{'id': 4616057632, 'create_time': 1669181021, 'create_time_ms': '1669181021194.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.002', 'price': '16490'}
{'id': 4616057630, 'create_time': 1669181021, 'create_time_ms': '1669181021191.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.0262', 'price': '16490'}
{'id': 4616057631, 'create_time': 1669181021, 'create_time_ms': '1669181021194.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.0046', 'price': '16490'}
{'id': 4616057629, 'create_time': 1669181021, 'create_time_ms': '1669181021187.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.0255', 'price': '16490'}
{'id': 4616057638, 'create_time': 1669181021, 'create_time_ms': '1669181021210.0', 'side': 'sell', 'currency_pair': 'BTC_USDT', 'amount': '0.0001', 'price': '16487.5'}

Go mod tag version

Hey,
I'm trying to lock the version in go.mod to github.com/gateio/gatews v0.2.4 (v0.2.4 is the latest release tag). But it seems that because an actual Golang code is in github.com/gateio/gatews/go directory and in project it's used as

import gate "github.com/gateio/gatews/go"

the go.mod is locking it to the latest commit hash github.com/gateio/gatews/go v0.0.0-20211015033957-f7c469464a59.

It's not somehow affecting our flow, just wanted to maintain a proper versions of modules.

Do you know how can I change this? Or maybe you could publish a better tag distinction?

Regards,
Thanks

Market orders

Is there any way to make a market order ? Like stop market ?
What are the options for this type of trade using api level ?

杠杆最小下单精度问题

实际下单数量pig是12250398.1 换算usdt=10
code=INVALID_PARAM_VALUE=>Your order size 12250398.1 is too small. The minimum is 1 USDT

[feature] Ping/Pong

I was hoping this would work:


	ws, err := gate.NewWsService(nil, nil, gate.NewConnConfFromOption(&gate.ConfOptions{
		Key: exchanges.GATEIO_KEY, Secret: exchanges.GATEIO_SECRET, MaxRetryConn: 10, SkipTlsVerify: false,
	}))

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

	pingCb := gate.NewCallBack(func(msg *gate.UpdateMsg) {
		// parse the message to struct we need
		log.Printf("%+v\n", msg)
	})

	ws.SetCallBack("server.ping", pingCb)
	err = ws.Subscribe("server.ping", []string{})

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

Response

2021/12/11 00:21:44 &{Time:1639192904 Id:<nil> Channel:ping Event:subscribe Error:Unknown channel ping Result:[110 117 108 108]}

Link: https://www.gate.io/docs/websocket/#ping

'available balance' via WS?

Hello,

is there a way to get/compute 'available balance' based on WS notifications?

When REST API is used to obtain account balance (https://www.gate.io/docs/developers/apiv4/en/#query-futures-account) the information includes total and available amounts (and doesn't include any sort of 'valid as of' time). WS notification (https://www.gate.io/docs/developers/futures/ws/en/#positions-notification) only provides total amount and change amount. But the available amount likely does not follow the same change. Is there a way to compute/keep track of it?

E.g. since total = position_margin + order_margin + available and position margin is part of position updates if I had the order_margin I could compute the available amount myself. But I don't know where to get order_margin from/how to keep track of it.

Thanks,
L.

win 10 64 位系统example 报错

Traceback (most recent call last):
File "C:/Users/14816/PycharmProjects/pythonProject1/examples/local_order_book.py", line 337, in
screen = Screen.open(300)
File "C:\Users\14816\PycharmProjects\pythonProject1\venv\lib\site-packages\asciimatics\screen.py", line 1304, in open
win_out.SetConsoleScreenBufferSize(info['Size'])
pywintypes.error: (87, 'SetConsoleScreenBufferSize', '参数错误。')

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.