├── bitget.exe ├── bitget ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-313.pyc │ ├── __init__.cpython-38.pyc │ ├── account_api.cpython-38.pyc │ ├── bitget_api.cpython-313.pyc │ ├── client.cpython-313.pyc │ ├── client.cpython-38.pyc │ ├── consts.cpython-313.pyc │ ├── consts.cpython-38.pyc │ ├── exceptions.cpython-313.pyc │ ├── exceptions.cpython-38.pyc │ ├── futures_api.cpython-38.pyc │ ├── index_api.cpython-38.pyc │ ├── lever_api.cpython-38.pyc │ ├── option_api.cpython-38.pyc │ ├── spot_api.cpython-38.pyc │ ├── swap_api.cpython-38.pyc │ ├── system_api.cpython-38.pyc │ ├── utils.cpython-313.pyc │ └── utils.cpython-38.pyc ├── bitget_api.py ├── client.py ├── consts.py ├── exceptions.py ├── utils.py ├── v1 │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-313.pyc │ ├── mix │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-313.pyc │ │ │ └── order_api.cpython-313.pyc │ │ ├── account_api.py │ │ ├── market_api.py │ │ └── order_api.py │ └── spot │ │ ├── __init__.py │ │ ├── account_api.py │ │ ├── market_api.py │ │ ├── order_api.py │ │ └── wallet_api.py ├── v2 │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-313.pyc │ ├── mix │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-313.pyc │ │ │ ├── account_api.cpython-313.pyc │ │ │ ├── market_api.cpython-313.pyc │ │ │ └── order_api.cpython-313.pyc │ │ ├── account_api.py │ │ ├── market_api.py │ │ └── order_api.py │ └── spot │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── __init__.cpython-313.pyc │ │ ├── account_api.cpython-313.pyc │ │ └── market_api.cpython-313.pyc │ │ ├── account_api.py │ │ ├── market_api.py │ │ ├── order_api.py │ │ └── wallet_api.py └── ws │ ├── __pycache__ │ └── bitget_ws_client.cpython-313.pyc │ └── bitget_ws_client.py ├── leia-me.txt ├── logo.ico └── main.py /bitget.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget.exe -------------------------------------------------------------------------------- /bitget/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /bitget/__pycache__/__init__.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/__init__.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/account_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/account_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/bitget_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/bitget_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/client.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/client.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/client.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/client.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/consts.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/consts.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/consts.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/consts.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/exceptions.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/exceptions.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/exceptions.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/exceptions.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/futures_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/futures_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/index_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/index_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/lever_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/lever_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/option_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/option_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/spot_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/spot_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/swap_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/swap_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/system_api.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/system_api.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/utils.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/utils.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/__pycache__/utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/__pycache__/utils.cpython-38.pyc -------------------------------------------------------------------------------- /bitget/bitget_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class BitgetApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def post(self, request_path, params): 11 | return self._request_with_params(POST, request_path, params) 12 | 13 | def get(self, request_path, params): 14 | return self._request_with_params(GET, request_path, params) 15 | -------------------------------------------------------------------------------- /bitget/client.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | from . import consts as c, utils, exceptions 4 | 5 | 6 | class Client(object): 7 | 8 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 9 | 10 | self.API_KEY = api_key 11 | self.API_SECRET_KEY = api_secret_key 12 | self.PASSPHRASE = passphrase 13 | self.use_server_time = use_server_time 14 | self.first = first 15 | 16 | def _request(self, method, request_path, params, cursor=False): 17 | if method == c.GET: 18 | request_path = request_path + utils.parse_params_to_str(params) 19 | # url 20 | url = c.API_URL + request_path 21 | 22 | # 获取本地时间 23 | timestamp = utils.get_timestamp() 24 | 25 | # sign & header 26 | if self.use_server_time: 27 | # 获取服务器时间接口 28 | timestamp = self._get_timestamp() 29 | 30 | body = json.dumps(params) if method == c.POST else "" 31 | sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY) 32 | if c.SIGN_TYPE == c.RSA: 33 | sign = utils.signByRSA(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY) 34 | header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE) 35 | 36 | if self.first: 37 | print("url:", url) 38 | print("method:", method) 39 | print("body:", body) 40 | print("headers:", header) 41 | # print("sign:", sign) 42 | self.first = False 43 | 44 | 45 | 46 | 47 | # send request 48 | response = None 49 | if method == c.GET: 50 | response = requests.get(url, headers=header) 51 | #print("response : ",response.text) 52 | elif method == c.POST: 53 | response = requests.post(url, data=body, headers=header) 54 | print("response : ",response.text) 55 | #response = requests.post(url, json=body, headers=header) 56 | elif method == c.DELETE: 57 | response = requests.delete(url, headers=header) 58 | 59 | print("status:", response.status_code) 60 | # exception handle 61 | if not str(response.status_code).startswith('2'): 62 | raise exceptions.BitgetAPIException(response) 63 | try: 64 | res_header = response.headers 65 | if cursor: 66 | r = dict() 67 | try: 68 | r['before'] = res_header['OK-BEFORE'] 69 | r['after'] = res_header['OK-AFTER'] 70 | except: 71 | pass 72 | return response.json(), r 73 | else: 74 | return response.json() 75 | 76 | except ValueError: 77 | raise exceptions.BitgetRequestException('Invalid Response: %s' % response.text) 78 | 79 | def _request_without_params(self, method, request_path): 80 | return self._request(method, request_path, {}) 81 | 82 | def _request_with_params(self, method, request_path, params, cursor=False): 83 | return self._request(method, request_path, params, cursor) 84 | 85 | def _get_timestamp(self): 86 | url = c.API_URL + c.SERVER_TIMESTAMP_URL 87 | response = requests.get(url) 88 | if response.status_code == 200: 89 | return response.json()['timestamp'] 90 | else: 91 | return "" 92 | -------------------------------------------------------------------------------- /bitget/consts.py: -------------------------------------------------------------------------------- 1 | # Base Url 2 | API_URL = 'https://api.bitget.com' 3 | CONTRACT_WS_URL = 'wss://ws.bitget.com/mix/v1/stream' 4 | 5 | # http header 6 | CONTENT_TYPE = 'Content-Type' 7 | OK_ACCESS_KEY = 'ACCESS-KEY' 8 | OK_ACCESS_SIGN = 'ACCESS-SIGN' 9 | OK_ACCESS_TIMESTAMP = 'ACCESS-TIMESTAMP' 10 | OK_ACCESS_PASSPHRASE = 'ACCESS-PASSPHRASE' 11 | APPLICATION_JSON = 'application/json' 12 | 13 | # header key 14 | LOCALE = 'locale' 15 | 16 | # method 17 | GET = "GET" 18 | POST = "POST" 19 | DELETE = "DELETE" 20 | 21 | # sign type 22 | RSA = "RSA" 23 | SHA256 = "SHA256" 24 | SIGN_TYPE = SHA256 25 | 26 | # ws 27 | REQUEST_PATH = '/user/verify' 28 | -------------------------------------------------------------------------------- /bitget/exceptions.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import json 3 | 4 | class BitgetAPIException(Exception): 5 | 6 | def __init__(self, response): 7 | self.code = 0 8 | try: 9 | json_res = response.json() 10 | except ValueError: 11 | self.message = 'Invalid JSON error message from Bitget: {}'.format(response.text) 12 | else: 13 | if "code" in json_res.keys() and "msg" in json_res.keys(): 14 | self.code = json_res['code'] 15 | self.message = json_res['msg'] 16 | else: 17 | self.code = 'Please wait a moment' 18 | self.message = 'Maybe something is wrong' 19 | 20 | self.status_code = response.status_code 21 | self.response = response 22 | self.request = getattr(response, 'request', None) 23 | 24 | def __str__(self): # pragma: no cover 25 | return 'API Request Error(code=%s): %s' % (self.code, self.message) 26 | 27 | 28 | 29 | class BitgetRequestException(Exception): 30 | 31 | def __init__(self, message): 32 | self.message = message 33 | 34 | def __str__(self): 35 | return 'BitgetRequestException: %s' % self.message 36 | 37 | 38 | 39 | class BitgetParamsException(Exception): 40 | 41 | def __init__(self, message): 42 | self.message = message 43 | 44 | def __str__(self): 45 | return 'BitgetParamsException: %s' % self.message 46 | -------------------------------------------------------------------------------- /bitget/utils.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import hmac 3 | import time 4 | 5 | from Crypto.Hash import SHA256 6 | from Crypto.PublicKey import RSA 7 | from Crypto.Signature import PKCS1_v1_5 as pk 8 | 9 | from . import consts as c 10 | 11 | 12 | def sign(message, secret_key): 13 | mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256') 14 | d = mac.digest() 15 | return str(base64.b64encode(d), 'utf8') 16 | 17 | def signByRSA(message, secret_key): 18 | privatekey = RSA.importKey(secret_key) 19 | h = SHA256.new(message.encode('utf-8')) 20 | signer = pk.new(privatekey) 21 | sign = signer.sign(h) 22 | return str(base64.b64encode(sign), 'utf8') 23 | 24 | 25 | def pre_hash(timestamp, method, request_path, body = ""): 26 | return str(timestamp) + str.upper(method) + request_path + body 27 | 28 | 29 | def get_header(api_key, sign, timestamp, passphrase): 30 | header = dict() 31 | header[c.CONTENT_TYPE] = c.APPLICATION_JSON 32 | header[c.OK_ACCESS_KEY] = api_key 33 | header[c.OK_ACCESS_SIGN] = sign 34 | header[c.OK_ACCESS_TIMESTAMP] = str(timestamp) 35 | header[c.OK_ACCESS_PASSPHRASE] = passphrase 36 | header[c.LOCALE] = 'zh-CN' 37 | 38 | return header 39 | 40 | 41 | def parse_params_to_str(params): 42 | params = [(key, val) for key, val in params.items()] 43 | params.sort(key=lambda x: x[0]) 44 | # from urllib.parse import urlencode 45 | # url = '?' +urlencode(params); 46 | url = '?' +toQueryWithNoEncode(params); 47 | if url == '?': 48 | return '' 49 | return url 50 | # url = '?' 51 | # for key, value in params.items(): 52 | # url = url + str(key) + '=' + str(value) + '&' 53 | # 54 | # return url[0:-1] 55 | 56 | def toQueryWithNoEncode(params): 57 | url = '' 58 | for key, value in params: 59 | url = url + str(key) + '=' + str(value) + '&' 60 | return url[0:-1] 61 | 62 | 63 | def get_timestamp(): 64 | return int(time.time() * 1000) 65 | 66 | 67 | def signature(timestamp, method, request_path, body, secret_key): 68 | if str(body) == '{}' or str(body) == 'None': 69 | body = '' 70 | message = str(timestamp) + str.upper(method) + request_path + str(body) 71 | mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256') 72 | d = mac.digest() 73 | return base64.b64encode(d) 74 | 75 | def check_none(value, msg=""): 76 | if not value: 77 | raise Exception(msg + " Invalid params!") -------------------------------------------------------------------------------- /bitget/v1/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python -------------------------------------------------------------------------------- /bitget/v1/__pycache__/__init__.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v1/__pycache__/__init__.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v1/mix/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python -------------------------------------------------------------------------------- /bitget/v1/mix/__pycache__/__init__.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v1/mix/__pycache__/__init__.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v1/mix/__pycache__/order_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v1/mix/__pycache__/order_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v1/mix/account_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class AccountApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def account(self, params): 11 | return self._request_with_params(GET, '/api/mix/v1/account/account', params) 12 | 13 | def accounts(self, params): 14 | return self._request_with_params(GET, '/api/mix/v1/account/accounts', params) 15 | 16 | def setLeverage(self, params): 17 | return self._request_with_params(POST, '/api/mix/v1/account/setLeverage', params) 18 | 19 | def setMargin(self, params): 20 | return self._request_with_params(POST, '/api/mix/v1/account/setMargin', params) 21 | 22 | def setMarginMode(self, params): 23 | return self._request_with_params(POST, '/api/mix/v1/account/setMarginMode', params) 24 | 25 | def setPositionMode(self, params): 26 | return self._request_with_params(POST, '/api/mix/v1/account/setPositionMode', params) 27 | 28 | def singlePosition(self, params): 29 | return self._request_with_params(GET, '/api/mix/v1/position/singlePosition', params) 30 | 31 | def allPosition(self, params): 32 | return self._request_with_params(GET, '/api/mix/v1/position/allPosition', params) 33 | -------------------------------------------------------------------------------- /bitget/v1/mix/market_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET 4 | 5 | 6 | class MarketApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def contracts(self, params): 11 | return self._request_with_params(GET, '/api/mix/v1/market/contracts', params) 12 | 13 | def orderbook(self, params): 14 | return self._request_with_params(GET, '/api/mix/v1/market/depth', params) 15 | 16 | def ticker(self, params): 17 | return self._request_with_params(GET, '/api/mix/v1/market/ticker', params) 18 | 19 | def tickers(self, params): 20 | return self._request_with_params(GET, '/api/mix/v1/market/tickers', params) 21 | 22 | def fills(self, params): 23 | return self._request_with_params(GET, '/api/mix/v1/market/fills', params) 24 | 25 | def candles(self, params): 26 | return self._request_with_params(GET, '/api/mix/v1/market/candles', params) 27 | -------------------------------------------------------------------------------- /bitget/v1/mix/order_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class OrderApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def placeOrder(self, params): 11 | return self._request_with_params(POST, '/api/mix/v1/order/placeOrder', params) 12 | 13 | def batchPlaceOrder(self, params): 14 | return self._request_with_params(POST, '/api/mix/v1/order/batch-orders', params) 15 | 16 | def cancelOrder(self, params): 17 | return self._request_with_params(POST, '/api/mix/v1/order/cancel-order', params) 18 | 19 | def batchCancelOrders(self, params): 20 | return self._request_with_params(POST, '/api/mix/v1/order/cancel-batch-orders', params) 21 | 22 | def ordersHistory(self, params): 23 | return self._request_with_params(GET, '/api/mix/v1/order/history', params) 24 | 25 | def ordersPending(self, params): 26 | return self._request_with_params(GET, '/api/mix/v1/order/current', params) 27 | 28 | def fills(self, params): 29 | return self._request_with_params(GET, '/api/mix/v1/order/fills', params) 30 | 31 | def placePlanOrder(self, params): 32 | return self._request_with_params(POST, '/api/mix/v1/plan/placePlan', params) 33 | 34 | def cancelPlan(self, params): 35 | return self._request_with_params(POST, '/api/mix/v1/plan/cancelPlan', params) 36 | 37 | def currentPlan(self, params): 38 | return self._request_with_params(GET, '/api/mix/v1/plan/currentPlan', params) 39 | 40 | def historyPlan(self, params): 41 | return self._request_with_params(GET, '/api/mix/v1/plan/historyPlan', params) 42 | 43 | def traderCloseOrder(self, params): 44 | return self._request_with_params(POST, '/api/mix/v1/trace/closeTrackOrder', params) 45 | 46 | def traderOrderCurrentTrack(self, params): 47 | return self._request_with_params(GET, '/api/mix/v1/trace/currentTrack', params) 48 | 49 | def traderOrderHistoryTrack(self, params): 50 | return self._request_with_params(GET, '/api/mix/v1/trace/historyTrack', params) 51 | 52 | def followerCloseByTrackingNo(self, params): 53 | return self._request_with_params(POST, '/api/mix/v1/trace/followerCloseByTrackingNo', params) 54 | 55 | def followerQueryCurrentOrders(self, params): 56 | return self._request_with_params(GET, '/api/mix/v1/trace/followerOrder', params) 57 | 58 | def followerQueryHistoryOrders(self, params): 59 | return self._request_with_params(GET, '/api/mix/v1/trace/followerHistoryOrders', params) 60 | -------------------------------------------------------------------------------- /bitget/v1/spot/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python -------------------------------------------------------------------------------- /bitget/v1/spot/account_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class AccountApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def getInfo(self, params): 11 | return self._request_with_params(GET, '/api/spot/v1/account/getInfo', params) 12 | 13 | def assetsLite(self, params): 14 | return self._request_with_params(GET, '/api/spot/v1/account/assets-lite', params) 15 | 16 | def bills(self, params): 17 | return self._request_with_params(GET, '/api/spot/v1/account/bills', params) 18 | 19 | def transferRecords(self, params): 20 | return self._request_with_params(GET, '/api/spot/v1/account/transferRecords', params) 21 | -------------------------------------------------------------------------------- /bitget/v1/spot/market_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET 4 | 5 | 6 | class MarketApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def currencies(self, params): 11 | return self._request_with_params(GET, '/api/spot/v1/public/currencies', params) 12 | 13 | def products(self, params): 14 | return self._request_with_params(GET, '/api/spot/v1/public/products', params) 15 | 16 | def product(self, params): 17 | return self._request_with_params(GET, '/api/spot/v1/public/product', params) 18 | 19 | def fills(self, params): 20 | return self._request_with_params(GET, '/api/spot/v1/market/fills', params) 21 | 22 | def depth(self, params): 23 | return self._request_with_params(GET, '/api/spot/v1/market/depth', params) 24 | 25 | def ticker(self, params): 26 | return self._request_with_params(GET, '/api/spot/v1/market/ticker', params) 27 | 28 | def tickers(self, params): 29 | return self._request_with_params(GET, '/api/spot/v1/market/tickers', params) 30 | 31 | def candles(self, params): 32 | return self._request_with_params(GET, '/api/spot/v1/market/candles', params) 33 | -------------------------------------------------------------------------------- /bitget/v1/spot/order_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class OrderApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def placeOrder(self, params): 11 | return self._request_with_params(POST, '/api/spot/v1/trade/orders', params) 12 | 13 | def batchOrders(self, params): 14 | return self._request_with_params(POST, '/api/spot/v1/trade/batch-orders', params) 15 | 16 | def cancelOrder(self, params): 17 | return self._request_with_params(POST, '/api/spot/v1/trade/cancel-order', params) 18 | 19 | def batchCancelOrder(self, params): 20 | return self._request_with_params(POST, '/api/spot/v1/trade/cancel-batch-orders', params) 21 | 22 | def openOrders(self, params): 23 | return self._request_with_params(GET, '/api/spot/v1/trade/open-orders', params) 24 | 25 | def historyOrders(self, params): 26 | return self._request_with_params(GET, '/api/spot/v1/trade/history', params) 27 | 28 | def fills(self, params): 29 | return self._request_with_params(GET, '/api/spot/v1/trade/fills', params) 30 | 31 | def placePlanOrder(self, params): 32 | return self._request_with_params(POST, '/api/spot/v1/plan/placePlan', params) 33 | 34 | def cancelPlanOrder(self, params): 35 | return self._request_with_params(POST, '/api/spot/v1/plan/cancelPlan', params) 36 | 37 | def currentPlanOrder(self, params): 38 | return self._request_with_params(POST, '/api/spot/v1/plan/currentPlan', params) 39 | 40 | def historyPlanOrder(self, params): 41 | return self._request_with_params(POST, '/api/spot/v1/plan/historyPlan', params) 42 | 43 | def traderOrderCloseTracking(self, params): 44 | return self._request_with_params(POST, '/api/spot/v1/trace/order/closeTrackingOrder', params) 45 | 46 | def traderOrderCurrentTrack(self, params): 47 | return self._request_with_params(POST, '/api/spot/v1/trace/order/orderCurrentList', params) 48 | 49 | def traderOrderHistoryTrack(self, params): 50 | return self._request_with_params(GET, '/api/spot/v1/trace/order/orderHistoryList', params) 51 | -------------------------------------------------------------------------------- /bitget/v1/spot/wallet_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class WalletApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def transfer(self, params): 11 | return self._request_with_params(POST, '/api/spot/v1/wallet/transfer', params) 12 | 13 | def depositAddress(self, params): 14 | return self._request_with_params(GET, '/api/spot/v1/wallet/deposit-address', params) 15 | 16 | def withdrawal(self, params): 17 | return self._request_with_params(POST, '/api/spot/v1/wallet/withdrawal', params) 18 | 19 | def withdrawalRecords(self, params): 20 | return self._request_with_params(GET, '/api/spot/v1/wallet/withdrawal-list', params) 21 | 22 | def depositRecords(self, params): 23 | return self._request_with_params(GET, '/api/spot/v1/wallet/deposit-list', params) 24 | -------------------------------------------------------------------------------- /bitget/v2/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python -------------------------------------------------------------------------------- /bitget/v2/__pycache__/__init__.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/__pycache__/__init__.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/mix/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python -------------------------------------------------------------------------------- /bitget/v2/mix/__pycache__/__init__.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/mix/__pycache__/__init__.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/mix/__pycache__/account_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/mix/__pycache__/account_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/mix/__pycache__/market_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/mix/__pycache__/market_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/mix/__pycache__/order_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/mix/__pycache__/order_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/mix/account_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class AccountApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def account(self, params): 11 | return self._request_with_params(GET, '/api/v2/mix/account/account', params) 12 | 13 | def accounts(self, params): 14 | return self._request_with_params(GET, '/api/v2/mix/account/accounts', params) 15 | 16 | def setLeverage(self, params): 17 | return self._request_with_params(POST, '/api/v2/mix/account/set-leverage', params) 18 | 19 | def setMargin(self, params): 20 | return self._request_with_params(POST, '/api/v2/mix/account/set-margin', params) 21 | 22 | def setMarginMode(self, params): 23 | return self._request_with_params(POST, '/api/v2/mix/account/set-margin-mode', params) 24 | 25 | def setPositionMode(self, params): 26 | return self._request_with_params(POST, '/api/v2/mix/account/set-position-mode', params) 27 | 28 | def openCount(self, params): 29 | return self._request_with_params(GET, '/api/v2/mix/account/open-count', params) 30 | 31 | def singlePosition(self, params): 32 | return self._request_with_params(GET, '/api/v2/mix/position/single-position', params) 33 | 34 | def allPosition(self, params): 35 | return self._request_with_params(GET, '/api/v2/mix/position/all-position', params) 36 | 37 | def historyPosition(self, params): 38 | return self._request_with_params(GET, '/api/v2/mix/position/history-position', params) 39 | -------------------------------------------------------------------------------- /bitget/v2/mix/market_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET 4 | 5 | 6 | class MarketApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def contracts(self, params): 11 | return self._request_with_params(GET, '/api/v2/mix/market/contracts', params) 12 | 13 | def orderbook(self, params): 14 | return self._request_with_params(GET, '/api/v2/mix/market/orderbook', params) 15 | 16 | def tickers(self, params): 17 | return self._request_with_params(GET, '/api/v2/mix/market/tickers', params) 18 | 19 | def fills(self, params): 20 | return self._request_with_params(GET, '/api/v2/mix/market/fills', params) 21 | 22 | def candles(self, params): 23 | return self._request_with_params(GET, '/api/v2/mix/market/candles', params) 24 | 25 | def ticker(self, params): 26 | return self._request_with_params(GET, '/api/v2/mix/market/ticker', params) 27 | -------------------------------------------------------------------------------- /bitget/v2/mix/order_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class OrderApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def placeOrder(self, params): 11 | return self._request_with_params(POST, '/api/v2/mix/order/place-order', params) 12 | 13 | def clickBackhand(self, params): 14 | return self._request_with_params(POST, '/api/v2/mix/order/click-backhand', params) 15 | 16 | def batchPlaceOrder(self, params): 17 | return self._request_with_params(POST, '/api/v2/mix/order/batch-place-order', params) 18 | 19 | def cancelOrder(self, params): 20 | return self._request_with_params(POST, '/api/v2/mix/order/cancel-order', params) 21 | 22 | def batchCancelOrders(self, params): 23 | return self._request_with_params(POST, '/api/v2/mix/order/batch-cancel-orders', params) 24 | 25 | def closePositions(self, params): 26 | return self._request_with_params(POST, '/api/v2/mix/order/close-positions', params) 27 | 28 | def ordersHistory(self, params): 29 | return self._request_with_params(GET, '/api/v2/mix/order/orders-history', params) 30 | 31 | def fillHistory(self, params): 32 | return self._request_with_params(GET, '/api/v2/mix/order/fill-history', params) 33 | 34 | def ordersPending(self, params): 35 | return self._request_with_params(GET, '/api/v2/mix/order/orders-pending', params) 36 | 37 | def detail(self, params): 38 | return self._request_with_params(GET, '/api/v2/mix/order/detail', params) 39 | 40 | def fills(self, params): 41 | return self._request_with_params(GET, '/api/v2/mix/order/fills', params) 42 | 43 | def placePlanOrder(self, params): 44 | return self._request_with_params(POST, '/api/v2/mix/order/place-plan-order', params) 45 | 46 | def cancelPlanOrder(self, params): 47 | return self._request_with_params(POST, '/api/v2/mix/order/cancel-plan-order', params) 48 | 49 | def ordersPlanPending(self, params): 50 | return self._request_with_params(GET, '/api/v2/mix/order/orders-plan-pending', params) 51 | 52 | def ordersPlanHistory(self, params): 53 | return self._request_with_params(GET, '/api/v2/mix/order/orders-plan-history', params) 54 | 55 | def traderOrderClosePositions(self, params): 56 | return self._request_with_params(POST, '/api/v2/copy/mix-trader/order-close-positions', params) 57 | 58 | def traderOrderCurrentTrack(self, params): 59 | return self._request_with_params(GET, '/api/v2/copy/mix-trader/order-current-track', params) 60 | 61 | def traderOrderHistoryTrack(self, params): 62 | return self._request_with_params(GET, '/api/v2/copy/mix-trader/order-history-track', params) 63 | 64 | def followerClosePositions(self, params): 65 | return self._request_with_params(POST, '/api/v2/copy/mix-follower/close-positions', params) 66 | 67 | def followerQueryCurrentOrders(self, params): 68 | return self._request_with_params(GET, '/api/v2/copy/mix-follower/query-current-orders', params) 69 | 70 | def followerQueryHistoryOrders(self, params): 71 | return self._request_with_params(GET, '/api/v2/copy/mix-follower/query-history-orders', params) 72 | -------------------------------------------------------------------------------- /bitget/v2/spot/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python -------------------------------------------------------------------------------- /bitget/v2/spot/__pycache__/__init__.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/spot/__pycache__/__init__.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/spot/__pycache__/account_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/spot/__pycache__/account_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/spot/__pycache__/market_api.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/v2/spot/__pycache__/market_api.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/v2/spot/account_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class AccountApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def info(self, params): 11 | return self._request_with_params(GET, '/api/v2/spot/account/info', params) 12 | 13 | def assets(self, params): 14 | return self._request_with_params(GET, '/api/v2/spot/account/assets', params) 15 | 16 | def bills(self, params): 17 | return self._request_with_params(GET, '/api/v2/spot/account/bills', params) 18 | 19 | def transferRecords(self, params): 20 | return self._request_with_params(GET, '/api/v2/spot/account/transferRecords', params) 21 | -------------------------------------------------------------------------------- /bitget/v2/spot/market_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET 4 | 5 | 6 | class MarketApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def coins(self, params): 11 | return self._request_with_params(GET, '/api/v2/spot/market/coins', params) 12 | 13 | def symbols(self, params): 14 | return self._request_with_params(GET, '/api/v2/spot/market/symbols', params) 15 | 16 | def fills(self, params): 17 | return self._request_with_params(GET, '/api/v2/spot/market/fills', params) 18 | 19 | def orderbook(self, params): 20 | return self._request_with_params(GET, '/api/v2/spot/market/orderbook', params) 21 | 22 | def tickers(self, params): 23 | return self._request_with_params(GET, '/api/v2/spot/market/tickers', params) 24 | 25 | def candles(self, params): 26 | return self._request_with_params(GET, '/api/v2/spot/market/candles', params) 27 | -------------------------------------------------------------------------------- /bitget/v2/spot/order_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class OrderApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def placeOrder(self, params): 11 | return self._request_with_params(POST, '/api/v2/spot/trade/place-order', params) 12 | 13 | def batchOrders(self, params): 14 | return self._request_with_params(POST, '/api/v2/spot/trade/batch-orders', params) 15 | 16 | def cancelOrder(self, params): 17 | return self._request_with_params(POST, '/api/v2/spot/trade/cancel-order', params) 18 | 19 | def batchCancelOrder(self, params): 20 | return self._request_with_params(POST, '/api/v2/spot/trade/batch-cancel-order', params) 21 | 22 | def historyOrders(self, params): 23 | return self._request_with_params(GET, '/api/v2/spot/trade/unfilled-orders', params) 24 | 25 | def historyOrders(self, params): 26 | return self._request_with_params(GET, '/api/v2/spot/trade/history-orders', params) 27 | 28 | def fills(self, params): 29 | return self._request_with_params(GET, '/api/v2/spot/trade/fills', params) 30 | 31 | def placePlanOrder(self, params): 32 | return self._request_with_params(POST, '/api/v2/spot/trade/place-plan-order', params) 33 | 34 | def modifyPlanOrder(self, params): 35 | return self._request_with_params(POST, '/api/v2/spot/trade/modify-plan-order', params) 36 | 37 | def cancelPlanOrder(self, params): 38 | return self._request_with_params(POST, '/api/v2/spot/trade/cancel-plan-order', params) 39 | 40 | def currentPlanOrder(self, params): 41 | return self._request_with_params(GET, '/api/v2/spot/trade/current-plan-order', params) 42 | 43 | def historyPlanOrder(self, params): 44 | return self._request_with_params(GET, '/api/v2/spot/trade/history-plan-order', params) 45 | 46 | def traderOrderCloseTracking(self, params): 47 | return self._request_with_params(POST, '/api/v2/copy/spot-trader/order-close-tracking', params) 48 | 49 | def traderOrderCurrentTrack(self, params): 50 | return self._request_with_params(GET, '/api/v2/copy/spot-trader/order-current-track', params) 51 | 52 | def traderOrderHistoryTrack(self, params): 53 | return self._request_with_params(GET, '/api/v2/copy/spot-trader/order-history-track', params) 54 | -------------------------------------------------------------------------------- /bitget/v2/spot/wallet_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from bitget.client import Client 3 | from bitget.consts import GET, POST 4 | 5 | 6 | class WalletApi(Client): 7 | def __init__(self, api_key, api_secret_key, passphrase, use_server_time=False, first=False): 8 | Client.__init__(self, api_key, api_secret_key, passphrase, use_server_time, first) 9 | 10 | def transfer(self, params): 11 | return self._request_with_params(POST, '/api/v2/spot/wallet/transfer', params) 12 | 13 | def depositAddress(self, params): 14 | return self._request_with_params(GET, '/api/v2/spot/wallet/deposit-address', params) 15 | 16 | def withdrawal(self, params): 17 | return self._request_with_params(POST, '/api/v2/spot/wallet/withdrawal', params) 18 | 19 | def withdrawalRecords(self, params): 20 | return self._request_with_params(GET, '/api/v2/spot/wallet/withdrawal-records', params) 21 | 22 | def depositRecords(self, params): 23 | return self._request_with_params(GET, '/api/v2/spot/wallet/deposit-records', params) 24 | -------------------------------------------------------------------------------- /bitget/ws/__pycache__/bitget_ws_client.cpython-313.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/bitget/ws/__pycache__/bitget_ws_client.cpython-313.pyc -------------------------------------------------------------------------------- /bitget/ws/bitget_ws_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import json 3 | import math 4 | import threading 5 | import time 6 | import traceback 7 | from threading import Timer 8 | from zlib import crc32 9 | 10 | import websocket 11 | 12 | from bitget.consts import GET 13 | from .. import consts as c, utils 14 | 15 | WS_OP_LOGIN = 'login' 16 | WS_OP_SUBSCRIBE = "subscribe" 17 | WS_OP_UNSUBSCRIBE = "unsubscribe" 18 | 19 | 20 | def handle(message): 21 | print("default:" + message) 22 | 23 | 24 | def handel_error(message): 25 | print("default_error:" + message) 26 | 27 | 28 | class BitgetWsClient: 29 | 30 | def __init__(self, url, need_login=False): 31 | utils.check_none(url, "url") 32 | self.__need_login = need_login 33 | self.__connection = False 34 | self.__login_status = False 35 | self.__reconnect_status = False 36 | self.__api_key = None 37 | self.__api_secret_key = None 38 | self.__passphrase = None 39 | self.__all_suribe = set() 40 | self.__listener = handle 41 | self.__error_listener = handel_error 42 | self.__url = url 43 | self.__scribe_map = {} 44 | self.__allbooks_map = {} 45 | 46 | def build(self): 47 | self.__ws_client = self.__init_client() 48 | __thread = threading.Thread(target=self.connect) 49 | __thread.start() 50 | 51 | while not self.has_connect(): 52 | print("start connecting... url: ", self.__url) 53 | time.sleep(1) 54 | 55 | if self.__need_login: 56 | self.__login() 57 | 58 | self.__keep_connected(25) 59 | 60 | return self 61 | 62 | def api_key(self, api_key): 63 | self.__api_key = api_key 64 | return self 65 | 66 | def api_secret_key(self, api_secret_key): 67 | self.__api_secret_key = api_secret_key 68 | return self 69 | 70 | def passphrase(self, passphrase): 71 | self.__passphrase = passphrase 72 | return self 73 | 74 | def listener(self, listener): 75 | self.__listener = listener 76 | return self 77 | 78 | def error_listener(self, error_listener): 79 | self.__error_listener = error_listener 80 | return self 81 | 82 | def has_connect(self): 83 | return self.__connection 84 | 85 | def __init_client(self): 86 | try: 87 | return websocket.WebSocketApp(self.__url, 88 | on_open=self.__on_open, 89 | on_message=self.__on_message, 90 | on_error=self.__on_error, 91 | on_close=self.__on_close) 92 | 93 | except Exception as ex: 94 | print(ex) 95 | 96 | def __login(self): 97 | utils.check_none(self.__api_key, "api key") 98 | utils.check_none(self.__api_secret_key, "api secret key") 99 | utils.check_none(self.__passphrase, "passphrase") 100 | timestamp = int(round(time.time())) 101 | sign = utils.sign(utils.pre_hash(timestamp, GET, c.REQUEST_PATH), self.__api_secret_key) 102 | if c.SIGN_TYPE == c.RSA: 103 | sign = utils.signByRSA(utils.pre_hash(timestamp, GET, c.REQUEST_PATH), self.__api_secret_key) 104 | ws_login_req = WsLoginReq(self.__api_key, self.__passphrase, str(timestamp), sign) 105 | self.send_message(WS_OP_LOGIN, [ws_login_req]) 106 | print("logging in......") 107 | while not self.__login_status: 108 | time.sleep(1) 109 | 110 | def connect(self): 111 | try: 112 | self.__ws_client.run_forever(ping_timeout=10) 113 | except Exception as ex: 114 | print(ex) 115 | 116 | def __keep_connected(self, interval): 117 | try: 118 | __timer_thread = Timer(interval, self.__keep_connected, (interval,)) 119 | __timer_thread.start() 120 | self.__ws_client.send("ping") 121 | except Exception as ex: 122 | print(ex) 123 | 124 | def send_message(self, op, args): 125 | message = json.dumps(BaseWsReq(op, args), default=lambda o: o.__dict__) 126 | print("send message:" + message) 127 | self.__ws_client.send(message) 128 | 129 | def subscribe(self, channels, listener=None): 130 | 131 | if listener: 132 | for chanel in channels: 133 | chanel.inst_type = str(chanel.inst_type) 134 | self.__scribe_map[chanel] = listener 135 | 136 | for channel in channels: 137 | self.__all_suribe.add(channel) 138 | 139 | self.send_message(WS_OP_SUBSCRIBE, channels) 140 | 141 | def unsubscribe(self, channels): 142 | try: 143 | for chanel in channels: 144 | if chanel in self.__scribe_map: 145 | del self.__scribe_map[chanel] 146 | 147 | for channel in channels: 148 | if chanel in self.__all_suribe: 149 | self.__all_suribe.remove(channel) 150 | 151 | self.send_message(WS_OP_UNSUBSCRIBE, channels) 152 | except Exception as e: 153 | pass 154 | 155 | def __on_open(self, ws): 156 | print('connection is success....') 157 | self.__connection = True 158 | self.__reconnect_status = False 159 | 160 | def __on_message(self, ws, message): 161 | 162 | if message == 'pong': 163 | print("Keep connected:" + message) 164 | return 165 | json_obj = json.loads(message) 166 | if "code" in json_obj and json_obj.get("code") != 0: 167 | if self.__error_listener: 168 | self.__error_listener(message) 169 | return 170 | 171 | if "event" in json_obj and json_obj.get("event") == "login": 172 | print("login msg:" + message) 173 | self.__login_status = True 174 | return 175 | listenner = None 176 | if "data" in json_obj: 177 | if not self.__check_sum(json_obj): 178 | return 179 | 180 | listenner = self.get_listener(json_obj) 181 | 182 | if listenner: 183 | listenner(message) 184 | return 185 | 186 | self.__listener(message) 187 | 188 | def __dict_books_info(self, dict): 189 | return BooksInfo(dict['asks'], dict['bids'], dict['checksum']) 190 | 191 | def __dict_to_subscribe_req(self, dict): 192 | if "instId" in dict: 193 | instId = dict['instId'] 194 | else: 195 | instId = dict['coin'] 196 | return SubscribeReq(dict['instType'], dict['channel'], instId) 197 | 198 | def get_listener(self, json_obj): 199 | try: 200 | if json_obj.get('arg'): 201 | json_str = str(json_obj.get('arg')).replace("\'", "\"") 202 | subscribe_req = json.loads(json_str, object_hook=self.__dict_to_subscribe_req) 203 | return self.__scribe_map.get(subscribe_req) 204 | except Exception as e: 205 | print(json_obj.get('arg'), e) 206 | pass 207 | 208 | def __on_error(self, ws, msg): 209 | print("error:", msg) 210 | self.__close() 211 | if not self.__reconnect_status: 212 | self.__re_connect() 213 | 214 | def __on_close(self, ws, close_status_code, close_msg): 215 | print("ws is closeing ......close_status:{},close_msg:{}".format(close_status_code, close_msg)) 216 | self.__close() 217 | if not self.__reconnect_status: 218 | self.__re_connect() 219 | 220 | def __re_connect(self): 221 | # 重连 222 | self.__reconnect_status = True 223 | print("start reconnection ...") 224 | self.build() 225 | for channel in self.__all_suribe : 226 | self.subscribe([channel]) 227 | pass 228 | 229 | def __close(self): 230 | self.__login_status = False 231 | self.__connection = False 232 | self.__ws_client.close() 233 | 234 | def __check_sum(self, json_obj): 235 | # noinspection PyBroadException 236 | try: 237 | if "arg" not in json_obj or "action" not in json_obj: 238 | return True 239 | arg = str(json_obj.get('arg')).replace("\'", "\"") 240 | action = str(json_obj.get('action')).replace("\'", "\"") 241 | data = str(json_obj.get('data')).replace("\'", "\"") 242 | 243 | subscribe_req = json.loads(arg, object_hook=self.__dict_to_subscribe_req) 244 | 245 | if subscribe_req.channel != "books": 246 | return True 247 | 248 | books_info = json.loads(data, object_hook=self.__dict_books_info)[0] 249 | 250 | if action == "snapshot": 251 | self.__allbooks_map[subscribe_req] = books_info 252 | return True 253 | if action == "update": 254 | all_books = self.__allbooks_map[subscribe_req] 255 | if all_books is None: 256 | return False 257 | 258 | all_books = all_books.merge(books_info) 259 | check_sum = all_books.check_sum(books_info.checksum) 260 | if not check_sum: 261 | self.unsubscribe([subscribe_req]) 262 | self.subscribe([subscribe_req]) 263 | return False 264 | self.__allbooks_map[subscribe_req] = all_books 265 | except Exception as e: 266 | msg = traceback.format_exc() 267 | print(msg) 268 | 269 | return True 270 | 271 | 272 | class BooksInfo: 273 | def __init__(self, asks, bids, checksum): 274 | self.asks = asks 275 | self.bids = bids 276 | self.checksum = checksum 277 | 278 | def merge(self, book_info): 279 | self.asks = self.innerMerge(self.asks, book_info.asks, False) 280 | self.bids = self.innerMerge(self.bids, book_info.bids, True) 281 | return self 282 | 283 | def innerMerge(self, all_list, update_list, is_reverse): 284 | price_and_value = {} 285 | for v in all_list: 286 | price_and_value[v[0]] = v 287 | 288 | for v in update_list: 289 | if v[1] == "0": 290 | del price_and_value[v[0]] 291 | continue 292 | price_and_value[v[0]] = v 293 | 294 | keys = sorted(price_and_value.keys(), reverse=is_reverse) 295 | 296 | result = [] 297 | 298 | for i in keys: 299 | result.append(price_and_value[i]) 300 | 301 | return result 302 | 303 | def check_sum(self, new_check_sum): 304 | crc32str = '' 305 | for x in range(25): 306 | if self.bids[x] is not None: 307 | crc32str = crc32str + self.bids[x][0] + ":" + self.bids[x][1] + ":" 308 | 309 | if self.asks[x] is not None: 310 | crc32str = crc32str + self.asks[x][0] + ":" + self.asks[x][1] + ":" 311 | 312 | crc32str = crc32str[0:len(crc32str) - 1] 313 | print(crc32str) 314 | merge_num = crc32(bytes(crc32str, encoding="utf8")) 315 | print("start checknum mergeVal:" + str(merge_num) + ",checkVal:" + str(new_check_sum)+",checkSin:"+str(self.__signed_int(merge_num))) 316 | return self.__signed_int(merge_num) == new_check_sum 317 | 318 | def __signed_int(self, checknum): 319 | int_max = math.pow(2, 31) - 1 320 | if checknum > int_max: 321 | return checknum - int_max * 2 - 2 322 | return checknum 323 | 324 | class SubscribeReq: 325 | 326 | def __init__(self, inst_type, channel, instId): 327 | self.inst_type = inst_type 328 | self.channel = channel 329 | self.inst_id = instId 330 | self.coin = instId 331 | 332 | def __eq__(self, other) -> bool: 333 | return self.__dict__ == other.__dict__ 334 | 335 | def __hash__(self) -> int: 336 | return hash(self.inst_type + self.channel + self.inst_id) 337 | 338 | 339 | class BaseWsReq: 340 | 341 | def __init__(self, op, args): 342 | self.op = op 343 | self.args = args 344 | 345 | 346 | class WsLoginReq: 347 | 348 | def __init__(self, api_key, passphrase, timestamp, sign): 349 | self.api_key = api_key 350 | self.passphrase = passphrase 351 | self.timestamp = timestamp 352 | self.sign = sign 353 | -------------------------------------------------------------------------------- /leia-me.txt: -------------------------------------------------------------------------------- 1 | Documentação da operação. 2 | 1. Execute o programa. 3 | 2. Insira "Chave API", "Chave Secreta", "Frase-senha", "Valor da Negociação" e Intervalo. 4 | 3. Selecione “Tipo” no menu suspenso. 5 | 4. Se desejar operação automática, marque "Automático/Manual" 6 | 5. Se você marcar "Automático/Manual", 7 | a negociação automática será iniciada e algumas informações serão exibidas. 8 | - Se quiser parar o método automático, desmarque-o. 9 | 6. Você pode fazer o método manual no Método Automático 10 | 7. Se você quiser alterar o valor da negociação, clique em "Desconectar" e defina-o. 11 | 8. Se você quiser encerrar o programa, clique em "Sair" -------------------------------------------------------------------------------- /logo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Upwork-Job32/bitget-App.python-project/bbdac66c7bde05185959e6b97f4a9ba8b07aab89/logo.ico -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import threading 3 | import time 4 | import bitget.v2.mix.account_api as AccountApi 5 | import bitget.v2.mix.market_api as MarketApi 6 | import bitget.v2.mix.order_api as OrderApi 7 | 8 | 9 | from bitget.exceptions import BitgetAPIException 10 | from tkinter import ttk, messagebox 11 | 12 | 13 | 14 | # === Create App Window === 15 | def create_main_window(): 16 | global root, data_thread, connect_status, stop_event 17 | connect_status = False 18 | stop_event = threading.Event() 19 | root = tk.Tk() 20 | root.title("Programa de Negociação Bitget") 21 | root.geometry("990x180") 22 | build_gui() 23 | # ======= Init GUI =========f 24 | dropdown.current(0) 25 | auto_checkButton.config(state="disabled") 26 | data_thread = threading.Thread(target=update_value, daemon=True) 27 | root.mainloop() 28 | 29 | 30 | # === Button === 31 | def connect(): 32 | global connect_status, account_API, market_API, order_API, connect_button 33 | global data_thread, stop_event 34 | try: 35 | if not connect_status: 36 | api_key = api_entry.get() 37 | api_secret = secret_entry.get() 38 | passphrase = phrase_entry.get() 39 | account_API = AccountApi.AccountApi(api_key, api_secret, passphrase) 40 | market_API = MarketApi.MarketApi(api_key, api_secret, passphrase) 41 | order_API = OrderApi.OrderApi(api_key, api_secret, passphrase) 42 | 43 | stop_event.clear() # Allow the thread to run 44 | if not data_thread or not data_thread.is_alive(): # Start the thread if not already running 45 | data_thread = threading.Thread(target=update_value, daemon=True) 46 | data_thread.start() 47 | auto_checkButton.config(state="normal") 48 | connect_button.config(text="Desconectar") 49 | secret_entry.config(state="readonly") 50 | api_entry.config(state="readonly") 51 | phrase_entry.config(state="readonly") 52 | amount_entry.config(state="readonly") 53 | dropdown.state(["disabled"]) 54 | time_entry.config(state = "disabled") 55 | else: 56 | if data_thread.is_alive(): 57 | stop_event.set() 58 | exchange_rate_label.config(text=f"Taxa de câmbio: -------------") 59 | wallet_available_label.config(text=f"Carteira disponível: -------------") 60 | cur_pos_entry.config(text=f"-------------") 61 | available_pos_entry.config(text=f"-------------") 62 | auto_checkButton.config(state="disabled") 63 | connect_button.config(text="Conectar") 64 | secret_entry.config(state="normal") 65 | api_entry.config(state="normal") 66 | phrase_entry.config(state="normal") 67 | amount_entry.config(state="normal") 68 | dropdown.state(["!disabled"]) 69 | time_entry.config(state = "normal") 70 | connect_status = not connect_status 71 | except BitgetAPIException as e: 72 | messagebox.Error(e) 73 | 74 | def exit_app(): 75 | root.quit() 76 | 77 | # === Build GUI Layout === 78 | def build_gui(): 79 | create_top_section() 80 | create_checkboxes() 81 | create_auth_section() 82 | create_footer() 83 | create_last() 84 | 85 | def dropdown_change(event): 86 | global symbol 87 | symbol = dropdown.get() 88 | # === GUI Sections === 89 | def create_top_section(): 90 | global dropdown, amount_entry, api_entry, connect_button 91 | global symbol 92 | dropdown = ttk.Combobox(root, values=["SOLUSDT", "BTCUSDT", "ETHUSDT"], width=20, state="readonly") 93 | dropdown.current(0) 94 | dropdown.bind("<>", dropdown_change) 95 | dropdown.grid(row=0, column=0, padx=10) 96 | symbol = dropdown.get() 97 | 98 | tk.Label(root, text="Valor da negociação").grid(row=0, column=1) 99 | amount_entry = tk.Entry(root, width=10) 100 | amount_entry.insert(0, "1") 101 | amount_entry.grid(row=0, column=2) 102 | 103 | tk.Label(root, text="API key").grid(row=0, column=4) 104 | api_entry = tk.Entry(root, width=45) 105 | api_entry.insert(0, "") 106 | api_entry.grid(row=0, column=5) 107 | connect_button = tk.Button(root, text="Conectar", width=10, command=connect) 108 | connect_button.grid(row=0, column=6) 109 | 110 | def create_checkboxes(): 111 | global auto_var, auto_checkButton, buy_checkButton 112 | global cur_pos_entry, available_pos_entry, time_entry 113 | 114 | auto_var = tk.BooleanVar(value=False) 115 | auto_checkButton = tk.Checkbutton(root, text="Automático/Manual", variable=auto_var) 116 | auto_checkButton.grid(row=1, column=0, sticky='w', padx=10) 117 | tk.Label(root, text="Máximo disponível: ").grid(row=1, column=1) 118 | cur_pos_entry = tk.Label(root, text = "-------------", width=20) 119 | cur_pos_entry.grid(row=1, column=2) 120 | tk.Label(root, text="Posição disponível:").grid(row=2, column=1) 121 | available_pos_entry = tk.Label(root, text = "-------------") 122 | available_pos_entry.grid(row=2, column=2) 123 | time_entry = tk.Entry(root, width=10) 124 | time_entry.insert(0, "60") 125 | time_entry.grid(row=2, column=0) 126 | 127 | def create_auth_section(): 128 | global secret_entry, phrase_entry 129 | 130 | tk.Label(root, text="Secret Key").grid(row=1, column=4) 131 | secret_entry = tk.Entry(root, width=45) 132 | secret_entry.insert(0, "") 133 | secret_entry.grid(row=1, column=5) 134 | 135 | tk.Label(root, text="PassPhrase").grid(row=2, column=4) 136 | phrase_entry = tk.Entry(root, width=45) 137 | phrase_entry.insert(0, "") 138 | phrase_entry.grid(row=2, column=5) 139 | 140 | 141 | def create_footer(): 142 | global exchange_rate_label, wallet_available_label, user_id_label, trading_status_label, current_sma_label, before_sma_label 143 | 144 | exchange_rate_label = tk.Label(root, text="Taxa de câmbio: -------------", width=30) 145 | exchange_rate_label.grid(row=4, column=0, pady=5) 146 | 147 | wallet_available_label = tk.Label(root, text="Carteira disponível: -------------") 148 | wallet_available_label.grid(row=4, column=1, padx=3, pady=5) 149 | trading_status_label = tk.Label(root, text="Status: ------") 150 | trading_status_label.grid(row=4, column=2, padx=3, pady=5) 151 | user_id_label = tk.Label(root, text = "Tempo: -------------") 152 | user_id_label.grid(row=4, column=5, padx=3, pady=5) 153 | current_sma_label = tk.Label(root, text = "Current SMA: -------------") 154 | current_sma_label.grid(row=3, column=1, padx=3, pady=5) 155 | before_sma_label = tk.Label(root, text = "Prev SMA: -------------") 156 | before_sma_label.grid(row=3, column=0, padx=3, pady=5) 157 | tk.Button(root, text="Sair", width=10, command=exit_app).grid(row=2, column=6) 158 | def create_last(): 159 | buy_open_button = tk.Button(root, text="Compre aberto", width=12, command = buyopen) 160 | buy_open_button.grid(row=6, column=0) 161 | sell_open_button = tk.Button(root, text="Vender aberto", width=12, command = sell_open) 162 | sell_open_button.config(state="disabled") 163 | sell_open_button.grid(row=6, column=1) 164 | buy_close_button = tk.Button(root, text="Compre Fechar", width=12, command = buy_close) 165 | buy_close_button.grid(row=6, column=2) 166 | sell_close_button = tk.Button(root, text="Vender Fechar", width=12, command = sell_close) 167 | sell_close_button.config(state="disabled") 168 | sell_close_button.grid(row=6, column=5) 169 | 170 | def update_value(): 171 | 172 | global current_price 173 | interval = float(time_entry.get()) 174 | start_time = time.time() 175 | start_candle_time = start_time 176 | price_list = [] 177 | prev_price = 0 178 | now_price = 0 179 | while not stop_event.is_set(): 180 | current_time = time.time() 181 | if not auto_var.get(): 182 | start_time = current_time 183 | current_candle_time = current_time 184 | user_id_label.config(text = f"Tempo: {int(current_time - start_time)}") 185 | try: 186 | exch_data = market_API.ticker({"productType": "USDT-FUTURES", "symbol": symbol}) 187 | wall_data = account_API.account({"productType": "USDT-FUTURES", "marginCoin": "USDT", "symbol": symbol}) 188 | pos_data = account_API.singlePosition({"productType": "USDT-FUTURES", "symbol":symbol, "marginCoin":"USDT"}) 189 | 190 | if exch_data['code'] == '00000' and wall_data['code'] == '00000' and pos_data['code'] == '00000': 191 | #manual method 192 | current_price = float(exch_data['data'][0]['lastPr']) 193 | price_list.append(current_price) 194 | crossedMarginLeverage = float(wall_data['data']['crossedMarginLeverage']) 195 | wallet_available = float(wall_data['data']['available']) 196 | exchange_rate_label.config(text=f"Taxa de câmbio: {current_price:.2f} USDT") 197 | wallet_available_label.config(text=f"Carteira disponível: {wallet_available:.2f} USDT") 198 | maximum_available = crossedMarginLeverage * wallet_available / current_price 199 | cur_pos_entry.config(text = f"{maximum_available:.2f}{symbol[:3]}") 200 | position_data = pos_data['data'] 201 | available_position = 0 202 | if not position_data: 203 | available_pos_entry.config(text = "0") 204 | available_position = 0 205 | else: 206 | available_position = position_data[0]['available'] 207 | available_pos_entry.config(text = f"{float(available_position): .2f}") 208 | 209 | if auto_var.get():#auto logic 210 | print(f"current_time: {current_time}, start_time: {start_time}") 211 | if current_candle_time - start_candle_time > interval: 212 | print("candle change") 213 | prev_price = now_price 214 | # start_sma = current_sma 215 | now_price = sum(price_list) / len(price_list) 216 | price_list = [] 217 | # current_candles = market_API.candles({"symbol": symbol, "granularity": "1m", "productType": "USDT-FUTURES"}) 218 | # current_sma = sma(current_candles['data']) 219 | start_candle_time = current_candle_time 220 | current_sma_label.config(text = f"Current SMA: {now_price:.2f}") 221 | before_sma_label.config(text = f"Prev SMA: {prev_price:.2f}") 222 | if(current_time - start_time > interval): 223 | print("trading time") 224 | if prev_price != 0: 225 | if now_price < prev_price: 226 | print("1", maximum_available, amount_entry.get()) 227 | if float(maximum_available) >1.001*float(amount_entry.get()): 228 | buy_trading("buy","open") 229 | trading_status_label.config(text=f"Status: Abrir") 230 | else: 231 | trading_status_label.config(text=f"Status:Não Abrir") 232 | else: 233 | print("2",available_position, current_price) 234 | if float(available_position) >=float(amount_entry.get()): 235 | buy_trading("buy", "close") 236 | trading_status_label.config(text=f"Status: Fechar") 237 | else: 238 | trading_status_label.config(text=f"Status: DesFechar") 239 | start_time = current_time 240 | 241 | else: 242 | exchange_rate_label.config(text=f"Taxa de câmbio: -------------") 243 | wallet_available_label.config(text=f"Carteira disponível: -------------") 244 | trading_status_label.config(text=f"Status: ------") 245 | except BitgetAPIException as e: 246 | print(f"Error in update_value: {e}") 247 | start_time = current_time 248 | start_candle_time = current_candle_time 249 | 250 | def buyopen(): 251 | buy_trading("buy", "open") 252 | 253 | def buy_close(): 254 | buy_trading("buy", "close") 255 | 256 | def sell_open(): 257 | buy_trading("sell", "open") 258 | 259 | def sell_close(): 260 | buy_trading("sell", "close") 261 | 262 | def buy_trading(tt,stat): 263 | global current_price 264 | try: 265 | params = { 266 | "symbol": symbol, 267 | "productType": "USDT-FUTURES", 268 | "marginMode": "isolated", 269 | "marginCoin": "USDT", 270 | "size": amount_entry.get(), 271 | "price" : str(current_price), 272 | "side" : tt, 273 | "tradeSide" : stat, 274 | "orderType" : "limit", 275 | } 276 | response = order_API.placeOrder(params) 277 | print(f"{tt} {stat}", response) 278 | except NameError: 279 | print("current_price is not initialized yet.") 280 | return 281 | 282 | def sma(data) : 283 | sum = 0 284 | for i in data: 285 | sum += float(i[1]) 286 | return sum / len(data) 287 | 288 | # === Launch App === 289 | if __name__ == "__main__": 290 | create_main_window() 291 | 292 | --------------------------------------------------------------------------------