├── binance_interface ├── __init__.py ├── api │ ├── __init__.py │ ├── client.py │ ├── cm │ │ ├── __init__.py │ │ ├── cm_account_trade.py │ │ ├── cm_market.py │ │ └── cm_portfolio.py │ ├── eo │ │ ├── __init__.py │ │ ├── eo_account_trade.py │ │ ├── eo_market.py │ │ └── eo_market_maker.py │ ├── margin │ │ ├── __init__.py │ │ ├── margin_account_trade.py │ │ └── margin_blvt.py │ ├── other │ │ ├── __init__.py │ │ ├── auto_invest.py │ │ ├── bs_wap.py │ │ ├── c2c.py │ │ ├── convert.py │ │ ├── crypto_loans.py │ │ ├── fiat.py │ │ ├── futures.py │ │ ├── futures_algo.py │ │ ├── gift_card.py │ │ ├── mining.py │ │ ├── nft.py │ │ ├── pay.py │ │ ├── portfolio.py │ │ ├── rebate.py │ │ ├── simple_earn.py │ │ ├── sub_account.py │ │ ├── vip_loans.py │ │ └── wallet.py │ ├── pm │ │ ├── __init__.py │ │ ├── pm_account.py │ │ ├── pm_cancel_order.py │ │ ├── pm_get_order.py │ │ ├── pm_market.py │ │ └── pm_set_order.py │ ├── proxy_host.py │ ├── spot │ │ ├── __init__.py │ │ ├── spot_account.py │ │ ├── spot_algo.py │ │ ├── spot_market.py │ │ └── spot_trade.py │ └── um │ │ ├── __init__.py │ │ ├── um_account_trade.py │ │ ├── um_market.py │ │ └── um_portfolio.py └── app │ ├── __init__.py │ ├── account │ ├── __init__.py │ ├── account_cm.py │ ├── account_spot.py │ └── account_um.py │ ├── candle_server │ ├── __init__.py │ ├── rule.py │ └── server.py │ ├── code │ ├── __init__.py │ ├── account.py │ ├── execute.py │ ├── market.py │ └── trade.py │ ├── exception │ ├── __init__.py │ ├── _base.py │ ├── param.py │ ├── req.py │ └── rule.py │ ├── market │ ├── __init__.py │ ├── _base.py │ ├── exchange_info.py │ ├── history_candle.py │ └── ticker.py │ ├── trade │ ├── __init__.py │ ├── trade_cm │ │ ├── __init__.py │ │ ├── _base.py │ │ ├── close.py │ │ ├── open.py │ │ ├── order.py │ │ └── quantity_and_price.py │ ├── trade_spot │ │ ├── __init__.py │ │ ├── _base.py │ │ ├── close.py │ │ ├── open.py │ │ ├── order.py │ │ └── quantity_and_price.py │ └── trade_um │ │ ├── __init__.py │ │ ├── _base.py │ │ ├── close.py │ │ ├── open.py │ │ ├── order.py │ │ └── quantity_and_price.py │ └── utils.py ├── examples ├── 1.1 Binance_Interface安装与介绍.ipynb ├── 1.2 API函数接口总览.ipynb ├── 1.3 API 现货行情接口.ipynb ├── 1.4 API U本位合约行情.ipynb ├── 1.5 API 币本位合约行情.ipynb ├── 1.6 API 现货交易账户.ipynb ├── 1.7 API U本位合约交易账户.ipynb ├── 1.8 API 币本位合约交易账户.ipynb ├── 2.1 APP 现货交易账户.ipynb ├── 2.10 APP 现货交易-市单价平仓.ipynb ├── 2.2 APP 现货行情-交易规则信息.ipynb ├── 2.3 APP 现货行情-实时行情.ipynb ├── 2.4 APP 现货行情-历史K线.ipynb ├── 2.5 APP 现货交易-基础订单.ipynb ├── 2.6 APP 现货交易-价格与数量.ipynb ├── 2.7 APP 现货交易-限价单开仓.ipynb ├── 2.8 APP 现货交易-市价单开仓.ipynb ├── 2.9 APP 现货交易-限单价平仓.ipynb ├── 3.1 APP U本位合约交易账户.ipynb ├── 3.10 APP U本位合约交易-市单价平仓.ipynb ├── 3.2 APP U本位合约行情-交易规则信息.ipynb ├── 3.3 APP U本位合约行情-实时行情.ipynb ├── 3.4 APP U本位合约行情-历史K线.ipynb ├── 3.5 APP U本位合约交易-基础订单.ipynb ├── 3.6 APP U本位合约交易-价格与数量.ipynb ├── 3.7 APP U本位合约交易-限价单开仓.ipynb ├── 3.8 APP U本位合约交易-市价单开仓.ipynb ├── 3.9 APP U本位合约交易-限单价平仓.ipynb ├── 4.1 APP 币本位合约交易账户.ipynb ├── 4.10 APP 币本位合约交易-市单价平仓.ipynb ├── 4.2 APP 币本位合约行情-交易规则信息.ipynb ├── 4.3 APP 币本位合约行情-实时行情.ipynb ├── 4.4 APP 币本位合约行情-历史K线.ipynb ├── 4.5 APP 币本位合约交易-基础订单.ipynb ├── 4.6 APP 币本位合约交易-价格与数量.ipynb ├── 4.7 APP 币本位合约交易-限价单开仓.ipynb ├── 4.8 APP 币本位合约交易-市价单开仓.ipynb ├── 4.9 APP 币本位合约交易-限单价平仓.ipynb ├── 5.1 APP K线服务 下载历史K线.ipynb ├── 5.2 APP K线服务 每日定时下载昨日历史K线.ipynb └── 5.3 APP K线服务 维护实时历史K线.ipynb ├── readme.md └── setup.py /binance_interface/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface import api 2 | from binance_interface import app 3 | from candlelite.crypto.binace_lite import BinanceLite 4 | import candlelite.crypto.binace_lite 5 | 6 | __version__ = '2.0.5' 7 | -------------------------------------------------------------------------------- /binance_interface/api/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.api.spot import SPOT # 现货 2 | from binance_interface.api.margin import Margin # 杠杆 3 | from binance_interface.api.um import UM # U本位合约 4 | from binance_interface.api.cm import CM # 币本位合约 5 | from binance_interface.api.eo import EO # 欧式期权 6 | from binance_interface.api.pm import PM # 统一账户 7 | from binance_interface.api.other import Other # 其他 8 | 9 | 10 | class Binance(): 11 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 12 | self.spot = SPOT(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 13 | self.margin = Margin(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 14 | self.um = UM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 15 | self.cm = CM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 16 | self.eo = EO(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 17 | self.pm = PM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 18 | self.other = Other(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | 20 | 21 | BinanceInterface = Binance 22 | API = Binance -------------------------------------------------------------------------------- /binance_interface/api/client.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import hashlib 3 | import json 4 | import requests 5 | import urllib.parse as up 6 | import time 7 | from binance_interface.api.proxy_host import proxy_host_map 8 | 9 | 10 | def request_retry_wrapper(retry_num=50, retry_delay=0.1): 11 | def wrapper1(func): 12 | def wrapper2(*args, **kwargs): 13 | for i in range(retry_num - 1): 14 | try: 15 | result = func(*args, **kwargs) 16 | if result['code'] == 200: 17 | return result 18 | elif result['code'] in [-1001, -1003, -1004, -1007, -1008, -1016]: 19 | time.sleep(retry_delay) 20 | continue 21 | else: 22 | return result 23 | except requests.exceptions.ConnectionError: 24 | time.sleep(retry_delay) 25 | result = func(*args, **kwargs) 26 | return result 27 | 28 | return wrapper2 29 | 30 | return wrapper1 31 | 32 | 33 | class Client(): 34 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 35 | self.key = key 36 | self.secret = secret 37 | self.proxies = proxies 38 | self.proxy_host = proxy_host 39 | self.session = requests.Session() 40 | self.session.headers.update( 41 | { 42 | "Content-Type": "application/json;charset=utf-8", 43 | "User-Agent": "binance-api", 44 | "X-MBX-APIKEY": key, 45 | } 46 | ) 47 | 48 | @request_retry_wrapper() 49 | def send_request(self, api_url, method, path, sign=True, **kwargs): 50 | params_no_empty = {} 51 | for key, v in kwargs.items(): 52 | if not (v == '' or v == None or v == []): 53 | if type(v) == list: 54 | params_no_empty[key] = json.dumps(v).replace(" ", "") 55 | else: 56 | params_no_empty[key] = v 57 | 58 | if sign: 59 | params_no_empty["timestamp"] = int(time.time() * 1000) 60 | query_string = up.urlencode(params_no_empty, True).replace("%40", "@") 61 | signature = self._get_sign(query_string) 62 | params_no_empty["signature"] = signature 63 | if not self.proxy_host: 64 | url = up.urljoin(api_url, path) 65 | else: 66 | proxy_api_url = proxy_host_map[api_url].format(host=self.proxy_host) 67 | url = proxy_api_url + path 68 | response = getattr(self.session, method.lower())( 69 | url=url, 70 | params=up.urlencode(params_no_empty, True).replace("%40", "@") 71 | ) 72 | data = response.json() 73 | # 如果有code 74 | if type(data) == dict and 'code' in data.keys(): 75 | result = data 76 | else: 77 | result = { 78 | 'code': 200, 79 | 'data': data, 80 | 'msg': '', 81 | } 82 | return result 83 | 84 | def _get_sign(self, data): 85 | m = hmac.new(self.secret.encode("utf-8"), data.encode("utf-8"), hashlib.sha256) 86 | return m.hexdigest() 87 | -------------------------------------------------------------------------------- /binance_interface/api/cm/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 币本位合约 3 | https://binance-docs.github.io/apidocs/delivery/cn/ 4 | ''' 5 | from binance_interface.api.cm.cm_market import CMMarket # 行情接口 6 | from binance_interface.api.cm.cm_account_trade import CMAccountTrade # 账户和交易接口 7 | from binance_interface.api.cm.cm_portfolio import CMPortfolio # 经典统一账户接口 8 | 9 | Market = CMMarket 10 | AccountTrade = CMAccountTrade 11 | Portfolio = CMPortfolio 12 | 13 | 14 | class CM(): 15 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 16 | self.market = CMMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 17 | self.accountTrade = CMAccountTrade(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 18 | self.portfolio = CMPortfolio(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | -------------------------------------------------------------------------------- /binance_interface/api/cm/cm_portfolio.py: -------------------------------------------------------------------------------- 1 | # 经典统一账户接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _CMPortfolioEndpoints(): 7 | 8 | 9 | get_pmExchangeInfo = ['https://dapi.binance.com', 'GET', '/dapi/v1/pmExchangeInfo', True] # 查询经典统一账户Notional Limit(USER_DATA) 10 | get_pmAccountInfo = ['https://dapi.binance.com', 'GET', '/dapi/v1/pmAccountInfo', True] # 查询经典统一账户账户信息 (USER_DATA) 11 | 12 | 13 | class CMPortfolio(Client): 14 | 15 | # 查询经典统一账户Notional Limit(USER_DATA) 16 | def get_pmExchangeInfo(self,symbol:str = '',pair:str = '',proxies={},proxy_host:str=None): 17 | ''' 18 | GET /dapi/v1/pmExchangeInfo 19 | 20 | 权重(IP):5 21 | 22 | 请求参数: 23 | Parameter Type Required Description 24 | 25 | symbol STRING NO 26 | pair STRING NO 27 | ''' 28 | return self.send_request(*_CMPortfolioEndpoints.get_pmExchangeInfo, **to_local(locals())) 29 | 30 | 31 | # 查询经典统一账户账户信息 (USER_DATA) 32 | def get_pmAccountInfo(self,asset:str = '',recvWindow:int = '',proxies={},proxy_host:str=None): 33 | ''' 34 | GET /dapi/v1/pmAccountInfo 35 | 36 | 权重(IP):5 37 | 38 | 请求参数: 39 | Parameter Type Required Description 40 | 41 | asset STRING YES 42 | recvWindow LONG NO 43 | ''' 44 | return self.send_request(*_CMPortfolioEndpoints.get_pmAccountInfo, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/eo/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 欧式期权 3 | https://binance-docs.github.io/apidocs/voptions/cn/ 4 | ''' 5 | from binance_interface.api.eo.eo_market import EOMarket # 行情接口 6 | from binance_interface.api.eo.eo_account_trade import EOAccountTrade # 账户和交易接口 7 | from binance_interface.api.eo.eo_market_maker import EOMarketMaker # 做市商接口 8 | 9 | Market = EOMarket 10 | AccountTrade = EOAccountTrade 11 | MarketMaker = EOMarketMaker 12 | 13 | 14 | class EO(): 15 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 16 | self.market = EOMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 17 | self.accountTrade = EOAccountTrade(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 18 | self.marketMaker = EOMarketMaker(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | -------------------------------------------------------------------------------- /binance_interface/api/eo/eo_market.py: -------------------------------------------------------------------------------- 1 | # 行情接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _EOMarketEndpoints(): 7 | 8 | 9 | get_ping = ['https://eapi.binance.com', 'GET', '/eapi/v1/ping', False] # 测试服务器连通性 PING【 10 | get_time = ['https://eapi.binance.com', 'GET', '/eapi/v1/time', False] # 获取服务器时间【 11 | get_exchangeInfo = ['https://eapi.binance.com', 'GET', '/eapi/v1/exchangeInfo', False] # 获取交易规则和交易对【 12 | get_depth = ['https://eapi.binance.com', 'GET', '/eapi/v1/depth', False] # 深度信息 13 | get_trades = ['https://eapi.binance.com', 'GET', '/eapi/v1/trades', False] # 近期成交 14 | get_historicalTrades = ['https://eapi.binance.com', 'GET', '/eapi/v1/historicalTrades', False] # 查询历史成交(MARKET_DATA) 15 | get_klines = ['https://eapi.binance.com', 'GET', '/eapi/v1/klines', False] # K线数据 16 | get_mark = ['https://eapi.binance.com', 'GET', '/eapi/v1/mark', False] # 查询期权标记价格 17 | get_ticker = ['https://eapi.binance.com', 'GET', '/eapi/v1/ticker', False] # 24hr价格变动情况 18 | get_index = ['https://eapi.binance.com', 'GET', '/eapi/v1/index', False] # 标的最新价格 19 | get_exerciseHistory = ['https://eapi.binance.com', 'GET', '/eapi/v1/exerciseHistory', False] # 历史行权记录 20 | get_openInterest = ['https://eapi.binance.com', 'GET', '/eapi/v1/openInterest', False] # 合约持仓量 21 | 22 | 23 | class EOMarket(Client): 24 | 25 | # 测试服务器连通性 PING 26 | def get_ping(self,proxies={},proxy_host:str=None): 27 | ''' 28 | GET /eapi/v1/ping 29 | 30 | 权重:1 31 | ''' 32 | return self.send_request(*_EOMarketEndpoints.get_ping, **to_local(locals())) 33 | 34 | 35 | # 获取服务器时间 36 | def get_time(self,proxies={},proxy_host:str=None): 37 | ''' 38 | GET /eapi/v1/time 39 | 40 | 权重:1 41 | ''' 42 | return self.send_request(*_EOMarketEndpoints.get_time, **to_local(locals())) 43 | 44 | 45 | # 获取交易规则和交易对 46 | def get_exchangeInfo(self,proxies={},proxy_host:str=None): 47 | ''' 48 | GET /eapi/v1/exchangeInfo 49 | 50 | 权重:1 51 | ''' 52 | return self.send_request(*_EOMarketEndpoints.get_exchangeInfo, **to_local(locals())) 53 | 54 | 55 | # 深度信息 56 | def get_depth(self,symbol:str = '',limit:int = '',proxies={},proxy_host:str=None): 57 | ''' 58 | GET /eapi/v1/depth 59 | 60 | 权重: 61 | 62 | 请求参数: 63 | Parameter Type Required Description 64 | 65 | symbol STRING YES 交易对 66 | limit INT NO 默认 100; 可选值:[10, 20, 50, 100, 500, 1000] 67 | ''' 68 | return self.send_request(*_EOMarketEndpoints.get_depth, **to_local(locals())) 69 | 70 | 71 | # 近期成交 72 | def get_trades(self,symbol:str = '',limit:int = '',proxies={},proxy_host:str=None): 73 | ''' 74 | GET /eapi/v1/trades 75 | 76 | 权重:5 77 | 78 | 请求参数: 79 | Parameter Type Required Description 80 | 81 | symbol STRING YES 交易对 82 | limit INT NO 默认:100,最大500 83 | ''' 84 | return self.send_request(*_EOMarketEndpoints.get_trades, **to_local(locals())) 85 | 86 | 87 | # 查询历史成交(MARKET_DATA) 88 | def get_historicalTrades(self,symbol:str = '',limit:int = '',fromId:int = '',proxies={},proxy_host:str=None): 89 | ''' 90 | GET /eapi/v1/historicalTrades 91 | 92 | 权重:20 93 | 94 | 请求参数: 95 | Parameter Type Required Description 96 | 97 | symbol STRING YES 交易对 98 | limit INT NO 默认值:100 最大值:500. 99 | fromId LONG NO 从哪一条成交id开始返回. 缺省返回最近的成交记录 100 | ''' 101 | return self.send_request(*_EOMarketEndpoints.get_historicalTrades, **to_local(locals())) 102 | 103 | 104 | # K线数据 105 | def get_klines(self,symbol:str = '',interval:str = '',startTime:int = '',endTime:int = '',limit:int = '',proxies={},proxy_host:str=None): 106 | ''' 107 | GET /eapi/v1/klines 108 | 109 | 权重:1 110 | 111 | 请求参数: 112 | Parameter Type Required Description 113 | 114 | symbol STRING YES 交易对 115 | interval ENUM YES 时间间隔 116 | startTime LONG NO 起始时间 117 | endTime LONG NO 结束时间 118 | limit INT NO 默认值:500 最大值:1500. 119 | ''' 120 | return self.send_request(*_EOMarketEndpoints.get_klines, **to_local(locals())) 121 | 122 | 123 | # 查询期权标记价格 124 | def get_mark(self,symbol:str = '',proxies={},proxy_host:str=None): 125 | ''' 126 | GET /eapi/v1/mark 127 | 128 | 权重:5 129 | 130 | 请求参数: 131 | Parameter Type Required Description 132 | 133 | symbol STRING NO 交易对 134 | ''' 135 | return self.send_request(*_EOMarketEndpoints.get_mark, **to_local(locals())) 136 | 137 | 138 | # 24hr价格变动情况 139 | def get_ticker(self,symbol:str = '',proxies={},proxy_host:str=None): 140 | ''' 141 | GET /eapi/v1/ticker 142 | 143 | 权重:5 144 | 145 | 请求参数: 146 | Parameter Type Required Description 147 | 148 | symbol STRING NO 交易对 149 | ''' 150 | return self.send_request(*_EOMarketEndpoints.get_ticker, **to_local(locals())) 151 | 152 | 153 | # 标的最新价格 154 | def get_index(self,underlying:str = '',proxies={},proxy_host:str=None): 155 | ''' 156 | GET /eapi/v1/index 157 | 158 | 权重:1 159 | 160 | 请求参数: 161 | Parameter Type Required Description 162 | 163 | underlying STRING YES 现货交易对如BTCUSDT 164 | ''' 165 | return self.send_request(*_EOMarketEndpoints.get_index, **to_local(locals())) 166 | 167 | 168 | # 历史行权记录 169 | def get_exerciseHistory(self,underlying:str = '',startTime:int = '',endTime:int = '',limit:int = '',proxies={},proxy_host:str=None): 170 | ''' 171 | GET /eapi/v1/exerciseHistory 172 | 173 | 权重:3 174 | 175 | 请求参数: 176 | Parameter Type Required Description 177 | 178 | underlying STRING NO 标的资产如BTCUSDT 179 | startTime LONG NO 开始时间 180 | endTime LONG NO 结束时间 181 | limit INT NO 默认值:100 最大值:100. 182 | ''' 183 | return self.send_request(*_EOMarketEndpoints.get_exerciseHistory, **to_local(locals())) 184 | 185 | 186 | # 合约持仓量 187 | def get_openInterest(self,underlyingAsset:str = '',expiration:str = '',proxies={},proxy_host:str=None): 188 | ''' 189 | GET /eapi/v1/openInterest 190 | 191 | 192 | 193 | 请求参数: 194 | Parameter Type Required Description 195 | 196 | underlyingAsset STRING YES 标的资产,如ETH或BTC 197 | expiration STRING YES 到期日,如221225 198 | ''' 199 | return self.send_request(*_EOMarketEndpoints.get_openInterest, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/eo/eo_market_maker.py: -------------------------------------------------------------------------------- 1 | # 做市商接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _EOMarketMakerEndpoints(): 7 | 8 | 9 | get_marginAccount = ['https://eapi.binance.com', 'GET', '/eapi/v1/marginAccount', False] # 保证金账户信息 10 | set_mmpSet = ['https://eapi.binance.com', 'POST', '/eapi/v1/mmpSet', False] # 设置MMP规则 11 | get_mmpSet = ['https://eapi.binance.com', 'GET', '/eapi/v1/mmpSet', False] # 获取MMP规则 12 | set_mmpReset = ['https://eapi.binance.com', 'POST', '/eapi/v1/mmpReset', False] # 重置MMP状态 13 | set_countdownCancelAll = ['https://eapi.binance.com', 'POST', '/eapi/v1/countdownCancelAll', True] # 设置倒计时取消所有订单配置 (TRADE) 14 | get_countdownCancelAll = ['https://eapi.binance.com', 'GET', '/eapi/v1/countdownCancelAll', True] # 获得倒计时自动取消所有订单配置 (TRADE) 15 | set_countdownCancelAllHeartBeat = ['https://eapi.binance.com', 'POST', '/eapi/v1/countdownCancelAllHeartBeat', True] # 重置倒计时取消所有订单心跳 (TRADE) 16 | 17 | 18 | class EOMarketMaker(Client): 19 | 20 | # 保证金账户信息 21 | def get_marginAccount(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 22 | ''' 23 | GET /eapi/v1/marginAccount 24 | 25 | 权重:3 26 | 27 | 请求参数: 28 | Parameter Type Required Description 29 | 30 | recvWindow LONG NO 31 | timestamp LONG NO 32 | ''' 33 | return self.send_request(*_EOMarketMakerEndpoints.get_marginAccount, **to_local(locals())) 34 | 35 | 36 | # 设置MMP规则 37 | def set_mmpSet(self,underlying:str = '',windowTimeInMilliseconds:int = '',frozenTimeInMilliseconds:int = '',qtyLimit:Union[int,float] = '',deltaLimit:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 38 | ''' 39 | POST /eapi/v1/mmpSet 40 | 41 | 权重:1 42 | 43 | 请求参数: 44 | Parameter Type Required Description 45 | 46 | underlying STRING YES 标的资产如BTCUSDT 47 | windowTimeInMilliseconds LONG YES MMP监控时间窗口(毫秒),在(0,5000]之间 48 | frozenTimeInMilliseconds LONG NO MMP冻结时间(毫秒),设置为0后代表账号为冻结状态,需要手动重置 49 | qtyLimit DECIMAL NO 数量限制 50 | deltaLimit DECIMAL NO 净delta限制 51 | recvWindow LONG NO 52 | timestamp LONG NO 53 | ''' 54 | return self.send_request(*_EOMarketMakerEndpoints.set_mmpSet, **to_local(locals())) 55 | 56 | 57 | # 获取MMP规则 58 | def get_mmpSet(self,underlying:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 59 | ''' 60 | GET /eapi/v1/mmpSet 61 | 62 | 权重:1 63 | 64 | 请求参数: 65 | Parameter Type Required Description 66 | 67 | underlying STRING YES 标的资产如BTCUSDT 68 | recvWindow LONG NO 69 | timestamp LONG NO 70 | ''' 71 | return self.send_request(*_EOMarketMakerEndpoints.get_mmpSet, **to_local(locals())) 72 | 73 | 74 | # 重置MMP状态 75 | def set_mmpReset(self,underlying:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 76 | ''' 77 | POST /eapi/v1/mmpReset 78 | 79 | 80 | 81 | 请求参数: 82 | Parameter Type Required Description 83 | 84 | underlying STRING YES 标的资产如BTCUSDT 85 | recvWindow LONG NO 86 | timestamp LONG NO 87 | ''' 88 | return self.send_request(*_EOMarketMakerEndpoints.set_mmpReset, **to_local(locals())) 89 | 90 | 91 | # 设置倒计时取消所有订单配置 (TRADE) 92 | def set_countdownCancelAll(self,underlying:str = '',countdownTime:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 93 | ''' 94 | POST /eapi/v1/countdownCancelAll 95 | 96 | 此接口用于设置倒计时取消所有订单(包括做市商保护订单与普通订单)配置,即在倒计时结束前心跳没有更新,特定标的资产的所有订单会被取消。若倒计时结束前心跳没有更新,所有的订单将会被取消,同时新订单会返回错误代码-2010。可以通过设置countdownTime为0取消此功能。权重:1 97 | 98 | 请求参数: 99 | Parameter Type Required Description 100 | 101 | underlying STRING YES 期权标的资产, 如 BTCUSDT 102 | countdownTime LONG YES 以毫秒计量倒计时长 (1000代表1秒)。 设为0时关闭倒计时。最小设为5000(负值无效) 103 | recvWindow LONG NO 104 | timestamp LONG YES 105 | ''' 106 | return self.send_request(*_EOMarketMakerEndpoints.set_countdownCancelAll, **to_local(locals())) 107 | 108 | 109 | # 获得倒计时自动取消所有订单配置 (TRADE) 110 | def get_countdownCancelAll(self,underlying:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 111 | ''' 112 | GET /eapi/v1/countdownCancelAll 113 | 114 | 权重:1 115 | 116 | 请求参数: 117 | Parameter Type Required Description 118 | 119 | underlying STRING YES 期权标的资产, 如BTCUSDT 120 | recvWindow LONG NO 121 | timestamp LONG YES 122 | ''' 123 | return self.send_request(*_EOMarketMakerEndpoints.get_countdownCancelAll, **to_local(locals())) 124 | 125 | 126 | # 重置倒计时取消所有订单心跳 (TRADE) 127 | def set_countdownCancelAllHeartBeat(self,underlyings:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 128 | ''' 129 | POST /eapi/v1/countdownCancelAllHeartBeat 130 | 131 | 权重:10 132 | 133 | 请求参数: 134 | Parameter Type Required Description 135 | 136 | underlyings STRING YES 期权标的资产, 如BTCUSDT 137 | recvWindow LONG NO 138 | timestamp LONG YES 139 | ''' 140 | return self.send_request(*_EOMarketMakerEndpoints.set_countdownCancelAllHeartBeat, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/margin/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 杠杆 3 | https://binance-docs.github.io/apidocs/spot/cn/ 4 | ''' 5 | 6 | from binance_interface.api.margin.margin_account_trade import MarginAccountTrade # 杠杆账户和交易接口 7 | from binance_interface.api.margin.margin_blvt import MarginBlvt # 杠杆代币接口 8 | 9 | AccountTrade = MarginAccountTrade 10 | Blvt = MarginBlvt 11 | 12 | 13 | class Margin(): 14 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 15 | self.blvt = MarginBlvt(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 16 | self.accountTrade = MarginAccountTrade(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 17 | -------------------------------------------------------------------------------- /binance_interface/api/margin/margin_blvt.py: -------------------------------------------------------------------------------- 1 | # 杠杆代币接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _MarginBlvtEndpoints(): 7 | 8 | 9 | get_blvt_tokenInfo = ['https://api.binance.com', 'GET', '/sapi/v1/blvt/tokenInfo', False] # 杠杆代币信息 (MARKET_DATA) 10 | set_blvt_subscribe = ['https://api.binance.com', 'POST', '/sapi/v1/blvt/subscribe', True] # 申购代币 (USER_DATA) 11 | get_blvt_subscribe_record = ['https://api.binance.com', 'GET', '/sapi/v1/blvt/subscribe/record', True] # 查询申购记录 (USER_DATA) 12 | set_blvt_redeem = ['https://api.binance.com', 'POST', '/sapi/v1/blvt/redeem', True] # 赎回代币 (USER_DATA) 13 | get_blvt_redeem_record = ['https://api.binance.com', 'GET', '/sapi/v1/blvt/redeem/record', True] # 查询赎回记录 (USER_DATA) 14 | get_blvt_userLimit = ['https://api.binance.com', 'GET', '/sapi/v1/blvt/userLimit', True] # 查询用户每日申购赎回限额 (USER_DATA) 15 | 16 | 17 | class MarginBlvt(Client): 18 | 19 | # 杠杆代币信息 (MARKET_DATA) 20 | def get_blvt_tokenInfo(self,tokenName:str = '',proxies={},proxy_host:str=None): 21 | ''' 22 | GET /sapi/v1/blvt/tokenInfo 23 | 24 | 权重(IP):1 25 | 26 | 请求参数: 27 | Parameter Type Required Description 28 | 29 | tokenName STRING NO BTCDOWN, BTCUP 30 | ''' 31 | return self.send_request(*_MarginBlvtEndpoints.get_blvt_tokenInfo, **to_local(locals())) 32 | 33 | 34 | # 申购代币 (USER_DATA) 35 | def set_blvt_subscribe(self,tokenName:str = '',cost:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 36 | ''' 37 | POST /sapi/v1/blvt/subscribe 38 | 39 | 权重(IP):1 40 | 41 | 请求参数: 42 | Parameter Type Required Description 43 | 44 | tokenName STRING YES BTCDOWN, BTCUP 45 | cost DECIMAL YES 46 | recvWindow LONG NO 47 | timestamp LONG YES 48 | ''' 49 | return self.send_request(*_MarginBlvtEndpoints.set_blvt_subscribe, **to_local(locals())) 50 | 51 | 52 | # 查询申购记录 (USER_DATA) 53 | def get_blvt_subscribe_record(self,tokenName:str = '',id:int = '',startTime:int = '',endTime:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 54 | ''' 55 | GET /sapi/v1/blvt/subscribe/record 56 | 57 | 权重(IP):1 58 | 59 | 请求参数: 60 | Parameter Type Required Description 61 | 62 | tokenName STRING NO BTCDOWN, BTCUP 63 | id LONG NO 64 | startTime LONG NO 65 | endTime LONG NO 66 | limit INT NO 默认 1000, 最大 1000 67 | recvWindow LONG NO 68 | timestamp LONG YES 69 | ''' 70 | return self.send_request(*_MarginBlvtEndpoints.get_blvt_subscribe_record, **to_local(locals())) 71 | 72 | 73 | # 赎回代币 (USER_DATA) 74 | def set_blvt_redeem(self,tokenName:str = '',amount:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 75 | ''' 76 | POST /sapi/v1/blvt/redeem 77 | 78 | 权重(IP):1 79 | 80 | 请求参数: 81 | Parameter Type Required Description 82 | 83 | tokenName STRING YES BTCDOWN, BTCUP 84 | amount DECIMAL YES 85 | recvWindow LONG NO 86 | timestamp LONG YES 87 | ''' 88 | return self.send_request(*_MarginBlvtEndpoints.set_blvt_redeem, **to_local(locals())) 89 | 90 | 91 | # 查询赎回记录 (USER_DATA) 92 | def get_blvt_redeem_record(self,tokenName:str = '',id:int = '',startTime:int = '',endTime:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 93 | ''' 94 | GET /sapi/v1/blvt/redeem/record 95 | 96 | 权重(IP):1 97 | 98 | 请求参数: 99 | Parameter Type Required Description 100 | 101 | tokenName STRING NO BTCDOWN, BTCUP 102 | id LONG NO 103 | startTime LONG NO 104 | endTime LONG NO 105 | limit INT NO 默认 1000, 最大 1000 106 | recvWindow LONG NO 107 | timestamp LONG YES 108 | ''' 109 | return self.send_request(*_MarginBlvtEndpoints.get_blvt_redeem_record, **to_local(locals())) 110 | 111 | 112 | # 查询用户每日申购赎回限额 (USER_DATA) 113 | def get_blvt_userLimit(self,tokenName:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 114 | ''' 115 | GET /sapi/v1/blvt/userLimit 116 | 117 | 权重(IP):1 118 | 119 | 请求参数: 120 | Parameter Type Required Description 121 | 122 | tokenName STRING NO BTCDOWN, BTCUP 123 | recvWindow LONG NO 124 | timestamp LONG YES 125 | ''' 126 | return self.send_request(*_MarginBlvtEndpoints.get_blvt_userLimit, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 其他 3 | https://binance-docs.github.io/apidocs/spot/cn/ 4 | ''' 5 | 6 | from binance_interface.api.other.auto_invest import AutoInvest # 定投接口 7 | from binance_interface.api.other.bs_wap import BsWap # 币安挖矿接口 8 | from binance_interface.api.other.c2c import C2C # C2C 接口 9 | from binance_interface.api.other.convert import Convert # 闪兑接口 10 | from binance_interface.api.other.crypto_loans import CryptoLoans # 质押借币接口 11 | from binance_interface.api.other.fiat import Fiat # 法币接口 12 | from binance_interface.api.other.futures import Futures # 合约接口 13 | from binance_interface.api.other.futures_algo import FuturesAlgo # 合约策略交易接口 14 | from binance_interface.api.other.gift_card import GiftCard # 币安礼品卡接口 15 | from binance_interface.api.other.mining import Mining # 矿池接口 16 | from binance_interface.api.other.nft import Nft # NFT 接口 17 | from binance_interface.api.other.pay import Pay # Pay 接口 18 | from binance_interface.api.other.portfolio import Portfolio # 经典统一账户接口 19 | from binance_interface.api.other.rebate import Rebate # 返佣接口 20 | from binance_interface.api.other.simple_earn import SimpleEarn # 赚币接口 21 | from binance_interface.api.other.sub_account import SubAccount # 子母账户接口 22 | from binance_interface.api.other.vip_loans import VipLoans # VIP借币接口 23 | from binance_interface.api.other.wallet import Wallet # 钱包接口 24 | 25 | 26 | class Other(): 27 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 28 | self.autoInvest = AutoInvest(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 定投接口 29 | self.bsWap = BsWap(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 币安挖矿接口 30 | self.c2c = C2C(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # C2C 接口 31 | self.convert = Convert(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 闪兑接口 32 | self.cryptoLoans = CryptoLoans(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 质押借币接口 33 | self.fiat = Fiat(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 法币接口 34 | self.futures = Futures(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 合约接口 35 | self.futuresAlgo = FuturesAlgo(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 合约策略交易接口 36 | self.giftCard = GiftCard(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 币安礼品卡接口 37 | self.mining = Mining(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 矿池接口 38 | self.nft = Nft(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # NFT 接口 39 | self.pay = Pay(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # Pay 接口 40 | self.portfolio = Portfolio(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 经典统一账户接口 41 | self.rebate = Rebate(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 返佣接口 42 | self.simpleEarn = SimpleEarn(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 赚币接口 43 | self.subAccount = SubAccount(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 子母账户接口 44 | self.vipLoans = VipLoans(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # VIP借币接口 45 | self.wallet = Wallet(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) # 钱包接口 46 | -------------------------------------------------------------------------------- /binance_interface/api/other/c2c.py: -------------------------------------------------------------------------------- 1 | # C2C 接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _C2CEndpoints(): 7 | 8 | 9 | get_c2c_orderMatch_listUserOrderHistory = ['https://api.binance.com', 'GET', '/sapi/v1/c2c/orderMatch/listUserOrderHistory', True] # 获取 C2C 交易历史记录 (USER_DATA) 10 | 11 | 12 | class C2C(Client): 13 | 14 | # 获取 C2C 交易历史记录 (USER_DATA) 15 | def get_c2c_orderMatch_listUserOrderHistory(self,tradeType:str = '',startTimestamp:int = '',endTimestamp:int = '',page:int = '',rows:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 16 | ''' 17 | GET /sapi/v1/c2c/orderMatch/listUserOrderHistory 18 | 19 | 权重(IP):1 20 | 21 | 请求参数: 22 | Parameter Type Required Description 23 | 24 | tradeType STRING YES BUY, SEll 25 | startTimestamp LONG NO 26 | endTimestamp LONG NO 27 | page INT NO default 1 28 | rows INT NO default 100, max 100 29 | recvWindow LONG NO 30 | timestamp LONG YES 31 | ''' 32 | return self.send_request(*_C2CEndpoints.get_c2c_orderMatch_listUserOrderHistory, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/convert.py: -------------------------------------------------------------------------------- 1 | # 闪兑接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _ConvertEndpoints(): 7 | 8 | 9 | get_convert_exchangeInfo = ['https://api.binance.com', 'GET', '/sapi/v1/convert/exchangeInfo', False] # 查询可交易币对信息 10 | get_convert_assetInfo = ['https://api.binance.com', 'GET', '/sapi/v1/convert/assetInfo', True] # 查询可交易币种精度 (USER_DATA) 11 | set_convert_getQuote = ['https://api.binance.com', 'POST', '/sapi/v1/convert/getQuote', True] # 发送获取报价请求 (USER_DATA) 12 | set_convert_acceptQuote = ['https://api.binance.com', 'POST', '/sapi/v1/convert/acceptQuote', True] # 接受报价 (TRADE) 13 | get_convert_orderStatus = ['https://api.binance.com', 'GET', '/sapi/v1/convert/orderStatus', True] # 查询订单状态 (USER_DATA) 14 | get_convert_tradeFlow = ['https://api.binance.com', 'GET', '/sapi/v1/convert/tradeFlow', True] # 获取闪兑交易记录 (USER_DATA) 15 | 16 | 17 | class Convert(Client): 18 | 19 | # 查询可交易币对信息 20 | def get_convert_exchangeInfo(self,fromAsset:str = '',toAsset:str = '',proxies={},proxy_host:str=None): 21 | ''' 22 | GET /sapi/v1/convert/exchangeInfo 23 | 24 | 权重(IP):3000 25 | 26 | 请求参数: 27 | Parameter Type Required Description 28 | 29 | fromAsset STRING EITHER OR BOTH 用户售出币种 30 | toAsset STRING EITHER OR BOTH 用户买入币种 31 | ''' 32 | return self.send_request(*_ConvertEndpoints.get_convert_exchangeInfo, **to_local(locals())) 33 | 34 | 35 | # 查询可交易币种精度 (USER_DATA) 36 | def get_convert_assetInfo(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 37 | ''' 38 | GET /sapi/v1/convert/assetInfo 39 | 40 | 权重(IP):100 41 | 42 | 请求参数: 43 | Parameter Type Required Description 44 | 45 | recvWindow LONG NO 此值不能大于 60000 46 | timestamp LONG YES 47 | ''' 48 | return self.send_request(*_ConvertEndpoints.get_convert_assetInfo, **to_local(locals())) 49 | 50 | 51 | # 发送获取报价请求 (USER_DATA) 52 | def set_convert_getQuote(self,fromAsset:str = '',toAsset:str = '',fromAmount:Union[int,float] = '',toAmount:Union[int,float] = '',walletType:str = '',validTime:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 53 | ''' 54 | POST /sapi/v1/convert/getQuote 55 | 56 | 权重(UID):200 57 | 58 | 请求参数: 59 | Parameter Type Required Description 60 | 61 | fromAsset STRING YES 62 | toAsset STRING YES 63 | fromAmount DECIMAL EITHER 这是成交后将被扣除的金额 64 | toAmount DECIMAL EITHER 这是成交后将会获得的金额 65 | walletType ENUM NO 可用值为SPOT 或者 FUNDING. 默认值是 SPOT 66 | validTime ENUM NO 可以支持10s、30s、1m、2m等值,默认值为 10s 67 | recvWindow LONG NO 此值不能大于 60000 68 | timestamp LONG YES 69 | ''' 70 | return self.send_request(*_ConvertEndpoints.set_convert_getQuote, **to_local(locals())) 71 | 72 | 73 | # 接受报价 (TRADE) 74 | def set_convert_acceptQuote(self,quoteId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 75 | ''' 76 | POST /sapi/v1/convert/acceptQuote 77 | 78 | 权重(UID):500 79 | 80 | 请求参数: 81 | Parameter Type Required Description 82 | 83 | quoteId STRING YES 84 | recvWindow LONG NO 此值不能大于 60000 85 | timestamp LONG YES 86 | ''' 87 | return self.send_request(*_ConvertEndpoints.set_convert_acceptQuote, **to_local(locals())) 88 | 89 | 90 | # 查询订单状态 (USER_DATA) 91 | def get_convert_orderStatus(self,orderId:str = '',quoteId:str = '',proxies={},proxy_host:str=None): 92 | ''' 93 | GET /sapi/v1/convert/orderStatus 94 | 95 | 权重(UID):100 96 | 97 | 请求参数: 98 | Parameter Type Required Description 99 | 100 | orderId STRING NO orderId 和quoteId需要填其中一个 101 | quoteId STRING NO orderId 和quoteId需要填其中一个 102 | ''' 103 | return self.send_request(*_ConvertEndpoints.get_convert_orderStatus, **to_local(locals())) 104 | 105 | 106 | # 获取闪兑交易记录 (USER_DATA) 107 | def get_convert_tradeFlow(self,startTime:int = '',endTime:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 108 | ''' 109 | GET /sapi/v1/convert/tradeFlow 110 | 111 | 权重(UID):3000 112 | 113 | 请求参数: 114 | Parameter Type Required Description 115 | 116 | startTime LONG YES 117 | endTime LONG YES 118 | limit INT NO 默认 100, 最大 1000 119 | recvWindow LONG NO 120 | timestamp LONG YES 121 | ''' 122 | return self.send_request(*_ConvertEndpoints.get_convert_tradeFlow, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/fiat.py: -------------------------------------------------------------------------------- 1 | # 法币接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _FiatEndpoints(): 7 | 8 | 9 | get_fiat_orders = ['https://api.binance.com', 'GET', '/sapi/v1/fiat/orders', True] # 获取法币充值/提现历史记录 (USER_DATA) 10 | get_fiat_payments = ['https://api.binance.com', 'GET', '/sapi/v1/fiat/payments', True] # 获取法币支付历史记录 (USER_DATA) 11 | 12 | 13 | class Fiat(Client): 14 | 15 | # 获取法币充值/提现历史记录 (USER_DATA) 16 | def get_fiat_orders(self,transactionType:str = '',beginTime:int = '',endTime:int = '',page:int = '',rows:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 17 | ''' 18 | GET /sapi/v1/fiat/orders 19 | 20 | 权重(UID):90000 21 | 22 | 请求参数: 23 | Parameter Type Required Description 24 | 25 | transactionType STRING YES 0-deposit,1-withdraw 26 | beginTime LONG NO 27 | endTime LONG NO 28 | page INT NO 默认 1 29 | rows INT NO 默认 100, 最大 500 30 | recvWindow LONG NO 31 | timestamp LONG YES 32 | ''' 33 | return self.send_request(*_FiatEndpoints.get_fiat_orders, **to_local(locals())) 34 | 35 | 36 | # 获取法币支付历史记录 (USER_DATA) 37 | def get_fiat_payments(self,transactionType:str = '',beginTime:int = '',endTime:int = '',page:int = '',rows:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 38 | ''' 39 | GET /sapi/v1/fiat/payments 40 | 41 | 42 | 43 | 请求参数: 44 | Parameter Type Required Description 45 | 46 | transactionType STRING YES 0-buy,1-sell 47 | beginTime LONG NO 48 | endTime LONG NO 49 | page INT NO 默认 1 50 | rows INT NO 默认 100, 最大 500 51 | recvWindow LONG NO 52 | timestamp LONG YES 53 | ''' 54 | return self.send_request(*_FiatEndpoints.get_fiat_payments, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/futures.py: -------------------------------------------------------------------------------- 1 | # 合约接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _FuturesEndpoints(): 7 | 8 | 9 | set_futures_transfer = ['https://api.binance.com', 'POST', '/sapi/v1/futures/transfer', True] # 合约资金划转 (USER_DATA) 10 | get_futures_transfer = ['https://api.binance.com', 'GET', '/sapi/v1/futures/transfer', True] # 获取合约资金划转历史 (USER_DATA) 11 | get_futures_histDataLink = ['https://api.binance.com', 'GET', '/sapi/v1/futures/histDataLink', True] # 获取合约订单薄历史数据下载地址(USER_DATA) 12 | 13 | 14 | class Futures(Client): 15 | 16 | # 合约资金划转 (USER_DATA) 17 | def set_futures_transfer(self,asset:str = '',amount:Union[int,float] = '',type:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 18 | ''' 19 | POST /sapi/v1/futures/transfer 20 | 21 | 权重(IP):1 22 | 23 | 请求参数: 24 | Parameter Type Required Description 25 | 26 | asset STRING YES The asset being transferred, e.g., USDT 27 | amount DECIMAL YES The amount to be transferred 28 | type INT YES 1:现货账户向USDT合约账户划转2:USDT合约账户向现货账户划转3:现货账户向币本位合约账户划转4:币本位合约账户向现货账户划转 29 | recvWindow LONG NO 30 | timestamp LONG YES 31 | ''' 32 | return self.send_request(*_FuturesEndpoints.set_futures_transfer, **to_local(locals())) 33 | 34 | 35 | # 获取合约资金划转历史 (USER_DATA) 36 | def get_futures_transfer(self,asset:str = '',startTime:int = '',endTime:int = '',current:int = '',size:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 37 | ''' 38 | GET /sapi/v1/futures/transfer 39 | 40 | 权重(IP):10 41 | 42 | 请求参数: 43 | Parameter Type Required Description 44 | 45 | asset STRING NO 46 | startTime LONG YES 47 | endTime LONG NO 48 | current LONG NO 当前页面. 起始计数为1. 默认值1 49 | size LONG NO 单页数据条目数,默认:10 最大:100 50 | recvWindow LONG NO 51 | timestamp LONG YES 52 | ''' 53 | return self.send_request(*_FuturesEndpoints.get_futures_transfer, **to_local(locals())) 54 | 55 | 56 | # 获取合约订单薄历史数据下载地址(USER_DATA) 57 | def get_futures_histDataLink(self,symbol:str = '',dataType:str = '',startTime:int = '',endTime:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 58 | ''' 59 | GET /sapi/v1/futures/histDataLink 60 | 61 | 权重(IP):200 62 | 63 | 请求参数: 64 | Parameter Type Required Description 65 | 66 | symbol STRING YES 交易对,如BTCUSDT或BTCUSD_PERP | 67 | dataType ENUM YES T_DEPTHfor ticklevel orderbook data,S_DEPTHfor orderbook snapshot data 68 | startTime LONG YES 69 | endTime LONG YES 70 | recvWindow LONG NO 71 | timestamp LONG YES 72 | ''' 73 | return self.send_request(*_FuturesEndpoints.get_futures_histDataLink, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/futures_algo.py: -------------------------------------------------------------------------------- 1 | # 合约策略交易接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _FuturesAlgoEndpoints(): 7 | 8 | 9 | set_algo_futures_newOrderVp = ['https://api.binance.com', 'POST', '/sapi/v1/algo/futures/newOrderVp', True] # 成交量份额参与算法(VP)下单 (TRADE) 10 | set_algo_futures_newOrderTwap = ['https://api.binance.com', 'POST', '/sapi/v1/algo/futures/newOrderTwap', True] # 时间加权平均价格策略(Twap)下单 (TRADE) 11 | cancel_algo_futures_order = ['https://api.binance.com', 'DELETE', '/sapi/v1/algo/futures/order', True] # 取消策略订单 (TRADE) 12 | get_algo_futures_openOrders = ['https://api.binance.com', 'GET', '/sapi/v1/algo/futures/openOrders', True] # 查询当前策略订单挂单 (USER_DATA) 13 | get_algo_futures_historicalOrders = ['https://api.binance.com', 'GET', '/sapi/v1/algo/futures/historicalOrders', True] # 查询历史策略订单 (USER_DATA) 14 | get_algo_futures_subOrders = ['https://api.binance.com', 'GET', '/sapi/v1/algo/futures/subOrders', True] # 查询执行子订单 (USER_DATA) 15 | 16 | 17 | class FuturesAlgo(Client): 18 | 19 | # 成交量份额参与算法(VP)下单 (TRADE) 20 | def set_algo_futures_newOrderVp(self,symbol:str = '',side:str = '',positionSide:str = '',quantity:Union[int,float] = '',urgency:str = '',clientAlgoId:str = '',reduceOnly:bool = '',limitPrice:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 21 | ''' 22 | POST /sapi/v1/algo/futures/newOrderVp 23 | 24 | 权重(UID):3000 25 | 26 | 请求参数: 27 | Parameter Type Required Description 28 | 29 | symbol STRING YES 交易对 eg. BTCUSDT 30 | side ENUM YES 买卖方向 ( BUY or SELL ) 31 | positionSide ENUM NO 持仓方向,单向持仓模式下非必填,默认且仅可填BOTH;在双向持仓模式下必填,且仅可选择 LONG 或 SHORT 32 | quantity DECIMAL YES 下单数量, 以合约币种(base asset)个数下单; 名义价值 (quantity*标记价格(base asset)) 需要大于 1,000 USDT,且不超过 1,000,000 USDT 33 | urgency ENUM YES 代表当前执行的相对速率; ENUM: LOW(慢), MEDIUM(中等), HIGH(快) 34 | clientAlgoId STRING NO 必须传入32位,如果未发送,则自动生成 35 | reduceOnly BOOLEAN NO true, false; 非双开模式下默认false;双开模式下不接受此参数; 开仓不接受此参数 36 | limitPrice DECIMAL NO 限价单价格; 若未发送,则以市场价下单 37 | recvWindow LONG NO 38 | timestamp LONG YES 39 | ''' 40 | return self.send_request(*_FuturesAlgoEndpoints.set_algo_futures_newOrderVp, **to_local(locals())) 41 | 42 | 43 | # 时间加权平均价格策略(Twap)下单 (TRADE) 44 | def set_algo_futures_newOrderTwap(self,symbol:str = '',side:str = '',positionSide:str = '',quantity:Union[int,float] = '',duration:int = '',clientAlgoId:str = '',reduceOnly:bool = '',limitPrice:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 45 | ''' 46 | POST /sapi/v1/algo/futures/newOrderTwap 47 | 48 | 权重(UID):3000 49 | 50 | 请求参数: 51 | Parameter Type Required Description 52 | 53 | symbol STRING YES 交易对 eg. BTCUSDT 54 | side ENUM YES 买卖方向 ( BUY or SELL ) 55 | positionSide ENUM NO 持仓方向,单向持仓模式下非必填,默认且仅可填BOTH;在双向持仓模式下必填,且仅可选择 LONG 或 SHORT 56 | quantity DECIMAL YES 下单数量, 以合约币种(base asset)个数下单; 名义价值 (quantity*标记价格(base asset)) 需要大于 10,000 USDT,且不超过 1,000,000 USDT 57 | duration LONG YES 请以秒为单位发送[300,86400];少于 5 分钟 => 默认为 5 分钟;大于 24h => 默认为 24h 58 | clientAlgoId STRING NO 必须传入32位,如果未发送,则自动生成 59 | reduceOnly BOOLEAN NO true, false; 非双开模式下默认false;双开模式下不接受此参数; 开仓不接受此参数 60 | limitPrice DECIMAL NO 限价单价格; 若未发送,则以市场价下单 61 | recvWindow LONG NO 62 | timestamp LONG YES 63 | ''' 64 | return self.send_request(*_FuturesAlgoEndpoints.set_algo_futures_newOrderTwap, **to_local(locals())) 65 | 66 | 67 | # 取消策略订单 (TRADE) 68 | def cancel_algo_futures_order(self,algoId:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 69 | ''' 70 | DELETE /sapi/v1/algo/futures/order 71 | 72 | 权重(IP):1 73 | 74 | 请求参数: 75 | Parameter Type Required Description 76 | 77 | algoId LONG YES eg. 14511 78 | recvWindow LONG NO 79 | timestamp LONG YES 80 | ''' 81 | return self.send_request(*_FuturesAlgoEndpoints.cancel_algo_futures_order, **to_local(locals())) 82 | 83 | 84 | # 查询当前策略订单挂单 (USER_DATA) 85 | def get_algo_futures_openOrders(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 86 | ''' 87 | GET /sapi/v1/algo/futures/openOrders 88 | 89 | 权重(IP):1 90 | 91 | 请求参数: 92 | Parameter Type Required Description 93 | 94 | recvWindow LONG NO 95 | timestamp LONG YES 96 | ''' 97 | return self.send_request(*_FuturesAlgoEndpoints.get_algo_futures_openOrders, **to_local(locals())) 98 | 99 | 100 | # 查询历史策略订单 (USER_DATA) 101 | def get_algo_futures_historicalOrders(self,symbol:str = '',side:str = '',startTime:int = '',endTime:int = '',page:int = '',pageSize:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 102 | ''' 103 | GET /sapi/v1/algo/futures/historicalOrders 104 | 105 | 权重(IP):1 106 | 107 | 请求参数: 108 | Parameter Type Required Description 109 | 110 | symbol STRING NO 交易对 eg. BTCUSDT 111 | side ENUM NO BUY 或者 SELL 112 | startTime LONG NO 毫秒级时间戳 eg.1641522717552 113 | endTime LONG NO 毫秒级时间戳 eg.1641522526562 114 | page INT NO 默认 1 115 | pageSize INT NO 最小 1, 最大 100; 默认 100 116 | recvWindow LONG NO 117 | timestamp LONG YES 118 | ''' 119 | return self.send_request(*_FuturesAlgoEndpoints.get_algo_futures_historicalOrders, **to_local(locals())) 120 | 121 | 122 | # 查询执行子订单 (USER_DATA) 123 | def get_algo_futures_subOrders(self,algoId:int = '',page:int = '',pageSize:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 124 | ''' 125 | GET /sapi/v1/algo/futures/subOrders 126 | 127 | 权重(IP):1 128 | 129 | 请求参数: 130 | Parameter Type Required Description 131 | 132 | algoId LONG YES 133 | page INT NO 默认1 134 | pageSize INT NO 最小 1, 最大 100; 默认 100 135 | recvWindow LONG NO 136 | timestamp LONG YES 137 | ''' 138 | return self.send_request(*_FuturesAlgoEndpoints.get_algo_futures_subOrders, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/gift_card.py: -------------------------------------------------------------------------------- 1 | # 币安礼品卡接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _GiftCardEndpoints(): 7 | 8 | 9 | set_giftcard_createCode = ['https://api.binance.com', 'POST', '/sapi/v1/giftcard/createCode', True] # 创建单币种礼品卡 (USER_DATA) 10 | set_giftcard_buyCode = ['https://api.binance.com', 'POST', '/sapi/v1/giftcard/buyCode', True] # 创建双币种礼品卡(固定价值,设置折扣) (TRADE) 11 | set_giftcard_redeemCode = ['https://api.binance.com', 'POST', '/sapi/v1/giftcard/redeemCode', True] # 兑现币安礼品卡 (USER_DATA) 12 | get_giftcard_verify = ['https://api.binance.com', 'GET', '/sapi/v1/giftcard/verify', True] # 通过礼品卡卡号验证币安礼品卡 (USER_DATA) 13 | get_giftcard_cryptography_rsa_public_key = ['https://api.binance.com', 'GET', '/sapi/v1/giftcard/cryptography/rsa-public-key', True] # 获取RSA Public Key (USER_DATA) 14 | get_giftcard_buyCode_token_limit = ['https://api.binance.com', 'GET', '/sapi/v1/giftcard/buyCode/token-limit', True] # 获取货币使用限制 (USER_DATA) 15 | 16 | 17 | class GiftCard(Client): 18 | 19 | # 创建单币种礼品卡 (USER_DATA) 20 | def set_giftcard_createCode(self,token:str = '',amount:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 21 | ''' 22 | POST /sapi/v1/giftcard/createCode 23 | 24 | 权重(IP):1 25 | 26 | 请求参数: 27 | Parameter Type Required Description 28 | 29 | token STRING YES 币安礼品卡中的数字货币币种 30 | amount DOUBLE YES 币安礼品卡中的数字货币数量 31 | recvWindow LONG NO 32 | timestamp LONG YES 33 | ''' 34 | return self.send_request(*_GiftCardEndpoints.set_giftcard_createCode, **to_local(locals())) 35 | 36 | 37 | # 创建双币种礼品卡(固定价值,设置折扣) (TRADE) 38 | def set_giftcard_buyCode(self,baseToken:str = '',faceToken:str = '',baseTokenAmount:Union[int,float] = '',discount:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 39 | ''' 40 | POST /sapi/v1/giftcard/buyCode 41 | 42 | 权重(IP):1 43 | 44 | 请求参数: 45 | Parameter Type Required Description 46 | 47 | baseToken STRING YES 你用来支付的货币,例如:BUSD 48 | faceToken STRING YES 你创建的礼品卡面额,例如:BNB。如果 faceToken = baseToken, 将等同于使用 createCode API 49 | baseTokenAmount DOUBLE YES 支付的货币数量,例如:1.002 50 | discount DOUBLE NO 稳定币定值礼品卡的折扣百分比,例如:1 代表 1% 的折扣。小数点精度需小于 6。 51 | recvWindow LONG NO 52 | timestamp LONG YES 53 | ''' 54 | return self.send_request(*_GiftCardEndpoints.set_giftcard_buyCode, **to_local(locals())) 55 | 56 | 57 | # 兑现币安礼品卡 (USER_DATA) 58 | def set_giftcard_redeemCode(self,code:str = '',externalUid:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 59 | ''' 60 | POST /sapi/v1/giftcard/redeemCode 61 | 62 | 权重(IP):1 63 | 64 | 请求参数: 65 | Parameter Type Required Description 66 | 67 | code STRING YES 用于赎回的币安礼品卡,支持加密&未加密两种方式 68 | externalUid String NO 每个外部用户 ID 代表合作伙伴平台上的某个用户。该功能帮助您识别不同用户的兑现行为,例如兑现频次和金额。它还有助于对单个账户进行风险和限额控制,例如设置单个账户每日兑现金额、频次和卡密输错次数的上限。这也将防止单个帐户突破合作伙伴的每日兑现限额从而导致合作伙伴的账户在当日无法继续制码或者兑现。如果您有外部的网站且有不同的用户在您的平台上兑现 币安礼品卡,我们强烈建议您使用此功能并将您用户的用户 ID 传输给我们来进行风控。为保护用户的信息安全,您可以选择以任何格式(上限为 400 个字符)传输用户 ID。 69 | recvWindow LONG NO 70 | timestamp LONG YES 71 | ''' 72 | return self.send_request(*_GiftCardEndpoints.set_giftcard_redeemCode, **to_local(locals())) 73 | 74 | 75 | # 通过礼品卡卡号验证币安礼品卡 (USER_DATA) 76 | def get_giftcard_verify(self,referenceNo:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 77 | ''' 78 | GET /sapi/v1/giftcard/verify 79 | 80 | 权重(IP):1 81 | 82 | 请求参数: 83 | Parameter Type Required Description 84 | 85 | referenceNo STRING YES 输入礼品卡卡号 86 | recvWindow LONG NO 87 | timestamp LONG YES 88 | ''' 89 | return self.send_request(*_GiftCardEndpoints.get_giftcard_verify, **to_local(locals())) 90 | 91 | 92 | # 获取RSA Public Key (USER_DATA) 93 | def get_giftcard_cryptography_rsa_public_key(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 94 | ''' 95 | GET /sapi/v1/giftcard/cryptography/rsa-public-key 96 | 97 | 权重(IP):1 98 | 99 | 请求参数: 100 | Parameter Type Required Description 101 | 102 | recvWindow LONG NO 103 | timestamp LONG YES 104 | ''' 105 | return self.send_request(*_GiftCardEndpoints.get_giftcard_cryptography_rsa_public_key, **to_local(locals())) 106 | 107 | 108 | # 获取货币使用限制 (USER_DATA) 109 | def get_giftcard_buyCode_token_limit(self,baseToken:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 110 | ''' 111 | GET /sapi/v1/giftcard/buyCode/token-limit 112 | 113 | 权重(IP):1 114 | 115 | 请求参数: 116 | Parameter Type Required Description 117 | 118 | baseToken STRING YES 你用来支付的货币,例如:BUSD 119 | recvWindow LONG NO 120 | timestamp LONG YES 121 | ''' 122 | return self.send_request(*_GiftCardEndpoints.get_giftcard_buyCode_token_limit, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/nft.py: -------------------------------------------------------------------------------- 1 | # NFT 接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _NftEndpoints(): 7 | 8 | 9 | get_nft_history_transactions = ['https://api.binance.com', 'GET', '/sapi/v1/nft/history/transactions', True] # 获取 NFT 资金流水记录 (USER_DATA) 10 | get_nft_history_deposit = ['https://api.binance.com', 'GET', '/sapi/v1/nft/history/deposit', True] # 获取 NFT 充值记录 (USER_DATA) 11 | get_nft_history_withdraw = ['https://api.binance.com', 'GET', '/sapi/v1/nft/history/withdraw', True] # 获取 NFT 提现记录 (USER_DATA) 12 | get_nft_user_getAsset = ['https://api.binance.com', 'GET', '/sapi/v1/nft/user/getAsset', True] # 获取 NFT 资产 (USER_DATA) 13 | 14 | 15 | class Nft(Client): 16 | 17 | # 获取 NFT 资金流水记录 (USER_DATA) 18 | def get_nft_history_transactions(self,orderType:int = '',startTime:int = '',endTime:int = '',limit:int = '',page:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 19 | ''' 20 | GET /sapi/v1/nft/history/transactions 21 | 22 | 权重(UID):3000 23 | 24 | 请求参数: 25 | Parameter Type Required Description 26 | 27 | orderType INT YES 0:买单,1:卖单,2:版税收入,3:一级市场买单,4:mint 费用 28 | startTime LONG NO 29 | endTime LONG NO 30 | limit INT NO 默认 50, 最大 50 31 | page INT NO 默认 1 32 | recvWindow LONG NO 33 | timestamp LONG YES 34 | ''' 35 | return self.send_request(*_NftEndpoints.get_nft_history_transactions, **to_local(locals())) 36 | 37 | 38 | # 获取 NFT 充值记录 (USER_DATA) 39 | def get_nft_history_deposit(self,startTime:int = '',endTime:int = '',limit:int = '',page:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 40 | ''' 41 | GET /sapi/v1/nft/history/deposit 42 | 43 | 权重(UID):3000 44 | 45 | 请求参数: 46 | Parameter Type Required Description 47 | 48 | startTime LONG NO 49 | endTime LONG NO 50 | limit INT NO 默认 50, 最大 50 51 | page INT NO 默认 1 52 | recvWindow LONG NO 53 | timestamp LONG YES 54 | ''' 55 | return self.send_request(*_NftEndpoints.get_nft_history_deposit, **to_local(locals())) 56 | 57 | 58 | # 获取 NFT 提现记录 (USER_DATA) 59 | def get_nft_history_withdraw(self,startTime:int = '',endTime:int = '',limit:int = '',page:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 60 | ''' 61 | GET /sapi/v1/nft/history/withdraw 62 | 63 | 权重(UID):3000 64 | 65 | 请求参数: 66 | Parameter Type Required Description 67 | 68 | startTime LONG NO 69 | endTime LONG NO 70 | limit INT NO 默认 50, 最大 50 71 | page INT NO 默认 1 72 | recvWindow LONG NO 73 | timestamp LONG YES 74 | ''' 75 | return self.send_request(*_NftEndpoints.get_nft_history_withdraw, **to_local(locals())) 76 | 77 | 78 | # 获取 NFT 资产 (USER_DATA) 79 | def get_nft_user_getAsset(self,limit:int = '',page:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 80 | ''' 81 | GET /sapi/v1/nft/user/getAsset 82 | 83 | 权重(UID):3000 84 | 85 | 请求参数: 86 | Parameter Type Required Description 87 | 88 | limit INT NO 默认 50, 最大 50 89 | page INT NO 默认 1 90 | recvWindow LONG NO 91 | timestamp LONG YES 92 | ''' 93 | return self.send_request(*_NftEndpoints.get_nft_user_getAsset, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/pay.py: -------------------------------------------------------------------------------- 1 | # Pay 接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _PayEndpoints(): 7 | 8 | 9 | get_pay_transactions = ['https://api.binance.com', 'GET', '/sapi/v1/pay/transactions', True] # 获取 Pay 交易历史记录 (USER_DATA) 10 | 11 | 12 | class Pay(Client): 13 | 14 | # 获取 Pay 交易历史记录 (USER_DATA) 15 | def get_pay_transactions(self,startTime:int = '',endTime:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 16 | ''' 17 | GET /sapi/v1/pay/transactions 18 | 19 | 权重(UID):3000 20 | 21 | 请求参数: 22 | Parameter Type Required Description 23 | 24 | startTime LONG NO 25 | endTime LONG NO 26 | limit INT NO 默认 100, 最大 100 27 | recvWindow LONG NO 28 | timestamp LONG YES 29 | ''' 30 | return self.send_request(*_PayEndpoints.get_pay_transactions, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/portfolio.py: -------------------------------------------------------------------------------- 1 | # 经典统一账户接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _PortfolioEndpoints(): 7 | 8 | 9 | get_portfolio_account = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/account', True] # 查询经典统一账户信息 (USER_DATA) 10 | get_portfolio_collateralRate = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/collateralRate', False] # 经典统一账户资产质押率 (MARKET_DATA) 11 | get_portfolio_pmLoan = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/pmLoan', True] # 查询经典统一账户穿仓借贷金额 (USER_DATA) 12 | set_portfolio_repay = ['https://api.binance.com', 'POST', '/sapi/v1/portfolio/repay', False] # 偿还经典统一账户穿仓负债 13 | get_portfolio_interest_history = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/interest-history', True] # 查询经典统一账户期货负余额收息历史(USER_DATA) 14 | get_portfolio_asset_index_price = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/asset-index-price', False] # 查询统一账户资产价格指数(MARKET_DATA) 15 | set_portfolio_auto_collection = ['https://api.binance.com', 'POST', '/sapi/v1/portfolio/auto-collection', True] # 资金归集(USER_DATA) 16 | set_portfolio_asset_collection = ['https://api.binance.com', 'POST', '/sapi/v1/portfolio/asset-collection', True] # 特定资产资金归集(USER_DATA) 17 | set_portfolio_bnb_transfer = ['https://api.binance.com', 'POST', '/sapi/v1/portfolio/bnb-transfer', True] # BNB划转(USER_DATA) 18 | set_portfolio_repay_futures_switch = ['https://api.binance.com', 'POST', '/sapi/v1/portfolio/repay-futures-switch', True] # 更改自动清还合约负余额模式(TRADE) 19 | get_portfolio_repay_futures_switch = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/repay-futures-switch', True] # 查询自动清还合约负余额模式(USER_DATA) 20 | set_portfolio_repay_futures_negative_balance = ['https://api.binance.com', 'POST', '/sapi/v1/portfolio/repay-futures-negative-balance', True] # 清还合约负余额(USER_DATA) 21 | get_portfolio_margin_asset_leverage = ['https://api.binance.com', 'GET', '/sapi/v1/portfolio/margin-asset-leverage', True] # 查询统一账户资产支持杠杆倍数(USER_DATA) 22 | 23 | 24 | class Portfolio(Client): 25 | 26 | # 查询经典统一账户信息 (USER_DATA) 27 | def get_portfolio_account(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 28 | ''' 29 | GET /sapi/v1/portfolio/account 30 | 31 | 权重(IP):5 32 | 33 | 请求参数: 34 | Parameter Type Required Description 35 | 36 | recvWindow LONG NO 37 | timestamp LONG YES 38 | ''' 39 | return self.send_request(*_PortfolioEndpoints.get_portfolio_account, **to_local(locals())) 40 | 41 | 42 | # 经典统一账户资产质押率 (MARKET_DATA) 43 | def get_portfolio_collateralRate(self,proxies={},proxy_host:str=None): 44 | ''' 45 | GET /sapi/v1/portfolio/collateralRate 46 | 47 | 权重(IP):50 48 | ''' 49 | return self.send_request(*_PortfolioEndpoints.get_portfolio_collateralRate, **to_local(locals())) 50 | 51 | 52 | # 查询经典统一账户穿仓借贷金额 (USER_DATA) 53 | def get_portfolio_pmLoan(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 54 | ''' 55 | GET /sapi/v1/portfolio/pmLoan 56 | 57 | 权重(UID):500 58 | 59 | 请求参数: 60 | Parameter Type Required Description 61 | 62 | recvWindow LONG NO 63 | timestamp LONG YES 64 | ''' 65 | return self.send_request(*_PortfolioEndpoints.get_portfolio_pmLoan, **to_local(locals())) 66 | 67 | 68 | # 偿还经典统一账户穿仓负债 69 | def set_portfolio_repay(self,from_:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 70 | ''' 71 | POST /sapi/v1/portfolio/repay 72 | 73 | 权重(UID):3000 74 | 75 | 请求参数: 76 | Parameter Type Required Description 77 | 78 | from STRING NO SPOT或MARGIN,默认SPOT 79 | recvWindow LONG NO 80 | timestamp LONG YES 81 | ''' 82 | data = to_local(locals()) 83 | data['from'] = data['from_'] 84 | del data['from_'] 85 | return self.send_request(*_PortfolioEndpoints.set_portfolio_repay, **data) 86 | 87 | 88 | # 查询经典统一账户期货负余额收息历史(USER_DATA) 89 | def get_portfolio_interest_history(self,asset:str = '',startTime:int = '',endTime:int = '',size:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 90 | ''' 91 | GET /sapi/v1/portfolio/interest-history 92 | 93 | 权重(IP):50 94 | 95 | 请求参数: 96 | Parameter Type Required Description 97 | 98 | asset STRING NO 99 | startTime LONG NO 起始时间 100 | endTime LONG NO 结束时间 101 | size LONG NO 返回的结果集数量 默认值:10 最大值:100 102 | recvWindow LONG NO 103 | timestamp LONG YES 104 | ''' 105 | return self.send_request(*_PortfolioEndpoints.get_portfolio_interest_history, **to_local(locals())) 106 | 107 | 108 | # 查询统一账户资产价格指数(MARKET_DATA) 109 | def get_portfolio_asset_index_price(self,asset:str = '',proxies={},proxy_host:str=None): 110 | ''' 111 | GET /sapi/v1/portfolio/asset-index-price 112 | 113 | 权重(IP): 114 | 115 | 请求参数: 116 | Parameter Type Required Description 117 | 118 | asset STRING NO 119 | ''' 120 | return self.send_request(*_PortfolioEndpoints.get_portfolio_asset_index_price, **to_local(locals())) 121 | 122 | 123 | # 资金归集(USER_DATA) 124 | def set_portfolio_auto_collection(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 125 | ''' 126 | POST /sapi/v1/portfolio/auto-collection 127 | 128 | 权重(IP): 129 | 130 | 请求参数: 131 | Parameter Type Required Description 132 | 133 | recvWindow LONG NO 134 | timestamp LONG YES 135 | ''' 136 | return self.send_request(*_PortfolioEndpoints.set_portfolio_auto_collection, **to_local(locals())) 137 | 138 | 139 | # 特定资产资金归集(USER_DATA) 140 | def set_portfolio_asset_collection(self,asset:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 141 | ''' 142 | POST /sapi/v1/portfolio/asset-collection 143 | 144 | 权重(IP): 145 | 146 | 请求参数: 147 | Parameter Type Required Description 148 | 149 | asset STRING YES 150 | recvWindow LONG NO 151 | timestamp LONG YES 152 | ''' 153 | return self.send_request(*_PortfolioEndpoints.set_portfolio_asset_collection, **to_local(locals())) 154 | 155 | 156 | # BNB划转(USER_DATA) 157 | def set_portfolio_bnb_transfer(self,amount:Union[int,float] = '',transferSide:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 158 | ''' 159 | POST /sapi/v1/portfolio/bnb-transfer 160 | 161 | 权重(IP): 162 | 163 | 请求参数: 164 | Parameter Type Required Description 165 | 166 | amount DECIMAL YES 167 | transferSide STRING YES "TO_UM","FROM_UM" 168 | recvWindow LONG NO 169 | timestamp LONG YES 170 | ''' 171 | return self.send_request(*_PortfolioEndpoints.set_portfolio_bnb_transfer, **to_local(locals())) 172 | 173 | 174 | # 更改自动清还合约负余额模式(TRADE) 175 | def set_portfolio_repay_futures_switch(self,autoRepay:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 176 | ''' 177 | POST /sapi/v1/portfolio/repay-futures-switch 178 | 179 | 权重(IP): 180 | 181 | 请求参数: 182 | Parameter Type Required Description 183 | 184 | autoRepay STRING YES 默认为true;false代表关闭自动清还合约负余额 185 | recvWindow LONG NO 186 | timestamp LONG YES 187 | ''' 188 | return self.send_request(*_PortfolioEndpoints.set_portfolio_repay_futures_switch, **to_local(locals())) 189 | 190 | 191 | # 查询自动清还合约负余额模式(USER_DATA) 192 | def get_portfolio_repay_futures_switch(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 193 | ''' 194 | GET /sapi/v1/portfolio/repay-futures-switch 195 | 196 | 权重(IP): 197 | 198 | 请求参数: 199 | Parameter Type Required Description 200 | 201 | recvWindow LONG NO 202 | timestamp LONG YES 203 | ''' 204 | return self.send_request(*_PortfolioEndpoints.get_portfolio_repay_futures_switch, **to_local(locals())) 205 | 206 | 207 | # 清还合约负余额(USER_DATA) 208 | def set_portfolio_repay_futures_negative_balance(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 209 | ''' 210 | POST /sapi/v1/portfolio/repay-futures-negative-balance 211 | 212 | 权重(IP): 213 | 214 | 请求参数: 215 | Parameter Type Required Description 216 | 217 | recvWindow LONG NO 218 | timestamp LONG YES 219 | ''' 220 | return self.send_request(*_PortfolioEndpoints.set_portfolio_repay_futures_negative_balance, **to_local(locals())) 221 | 222 | 223 | # 查询统一账户资产支持杠杆倍数(USER_DATA) 224 | def get_portfolio_margin_asset_leverage(self,proxies={},proxy_host:str=None): 225 | ''' 226 | GET /sapi/v1/portfolio/margin-asset-leverage 227 | 228 | 权重(IP): 229 | ''' 230 | return self.send_request(*_PortfolioEndpoints.get_portfolio_margin_asset_leverage, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/rebate.py: -------------------------------------------------------------------------------- 1 | # 返佣接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _RebateEndpoints(): 7 | 8 | 9 | get_rebate_taxQuery = ['https://api.binance.com', 'GET', '/sapi/v1/rebate/taxQuery', True] # 获取现货返佣历史记录 (USER_DATA) 10 | 11 | 12 | class Rebate(Client): 13 | 14 | # 获取现货返佣历史记录 (USER_DATA) 15 | def get_rebate_taxQuery(self,startTime:int = '',endTime:int = '',page:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 16 | ''' 17 | GET /sapi/v1/rebate/taxQuery 18 | 19 | 权重(UID):12000 20 | 21 | 请求参数: 22 | Parameter Type Required Description 23 | 24 | startTime LONG NO 25 | endTime LONG NO 26 | page INT NO 默认 1 27 | recvWindow LONG NO 28 | timestamp LONG YES 29 | ''' 30 | return self.send_request(*_RebateEndpoints.get_rebate_taxQuery, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/other/vip_loans.py: -------------------------------------------------------------------------------- 1 | # VIP借币接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _VipLoansEndpoints(): 7 | 8 | 9 | get_loan_vip_ongoing_orders = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/ongoing/orders', True] # 查询VIP借币借款中订单 (USER_DATA) 10 | set_loan_vip_repay = ['https://api.binance.com', 'POST', '/sapi/v1/loan/vip/repay', True] # VIP借币还款 (TRADE) 11 | get_loan_vip_repay_history = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/repay/history', True] # 查询VIP借币还款记录历史 (USER_DATA) 12 | set_loan_vip_renew = ['https://api.binance.com', 'POST', '/sapi/v1/loan/vip/renew', True] # VIP 借币续期 (TRADE) 13 | get_loan_vip_collateral_account = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/collateral/account', True] # 查询VIP子账户冻结抵押物金额 (USER_DATA) 14 | set_loan_vip_borrow = ['https://api.binance.com', 'POST', '/sapi/v1/loan/vip/borrow', True] # VIP 借币借款 (TRADE) 15 | get_loan_vip_loanable_data = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/loanable/data', True] # 查询VIP借币可借币种数据(USER_DATA) 16 | get_loan_vip_collateral_data = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/collateral/data', True] # 查询VIP借币抵押币种数据(USER_DATA) 17 | get_loan_vip_request_data = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/request/data', True] # 查询申请状态(USER_DATA) 18 | get_loan_vip_request_interestRate = ['https://api.binance.com', 'GET', '/sapi/v1/loan/vip/request/interestRate', True] # 查询借款利率(USER_DATA) 19 | 20 | 21 | class VipLoans(Client): 22 | 23 | # 查询VIP借币借款中订单 (USER_DATA) 24 | def get_loan_vip_ongoing_orders(self,orderId:int = '',collateralAccountId:int = '',loanCoin:str = '',collateralCoin:str = '',current:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 25 | ''' 26 | GET /sapi/v1/loan/vip/ongoing/orders 27 | 28 | 权重(IP):400 29 | 30 | 请求参数: 31 | Parameter Type Required Description 32 | 33 | orderId LONG NO 34 | collateralAccountId LONG NO 35 | loanCoin STRING NO 36 | collateralCoin STRING NO 37 | current LONG NO 当前查询页数,从1开始。默认值:1,最大:1000 38 | limit LONG NO 默认值:10,最大:100 39 | recvWindow LONG NO 40 | timestamp LONG YES 41 | ''' 42 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_ongoing_orders, **to_local(locals())) 43 | 44 | 45 | # VIP借币还款 (TRADE) 46 | def set_loan_vip_repay(self,orderId:int = '',amount:Union[int,float] = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 47 | ''' 48 | POST /sapi/v1/loan/vip/repay 49 | 50 | 权重(UID):6000 51 | 52 | 请求参数: 53 | Parameter Type Required Description 54 | 55 | orderId LONG YES 56 | amount DECIMAL YES 57 | recvWindow LONG NO 58 | timestamp LONG YES 59 | ''' 60 | return self.send_request(*_VipLoansEndpoints.set_loan_vip_repay, **to_local(locals())) 61 | 62 | 63 | # 查询VIP借币还款记录历史 (USER_DATA) 64 | def get_loan_vip_repay_history(self,orderId:int = '',loanCoin:str = '',startTime:int = '',endTime:int = '',current:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 65 | ''' 66 | GET /sapi/v1/loan/vip/repay/history 67 | 68 | 权重(IP):400 69 | 70 | 请求参数: 71 | Parameter Type Required Description 72 | 73 | orderId LONG NO 74 | loanCoin STRING NO 75 | startTime LONG NO 76 | endTime LONG NO 77 | current LONG NO 当前查询页数,从1开始。默认值:1,最大:1000 78 | limit LONG NO 默认值:10,最大:100 79 | recvWindow LONG NO 80 | timestamp LONG YES 81 | ''' 82 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_repay_history, **to_local(locals())) 83 | 84 | 85 | # VIP 借币续期 (TRADE) 86 | def set_loan_vip_renew(self,orderId:int = '',loanTerm:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 87 | ''' 88 | POST /sapi/v1/loan/vip/renew 89 | 90 | 权重(UID):6000 91 | 92 | 请求参数: 93 | Parameter Type Required Description 94 | 95 | orderId LONG YES 96 | loanTerm INT NO 30/60 天 97 | recvWindow LONG NO 98 | timestamp LONG YES 99 | ''' 100 | return self.send_request(*_VipLoansEndpoints.set_loan_vip_renew, **to_local(locals())) 101 | 102 | 103 | # 查询VIP子账户冻结抵押物金额 (USER_DATA) 104 | def get_loan_vip_collateral_account(self,orderId:int = '',collateralAccountId:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 105 | ''' 106 | GET /sapi/v1/loan/vip/collateral/account 107 | 108 | 权重(IP):6000 109 | 110 | 请求参数: 111 | Parameter Type Required Description 112 | 113 | orderId LONG NO 114 | collateralAccountId LONG NO 115 | recvWindow LONG NO 116 | timestamp LONG YES 117 | ''' 118 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_collateral_account, **to_local(locals())) 119 | 120 | 121 | # VIP 借币借款 (TRADE) 122 | def set_loan_vip_borrow(self,loanAccountId:int = '',loanCoin:str = '',loanAmount:Union[int,float] = '',collateralAccountId:str = '',collateralCoin:str = '',isFlexibleRate:bool = '',loanTerm:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 123 | ''' 124 | POST /sapi/v1/loan/vip/borrow 125 | 126 | 权重(UID):6000 127 | 128 | 请求参数: 129 | Parameter Type Required Description 130 | 131 | loanAccountId LONG YES 132 | loanCoin STRING YES 133 | loanAmount DECIMAL YES 134 | collateralAccountId STRING YES 多个用,分割 135 | collateralCoin STRING YES 多个用,分割 136 | isFlexibleRate BOOLEAN YES 137 | loanTerm INT NO 选择固定利率时此为必填选项;选择浮动利率时选填:30/60 days 138 | recvWindow LONG NO 139 | timestamp LONG YES 140 | ''' 141 | return self.send_request(*_VipLoansEndpoints.set_loan_vip_borrow, **to_local(locals())) 142 | 143 | 144 | # 查询VIP借币可借币种数据(USER_DATA) 145 | def get_loan_vip_loanable_data(self,loanCoin:str = '',vipLevel:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 146 | ''' 147 | GET /sapi/v1/loan/vip/loanable/data 148 | 149 | 权重(IP):400 150 | 151 | 请求参数: 152 | Parameter Type Required Description 153 | 154 | loanCoin STRING NO 155 | vipLevel INT NO 默认值:用户的VIP等级 156 | recvWindow LONG NO 157 | timestamp LONG YES 158 | ''' 159 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_loanable_data, **to_local(locals())) 160 | 161 | 162 | # 查询VIP借币抵押币种数据(USER_DATA) 163 | def get_loan_vip_collateral_data(self,collateralCoin:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 164 | ''' 165 | GET /sapi/v1/loan/vip/collateral/data 166 | 167 | 权重(IP):400 168 | 169 | 请求参数: 170 | Parameter Type Required Description 171 | 172 | collateralCoin STRING NO 173 | recvWindow LONG NO 174 | timestamp LONG YES 175 | ''' 176 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_collateral_data, **to_local(locals())) 177 | 178 | 179 | # 查询申请状态(USER_DATA) 180 | def get_loan_vip_request_data(self,current:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 181 | ''' 182 | GET /sapi/v1/loan/vip/request/data 183 | 184 | 权重(UID):400 185 | 186 | 请求参数: 187 | Parameter Type Required Description 188 | 189 | current LONG NO 目前查询的页面。从1开始,默认:1,最大:1000 190 | limit LONG NO 默认: 10, 最大: 100 191 | recvWindow LONG NO 192 | timestamp LONG YES 193 | ''' 194 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_request_data, **to_local(locals())) 195 | 196 | 197 | # 查询借款利率(USER_DATA) 198 | def get_loan_vip_request_interestRate(self,loanCoin:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 199 | ''' 200 | GET /sapi/v1/loan/vip/request/interestRate 201 | 202 | 权重(UID):400 203 | 204 | 请求参数: 205 | Parameter Type Required Description 206 | 207 | loanCoin STRING YES 最多10个币种, 多个用","隔开 208 | recvWindow LONG NO 209 | timestamp LONG YES 210 | ''' 211 | return self.send_request(*_VipLoansEndpoints.get_loan_vip_request_interestRate, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/pm/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 统一账户 3 | https://binance-docs.github.io/apidocs/pm/cn/ 4 | ''' 5 | 6 | from binance_interface.api.pm.pm_market import PMMarket # 行情接口 7 | from binance_interface.api.pm.pm_account import PMAccount # 账户信息 8 | from binance_interface.api.pm.pm_get_order import PMGetOrder # 查询订单 9 | from binance_interface.api.pm.pm_set_order import PMSetOrder # 下单接口 10 | from binance_interface.api.pm.pm_cancel_order import PMCancelOrder # 撤单接口 11 | 12 | Market = PMMarket 13 | Account = PMAccount 14 | GetOrder = PMGetOrder 15 | SetOrder = PMSetOrder 16 | CancelOrder = PMCancelOrder 17 | 18 | 19 | class PM(): 20 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 21 | self.market = PMMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 22 | self.account = PMAccount(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 23 | self.getOrder = PMGetOrder(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 24 | self.setOrder = PMSetOrder(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 25 | self.cancelOrder = PMCancelOrder(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 26 | -------------------------------------------------------------------------------- /binance_interface/api/pm/pm_cancel_order.py: -------------------------------------------------------------------------------- 1 | # 撤单接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _PMCancelOrderEndpoints(): 7 | 8 | 9 | cancel_um_order = ['https://papi.binance.com', 'DELETE', '/papi/v1/um/order', True] # 撤销UM订单 (TRADE) 10 | cancel_um_allOpenOrders = ['https://papi.binance.com', 'DELETE', '/papi/v1/um/allOpenOrders', True] # 撤销全部UM订单 (TRADE) 11 | cancel_cm_order = ['https://papi.binance.com', 'DELETE', '/papi/v1/cm/order', True] # 撤销CM订单 (TRADE) 12 | cancel_cm_allOpenOrders = ['https://papi.binance.com', 'DELETE', '/papi/v1/cm/allOpenOrders', True] # 撤销全部CM订单 (TRADE) 13 | cancel_margin_order = ['https://papi.binance.com', 'DELETE', '/papi/v1/margin/order', True] # 杠杆账户撤销订单 (TRADE) 14 | cancel_margin_allOpenOrders = ['https://papi.binance.com', 'DELETE', '/papi/v1/margin/allOpenOrders', True] # 杠杆账户撤销单一交易对的所有挂单 (TRADE) 15 | cancel_margin_orderList = ['https://papi.binance.com', 'DELETE', '/papi/v1/margin/orderList', True] # 取消杠杆账户OCO订单 (TRADE) 16 | cancel_um_conditional_order = ['https://papi.binance.com', 'DELETE', '/papi/v1/um/conditional/order', True] # 取消UM条件订单 (TRADE) 17 | cancel_um_conditional_allOpenOrders = ['https://papi.binance.com', 'DELETE', '/papi/v1/um/conditional/allOpenOrders', True] # 取消全部UM条件单 (TRADE) 18 | cancel_cm_conditional_order = ['https://papi.binance.com', 'DELETE', '/papi/v1/cm/conditional/order', True] # 取消CM条件订单 (TRADE) 19 | cancel_cm_conditional_allOpenOrders = ['https://papi.binance.com', 'DELETE', '/papi/v1/cm/conditional/allOpenOrders', True] # 取消全部CM条件单 (TRADE) 20 | 21 | 22 | class PMCancelOrder(Client): 23 | 24 | # 撤销UM订单 (TRADE) 25 | def cancel_um_order(self,symbol:str = '',orderId:int = '',origClientOrderId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 26 | ''' 27 | DELETE /papi/v1/um/order 28 | 29 | 权重:1 30 | 31 | 请求参数: 32 | Parameter Type Required Description 33 | 34 | symbol STRING YES 35 | orderId LONG NO 36 | origClientOrderId STRING NO 37 | recvWindow LONG NO 38 | timestamp LONG YES 39 | ''' 40 | return self.send_request(*_PMCancelOrderEndpoints.cancel_um_order, **to_local(locals())) 41 | 42 | 43 | # 撤销全部UM订单 (TRADE) 44 | def cancel_um_allOpenOrders(self,symbol:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 45 | ''' 46 | DELETE /papi/v1/um/allOpenOrders 47 | 48 | 权重:1 49 | 50 | 请求参数: 51 | Parameter Type Required Description 52 | 53 | symbol STRING YES 54 | recvWindow LONG NO 55 | timestamp LONG YES 56 | ''' 57 | return self.send_request(*_PMCancelOrderEndpoints.cancel_um_allOpenOrders, **to_local(locals())) 58 | 59 | 60 | # 撤销CM订单 (TRADE) 61 | def cancel_cm_order(self,symbol:str = '',orderId:int = '',origClientOrderId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 62 | ''' 63 | DELETE /papi/v1/cm/order 64 | 65 | 权重:1 66 | 67 | 请求参数: 68 | Parameter Type Required Description 69 | 70 | symbol STRING YES 71 | orderId LONG NO 72 | origClientOrderId STRING NO 73 | recvWindow LONG NO 74 | timestamp LONG YES 75 | ''' 76 | return self.send_request(*_PMCancelOrderEndpoints.cancel_cm_order, **to_local(locals())) 77 | 78 | 79 | # 撤销全部CM订单 (TRADE) 80 | def cancel_cm_allOpenOrders(self,symbol:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 81 | ''' 82 | DELETE /papi/v1/cm/allOpenOrders 83 | 84 | 权重:1 85 | 86 | 请求参数: 87 | Parameter Type Required Description 88 | 89 | symbol STRING YES 90 | recvWindow LONG NO 91 | timestamp LONG YES 92 | ''' 93 | return self.send_request(*_PMCancelOrderEndpoints.cancel_cm_allOpenOrders, **to_local(locals())) 94 | 95 | 96 | # 杠杆账户撤销订单 (TRADE) 97 | def cancel_margin_order(self,symbol:str = '',orderId:int = '',origClientOrderId:str = '',newClientOrderId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 98 | ''' 99 | DELETE /papi/v1/margin/order 100 | 101 | 权重:2 102 | 103 | 请求参数: 104 | Parameter Type Required Description 105 | 106 | symbol STRING YES 107 | orderId LONG NO 108 | origClientOrderId STRING NO 109 | newClientOrderId STRING NO 用于唯一识别此撤销订单,默认自动生成。 110 | recvWindow LONG NO 赋值不能超过60000 111 | timestamp LONG YES 112 | ''' 113 | return self.send_request(*_PMCancelOrderEndpoints.cancel_margin_order, **to_local(locals())) 114 | 115 | 116 | # 杠杆账户撤销单一交易对的所有挂单 (TRADE) 117 | def cancel_margin_allOpenOrders(self,symbol:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 118 | ''' 119 | DELETE /papi/v1/margin/allOpenOrders 120 | 121 | 权重:5 122 | 123 | 请求参数: 124 | Parameter Type Required Description 125 | 126 | symbol STRING YES 127 | recvWindow LONG NO 赋值不能超过 60000 128 | timestamp LONG YES 129 | ''' 130 | return self.send_request(*_PMCancelOrderEndpoints.cancel_margin_allOpenOrders, **to_local(locals())) 131 | 132 | 133 | # 取消杠杆账户OCO订单 (TRADE) 134 | def cancel_margin_orderList(self,symbol:str = '',orderListId:int = '',listClientOrderId:str = '',newClientOrderId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 135 | ''' 136 | DELETE /papi/v1/margin/orderList 137 | 138 | 权重:2 139 | 140 | 请求参数: 141 | Parameter Type Required Description 142 | 143 | symbol STRING YES 144 | orderListId LONG NO orderListId或listClientOrderId必须被提供 145 | listClientOrderId STRING NO orderListId或listClientOrderId必须被提供 146 | newClientOrderId STRING NO 用户自定义的本次撤销操作的ID(注意不是被撤销的订单的自定义ID)。如无指定会自动赋值 147 | recvWindow LONG NO 赋值不能超过 60000 148 | timestamp LONG YES 149 | ''' 150 | return self.send_request(*_PMCancelOrderEndpoints.cancel_margin_orderList, **to_local(locals())) 151 | 152 | 153 | # 取消UM条件订单 (TRADE) 154 | def cancel_um_conditional_order(self,symbol:str = '',strategyId:int = '',newClientStrategyId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 155 | ''' 156 | DELETE /papi/v1/um/conditional/order 157 | 158 | 权重:1 159 | 160 | 请求参数: 161 | Parameter Type Required Description 162 | 163 | symbol STRING YES 164 | strategyId LONG NO 165 | newClientStrategyId STRING NO 166 | recvWindow LONG NO 167 | timestamp LONG YES 168 | ''' 169 | return self.send_request(*_PMCancelOrderEndpoints.cancel_um_conditional_order, **to_local(locals())) 170 | 171 | 172 | # 取消全部UM条件单 (TRADE) 173 | def cancel_um_conditional_allOpenOrders(self,symbol:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 174 | ''' 175 | DELETE /papi/v1/um/conditional/allOpenOrders 176 | 177 | 权重:1 178 | 179 | 请求参数: 180 | Parameter Type Required Description 181 | 182 | symbol STRING YES 183 | recvWindow LONG NO 184 | timestamp LONG YES 185 | ''' 186 | return self.send_request(*_PMCancelOrderEndpoints.cancel_um_conditional_allOpenOrders, **to_local(locals())) 187 | 188 | 189 | # 取消CM条件订单 (TRADE) 190 | def cancel_cm_conditional_order(self,symbol:str = '',strategyId:int = '',newClientStrategyId:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 191 | ''' 192 | DELETE /papi/v1/cm/conditional/order 193 | 194 | 权重(Order):1 195 | 196 | 请求参数: 197 | Parameter Type Required Description 198 | 199 | symbol STRING YES 200 | strategyId LONG NO 201 | newClientStrategyId STRING NO 202 | recvWindow LONG NO 203 | timestamp LONG YES 204 | ''' 205 | return self.send_request(*_PMCancelOrderEndpoints.cancel_cm_conditional_order, **to_local(locals())) 206 | 207 | 208 | # 取消全部CM条件单 (TRADE) 209 | def cancel_cm_conditional_allOpenOrders(self,symbol:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 210 | ''' 211 | DELETE /papi/v1/cm/conditional/allOpenOrders 212 | 213 | 权重:1 214 | 215 | 请求参数: 216 | Parameter Type Required Description 217 | 218 | symbol STRING YES 219 | recvWindow LONG NO 220 | timestamp LONG YES 221 | ''' 222 | return self.send_request(*_PMCancelOrderEndpoints.cancel_cm_conditional_allOpenOrders, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/pm/pm_market.py: -------------------------------------------------------------------------------- 1 | # 行情接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _PMMarketEndpoints(): 7 | 8 | 9 | get_ping = ['https://papi.binance.com', 'GET', '/papi/v1/ping', False] # 测试服务器连通性 PING 10 | 11 | 12 | class PMMarket(Client): 13 | 14 | # 测试服务器连通性 PING 15 | def get_ping(self,proxies={},proxy_host:str=None): 16 | ''' 17 | GET /papi/v1/ping 18 | 19 | 权重:1 20 | 21 | 22 | ''' 23 | return self.send_request(*_PMMarketEndpoints.get_ping, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/proxy_host.py: -------------------------------------------------------------------------------- 1 | proxy_host_map = { 2 | 'https://api.binance.com': '{host}/api', # SPOT 3 | 'https://fapi.binance.com': '{host}/fapi', # UM 4 | 'https://dapi.binance.com': '{host}/dapi', # CM 5 | 'https://eapi.binance.com': '{host}/eapi', # EO 6 | 'https://papi.binance.com': '{host}/papi', # PM 7 | } 8 | -------------------------------------------------------------------------------- /binance_interface/api/spot/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 现货 3 | https://binance-docs.github.io/apidocs/spot/cn/ 4 | ''' 5 | from binance_interface.api.spot.spot_algo import SPOTAlgo # 现货策略交易接口 6 | from binance_interface.api.spot.spot_trade import SPOTTrade # 现货交易接口 7 | from binance_interface.api.spot.spot_market import SPOTMarket # 行情接口 8 | from binance_interface.api.spot.spot_account import SPOTAccount # 现货账户接口 9 | 10 | Algo = SPOTAlgo 11 | Trade = SPOTTrade 12 | Market = SPOTMarket 13 | Account = SPOTAccount 14 | 15 | 16 | class SPOT(): 17 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 18 | self.Algo = SPOTAlgo(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | self.trade = SPOTTrade(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 20 | self.market = SPOTMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 21 | self.account = SPOTAccount(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 22 | -------------------------------------------------------------------------------- /binance_interface/api/spot/spot_account.py: -------------------------------------------------------------------------------- 1 | # 现货账户接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _SPOTAccountEndpoints(): 7 | 8 | 9 | get_account = ['https://api.binance.com', 'GET', '/api/v3/account', True] # 账户信息 (USER_DATA) 10 | get_myTrades = ['https://api.binance.com', 'GET', '/api/v3/myTrades', True] # 账户成交历史 (USER_DATA) 11 | get_rateLimit_order = ['https://api.binance.com', 'GET', '/api/v3/rateLimit/order', True] # 查询目前下单数 (TRADE) 12 | get_myPreventedMatches = ['https://api.binance.com', 'GET', '/api/v3/myPreventedMatches', True] # 获取 Prevented Matches (USER_DATA) 13 | get_myAllocations = ['https://api.binance.com', 'GET', '/api/v3/myAllocations', True] # 查询分配结果 (USER_DATA) 14 | get_account_commission = ['https://api.binance.com', 'GET', '/api/v3/account/commission', True] # 查询佣金费率 (USER_DATA) 15 | 16 | 17 | class SPOTAccount(Client): 18 | 19 | 20 | # 账户信息 (USER_DATA) 21 | def get_account(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 22 | ''' 23 | GET /api/v3/account 24 | 25 | 权重(IP):20 26 | 27 | 请求参数: 28 | Parameter Type Required Description 29 | 30 | recvWindow LONG NO 赋值不能大于60000 31 | timestamp LONG YES 32 | ''' 33 | return self.send_request(*_SPOTAccountEndpoints.get_account, **to_local(locals())) 34 | 35 | 36 | # 账户成交历史 (USER_DATA) 37 | def get_myTrades(self,symbol:str = '',orderId:int = '',startTime:int = '',endTime:int = '',fromId:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 38 | ''' 39 | GET /api/v3/myTrades 40 | 41 | 权重(IP):20 42 | 43 | 请求参数: 44 | Parameter Type Required Description 45 | 46 | symbol STRING YES 47 | orderId LONG NO 必须要和参数symbol一起使用. 48 | startTime LONG NO 49 | endTime LONG NO 50 | fromId LONG NO 起始Trade id。 默认获取最新交易。 51 | limit INT NO 默认 500; 最大 1000. 52 | recvWindow LONG NO 赋值不能超过60000 53 | timestamp LONG YES 54 | ''' 55 | return self.send_request(*_SPOTAccountEndpoints.get_myTrades, **to_local(locals())) 56 | 57 | 58 | # 查询目前下单数 (TRADE) 59 | def get_rateLimit_order(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 60 | ''' 61 | GET /api/v3/rateLimit/order 62 | 63 | 权重(IP):40 64 | 65 | 请求参数: 66 | Parameter Type Required Description 67 | 68 | recvWindow LONG NO 赋值不得大于60000 69 | timestamp LONG YES 70 | ''' 71 | return self.send_request(*_SPOTAccountEndpoints.get_rateLimit_order, **to_local(locals())) 72 | 73 | 74 | # 获取 Prevented Matches (USER_DATA) 75 | def get_myPreventedMatches(self,symbol:str = '',preventedMatchId:int = '',orderId:int = '',fromPreventedMatchId:int = '',limit:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 76 | ''' 77 | GET /api/v3/myPreventedMatches 78 | 79 | 权重(IP): 80 | 81 | 请求参数: 82 | Parameter Type Required Description 83 | 84 | symbol STRING YES 85 | preventedMatchId LONG NO 86 | orderId LONG NO 87 | fromPreventedMatchId LONG NO 88 | limit INT NO 默认:500;最大:1000 89 | recvWindow LONG NO 赋值不得大于60000 90 | timestamp LONG YES 91 | ''' 92 | return self.send_request(*_SPOTAccountEndpoints.get_myPreventedMatches, **to_local(locals())) 93 | 94 | 95 | # 查询分配结果 (USER_DATA) 96 | def get_myAllocations(self,symbol:str = '',startTime:int = '',endTime:int = '',fromAllocationId:int = '',limit:int = '',orderId:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 97 | ''' 98 | GET /api/v3/myAllocations 99 | 100 | 权重:20 101 | 102 | 请求参数: 103 | Parameter Type Required Description 104 | 105 | symbol STRING Yes 106 | startTime LONG No 107 | endTime LONG No 108 | fromAllocationId INT No 109 | limit INT No 默认值 500; 最大值 1000 110 | orderId LONG No 111 | recvWindow LONG No 不能大于60000 112 | timestamp LONG No 113 | ''' 114 | return self.send_request(*_SPOTAccountEndpoints.get_myAllocations, **to_local(locals())) 115 | 116 | 117 | # 查询佣金费率 (USER_DATA) 118 | def get_account_commission(self,symbol:str = '',proxies={},proxy_host:str=None): 119 | ''' 120 | GET /api/v3/account/commission 121 | 122 | 权重:20 123 | 124 | 请求参数: 125 | Parameter Type Required Description 126 | 127 | symbol STRING YES 128 | ''' 129 | return self.send_request(*_SPOTAccountEndpoints.get_account_commission, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/spot/spot_algo.py: -------------------------------------------------------------------------------- 1 | # 现货策略交易接口 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _SPOTAlgoEndpoints(): 7 | 8 | 9 | set_algo_spot_newOrderTwap = ['https://api.binance.com', 'POST', '/sapi/v1/algo/spot/newOrderTwap', True] # 时间加权平均价格策略(Twap)下单 (TRADE) 10 | cancel_algo_spot_order = ['https://api.binance.com', 'DELETE', '/sapi/v1/algo/spot/order', True] # 取消TWAP策略订单 (TRADE) 11 | get_algo_spot_openOrders = ['https://api.binance.com', 'GET', '/sapi/v1/algo/spot/openOrders', True] # 查询当前策略订单挂单 (USER_DATA) 12 | get_algo_spot_historicalOrders = ['https://api.binance.com', 'GET', '/sapi/v1/algo/spot/historicalOrders', True] # 查询历史策略订单 (USER_DATA) 13 | get_algo_spot_subOrders = ['https://api.binance.com', 'GET', '/sapi/v1/algo/spot/subOrders', True] # 查询执行子订单 (USER_DATA) 14 | 15 | 16 | class SPOTAlgo(Client): 17 | 18 | # 时间加权平均价格策略(Twap)下单 (TRADE) 19 | def set_algo_spot_newOrderTwap(self,symbol:str = '',side:str = '',quantity:Union[int,float] = '',duration:int = '',clientAlgoId:str = '',limitPrice:Union[int,float] = '',stpMode:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 20 | ''' 21 | POST /sapi/v1/algo/spot/newOrderTwap 22 | 23 | 权重(UID):3000 24 | 25 | 请求参数: 26 | Parameter Type Required Description 27 | 28 | symbol STRING YES 交易对 eg. BTCUSDT 29 | side ENUM YES 买卖方向 ( BUY or SELL ) 30 | quantity DECIMAL YES 下单数量, 以Base资产个数下单; 名义价值 (quantity* 最新价格(base asset)) 需要大于 1,000 USDT,且不超过 100,000 USDT 31 | duration LONG YES 请以秒为单位发送[300,86400];少于 5 分钟 => 默认为 5 分钟;大于 24h => 默认为 24h 32 | clientAlgoId STRING NO 必须传入32位,如果未发送,则自动生成 33 | limitPrice DECIMAL NO 限价单价格; 若未发送,则以市场价下单 34 | stpMode ENUM NO 允许的 ENUM 取决于交易对的配置。支持的值有EXPIRE_TAKER,EXPIRE_MAKER,EXPIRE_BOTH,NONE 35 | recvWindow LONG NO 36 | timestamp LONG YES 37 | ''' 38 | return self.send_request(*_SPOTAlgoEndpoints.set_algo_spot_newOrderTwap, **to_local(locals())) 39 | 40 | 41 | # 取消TWAP策略订单 (TRADE) 42 | def cancel_algo_spot_order(self,algoId:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 43 | ''' 44 | DELETE /sapi/v1/algo/spot/order 45 | 46 | 权重(IP):1 47 | 48 | 请求参数: 49 | Parameter Type Required Description 50 | 51 | algoId LONG YES eg. 14511 52 | recvWindow LONG NO 53 | timestamp LONG YES 54 | ''' 55 | return self.send_request(*_SPOTAlgoEndpoints.cancel_algo_spot_order, **to_local(locals())) 56 | 57 | 58 | # 查询当前策略订单挂单 (USER_DATA) 59 | def get_algo_spot_openOrders(self,recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 60 | ''' 61 | GET /sapi/v1/algo/spot/openOrders 62 | 63 | 权重(IP):1 64 | 65 | 请求参数: 66 | Parameter Type Required Description 67 | 68 | recvWindow LONG NO 69 | timestamp LONG YES 70 | ''' 71 | return self.send_request(*_SPOTAlgoEndpoints.get_algo_spot_openOrders, **to_local(locals())) 72 | 73 | 74 | # 查询历史策略订单 (USER_DATA) 75 | def get_algo_spot_historicalOrders(self,symbol:str = '',side:str = '',startTime:int = '',endTime:int = '',page:int = '',pageSize:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 76 | ''' 77 | GET /sapi/v1/algo/spot/historicalOrders 78 | 79 | 权重(IP):1 80 | 81 | 请求参数: 82 | Parameter Type Required Description 83 | 84 | symbol STRING NO 交易对 eg. BTCUSDT 85 | side ENUM NO BUY 或者 SELL 86 | startTime LONG NO 毫秒级时间戳 eg.1641522717552 87 | endTime LONG NO 毫秒级时间戳 eg.1641522526562 88 | page INT NO 默认 1 89 | pageSize INT NO 最小 1, 最大 100; 默认 100 90 | recvWindow LONG NO 91 | timestamp LONG YES 92 | ''' 93 | return self.send_request(*_SPOTAlgoEndpoints.get_algo_spot_historicalOrders, **to_local(locals())) 94 | 95 | 96 | # 查询执行子订单 (USER_DATA) 97 | def get_algo_spot_subOrders(self,algoId:int = '',page:int = '',pageSize:int = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 98 | ''' 99 | GET /sapi/v1/algo/spot/subOrders 100 | 101 | 权重(IP):1 102 | 103 | 请求参数: 104 | Parameter Type Required Description 105 | 106 | algoId LONG YES 107 | page INT NO 默认1 108 | pageSize INT NO 最小 1, 最大 100; 默认 100 109 | recvWindow LONG NO 110 | timestamp LONG YES 111 | ''' 112 | return self.send_request(*_SPOTAlgoEndpoints.get_algo_spot_subOrders, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/api/um/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | U本位合约 3 | https://binance-docs.github.io/apidocs/futures/cn/ 4 | ''' 5 | 6 | from binance_interface.api.um.um_account_trade import UMAccountTrade # 账户和交易接口 7 | from binance_interface.api.um.um_market import UMMarket # 行情接口 8 | from binance_interface.api.um.um_portfolio import UMPortfolio # 经典统一账户 9 | 10 | AccountTrade = UMAccountTrade 11 | Market = UMMarket 12 | Portfolio = UMPortfolio 13 | 14 | 15 | class UM(): 16 | def __init__(self, key='', secret='', proxies={}, proxy_host: str = None): 17 | self.accountTrade = UMAccountTrade(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 18 | self.market = UMMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | self.portfolio = UMPortfolio(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 20 | -------------------------------------------------------------------------------- /binance_interface/api/um/um_portfolio.py: -------------------------------------------------------------------------------- 1 | # 经典统一账户 2 | from paux.param import to_local 3 | from binance_interface.api.client import Client 4 | from typing import Union 5 | 6 | class _UMPortfolioEndpoints(): 7 | 8 | 9 | get_pmAccountInfo = ['https://fapi.binance.com', 'GET', '/fapi/v1/pmAccountInfo', True] # 查询经典统一账户账户信息 (USER_DATA) 10 | 11 | 12 | class UMPortfolio(Client): 13 | 14 | # 查询经典统一账户账户信息 (USER_DATA) 15 | def get_pmAccountInfo(self,asset:str = '',recvWindow:int = '',timestamp:int = '',proxies={},proxy_host:str=None): 16 | ''' 17 | GET /fapi/v1/pmAccountInfo 18 | 19 | 权重(IP):5 20 | 21 | 请求参数: 22 | Parameter Type Required Description 23 | 24 | asset STRING YES 25 | recvWindow LONG NO 26 | timestamp LONG YES 27 | ''' 28 | return self.send_request(*_UMPortfolioEndpoints.get_pmAccountInfo, **to_local(locals())) -------------------------------------------------------------------------------- /binance_interface/app/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.account import AccountSPOT, AccountUM, AccountCM 2 | from binance_interface.app.market import MarketSPOT, MarketUM, MarketCM 3 | from binance_interface.app.trade import TradeSPOT, TradeUM, TradeCM 4 | 5 | 6 | class BinanceSPOT(): 7 | def __init__(self, 8 | key: str, 9 | secret: str, 10 | timezone: str = 'America/New_York', 11 | proxies={}, 12 | proxy_host: str = None, 13 | ): 14 | self.account = AccountSPOT(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 15 | self.market = MarketSPOT(key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 16 | self.trade = TradeSPOT(key=key, secret=secret, timezone=timezone, account=self.account, market=self.market, 17 | proxies=proxies, proxy_host=proxy_host) 18 | self.timezone = timezone 19 | 20 | 21 | class BinanceUM(): 22 | def __init__(self, 23 | key: str, 24 | secret: str, 25 | timezone: str = 'America/New_York', 26 | proxies={}, 27 | proxy_host: str = None, 28 | ): 29 | self.account = AccountUM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 30 | self.market = MarketUM(key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 31 | self.trade = TradeUM(key=key, secret=secret, timezone=timezone, account=self.account, market=self.market, 32 | proxies=proxies, proxy_host=proxy_host) 33 | self.timezone = timezone 34 | 35 | 36 | class BinanceCM(): 37 | def __init__(self, 38 | key: str, 39 | secret: str, 40 | timezone: str = 'America/New_York', 41 | proxies={}, 42 | proxy_host: str = None, 43 | ): 44 | self.account = AccountCM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 45 | self.market = MarketCM(key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 46 | self.trade = TradeCM(key=key, secret=secret, timezone=timezone, account=self.account, market=self.market, 47 | proxies=proxies, proxy_host=proxy_host) 48 | self.timezone = timezone 49 | 50 | 51 | AppSPOT = BinanceSPOT 52 | AppUM = BinanceUM 53 | AppCM = BinanceCM 54 | -------------------------------------------------------------------------------- /binance_interface/app/account/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.account.account_cm import AccountCM 2 | from binance_interface.app.account.account_um import AccountUM 3 | from binance_interface.app.account.account_spot import AccountSPOT 4 | -------------------------------------------------------------------------------- /binance_interface/app/account/account_cm.py: -------------------------------------------------------------------------------- 1 | from typing import Literal, Union 2 | from paux.param import to_local 3 | from binance_interface.api.cm import CM 4 | from binance_interface.app import code 5 | from binance_interface.app import utils 6 | from binance_interface.app import exception 7 | 8 | 9 | class AccountCM(): 10 | 11 | def __init__(self, key: str, secret: str, proxies={}, proxy_host: str = None): 12 | self.cmAPI = CM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 13 | 14 | # 获取账户信息 Weight: 5 15 | def get_account(self, recvWindow: int = '') -> dict: 16 | return self.cmAPI.accountTrade.get_account(**to_local(locals())) 17 | 18 | # 获取全部产品余额 Weight: 1 19 | def get_balances(self, assets=[]): 20 | ''' 21 | :param asset: 获取的货币,空表示全部 22 | :param recvWindow: 23 | :return: 24 | ''' 25 | api_balance_result = self.cmAPI.accountTrade.get_balance() 26 | if not api_balance_result['code'] == 200: 27 | return api_balance_result 28 | balances_result = {'code': 200, 'data': [], 'msg': ''} 29 | for balance in api_balance_result['data']: 30 | this_asset = balance['asset'] 31 | if assets and this_asset not in assets: 32 | continue 33 | balances_result['data'].append(balance) 34 | return balances_result 35 | 36 | # 获取单个产品余额 Weight: 1 37 | def get_balance(self, asset: str = '', symbol: str = '', base_asset: str = ''): 38 | ''' 39 | :param asset: 货币名称 40 | :param symbol: 产品名称 41 | :param base_asset: 产品的交易基础货币 42 | asset与symbol不能同时为空 43 | 44 | 例如:对于产品:BTCUSDT,其中: 45 | asset = 'BTC' 46 | symbol = 'BTCUSDT' 47 | base_asset = 'USDT' 48 | ''' 49 | if not asset and not symbol: 50 | raise exception.ParamException('asset and symbol can not be empty together') 51 | if not asset: 52 | asset = utils.get_asset(symbol=symbol, base_asset=base_asset) 53 | balances_result = self.get_balances() 54 | if balances_result['code'] != 200: 55 | return balances_result 56 | for balance in balances_result['data']: 57 | if balance['asset'] == asset: 58 | result = { 59 | 'code': 200, 60 | 'data': balance, 61 | 'msg': '' 62 | } 63 | return result 64 | else: 65 | msg = f'Can not find asset = {asset}' 66 | result = { 67 | 'code': code.ASSET_ERROR[0], 68 | 'data': {}, 69 | 'msg': msg, 70 | } 71 | return result 72 | 73 | # 获取全部产品余额字典 Weight: 1 74 | def get_balancesMap(self, assets=[]): 75 | ''' 76 | :param assets: 获取的货币,空表示全部 77 | :return: 78 | ''' 79 | balances_result = self.get_balances(assets=assets) 80 | if not balances_result['code'] == 200: 81 | return balances_result 82 | balancesMap = {} 83 | for balance in balances_result['data']: 84 | balance: dict 85 | asset = balance['asset'] 86 | balancesMap[asset] = balance 87 | result = {'code': 200, 'data': balancesMap, 'msg': ''} 88 | return result 89 | 90 | # 调整开仓杠杆 Weight : 1 91 | def set_leverage( 92 | self, 93 | symbol: str, 94 | leverage: int = '', 95 | recvWindow: int = '' 96 | ) -> dict: 97 | ''' 98 | 99 | Name Type Mandatory Description 100 | symbol str YES 交易对 101 | leverage int YES 目标杠杆倍数 102 | ''' 103 | return self.cmAPI.accountTrade.set_leverage(**to_local(locals())) 104 | 105 | # 更改持仓模式 Weight : 1 106 | def set_marginType( 107 | self, 108 | symbol: str, 109 | marginType: Literal['ISOLATED', 'CROSSED'], 110 | recvWindow: int = '' 111 | ) -> dict: 112 | ''' 113 | https://binance-docs.github.io/apidocs/delivery/cn/#trade-12 114 | 115 | Name Type Mandatory Description 116 | symbol str YES 交易对 117 | marginType str YES 保证金模式 ISOLATED(逐仓), CROSSED(全仓) 118 | ''' 119 | result = self.cmAPI.accountTrade.set_marginType(**to_local(locals())) 120 | # 4046 NO_NEED_TO_CHANGE_MARGIN_TYPE 不需要切换仓位模式。 121 | if result['code'] in [-4046, 200]: 122 | result['code'] = 200 123 | return result 124 | 125 | # 获取全部产品的持仓信息 Weight: 5 126 | def get_positions(self,symbols=[]): 127 | ''' 128 | :param symbols: 获取的产品列表,空表示全部 129 | :return: 130 | ''' 131 | result = self.get_account() 132 | if result['code'] != 200: 133 | return result 134 | else: 135 | positions = { 136 | 'CROSSED': { 137 | 'LONG': [], 138 | 'SHORT': [], 139 | }, 140 | 'ISOLATED': { 141 | 'LONG': [], 142 | 'SHORT': [], 143 | } 144 | } 145 | for v in result['data']['positions']: 146 | if 'positionAmt' in v.keys() and float(v['positionAmt']) > 0: 147 | this_symbol = v['symbol'] 148 | if symbols and this_symbol not in symbols: 149 | continue 150 | if v['isolated'] == True: 151 | mode = 'ISOLATED' 152 | else: 153 | mode = 'CROSSED' 154 | posSide = v['positionSide'].upper() 155 | positions[mode][posSide].append(v) 156 | result['data'] = positions 157 | return result 158 | 159 | # 获取单个产品的持仓信息 Weight: 5 160 | def get_position(self, symbol: str) -> dict: 161 | result = self.get_positions() 162 | if result['code'] != 200: 163 | return result 164 | positions = { 165 | 'CROSSED': { 166 | 'LONG': {}, 167 | 'SHORT': {}, 168 | }, 169 | 'ISOLATED': { 170 | 'LONG': {}, 171 | 'SHORT': {}, 172 | } 173 | } 174 | for mode, mode_data in result['data'].items(): 175 | for posSide, posSide_datas in mode_data.items(): 176 | for posSide_data in posSide_datas: 177 | if posSide_data['symbol'] == symbol: 178 | positions[mode][posSide] = posSide_data 179 | result['data'] = positions 180 | return result 181 | 182 | 183 | # 获取全部产品的持仓信息字典 Weight: 5 184 | def get_positionsMap(self, symbols=[]) -> dict: 185 | ''' 186 | :param symbols: 获取的产品列表,空表示全部 187 | :return: 188 | ''' 189 | result = self.get_positions(symbols=symbols) 190 | if result['code'] != 200: 191 | return result 192 | positions = { 193 | 'CROSSED': { 194 | 'LONG': {}, 195 | 'SHORT': {}, 196 | }, 197 | 'ISOLATED': { 198 | 'LONG': {}, 199 | 'SHORT': {}, 200 | } 201 | } 202 | for mode, mode_data in result['data'].items(): 203 | for posSide, posSide_datas in mode_data.items(): 204 | for posSide_data in posSide_datas: 205 | symbol = posSide_data['symbol'] 206 | positions[mode][posSide][symbol] = posSide_data 207 | result['data'] = positions 208 | return result 209 | -------------------------------------------------------------------------------- /binance_interface/app/account/account_spot.py: -------------------------------------------------------------------------------- 1 | from paux.param import to_local 2 | from binance_interface.api.spot import SPOT 3 | from binance_interface.app import code 4 | from binance_interface.app import utils 5 | from binance_interface.app import exception 6 | 7 | 8 | class AccountSPOT(): 9 | 10 | def __init__(self, key: str, secret: str, proxies={}, proxy_host: str = None): 11 | self.spotAPI = SPOT(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 12 | 13 | # 获取账户信息 Weight: 20 14 | def get_account(self, recvWindow: int = '') -> dict: 15 | return self.spotAPI.account.get_account(**to_local(locals())) 16 | 17 | # 获取全部现货余额 Weight: 20 18 | def get_balances(self, assets=[]): 19 | ''' 20 | :param assets:获取的货币,空表示全部 21 | :return: 22 | ''' 23 | api_account_result = self.get_account() 24 | if api_account_result['code'] != 200: 25 | return api_account_result 26 | 27 | balances_result = {'code': 200, 'data': [], 'msg': ''} 28 | 29 | for balance in api_account_result['data']['balances']: 30 | this_asset = balance['asset'] 31 | if assets and this_asset not in assets: 32 | continue 33 | balances_result['data'].append(balance) 34 | return balances_result 35 | 36 | # 获取单个现货余额 Weight: 20 37 | def get_balance(self, asset: str = '', symbol: str = '', base_asset: str = ''): 38 | ''' 39 | :param asset: 货币名称 40 | :param symbol: 产品名称 41 | :param base_asset: 产品的交易基础货币 42 | asset与symbol不能同时为空 43 | 44 | 例如:对于产品:BTCUSDT,其中: 45 | asset = 'BTC' 46 | symbol = 'BTCUSDT' 47 | base_asset = 'USDT' 48 | ''' 49 | if not asset and not symbol: 50 | raise exception.ParamException('asset and symbol can not be empty together') 51 | if not asset: 52 | asset = utils.get_asset(symbol=symbol, base_asset=base_asset) 53 | account_result = self.get_account() 54 | if account_result['code'] != 200: 55 | return account_result 56 | for balance in account_result['data']['balances']: 57 | if balance['asset'] == asset: 58 | result = { 59 | 'code': 200, 60 | 'data': balance, 61 | 'msg': '' 62 | } 63 | return result 64 | else: 65 | msg = f'Can not find asset = {asset}' 66 | result = { 67 | 'code': code.ASSET_ERROR[0], 68 | 'data': {}, 69 | 'msg': msg, 70 | } 71 | return result 72 | 73 | # 获取全部现货余额字典 Weight: 20 74 | def get_balancesMap(self, assets=[]): 75 | ''' 76 | :param assets:获取的货币,空表示全部 77 | :return: 78 | ''' 79 | balances_result = self.get_balances(assets=assets) 80 | if not balances_result['code'] == 200: 81 | return balances_result 82 | balancesMap = {} 83 | for balance in balances_result['data']: 84 | balance: dict 85 | asset = balance['asset'] 86 | balancesMap[asset] = balance 87 | result = {'code': 200, 'data': balancesMap, 'msg': ''} 88 | return result 89 | -------------------------------------------------------------------------------- /binance_interface/app/account/account_um.py: -------------------------------------------------------------------------------- 1 | from typing import Literal, Union 2 | from paux.param import to_local 3 | from binance_interface.api.um import UM 4 | from binance_interface.app import code 5 | from binance_interface.app import utils 6 | from binance_interface.app import exception 7 | 8 | 9 | class AccountUM(): 10 | 11 | def __init__(self, key: str, secret: str, proxies={}, proxy_host: str = None): 12 | self.umAPI = UM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 13 | 14 | # 获取账户信息 Weight: 5 15 | def get_account(self, recvWindow: int = '') -> dict: 16 | return self.umAPI.accountTrade.get_account(**to_local(locals())) 17 | 18 | # 获取全部产品余额 Weight: 5 19 | def get_balances(self, assets=[]): 20 | ''' 21 | :param asset: 获取的货币,空表示全部 22 | :param recvWindow: 23 | :return: 24 | ''' 25 | api_balance_result = self.umAPI.accountTrade.get_balance() 26 | if not api_balance_result['code'] == 200: 27 | return api_balance_result 28 | balances_result = {'code': 200, 'data': [], 'msg': ''} 29 | for balance in api_balance_result['data']: 30 | this_asset = balance['asset'] 31 | if assets and this_asset not in assets: 32 | continue 33 | balances_result['data'].append(balance) 34 | return balances_result 35 | 36 | # 获取单个产品余额 Weight: 5 37 | def get_balance(self, asset: str = '', symbol: str = '', base_asset: str = ''): 38 | ''' 39 | :param asset: 货币名称 40 | :param symbol: 产品名称 41 | :param base_asset: 产品的交易基础货币 42 | asset与symbol不能同时为空 43 | 44 | 例如:对于产品:BTCUSDT,其中: 45 | asset = 'BTC' 46 | symbol = 'BTCUSDT' 47 | base_asset = 'USDT' 48 | ''' 49 | if not asset and not symbol: 50 | raise exception.ParamException('asset and symbol can not be empty together') 51 | if not asset: 52 | asset = utils.get_asset(symbol=symbol, base_asset=base_asset) 53 | balances_result = self.get_balances() 54 | if balances_result['code'] != 200: 55 | return balances_result 56 | for balance in balances_result['data']: 57 | if balance['asset'] == asset: 58 | result = { 59 | 'code': 200, 60 | 'data': balance, 61 | 'msg': '' 62 | } 63 | return result 64 | else: 65 | msg = f'Can not find asset = {asset}' 66 | result = { 67 | 'code': code.ASSET_ERROR[0], 68 | 'data': {}, 69 | 'msg': msg, 70 | } 71 | return result 72 | 73 | # 获取全部产品余额字典 Weight: 5 74 | def get_balancesMap(self, assets=[]): 75 | ''' 76 | :param assets: 获取的货币,空表示全部 77 | :return: 78 | ''' 79 | balances_result = self.get_balances(assets=assets) 80 | if not balances_result['code'] == 200: 81 | return balances_result 82 | balancesMap = {} 83 | for balance in balances_result['data']: 84 | balance: dict 85 | asset = balance['asset'] 86 | balancesMap[asset] = balance 87 | result = {'code': 200, 'data': balancesMap, 'msg': ''} 88 | return result 89 | 90 | # 调整开仓杠杆 Weight : 1 91 | def set_leverage( 92 | self, 93 | symbol: str, 94 | leverage: int = '', 95 | recvWindow: int = '' 96 | ) -> dict: 97 | ''' 98 | Name Type Mandatory Description 99 | symbol str YES 交易对 100 | leverage int YES 目标杠杆倍数 101 | ''' 102 | return self.umAPI.accountTrade.set_leverage(**to_local(locals())) 103 | 104 | # 更改持仓模式 Weight : 1 105 | def set_marginType( 106 | self, 107 | symbol: str, 108 | marginType: Literal['ISOLATED', 'CROSSED'], 109 | recvWindow: int = '' 110 | ) -> dict: 111 | ''' 112 | https://binance-docs.github.io/apidocs/delivery/cn/#trade-12 113 | 114 | Name Type Mandatory Description 115 | symbol str YES 交易对 116 | marginType str YES 保证金模式 ISOLATED(逐仓), CROSSED(全仓) 117 | ''' 118 | result = self.umAPI.accountTrade.set_marginType(**to_local(locals())) 119 | # 4046 NO_NEED_TO_CHANGE_MARGIN_TYPE 不需要切换仓位模式。 120 | if result['code'] in [-4046, 200]: 121 | result['code'] = 200 122 | return result 123 | 124 | # 获取全部产品的持仓信息 Weight: 5 125 | def get_positions(self, symbols=[]): 126 | ''' 127 | :param symbols: 获取的产品列表,空表示全部 128 | ''' 129 | result = self.get_account() 130 | if result['code'] != 200: 131 | return result 132 | else: 133 | positions = { 134 | 'CROSSED': { 135 | 'LONG': [], 136 | 'SHORT': [], 137 | }, 138 | 'ISOLATED': { 139 | 'LONG': [], 140 | 'SHORT': [], 141 | } 142 | } 143 | for v in result['data']['positions']: 144 | if 'positionAmt' in v.keys() and float(v['positionAmt']) > 0: 145 | this_symbol = v['symbol'] 146 | if symbols and this_symbol not in symbols: 147 | continue 148 | if v['isolated'] == True: 149 | mode = 'ISOLATED' 150 | else: 151 | mode = 'CROSSED' 152 | posSide = v['positionSide'].upper() 153 | positions[mode][posSide].append(v) 154 | result['data'] = positions 155 | return result 156 | 157 | # 获取单个产品的持仓信息 Weight: 5 158 | def get_position(self, symbol: str) -> dict: 159 | ''' 160 | :param symbol: 产品名称 161 | :return: 162 | ''' 163 | result = self.get_positions() 164 | if result['code'] != 200: 165 | return result 166 | positions = { 167 | 'CROSSED': { 168 | 'LONG': {}, 169 | 'SHORT': {}, 170 | }, 171 | 'ISOLATED': { 172 | 'LONG': {}, 173 | 'SHORT': {}, 174 | } 175 | } 176 | for mode, mode_data in result['data'].items(): 177 | for posSide, posSide_datas in mode_data.items(): 178 | for posSide_data in posSide_datas: 179 | if posSide_data['symbol'] == symbol: 180 | positions[mode][posSide] = posSide_data 181 | result['data'] = positions 182 | return result 183 | 184 | # 获取全部产品的持仓信息字典 Weight: 5 185 | def get_positionsMap(self, symbols=[]) -> dict: 186 | ''' 187 | :param symbols: 获取的产品列表,空表示全部 188 | :return: 189 | ''' 190 | result = self.get_positions(symbols=symbols) 191 | if result['code'] != 200: 192 | return result 193 | positions = { 194 | 'CROSSED': { 195 | 'LONG': {}, 196 | 'SHORT': {}, 197 | }, 198 | 'ISOLATED': { 199 | 'LONG': {}, 200 | 'SHORT': {}, 201 | } 202 | } 203 | for mode, mode_data in result['data'].items(): 204 | for posSide, posSide_datas in mode_data.items(): 205 | for posSide_data in posSide_datas: 206 | symbol = posSide_data['symbol'] 207 | positions[mode][posSide][symbol] = posSide_data 208 | result['data'] = positions 209 | return result 210 | -------------------------------------------------------------------------------- /binance_interface/app/candle_server/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.candle_server.rule import CandleRule 2 | from binance_interface.app.candle_server.server import CandleServer 3 | -------------------------------------------------------------------------------- /binance_interface/app/candle_server/rule.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | from candlelite.crypto.binace_lite import ( 3 | BINANCE_TIMEZONE, # 历史K线默认时区 4 | BINANCE_CANDLE_DATE_BASE_DIR, # 历史K线以日期为单位的默认存储路径 5 | BINANCE_DEFAULT_BAR, # 历史K线默认时间粒度 6 | ) 7 | 8 | 9 | class CandleRule(): 10 | # 服务占用权重上限的比例 现货交易权重上限1200 合约交易权重上限2400 11 | SERVER_WEIGHT = 0.75 12 | # 收集的产品 all表示全部正在交易的产品 13 | SYMBOLS: Union[str, list] = 'all' 14 | # 过滤的产品 15 | SYMBOLS_FILTER: list = [] 16 | # 产品名称中需要包含的内容 17 | SYMBOL_CONTAINS = '' 18 | # 产品名称必须以何内容结尾 19 | SYMBOL_ENDSWITH = '' 20 | # candle_map 更新时间间隔(秒) 21 | UPDATE_INTERVAL_SECONDS: int = 3 22 | # candle_map 缓存K线数据长度 23 | LENGTH: int = 1440 * 2 24 | # 时间颗粒度 25 | BAR: str = BINANCE_DEFAULT_BAR 26 | # candle_map 保存缓存文件时间间隔(秒) None:不保存缓存 27 | CACHE_DELAY_SECONDS: Union[int, None] = 60 * 60 28 | # 服务启动 需维护本地多少天的历史K线数据 29 | LOCAL_CANDLE_DAYS: int = 2 30 | # 每日下载昨日历史K线数据的时刻 格式:%H:%M:%S None表示不下载 31 | DOWNLOAD_TIME: Union[str,None] = '00:10:00' 32 | # 以天为单位的数据存储路径 33 | CANDLE_DIR = BINANCE_CANDLE_DATE_BASE_DIR 34 | # 缓存数据路径 35 | CACHE_DIR = './BINANCE_CACHE' 36 | # 时区 37 | TIMEZONE = BINANCE_TIMEZONE 38 | # KEY 通常无需填写 39 | KEY: str = None 40 | # SECRET 通常无需填写 41 | SECRET: str = None 42 | # 日志文件夹 43 | LOG_DIRPATH = './BINANCE_CANDLE_SERVER_LOG_DATA' 44 | # 日志文件级别 45 | LOG_FILE_LEVEL = 'INFO' 46 | # 日志打印级别 47 | LOG_CONSOLE_LEVEL = 'DEBUG' 48 | -------------------------------------------------------------------------------- /binance_interface/app/code/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.code.account import * 2 | from binance_interface.app.code.execute import * 3 | from binance_interface.app.code.market import * 4 | from binance_interface.app.code.trade import * 5 | -------------------------------------------------------------------------------- /binance_interface/app/code/account.py: -------------------------------------------------------------------------------- 1 | ASSET_ERROR = ['ASSET_ERROR', '找不到Asset'] 2 | -------------------------------------------------------------------------------- /binance_interface/app/code/execute.py: -------------------------------------------------------------------------------- 1 | FUNC_EXCEPTION = ['FUNC_EXCEPTION', 'Function execution error'] -------------------------------------------------------------------------------- /binance_interface/app/code/market.py: -------------------------------------------------------------------------------- 1 | # 交易对信息错误 2 | EXCHANGE_INFO_ERROR = ['EXCHANGE_INFO_ERROR', 'Transaction rules and transaction pair errors'] 3 | # 历史K线时间起点错误 4 | CANDLE_START_ERROR = ['CANDLE_START_ERROR', 'History candle start ts error'] 5 | # 历史K线时间终点错误 6 | CANDLE_END_ERROR = ['CANDLE_END_ERROR', 'History candle end ts error'] 7 | # 历史K线长度错误 8 | CANDLE_LENGTH_ERROR = ['CANDLE_LENGTH_ERROR', 'History candle length error'] 9 | # 历史K线时间间隔错误 10 | CANDLE_INTERVAL_ERROR = ['CANDLE_INTERVAL_ERROR', 'History candle ts interval error'] -------------------------------------------------------------------------------- /binance_interface/app/code/trade.py: -------------------------------------------------------------------------------- 1 | ROUND_QUANTITY_ERROR = ['ROUND_QUANTITY_ERROR', ' Trade quantity round error'] 2 | ROUND_PRICE_ERROR = ['ROUND_PRICE_ERROR', 'Trade price round error'] 3 | 4 | QUANTITY_TO_F_ERROR = ['QUANTITY_TO_F_ERROR', 'Trade quantity convert to string error'] 5 | PRICE_TO_F_ERROR = ['PRICE_TO_F_ERROR', 'Trade price convert to string error'] 6 | 7 | TRADE_BUY_TIMEOUT = ['TRADE_BUY_TIMEOUT', 'Not all transactions have been completed after the purchase time'] 8 | TRADE_SELL_TIMEOUT = ['TRADE_SELL_TIMEOUT', 'Not all transactions have been completed after the selling time'] 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /binance_interface/app/exception/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.exception.param import * 2 | from binance_interface.app.exception.req import * 3 | from binance_interface.app.exception.rule import * 4 | -------------------------------------------------------------------------------- /binance_interface/app/exception/_base.py: -------------------------------------------------------------------------------- 1 | class AbstractEXP(Exception): 2 | error_msg: str 3 | 4 | def __str__(self): 5 | return self.error_msg 6 | -------------------------------------------------------------------------------- /binance_interface/app/exception/param.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.exception._base import AbstractEXP 2 | 3 | 4 | class ParamException(AbstractEXP): 5 | def __init__(self, msg): 6 | self.error_msg = msg 7 | 8 | 9 | class ParamRoundPriceTypeException(AbstractEXP): 10 | def __init__(self, type, pmt='type must in ["CEIL","FLOOR"]'): 11 | self.error_msg = 'type = {type} \n{pmt}'.format( 12 | type=str(type), 13 | pmt=pmt, 14 | ) 15 | 16 | 17 | class ParamPositionSideException(AbstractEXP): 18 | def __init__(self, positionSide, pmt='positionSide must in ["LONG","SHORT"]'): 19 | self.error_msg = 'positionSide = {positionSide} \n{pmt}'.format( 20 | positionSide=str(positionSide), 21 | pmt=pmt, 22 | ) 23 | -------------------------------------------------------------------------------- /binance_interface/app/exception/req.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.exception._base import AbstractEXP 2 | 3 | 4 | # 请求状态码异常 5 | class CodeException(AbstractEXP): 6 | def __init__(self, msg): 7 | self.error_msg = msg 8 | 9 | 10 | # 请求异常 11 | class RequestException(AbstractEXP): 12 | def __init__(self, msg): 13 | self.error_msg = msg 14 | -------------------------------------------------------------------------------- /binance_interface/app/exception/rule.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.exception._base import AbstractEXP 2 | 3 | 4 | # 规则异常 5 | class RuleException(AbstractEXP): 6 | def __init__(self, msg): 7 | self.error_msg = msg 8 | -------------------------------------------------------------------------------- /binance_interface/app/market/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.market.ticker import Ticker # 实时价格 2 | from binance_interface.app.market.history_candle import HistoryCandle # 历史K线 3 | from binance_interface.app.market.exchange_info import ExchangeInfo # 交易对信息 4 | 5 | __all__ = ['Market', 'MarketSPOT', 'MarketUM', 'MarketCM'] 6 | 7 | 8 | class Market(HistoryCandle, Ticker, ExchangeInfo): 9 | pass 10 | 11 | 12 | class MarketSPOT(Market): 13 | def __init__(self, key: str = '', secret: str = '', timezone: str = 'America/New_York', proxies={}, proxy_host: str = None, ): 14 | instType = 'SPOT' 15 | super(MarketSPOT, self).__init__(instType=instType, key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 16 | 17 | 18 | class MarketUM(Market): 19 | def __init__(self, key: str = '', secret: str = '', timezone: str = 'America/New_York',proxies={}, proxy_host: str = None, ): 20 | instType = 'UM' 21 | super(MarketUM, self).__init__(instType=instType, key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 22 | 23 | 24 | class MarketCM(Market): 25 | def __init__(self, key: str = '', secret: str = '', timezone: str = 'America/New_York',proxies={}, proxy_host: str = None, ): 26 | instType = 'CM' 27 | super(MarketCM, self).__init__(instType=instType, key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 28 | -------------------------------------------------------------------------------- /binance_interface/app/market/_base.py: -------------------------------------------------------------------------------- 1 | from typing import Literal 2 | from binance_interface.app import exception 3 | from binance_interface.api.spot.spot_market import SPOTMarket 4 | from binance_interface.api.um.um_market import UMMarket 5 | from binance_interface.api.cm.cm_market import CMMarket 6 | from binance_interface.api.eo.eo_market import EOMarket 7 | 8 | 9 | # 市场信息基类 10 | class MarketBase(): 11 | 12 | def __init__( 13 | self, 14 | instType: Literal['SPOT', 'UM', 'CM'], 15 | key: str = '', 16 | secret: str = '', 17 | timezone='America/New_York', 18 | proxies={}, 19 | proxy_host: str = None, 20 | ): 21 | ''' 22 | 主要为了处理inst 23 | instType = 'SPOT' self.inst -> self.spot 24 | instType = 'UM' self.inst -> self.um 25 | instType = 'CM' self.inst -> self.cm 26 | 27 | :param instType: 产品类型 28 | SPOT: 现货 29 | UM: U本位合约 30 | CM: 币本位合约 31 | :param key: API KEY 可以不填写 32 | :param secret: API SECRET 可以不填写 33 | :param timezone: 时区 34 | America/New_York: 美国时间 35 | Asia/Shanghai: 中国时间 36 | ''' 37 | # 时区与产品类别 38 | self.timezone = timezone 39 | self.instType = instType.upper() 40 | # inst 41 | if self.instType == 'SPOT': # 现货交易 42 | self.marketAPI = SPOTMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 43 | elif self.instType == 'UM': # U本位 44 | self.marketAPI = UMMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 45 | elif self.instType == 'CM': # 币本位 46 | self.marketAPI = CMMarket(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 47 | else: 48 | msg = '[instType error] your input instType={instType} instType must in ["SPOT","UM","CM"]'.format( 49 | instType=str(instType) 50 | ) 51 | raise exception.ParamException(msg) 52 | -------------------------------------------------------------------------------- /binance_interface/app/market/exchange_info.py: -------------------------------------------------------------------------------- 1 | import time 2 | from binance_interface.app import code 3 | from binance_interface.app.market._base import MarketBase 4 | 5 | __all__ = ['ExchangeInfo'] 6 | 7 | 8 | # 交易规则与交易对信息 9 | class ExchangeInfo(MarketBase): 10 | ''' 11 | 现货 12 | https://binance-docs.github.io/apidocs/spot/cn/#e7746f7d60 13 | U本位合约 14 | https://binance-docs.github.io/apidocs/futures/cn/#0f3f2d5ee7 15 | 币本位合约 16 | https://binance-docs.github.io/apidocs/delivery/cn/#185368440e 17 | ''' 18 | 19 | # 以缓存的方式获取全部产品的交易规则与交易对 20 | # Weight: 现货10 合约1 使用缓存0 21 | def get_exchangeInfos( 22 | self, 23 | expire_seconds: int = 60 * 5 24 | ) -> dict: 25 | ''' 26 | :param expire_seconds: 缓存时间(秒) 27 | 28 | 29 | 使用的缓存数据格式: 30 | self._exchangeInfo_cache = [ 31 | { 32 | 'code':<状态码>, 33 | 'data':, 34 | 'msg':<提示信息>, 35 | }, 36 | <上次更新的毫秒时间戳> 37 | ] 38 | ''' 39 | if ( 40 | # 无缓存数据 41 | not hasattr(self, '_exchangeInfo_caches') 42 | or 43 | # 缓存数据过期 44 | getattr(self, '_exchangeInfo_caches')[1] - time.time() * 1000 >= expire_seconds 45 | ): 46 | # 更新数据并设置时间戳 47 | setattr(self, '_exchangeInfo_caches', [self.marketAPI.get_exchangeInfo(), time.time() * 1000]) 48 | # 返回缓存数据 49 | return getattr(self, '_exchangeInfo_caches')[0] 50 | 51 | # 以缓存的方式获取一个产品的交易规则与交易对 52 | # Weight: 现货10 合约1 使用缓存0 53 | def get_exchangeInfo( 54 | self, 55 | symbol: str, 56 | expire_seconds: int = 60 * 5, 57 | ) -> dict: 58 | ''' 59 | :param symbol: 产品 60 | :param expire_seconds: 缓存时间(秒) 61 | ''' 62 | exchangeInfos_result = self.get_exchangeInfos(expire_seconds) 63 | # [ERROR RETURN] 异常交易规则与交易 64 | if exchangeInfos_result['code'] != 200: 65 | return exchangeInfos_result 66 | # 寻找symbol的信息 67 | for symbol_data in exchangeInfos_result['data']['symbols']: 68 | if symbol_data['symbol'] == symbol: 69 | symbol_data = symbol_data 70 | break 71 | else: 72 | symbol_data = None 73 | # [ERROR RETURN] 没有找到symbol的交易规则与交易对信息 74 | if symbol_data == None: 75 | result = { 76 | 'code': code.EXCHANGE_INFO_ERROR[0], 77 | 'data': exchangeInfos_result['data'], 78 | 'msg': f'Symbol not found symbol={symbol}' 79 | } 80 | return result 81 | # 将filters中的列表转换为字典,里面可能包含下单价格与数量精度 82 | symbol_data['filter'] = {} 83 | for filter_data in symbol_data['filters']: 84 | symbol_data['filter'][ 85 | filter_data['filterType'] 86 | ] = filter_data 87 | # [RETURN] 88 | result = { 89 | 'code': 200, 90 | 'data': symbol_data, 91 | 'msg': '', 92 | } 93 | return result 94 | 95 | # 获取可以交易的产品列表 96 | # Weight: 现货10 合约1 使用缓存0 97 | def get_symbols_trading_on( 98 | self, 99 | expire_seconds: int = 60 * 5 100 | ) -> dict: 101 | ''' 102 | :param expire_seconds: 缓存时间(秒) 103 | ''' 104 | exchangeInfos_result = self.get_exchangeInfos(expire_seconds) 105 | # [ERROR RETURN] 异常交易规则与交易 106 | if exchangeInfos_result['code'] != 200: 107 | return exchangeInfos_result 108 | # 正在交易的产品名称 status == 'TRADING' 109 | if self.instType == 'CM': # 币本位合约交易的状态名称特殊 110 | status_name = 'contractStatus' 111 | else: 112 | status_name = 'status' 113 | symbols = [ 114 | data['symbol'] 115 | for data in exchangeInfos_result['data']['symbols'] 116 | if data[status_name] == 'TRADING' 117 | ] 118 | # [RETURN] 119 | result = { 120 | 'code': 200, 121 | 'data': symbols, 122 | 'msg': '' 123 | } 124 | return result 125 | 126 | # 获取不可交易的产品列表 127 | # Weight: 现货10 合约1 使用缓存0 128 | def get_symbols_trading_off( 129 | self, 130 | expire_seconds: int = 60 * 5 131 | ) -> dict: 132 | ''' 133 | :param expire_seconds: 缓存时间(秒) 134 | ''' 135 | 136 | exchangeInfos_result = self.get_exchangeInfos(expire_seconds) 137 | # [ERROR RETURN] 异常交易规则与交易 138 | if exchangeInfos_result['code'] != 200: 139 | return exchangeInfos_result 140 | # 不可交易的产品名称 status != 'TRADING' 141 | if self.instType == 'CM': # 币本位合约交易的状态名称特殊 142 | status_name = 'contractStatus' 143 | else: 144 | status_name = 'status' 145 | 146 | symbols = [ 147 | data['symbol'] 148 | for data in exchangeInfos_result['data']['symbols'] 149 | if data[status_name] != 'TRADING' 150 | ] 151 | # [RETURN] 152 | result = { 153 | 'code': 200, 154 | 'data': symbols, 155 | 'msg': '' 156 | } 157 | return result 158 | 159 | # 获取全部的产品列表 160 | # Weight: 现货10 合约1 使用缓存0 161 | def get_symbols_all( 162 | self, 163 | expire_seconds: int = 60 * 5 164 | ) -> dict: 165 | ''' 166 | :param expire_seconds: 缓存时间(秒) 167 | ''' 168 | 169 | exchangeInfos_result = self.get_exchangeInfos(expire_seconds) 170 | # [ERROR RETURN] 异常交易规则与交易 171 | if exchangeInfos_result['code'] != 200: 172 | return exchangeInfos_result 173 | symbols = [ 174 | data['symbol'] 175 | for data in exchangeInfos_result['data']['symbols'] 176 | ] 177 | # [RETURN] 178 | result = { 179 | 'code': 200, 180 | 'data': symbols, 181 | 'msg': '' 182 | } 183 | return result 184 | -------------------------------------------------------------------------------- /binance_interface/app/market/ticker.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.market._base import MarketBase 2 | from typing import Union 3 | 4 | __all__ = ['Ticker'] 5 | 6 | 7 | class Ticker(MarketBase): 8 | 9 | # 获取全部产品的最优挂单 10 | # Weight: 现货 2 合约 5 11 | def get_bookTickers(self, symbols=[]) -> dict: 12 | ''' 13 | :param symbols: 获取的产品名称,空为全部产品 14 | 15 | 现货 16 | https://binance-docs.github.io/apidocs/spot/cn/#5393cd07b4 17 | U本位合约 18 | https://binance-docs.github.io/apidocs/futures/cn/#5393cd07b4 19 | 币本位合约 20 | https://binance-docs.github.io/apidocs/delivery/cn/#5393cd07b4 21 | ''' 22 | api_bookTicker_result = self.marketAPI.get_ticker_bookTicker() 23 | if not api_bookTicker_result['code'] == 200: 24 | return api_bookTicker_result 25 | 26 | bookTicker_result = {'code': 200, 'data': [], 'msg': ''} 27 | for ticker in api_bookTicker_result['data']: 28 | this_symbol = ticker['symbol'] 29 | if symbols and this_symbol not in symbols: 30 | continue 31 | bookTicker_result['data'].append(ticker) 32 | 33 | return bookTicker_result 34 | 35 | # 获取全部产品的最优挂单 (字典格式) 36 | # Weight: 现货 2 合约 5 37 | def get_bookTickersMap(self, symbols=[]) -> dict: 38 | ''' 39 | :param symbols: 获取的产品名称,空为全部产品 40 | :return: 41 | ''' 42 | get_bookTickers_result = self.get_bookTickers(symbols=symbols) 43 | # [ERROR RETURN] 数据异常 44 | if get_bookTickers_result['code'] != 200: 45 | return get_bookTickers_result 46 | data_map = {} 47 | for ticker in get_bookTickers_result['data']: 48 | symbol = ticker['symbol'] 49 | data_map[symbol] = ticker 50 | 51 | get_bookTickers_result['data'] = data_map 52 | return get_bookTickers_result 53 | 54 | # 获取一个产品的最优挂单 55 | # Weight: 现货 1 合约 2 56 | def get_bookTicker(self, symbol: str) -> dict: 57 | ''' 58 | 现货 59 | https://binance-docs.github.io/apidocs/spot/cn/#5393cd07b4 60 | U本位合约 61 | https://binance-docs.github.io/apidocs/futures/cn/#5393cd07b4 62 | 币本位合约 63 | https://binance-docs.github.io/apidocs/delivery/cn/#5393cd07b4 64 | :param symbol: 产品 65 | ''' 66 | bookTicker_result = self.marketAPI.get_ticker_bookTicker(symbol=symbol) 67 | if not bookTicker_result['code'] == 200: 68 | return bookTicker_result 69 | # 兼容CM 70 | if type(bookTicker_result['data']) == list: 71 | bookTicker_result['data'] = bookTicker_result['data'][0] 72 | return bookTicker_result 73 | 74 | # 获取全部产品的最新价格 75 | # Weight: 2 76 | def get_tickerPrices(self, symbols=[]): 77 | ''' 78 | :param symbols: 获取的产品列表,空表示全部 79 | 80 | 现货 81 | https://binance-docs.github.io/apidocs/spot/cn/#8ff46b58de 82 | U本位合约 83 | https://binance-docs.github.io/apidocs/futures/cn/#8ff46b58de 84 | 币本位合约 85 | https://binance-docs.github.io/apidocs/delivery/cn/#8ff46b58de 86 | ''' 87 | api_ticker_price_result = self.marketAPI.get_ticker_price(symbol='') 88 | if not api_ticker_price_result['code'] == 200: 89 | return api_ticker_price_result 90 | ticker_price_result = {'code': 200, 'data': [], 'msg': ''} 91 | for ticker in api_ticker_price_result['data']: 92 | this_symbol = ticker['symbol'] 93 | if symbols and this_symbol not in symbols: 94 | continue 95 | ticker_price_result['data'].append(ticker) 96 | 97 | return ticker_price_result 98 | 99 | # 获取全部产品的最新价格 (字典格式) 100 | # Weight: 2 101 | def get_tickerPricesMap(self, symbols=[]): 102 | ''' 103 | :param symbols: 获取的产品列表,空表示全部 104 | ''' 105 | get_tickerPrices_result = self.get_tickerPrices(symbols=symbols) 106 | # [ERROR RETURN] 数据异常 107 | if get_tickerPrices_result['code'] != 200: 108 | return get_tickerPrices_result 109 | data_map = {} 110 | for ticker in get_tickerPrices_result['data']: 111 | symbol = ticker['symbol'] 112 | data_map[symbol] = ticker 113 | 114 | get_tickerPrices_result['data'] = data_map 115 | return get_tickerPrices_result 116 | 117 | # 获取一个产品的最新价格 118 | # Weight: 1 119 | def get_tickerPrice(self, symbol: str): 120 | ''' 121 | 现货 122 | https://binance-docs.github.io/apidocs/spot/cn/#8ff46b58de 123 | U本位合约 124 | https://binance-docs.github.io/apidocs/futures/cn/#8ff46b58de 125 | 币本位合约 126 | https://binance-docs.github.io/apidocs/delivery/cn/#8ff46b58de 127 | :param symbol: 产品 128 | ''' 129 | return self.marketAPI.get_ticker_price(symbol=symbol) 130 | 131 | # 深度信息 132 | def get_depth(self, symbol: str, limit: Union[int, str] = ''): 133 | ''' 134 | 现货 135 | https://binance-docs.github.io/apidocs/spot/cn/#38a975b802 136 | U本位合约 137 | https://binance-docs.github.io/apidocs/futures/cn/#38a975b802 138 | 币本位合约 139 | https://binance-docs.github.io/apidocs/delivery/cn/#38a975b802 140 | :param symbol: 产品 141 | :param limit: 数量 142 | ''' 143 | return self.marketAPI.get_depth(symbol=symbol, limit=limit) 144 | -------------------------------------------------------------------------------- /binance_interface/app/trade/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.trade.trade_spot import TradeSPOT 2 | from binance_interface.app.trade.trade_um import TradeUM 3 | from binance_interface.app.trade.trade_cm import TradeCM 4 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_cm/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.trade.trade_cm.open import TradeOpen 2 | from binance_interface.app.trade.trade_cm.close import TradeClose 3 | 4 | 5 | class TradeCM(TradeOpen, TradeClose): 6 | pass 7 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_cm/_base.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.account import AccountCM 2 | from binance_interface.app.market import MarketCM 3 | from binance_interface.api.cm import CM 4 | 5 | 6 | class TradeCMBase(): 7 | def __init__( 8 | self, 9 | key: str, 10 | secret: str, 11 | timezone: str = 'America/New_York', 12 | account=None, 13 | market=None, 14 | proxies={}, 15 | proxy_host: str = None, 16 | ): 17 | if not account: 18 | self._account = AccountCM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | else: 20 | self._account = account 21 | 22 | if not market: 23 | self._market = MarketCM(key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 24 | else: 25 | self._market = market 26 | self.timezone = timezone 27 | self.cmAPI = CM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 28 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_spot/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.trade.trade_spot.open import TradeOpen 2 | from binance_interface.app.trade.trade_spot.close import TradeClose 3 | 4 | 5 | class TradeSPOT(TradeOpen, TradeClose): 6 | pass 7 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_spot/_base.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.account import AccountSPOT 2 | from binance_interface.app.market import MarketSPOT 3 | from binance_interface.api.spot import SPOT 4 | 5 | 6 | class TradeSPOTBase(): 7 | def __init__( 8 | self, 9 | key: str, 10 | secret: str, 11 | timezone: str = 'America/New_York', 12 | account=None, 13 | market=None, 14 | proxies={}, 15 | proxy_host: str = None, 16 | ): 17 | if not account: 18 | self._account = AccountSPOT(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | else: 20 | self._account = account 21 | 22 | if not market: 23 | self._market = MarketSPOT(key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 24 | else: 25 | self._market = market 26 | self.timezone = timezone 27 | self.spotAPI = SPOT(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 28 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_spot/order.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import paux.date 3 | from typing import Union 4 | from binance_interface.app.trade.trade_spot._base import TradeSPOTBase 5 | from paux.param import to_local 6 | import time 7 | 8 | 9 | class TradeOrder(TradeSPOTBase): 10 | # 订单状态 11 | class ORDER_STATUS(): 12 | NEW = 'NEW' # 新建订单 13 | PARTIALLY_FILLED = 'PARTIALLY_FILLED' # 部分成交 14 | FILLED = 'FILLED' # 全部成交 15 | CANCELED = 'CANCELED' # 已撤销 16 | REJECTED = 'REJECTED' # 订单被拒绝 17 | EXPIRED = 'EXPIRED' # 订单过期(根据timeInForce参数规则) 18 | 19 | # 下单 (TRADE) Weight : 1 20 | def set_order( 21 | self, 22 | symbol: str, 23 | side: str, 24 | type: str, 25 | timeInForce: str = '', 26 | quantity: Union[float, int, str] = '', 27 | quoteOrderQty: Union[float, int, str] = '', 28 | price: Union[float, int, str] = '', 29 | newClientOrderId: str = '', 30 | stopPrice: Union[float, int, str] = '', 31 | trailingDelta: int = '', 32 | icebergQty: Union[float, int, str] = '', 33 | newOrderRespType: str = '', 34 | strategyId: int = '', 35 | strategyType: int = '', 36 | recvWindow: int = '' 37 | ): 38 | ''' 39 | https://binance-docs.github.io/apidocs/spot/cn/#trade-3 40 | 41 | Name Type Mandatory Description 42 | symbol str YES 43 | side str YES 详见枚举定义:订单方向 44 | type str YES 详见枚举定义:订单类型 45 | timeInForce str NO 详见枚举定义:有效方式 46 | quantity Union[float,int] NO 47 | quoteOrderQty Union[float,int] NO 48 | price Union[float,int] NO 49 | newClientOrderId str NO 客户自定义的唯一订单ID。 如果未发送,则自动生成 50 | stopPrice Union[float,int] NO 51 | trailingDelta int NO 52 | icebergQty Union[float,int] NO 53 | newOrderRespType str NO 设置响应JSON。 ACK,RESULT或FULL; "MARKET"和" LIMIT"订单类型默认为"FULL",所有其他订单默认为"ACK"。 54 | strategyId int NO 55 | strategyType int NO 56 | recvWindow int NO 57 | 58 | :param side: 买卖方向 59 | BUY: 购买 60 | SELL: 卖出 61 | :param timeInForce: 有效方法 限价单必须填写,市价单无需填写 62 | GTC: 成交为止, 一直有效 63 | IOC: 无法立即成交(吃单)的部分就撤销 64 | FOK: 无法全部立即成交就撤销 65 | GTX: 无法成为挂单方就撤销 66 | ''' 67 | 68 | return self.spotAPI.trade.set_order(**to_local(locals())) 69 | 70 | # 查询订单 (USER_DATA) Weight : 2 71 | def get_order( 72 | self, 73 | symbol: str, 74 | orderId: int = '', 75 | origClientOrderId: str = '', 76 | recvWindow: int = '' 77 | ): 78 | ''' 79 | https://binance-docs.github.io/apidocs/spot/cn/#user_data-20 80 | 81 | Name Type Mandatory Description 82 | symbol str YES 83 | orderId int NO 84 | origClientOrderId str NO 85 | recvWindow int NO 86 | 87 | 系统订单号和用户订单号不能同时为空 88 | 请注意,如果订单满足如下条件,不会被查询到: 89 | 订单的最终状态为 CANCELED 或者 EXPIRED 90 | 并且 91 | 订单没有任何的成交记录 92 | 并且 93 | 订单生成时间 + 7天 < 当前时间 94 | ''' 95 | return self.spotAPI.trade.get_order(**to_local(locals())) 96 | 97 | # 查看当前挂单 (USER_DATA) Weight 1 | 80 98 | def get_orders_pending( 99 | self, 100 | symbol: str = '', 101 | start: Union[str, int, float, datetime.datetime] = '', 102 | end: Union[str, int, float, datetime.datetime] = '', 103 | recvWindow: int = '', 104 | ): 105 | ''' 106 | :param symbol: 产品ID 107 | :param start: 订单起始时间需>=start 108 | :param end: 订单终止时间需<=end 109 | 110 | 权重: 111 | 6 单一交易对 112 | 80 交易对参数缺失 113 | ''' 114 | result = self.spotAPI.trade.get_openOrders( 115 | symbol=symbol,recvWindow=recvWindow, 116 | ) 117 | if not result['code'] == 200: 118 | return result 119 | if start: 120 | start = paux.date.to_ts(start, timezone=self.timezone) 121 | if end: 122 | end = paux.date.to_ts(end, timezone=self.timezone) 123 | data2 = [] 124 | for data in result['data']: 125 | if start and not data['time'] >= start: 126 | continue 127 | if end and not data['time'] <= end: 128 | continue 129 | data2.append(data) 130 | result['data'] = data2 131 | return result 132 | 133 | # 查看当前购买挂单 (USER_DATA) Weight 1 | 80 134 | def get_orders_pending_open( 135 | self, 136 | symbol: str = '', 137 | start: Union[str, int, float, datetime.datetime] = '', 138 | end: Union[str, int, float, datetime.datetime] = '', 139 | recvWindow: int = '', 140 | ): 141 | result = self.get_orders_pending( 142 | symbol=symbol, start=start, end=end, recvWindow=recvWindow 143 | ) 144 | if not result['code'] == 200: 145 | return result 146 | SIDE = 'BUY' 147 | data_open = [] 148 | for data in result['data']: 149 | if data['side'] == SIDE: 150 | data_open.append(data) 151 | result['data'] = data_open 152 | return result 153 | 154 | # 查看当前卖出挂单 (USER_DATA) Weight 1 | 80 155 | def get_orders_pending_close( 156 | self, 157 | symbol: str = '', 158 | start: Union[str, int, float, datetime.datetime] = '', 159 | end: Union[str, int, float, datetime.datetime] = '', 160 | recvWindow: int = '', 161 | ): 162 | result = self.get_orders_pending( 163 | symbol=symbol, start=start, end=end, recvWindow=recvWindow 164 | ) 165 | if not result['code'] == 200: 166 | return result 167 | SIDE = 'SELL' 168 | data_open = [] 169 | for data in result['data']: 170 | if data['side'] == SIDE: 171 | data_open.append(data) 172 | result['data'] = data_open 173 | return result 174 | 175 | # 撤销订单 (TRADE) Weight : 1 176 | def cancel_order( 177 | self, 178 | symbol: str, 179 | orderId: int = '', 180 | origClientOrderId: str = '', 181 | newClientOrderId: str = '', 182 | recvWindow: int = '' 183 | ): 184 | ''' 185 | https://binance-docs.github.io/apidocs/spot/cn/#trade-4 186 | 187 | Name Type Mandatory Description 188 | symbol str YES 交易对 189 | orderId int NO 系统订单号 190 | origClientOrderId str NO 用户自定义的订单号 191 | newClientOrderId str NO 用户自定义的本次撤销操作的ID(注意不是被撤销的订单的自定义ID)。如无指定会自动赋值。 192 | recvWindow int NO 193 | 194 | orderId 与 origClientOrderId 必须至少发送一个 195 | ''' 196 | return self.spotAPI.trade.cancel_order(**to_local(locals())) 197 | 198 | # 等待订单成交 199 | def wait_order_FILLED(self, symbol: str, orderId: int = '', origClientOrderId: str = '', timeout=60, delay=0.2): 200 | start_time = time.time() 201 | while True: 202 | # 查询订单 203 | order_result = self.get_order(symbol=symbol, orderId=orderId, origClientOrderId=origClientOrderId) 204 | # [ERROR_RETURN] code异常 205 | if order_result['code'] != 200: 206 | return order_result 207 | # [SUCCESS_RETURN] 全部成交 208 | if order_result['data']['status'] == self.ORDER_STATUS.FILLED: 209 | return order_result 210 | # [TIMEOUT_RETURN] 超时 211 | if time.time() - start_time >= timeout: 212 | return order_result 213 | time.sleep(delay) 214 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_spot/quantity_and_price.py: -------------------------------------------------------------------------------- 1 | from typing import Literal, Union 2 | from paux import order as _order 3 | from paux.digit import origin_float 4 | from binance_interface.app.trade.trade_spot._base import TradeSPOTBase 5 | from binance_interface.app import exception 6 | from binance_interface.app import code 7 | 8 | 9 | class TradeQuantityAndPrice(TradeSPOTBase): 10 | # 下单数量圆整 11 | # Weight 0 | 1 12 | def round_quantity( 13 | self, 14 | quantity: Union[int, float, str, origin_float], 15 | symbol: str, 16 | stepSize: str = None, 17 | minQty: str = None, 18 | maxQty: str = None, 19 | expire_seconds=60 * 5, 20 | ) -> dict: 21 | ''' 22 | :param quantity: 下单数量 23 | :param symbol: 合约产品 24 | :param stepSize: 订单最小数量间隔 25 | :param minQty: 最小数量 26 | :param maxQty: 最大数量 27 | :param use_cache: 使用缓存获取交易规则和交易对信息 28 | :param expire_seconds: 缓存过期时间 (秒) 29 | 30 | stepSize minQty maxQty任意为空,通过market.exchangeInfo获取交易规则与交易对信息 31 | ''' 32 | 33 | # 填充stepSize minQty maxQty 34 | if stepSize in [None, ''] or minQty in [None, ''] or maxQty in [None, '']: 35 | exchangeInfo = self._market.get_exchangeInfo( 36 | symbol=symbol, 37 | expire_seconds=expire_seconds 38 | ) 39 | if exchangeInfo['code'] != 200: 40 | return exchangeInfo 41 | if stepSize in [None, '']: 42 | stepSize = exchangeInfo['data']['filter']['LOT_SIZE']['stepSize'] 43 | if minQty in [None, '']: 44 | minQty = exchangeInfo['data']['filter']['LOT_SIZE']['minQty'] 45 | if maxQty in [None, '']: 46 | maxQty = exchangeInfo['data']['filter']['LOT_SIZE']['maxQty'] 47 | # code = 0 | -1 | -2 48 | round_quantity_result = _order.round_quantity( 49 | quantity=quantity, 50 | stepSize=stepSize, 51 | minQty=minQty, 52 | maxQty=maxQty 53 | ) 54 | # code -> [200,code.ROUND_QUANTITY_ERROR[0]] 55 | if round_quantity_result['code'] == 0: 56 | round_quantity_result['code'] = 200 57 | else: 58 | round_quantity_result['code'] = code.ROUND_QUANTITY_ERROR[0] 59 | round_quantity_result['msg'] = f'symbol={symbol} ' + round_quantity_result['msg'] 60 | return round_quantity_result 61 | 62 | # 价格圆整 63 | # Weight 0 | 1 64 | def round_price( 65 | self, 66 | price: Union[int, float], 67 | symbol: str, 68 | type: Literal['CEIL', 'FLOOR', 'ceil', 'floor'], 69 | tickSize: str = None, 70 | minPrice: str = None, 71 | maxPrice: str = None, 72 | expire_seconds=60 * 5, 73 | ) -> dict: 74 | ''' 75 | :param price: 价格 76 | :param symbol: 合约产品 77 | :param type: 圆整方式 78 | CEIL: 向上圆整 79 | FLOOR: 向下圆整 80 | :param tickSize: 订单价格的最小间隔 81 | :param minPrice: 最小价格 82 | :param maxPrice: 最大价格 83 | :param use_cache: 使用缓存获取交易规则和交易对信息 84 | :param expire_seconds: 缓存过期时间 (秒) 85 | 86 | tickSize minPrice maxPrice任意为空,通过market.exchangeInfo获取交易规则与交易对信息 87 | ''' 88 | # 验证type 89 | if type not in ['CEIL', 'FLOOR']: 90 | raise exception.ParamRoundPriceTypeException(type=type) 91 | # tickSize maxPrice minPrice 92 | if tickSize in [None, ''] or maxPrice in [None, ''] or minPrice in [None, '']: 93 | exchangeInfo = self._market.get_exchangeInfo( 94 | symbol=symbol, 95 | expire_seconds=expire_seconds 96 | ) 97 | if exchangeInfo['code'] != 200: 98 | return exchangeInfo 99 | if tickSize in [None, '']: 100 | tickSize = exchangeInfo['data']['filter']['PRICE_FILTER']['tickSize'] 101 | if minPrice in [None, '']: 102 | minPrice = exchangeInfo['data']['filter']['PRICE_FILTER']['minPrice'] 103 | if maxPrice in [None, '']: 104 | maxPrice = exchangeInfo['data']['filter']['PRICE_FILTER']['maxPrice'] 105 | # code = 0 | -1 | -2 106 | round_price_result = _order.round_price( 107 | price=price, 108 | type=type, 109 | tickSize=tickSize, 110 | minPrice=minPrice, 111 | maxPrice=maxPrice 112 | ) 113 | # code -> [200,code.ROUND_PRICE_ERROR[0]] 114 | if round_price_result['code'] == 0: 115 | round_price_result['code'] = 200 116 | else: 117 | round_price_result['code'] = code.ROUND_PRICE_ERROR[0] 118 | round_price_result['msg'] = f'symbol={symbol} ' + round_price_result['msg'] 119 | return round_price_result 120 | 121 | # 根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量 122 | # Weight 0 | 1 123 | def get_quantity( 124 | self, 125 | openPrice: Union[int, float], 126 | openMoney: Union[int, float], 127 | symbol: str, 128 | stepSize: str = None, 129 | leverage: int = 1, 130 | minQty: str = None, 131 | maxQty: str = None, 132 | expire_seconds=60 * 5, 133 | ) -> dict: 134 | ''' 135 | :param openPrice: 开仓价格 136 | :param openMoney: 开仓金额 137 | :param symbol: 合约产品 138 | :param stepSize: 订单最小数量间隔 139 | :param leverage: 杠杆数量 140 | :param minQty: 最小数量 141 | :param maxQty: 最大数量 142 | :param use_cache: 使用缓存获取交易规则和交易对信息 143 | :param expire_seconds: 缓存过期时间 (秒) 144 | 145 | stepSize minQty maxQty任意为空,通过market.exchangeInfo获取交易规则与交易对信息 146 | ''' 147 | # stepSize minQty maxQty 148 | if stepSize in [None, ''] or minQty in [None, ''] or maxQty in [None, '']: 149 | exchangeInfo = self._market.get_exchangeInfo( 150 | symbol=symbol, 151 | expire_seconds=expire_seconds 152 | ) 153 | if exchangeInfo['code'] != 200: 154 | return exchangeInfo 155 | if stepSize in [None, '']: 156 | stepSize = exchangeInfo['data']['filter']['LOT_SIZE']['stepSize'] 157 | if minQty in [None, '']: 158 | minQty = exchangeInfo['data']['filter']['LOT_SIZE']['minQty'] 159 | if maxQty in [None, '']: 160 | maxQty = exchangeInfo['data']['filter']['LOT_SIZE']['maxQty'] 161 | # 未圆整的下单数量 162 | quantity = openMoney * leverage / openPrice 163 | # 返回圆整结果 164 | return self.round_quantity( 165 | quantity=quantity, 166 | symbol=symbol, 167 | stepSize=stepSize, 168 | minQty=minQty, 169 | maxQty=maxQty, 170 | expire_seconds=expire_seconds, 171 | ) 172 | 173 | # 将下单数量转化为字符串 174 | # Weight 0 | 1 175 | def quantity_to_f( 176 | self, 177 | quantity: Union[int, float], 178 | symbol: str, 179 | stepSize: str = None, 180 | expire_seconds=60 * 5, 181 | 182 | ) -> dict: 183 | ''' 184 | :param quantity: 下单数量 185 | :param symbol: 合约产品 186 | :param stepSize: 订单最小数量间隔 187 | :param use_cache: 使用缓存获取交易规则和交易对信息 188 | :param expire_seconds: 缓存过期时间 (秒) 189 | 190 | stepSize为空,通过market.exchangeInfo获取交易规则与交易对信息 191 | ''' 192 | # stepSize 193 | if stepSize in [None, '']: 194 | exchangeInfo = self._market.get_exchangeInfo( 195 | symbol=symbol, 196 | expire_seconds=expire_seconds 197 | ) 198 | if exchangeInfo['code'] != 200: 199 | return exchangeInfo 200 | stepSize = exchangeInfo['data']['filter']['LOT_SIZE']['stepSize'] 201 | # code : 0 | -1 202 | quantity_to_f_result = _order.quantity_to_f( 203 | quantity=quantity, 204 | stepSize=stepSize, 205 | ) 206 | # code -> [200,code.QUANTITY_TO_F_ERROR[0]] 207 | if quantity_to_f_result['code'] == 0: 208 | quantity_to_f_result['code'] = 200 209 | else: 210 | quantity_to_f_result['code'] = code.QUANTITY_TO_F_ERROR[0] 211 | quantity_to_f_result['msg'] = f'symbol={symbol} ' + quantity_to_f_result['msg'] 212 | return quantity_to_f_result 213 | 214 | # 将价格转化为字符串 215 | # Weight 0 | 1 216 | def price_to_f( 217 | self, 218 | price: Union[int, float], 219 | symbol: str, 220 | tickSize: str = None, 221 | expire_seconds=60 * 5, 222 | ) -> dict: 223 | ''' 224 | :param price: 价格 225 | :param symbol: 合约产品 226 | :param tickSize: 订单最小价格间隔 227 | :param use_cache: 使用缓存获取交易规则和交易对信息 228 | :param expire_seconds: 缓存过期时间 (秒) 229 | 230 | tickSize为空,通过market.exchangeInfo获取交易规则与交易对信息 231 | ''' 232 | # tickSize 233 | if tickSize in [None, '']: 234 | exchangeInfo = self._market.get_exchangeInfo( 235 | symbol=symbol, 236 | expire_seconds=expire_seconds 237 | ) 238 | if exchangeInfo['code'] != 200: 239 | return exchangeInfo 240 | tickSize = exchangeInfo['data']['filter']['PRICE_FILTER']['tickSize'] 241 | # code : 0 | -1 242 | price_to_f_result = _order.price_to_f( 243 | price=price, 244 | tickSize=tickSize 245 | ) 246 | # code->[200,code.PRICE_TO_F_ERROR[0]] 247 | if price_to_f_result['code'] == 0: 248 | price_to_f_result['code'] = 200 249 | else: 250 | price_to_f_result['code'] = code.PRICE_TO_F_ERROR[0] 251 | price_to_f_result['msg'] = f'symbol={symbol} ' + price_to_f_result['msg'] 252 | return price_to_f_result 253 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_um/__init__.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.trade.trade_um.open import TradeOpen 2 | from binance_interface.app.trade.trade_um.close import TradeClose 3 | 4 | 5 | class TradeUM(TradeOpen, TradeClose): 6 | pass 7 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_um/_base.py: -------------------------------------------------------------------------------- 1 | from binance_interface.app.account import AccountUM 2 | from binance_interface.app.market import MarketUM 3 | from binance_interface.api.um import UM 4 | 5 | 6 | class TradeUMBase(): 7 | def __init__( 8 | self, 9 | key: str, 10 | secret: str, 11 | timezone: str = 'America/New_York', 12 | account=None, 13 | market=None, 14 | proxies={}, 15 | proxy_host: str = None, 16 | ): 17 | if not account: 18 | self._account = AccountUM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 19 | else: 20 | self._account = account 21 | 22 | if not market: 23 | self._market = MarketUM(key=key, secret=secret, timezone=timezone, proxies=proxies, proxy_host=proxy_host) 24 | else: 25 | self._market = market 26 | self.timezone = timezone 27 | self.umAPI = UM(key=key, secret=secret, proxies=proxies, proxy_host=proxy_host) 28 | -------------------------------------------------------------------------------- /binance_interface/app/trade/trade_um/quantity_and_price.py: -------------------------------------------------------------------------------- 1 | from typing import Literal, Union 2 | from paux import order as _order 3 | from paux.digit import origin_float 4 | from binance_interface.app.trade.trade_um._base import TradeUMBase 5 | from binance_interface.app import exception 6 | from binance_interface.app import code 7 | 8 | 9 | class TradeQuantityAndPrice(TradeUMBase): 10 | # 下单数量圆整 11 | # Weight 0 | 1 12 | def round_quantity( 13 | self, 14 | quantity: Union[int, float, str, origin_float], 15 | symbol: str, 16 | stepSize: str = None, 17 | minQty: str = None, 18 | maxQty: str = None, 19 | expire_seconds=60 * 5, 20 | ) -> dict: 21 | ''' 22 | :param quantity: 下单数量 23 | :param symbol: 合约产品 24 | :param stepSize: 订单最小数量间隔 25 | :param minQty: 最小数量 26 | :param maxQty: 最大数量 27 | :param use_cache: 使用缓存获取交易规则和交易对信息 28 | :param expire_seconds: 缓存过期时间 (秒) 29 | 30 | stepSize minQty maxQty任意为空,通过market.exchangeInfo获取交易规则与交易对信息 31 | ''' 32 | 33 | # 填充stepSize minQty maxQty 34 | if stepSize in [None, ''] or minQty in [None, ''] or maxQty in [None, '']: 35 | exchangeInfo = self._market.get_exchangeInfo( 36 | symbol=symbol, 37 | expire_seconds=expire_seconds 38 | ) 39 | if exchangeInfo['code'] != 200: 40 | return exchangeInfo 41 | if stepSize in [None, '']: 42 | stepSize = exchangeInfo['data']['filter']['LOT_SIZE']['stepSize'] 43 | if minQty in [None, '']: 44 | minQty = exchangeInfo['data']['filter']['LOT_SIZE']['minQty'] 45 | if maxQty in [None, '']: 46 | maxQty = exchangeInfo['data']['filter']['LOT_SIZE']['maxQty'] 47 | # code = 0 | -1 | -2 48 | round_quantity_result = _order.round_quantity( 49 | quantity=quantity, 50 | stepSize=stepSize, 51 | minQty=minQty, 52 | maxQty=maxQty 53 | ) 54 | # code -> [200,code.ROUND_QUANTITY_ERROR[0]] 55 | if round_quantity_result['code'] == 0: 56 | round_quantity_result['code'] = 200 57 | else: 58 | round_quantity_result['code'] = code.ROUND_QUANTITY_ERROR[0] 59 | round_quantity_result['msg'] = f'symbol={symbol} ' + round_quantity_result['msg'] 60 | return round_quantity_result 61 | 62 | # 价格圆整 63 | # Weight 0 | 1 64 | def round_price( 65 | self, 66 | price: Union[int, float], 67 | symbol: str, 68 | type: Literal['CEIL', 'FLOOR', 'ceil', 'floor'], 69 | tickSize: str = None, 70 | minPrice: str = None, 71 | maxPrice: str = None, 72 | expire_seconds=60 * 5, 73 | ) -> dict: 74 | ''' 75 | :param price: 价格 76 | :param symbol: 合约产品 77 | :param type: 圆整方式 78 | CEIL: 向上圆整 79 | FLOOR: 向下圆整 80 | :param tickSize: 订单价格的最小间隔 81 | :param minPrice: 最小价格 82 | :param maxPrice: 最大价格 83 | :param use_cache: 使用缓存获取交易规则和交易对信息 84 | :param expire_seconds: 缓存过期时间 (秒) 85 | 86 | tickSize minPrice maxPrice任意为空,通过market.exchangeInfo获取交易规则与交易对信息 87 | ''' 88 | # 验证type 89 | if type not in ['CEIL', 'FLOOR']: 90 | raise exception.ParamRoundPriceTypeException(type=type) 91 | # tickSize maxPrice minPrice 92 | if tickSize in [None, ''] or maxPrice in [None, ''] or minPrice in [None, '']: 93 | exchangeInfo = self._market.get_exchangeInfo( 94 | symbol=symbol, 95 | expire_seconds=expire_seconds 96 | ) 97 | if exchangeInfo['code'] != 200: 98 | return exchangeInfo 99 | if tickSize in [None, '']: 100 | tickSize = exchangeInfo['data']['filter']['PRICE_FILTER']['tickSize'] 101 | if minPrice in [None, '']: 102 | minPrice = exchangeInfo['data']['filter']['PRICE_FILTER']['minPrice'] 103 | if maxPrice in [None, '']: 104 | maxPrice = exchangeInfo['data']['filter']['PRICE_FILTER']['maxPrice'] 105 | # code = 0 | -1 | -2 106 | round_price_result = _order.round_price( 107 | price=price, 108 | type=type, 109 | tickSize=tickSize, 110 | minPrice=minPrice, 111 | maxPrice=maxPrice 112 | ) 113 | # code -> [200,code.ROUND_PRICE_ERROR[0]] 114 | if round_price_result['code'] == 0: 115 | round_price_result['code'] = 200 116 | else: 117 | round_price_result['code'] = code.ROUND_PRICE_ERROR[0] 118 | round_price_result['msg'] = f'symbol={symbol} ' + round_price_result['msg'] 119 | return round_price_result 120 | 121 | # 根据合约产品的开仓金额、杠杆倍数、开仓价格获取购买数量 122 | # Weight 0 | 1 123 | def get_quantity( 124 | self, 125 | openPrice: Union[int, float], 126 | openMoney: Union[int, float], 127 | symbol: str, 128 | stepSize: str = None, 129 | leverage: int = 1, 130 | minQty: str = None, 131 | maxQty: str = None, 132 | expire_seconds=60 * 5, 133 | ) -> dict: 134 | ''' 135 | :param openPrice: 开仓价格 136 | :param openMoney: 开仓金额 137 | :param symbol: 合约产品 138 | :param stepSize: 订单最小数量间隔 139 | :param leverage: 杠杆数量 140 | :param minQty: 最小数量 141 | :param maxQty: 最大数量 142 | :param use_cache: 使用缓存获取交易规则和交易对信息 143 | :param expire_seconds: 缓存过期时间 (秒) 144 | 145 | stepSize minQty maxQty任意为空,通过market.exchangeInfo获取交易规则与交易对信息 146 | ''' 147 | # stepSize minQty maxQty 148 | if stepSize in [None, ''] or minQty in [None, ''] or maxQty in [None, '']: 149 | exchangeInfo = self._market.get_exchangeInfo( 150 | symbol=symbol, 151 | expire_seconds=expire_seconds 152 | ) 153 | if exchangeInfo['code'] != 200: 154 | return exchangeInfo 155 | if stepSize in [None, '']: 156 | stepSize = exchangeInfo['data']['filter']['LOT_SIZE']['stepSize'] 157 | if minQty in [None, '']: 158 | minQty = exchangeInfo['data']['filter']['LOT_SIZE']['minQty'] 159 | if maxQty in [None, '']: 160 | maxQty = exchangeInfo['data']['filter']['LOT_SIZE']['maxQty'] 161 | # 未圆整的下单数量 162 | quantity = openMoney * leverage / openPrice 163 | # 返回圆整结果 164 | return self.round_quantity( 165 | quantity=quantity, 166 | symbol=symbol, 167 | stepSize=stepSize, 168 | minQty=minQty, 169 | maxQty=maxQty, 170 | expire_seconds=expire_seconds, 171 | ) 172 | 173 | # 将下单数量转化为字符串 174 | # Weight 0 | 1 175 | def quantity_to_f( 176 | self, 177 | quantity: Union[int, float], 178 | symbol: str, 179 | stepSize: str = None, 180 | expire_seconds=60 * 5, 181 | 182 | ) -> dict: 183 | ''' 184 | :param quantity: 下单数量 185 | :param symbol: 合约产品 186 | :param stepSize: 订单最小数量间隔 187 | :param use_cache: 使用缓存获取交易规则和交易对信息 188 | :param expire_seconds: 缓存过期时间 (秒) 189 | 190 | stepSize为空,通过market.exchangeInfo获取交易规则与交易对信息 191 | ''' 192 | # stepSize 193 | if stepSize in [None, '']: 194 | exchangeInfo = self._market.get_exchangeInfo( 195 | symbol=symbol, 196 | expire_seconds=expire_seconds 197 | ) 198 | if exchangeInfo['code'] != 200: 199 | return exchangeInfo 200 | stepSize = exchangeInfo['data']['filter']['LOT_SIZE']['stepSize'] 201 | # code : 0 | -1 202 | quantity_to_f_result = _order.quantity_to_f( 203 | quantity=quantity, 204 | stepSize=stepSize, 205 | ) 206 | # code -> [200,code.QUANTITY_TO_F_ERROR[0]] 207 | if quantity_to_f_result['code'] == 0: 208 | quantity_to_f_result['code'] = 200 209 | else: 210 | quantity_to_f_result['code'] = code.QUANTITY_TO_F_ERROR[0] 211 | quantity_to_f_result['msg'] = f'symbol={symbol} ' + quantity_to_f_result['msg'] 212 | return quantity_to_f_result 213 | 214 | # 将价格转化为字符串 215 | # Weight 0 | 1 216 | def price_to_f( 217 | self, 218 | price: Union[int, float], 219 | symbol: str, 220 | tickSize: str = None, 221 | expire_seconds=60 * 5, 222 | ) -> dict: 223 | ''' 224 | :param price: 价格 225 | :param symbol: 合约产品 226 | :param tickSize: 订单最小价格间隔 227 | :param use_cache: 使用缓存获取交易规则和交易对信息 228 | :param expire_seconds: 缓存过期时间 (秒) 229 | 230 | tickSize为空,通过market.exchangeInfo获取交易规则与交易对信息 231 | ''' 232 | # tickSize 233 | if tickSize in [None, '']: 234 | exchangeInfo = self._market.get_exchangeInfo( 235 | symbol=symbol, 236 | expire_seconds=expire_seconds 237 | ) 238 | if exchangeInfo['code'] != 200: 239 | return exchangeInfo 240 | tickSize = exchangeInfo['data']['filter']['PRICE_FILTER']['tickSize'] 241 | # code : 0 | -1 242 | price_to_f_result = _order.price_to_f( 243 | price=price, 244 | tickSize=tickSize 245 | ) 246 | # code->[200,code.PRICE_TO_F_ERROR[0]] 247 | if price_to_f_result['code'] == 0: 248 | price_to_f_result['code'] = 200 249 | else: 250 | price_to_f_result['code'] = code.PRICE_TO_F_ERROR[0] 251 | price_to_f_result['msg'] = f'symbol={symbol} ' + price_to_f_result['msg'] 252 | return price_to_f_result 253 | -------------------------------------------------------------------------------- /binance_interface/app/utils.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | from copy import deepcopy 3 | from pprint import pprint 4 | 5 | 6 | def get_asset(symbol, base_asset): 7 | symbol = symbol.strip() 8 | base_asset = base_asset.strip() 9 | if base_asset and symbol.endswith(base_asset): 10 | asset = symbol[0:-len(base_asset)] 11 | return asset 12 | else: 13 | return symbol 14 | 15 | 16 | def eprint_old(data, length=2): 17 | """ 18 | Formats and prints the given data in a structured way, compatible with both list and dict types in 'data' field. 19 | Includes "... ..." to indicate more items in the list. 20 | 21 | Args: 22 | data (dict): The data to be formatted and printed. 23 | """ 24 | try: 25 | texts = [] 26 | texts.append("{") 27 | for key, value in data.items(): 28 | if key == "data": 29 | if type(value) == [str, int, float, bool]: 30 | texts.append(f" '{key}': {value},\n") 31 | elif type(value) == list: 32 | texts.append(f" '{key}': [") 33 | # Check if the first item in data is a list or a dict to determine the format 34 | if len(value) == 0: 35 | texts[-1] += '],\n' 36 | else: 37 | texts[-1] += '\n' 38 | if isinstance(value[0], dict): 39 | # Handling dict format 40 | for i, item in enumerate(value): 41 | if i == length: # For the second entry, add ... 42 | texts.append(" ... ...\n") 43 | break 44 | texts.append(" {\n") 45 | for sub_key, sub_value in item.items(): 46 | texts.append(f" '{sub_key}': {repr(sub_value)},\n") 47 | 48 | texts.append(" },\n") 49 | else: 50 | # Handling list format 51 | for i, item in enumerate(value): 52 | if i == length: # For the second entry, add ... 53 | texts.append(" ... ...\n") 54 | break 55 | texts.append(" [\n") 56 | for j, elem in enumerate(item): 57 | end_char = "," if j < len(item) - 1 else "" 58 | texts.append(f" {repr(elem)}{end_char}\n") 59 | texts.append(" ],\n") 60 | texts.append(" ]\n") 61 | elif type(value) == dict: 62 | texts.append(" '{key}': {".format(key=key)) 63 | # Check if the first item in data is a list or a dict to determine the format 64 | if len(value) == 0: 65 | texts[-1] += '},\n' 66 | else: 67 | texts[-1] += '\n' 68 | if isinstance(value[0], dict): 69 | # Handling dict format 70 | for i, item in enumerate(value): 71 | if i == length: # For the second entry, add ... 72 | texts.append(" ... ...\n") 73 | break 74 | texts.append(" {\n") 75 | for sub_key, sub_value in item.items(): 76 | texts.append(f" '{sub_key}': {repr(sub_value)},\n") 77 | 78 | texts.append(" },\n") 79 | else: 80 | # Handling list format 81 | for i, item in enumerate(value): 82 | if i == length: # For the second entry, add ... 83 | texts.append(" ... ...\n") 84 | break 85 | texts.append(" [\n") 86 | for j, elem in enumerate(item): 87 | end_char = "," if j < len(item) - 1 else "" 88 | texts.append(f" {repr(elem)}{end_char}\n") 89 | texts.append(" ],\n") 90 | texts.append(" ]\n") 91 | 92 | pass 93 | else: 94 | raise Exception('使用pprint') 95 | 96 | else: 97 | if key == 'code': 98 | texts.append(f"'{key}': {repr(value)},\n") 99 | elif key == 'msg': 100 | texts.append(f" '{key}': {repr(value)},") 101 | else: 102 | texts.append(f" '{key}': {repr(value)},\n") 103 | 104 | texts.append("}") 105 | print(''.join(texts)) 106 | except: 107 | print(traceback.format_exc()) 108 | pprint(data) 109 | 110 | 111 | def get_short_data(data, length, value_omit='......', key_omit='...', ): 112 | result_data = data 113 | if type(data) == list: 114 | if len(data) > length: 115 | for i in range(length): 116 | data[i] = get_short_data(data[i], length) 117 | result_data = data[0:length] + [value_omit, ] 118 | elif type(data) == dict: 119 | if len(data) > length: 120 | result_data = {} 121 | for i, (sub_key, sub_value) in enumerate(data.items()): 122 | if i >= length: 123 | break 124 | sub_value = get_short_data(sub_value, length) 125 | result_data[sub_key] = sub_value 126 | result_data[key_omit] = value_omit 127 | return result_data 128 | 129 | 130 | def eprint(result, length=5, data_length=30, value_omit='......', key_omit='...', width=120): 131 | result_copy = deepcopy(result) 132 | if 'data' in result_copy.keys(): 133 | if type(result_copy['data']) == list: 134 | short_datas = [] 135 | for data in result['data'][0:data_length]: 136 | short_data = get_short_data(data, length) 137 | short_datas.append(short_data) 138 | if len(result['data']) > data_length: 139 | short_datas.append(value_omit) 140 | 141 | elif type(result_copy['data']) == dict: 142 | short_datas = {} 143 | for i, (key, data) in enumerate(result_copy['data'].items()): 144 | if i > data_length: 145 | break 146 | short_data = get_short_data(data, length) 147 | short_datas[key] = short_data 148 | 149 | if len(result['data']) > data_length: 150 | short_datas[key_omit] = value_omit 151 | else: 152 | short_datas = result_copy['data'] 153 | result_copy['data'] = short_datas 154 | pprint(result_copy, sort_dicts=False, width=width) 155 | -------------------------------------------------------------------------------- /examples/1.1 Binance_Interface安装与介绍.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e96e1fba", 6 | "metadata": {}, 7 | "source": [ 8 | "## 1. Binance_Interface安装\n", 9 | "\n", 10 | "pip3 install binance_interface --upgrade" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "04078cab", 16 | "metadata": {}, 17 | "source": [ 18 | "## 2. Binance_Interface介绍\n", 19 | "\n", 20 | "Binance_Interface包含对Rest API接口的完全封装与APP高级封装,并长期更新维护,保证框架的有效性。\n", 21 | "\n", 22 | "**框架结构**\n", 23 | "\n", 24 | "Binance_Interface\n", 25 | "\n", 26 | "- api 官方原始接口封装\n", 27 | " - SPOT 现货\n", 28 | " - SPOTAccount 账户接口\n", 29 | " - SPOTTrade 交易接口\n", 30 | " - SPOTMarket 行情接口\n", 31 | " - SPOTAlgo 策略交易接口\n", 32 | " - margin 杠杆\n", 33 | " - MarginAccountTrade 杠杆账户和交易接口\n", 34 | " - MarginBlvt 杠杆代币接口\n", 35 | " - um U本位合约\n", 36 | " - UMAccountTrade 账户和交易接口\n", 37 | " - UMMarket 行情接口\n", 38 | " - UMPortfolio 经典统一账户\n", 39 | " - cm 币本位合约\n", 40 | " - CMAccountTrade 账户和交易接口\n", 41 | " - CMMarket 行情接口\n", 42 | " - CMPortfolio 经典统一账户接口\n", 43 | " - eo 欧式期权\n", 44 | " - EOAccountTrade 账户和交易接口\n", 45 | " - EOMarket 行情接口\n", 46 | " - EOMarketMaker 做市商接口\n", 47 | " - pm 统一账户\n", 48 | " - PMAccount 账户信息\n", 49 | " - PMMarket 行情接口\n", 50 | " - PMGetOrder 查询订单\n", 51 | " - PMSetOrder 下单接口\n", 52 | " - PMCancelOrder 撤单接口\n", 53 | " - other 其他接口\n", 54 | " - AutoInvest 定投接口\n", 55 | " - BsWap 币安挖矿接口\n", 56 | " - C2C C2C 接口\n", 57 | " - Convert 闪兑接口\n", 58 | " - CryptoLoans 质押借币接口\n", 59 | " - Fiat 法币接口\n", 60 | " - Futures 合约接口\n", 61 | " - FuturesAlgo 合约策略交易接口\n", 62 | " - GiftCard 币安礼品卡接口\n", 63 | " - Mining 矿池接口\n", 64 | " - Nft NFT 接口\n", 65 | " - Pay Pay 接口\n", 66 | " - Portfolio 经典统一账户接口\n", 67 | " - Rebate 返佣接口\n", 68 | " - SimpleEarn 赚币接口\n", 69 | " - SubAccount 子母账户接口\n", 70 | " - VipLoans VIP借币接口\n", 71 | " - Wallet 钱包接口\n", 72 | "- app 常用接口与便捷功能封装\n", 73 | " - account(账户APP)\n", 74 | " - AccountSPOT\n", 75 | " - AccountUM\n", 76 | " - AccountCM\n", 77 | " - market(行情APP)\n", 78 | " - MarketSPOT\n", 79 | " - MarketUM\n", 80 | " - MarketCM\n", 81 | " - trade(便捷交易APP,支持异步下单,挂单超时取消等)\n", 82 | " - TradeSPOT\n", 83 | " - TradeUM\n", 84 | " - TradeCM\n", 85 | " - candle_server(K线服务,支持实时多产品K线异步维护)\n", 86 | " - CandleServer\n", 87 | " - CandleRule\n" 88 | ] 89 | } 90 | ], 91 | "metadata": { 92 | "kernelspec": { 93 | "display_name": "Python 3 (ipykernel)", 94 | "language": "python", 95 | "name": "python3" 96 | }, 97 | "language_info": { 98 | "codemirror_mode": { 99 | "name": "ipython", 100 | "version": 3 101 | }, 102 | "file_extension": ".py", 103 | "mimetype": "text/x-python", 104 | "name": "python", 105 | "nbconvert_exporter": "python", 106 | "pygments_lexer": "ipython3", 107 | "version": "3.8.4" 108 | } 109 | }, 110 | "nbformat": 4, 111 | "nbformat_minor": 5 112 | } 113 | -------------------------------------------------------------------------------- /examples/2.6 APP 现货交易-价格与数量.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e0159046", 6 | "metadata": {}, 7 | "source": [ 8 | "## 1. APP 现货交易-价格与数量函数总览" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "83103087", 14 | "metadata": {}, 15 | "source": [ 16 | "|方法|解释|\n", 17 | "|:---|:---|\n", 18 | "|round_quantity|下单数量圆整|\n", 19 | "|round_price|价格圆整|\n", 20 | "|get_quantity|根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量|\n", 21 | "|quantity_to_f|将下单数量转化为字符串|\n", 22 | "|price_to_f|将价格转化为字符串|" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "id": "88249a61", 28 | "metadata": {}, 29 | "source": [ 30 | "## 2. 模型实例化" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 1, 36 | "id": "da0bee75", 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "from binance_interface.app import BinanceSPOT\n", 41 | "from binance_interface.app.utils import eprint" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 2, 47 | "id": "dfbb1e93", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "# 转发:需搭建转发服务器,可参考:https://github.com/pyted/binance_resender\n", 52 | "proxy_host = None\n", 53 | "key = 'xxxx'\n", 54 | "secret = 'xxxx'\n", 55 | "\n", 56 | "binanceSPOT = BinanceSPOT(\n", 57 | " key=key, secret=secret,\n", 58 | " proxy_host=proxy_host\n", 59 | ")\n", 60 | "trade = binanceSPOT.trade" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "id": "6352116d", 66 | "metadata": {}, 67 | "source": [ 68 | "## 3. 下单数量圆整 round_quantity" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 3, 74 | "id": "76c816d4", 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "name": "stdout", 79 | "output_type": "stream", 80 | "text": [ 81 | "{'code': 200, 'data': 0.12345, 'msg': ''}\n" 82 | ] 83 | } 84 | ], 85 | "source": [ 86 | "# 以产品数量的最小精度向下取圆整\n", 87 | "quantity_result = trade.round_quantity(\n", 88 | " symbol='BTCUSDT',\n", 89 | " quantity=0.12345678912345,\n", 90 | ")\n", 91 | "print(quantity_result)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "8f848e3f", 97 | "metadata": {}, 98 | "source": [ 99 | "## 4. 价格圆整 round_price" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 4, 105 | "id": "2d37074b", 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "name": "stdout", 110 | "output_type": "stream", 111 | "text": [ 112 | "{'code': 200, 'data': 12345.68, 'msg': ''}\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "# 以产品价格的最小精度取圆整\n", 118 | "price_result = trade.round_price(\n", 119 | " price=12345.67891234,\n", 120 | " symbol='BTCUSDT',\n", 121 | " type='CEIL', # 向上取圆整\n", 122 | ")\n", 123 | "print(price_result)" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 5, 129 | "id": "df74c21e", 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "name": "stdout", 134 | "output_type": "stream", 135 | "text": [ 136 | "{'code': 200, 'data': 12345.67, 'msg': ''}\n" 137 | ] 138 | } 139 | ], 140 | "source": [ 141 | "# 以产品价格的最小精度取圆整\n", 142 | "price_result = trade.round_price(\n", 143 | " price=12345.67891234,\n", 144 | " symbol='BTCUSDT',\n", 145 | " type='FLOOR', # 向下取圆整\n", 146 | ")\n", 147 | "print(price_result)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "id": "26193de1", 153 | "metadata": {}, 154 | "source": [ 155 | "## 5. 根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量 get_quantity" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 6, 161 | "id": "08257c00", 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "{'code': 200, 'data': 0.01885, 'msg': ''}\n" 169 | ] 170 | } 171 | ], 172 | "source": [ 173 | "quantity_result = trade.get_quantity(\n", 174 | " openPrice=21212.12,\n", 175 | " openMoney=400,\n", 176 | " symbol='BTCUSDT',\n", 177 | ")\n", 178 | "print(quantity_result)" 179 | ] 180 | }, 181 | { 182 | "cell_type": "markdown", 183 | "id": "5854236c", 184 | "metadata": {}, 185 | "source": [ 186 | "## 6. 将下单数量转化为字符串 quantity_to_f" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": 7, 192 | "id": "c28ca261", 193 | "metadata": {}, 194 | "outputs": [ 195 | { 196 | "name": "stdout", 197 | "output_type": "stream", 198 | "text": [ 199 | "{'code': 200, 'data': '0.01885', 'msg': ''}\n" 200 | ] 201 | } 202 | ], 203 | "source": [ 204 | "quantity_to_f_result = trade.quantity_to_f(\n", 205 | " quantity=0.01885,\n", 206 | " symbol='BTCUSDT',\n", 207 | ")\n", 208 | "print(quantity_to_f_result)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "id": "4922ce6c", 214 | "metadata": {}, 215 | "source": [ 216 | "## 7. 将价格转化为字符串 price_to_f" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 8, 222 | "id": "b1833f1d", 223 | "metadata": {}, 224 | "outputs": [ 225 | { 226 | "name": "stdout", 227 | "output_type": "stream", 228 | "text": [ 229 | "{'code': 200, 'data': '12345.12', 'msg': ''}\n" 230 | ] 231 | } 232 | ], 233 | "source": [ 234 | "price_to_f_result = trade.price_to_f(\n", 235 | " price=12345.12,\n", 236 | " symbol='BTCUSDT',\n", 237 | ")\n", 238 | "print(price_to_f_result)" 239 | ] 240 | } 241 | ], 242 | "metadata": { 243 | "kernelspec": { 244 | "display_name": "Python 3 (ipykernel)", 245 | "language": "python", 246 | "name": "python3" 247 | }, 248 | "language_info": { 249 | "codemirror_mode": { 250 | "name": "ipython", 251 | "version": 3 252 | }, 253 | "file_extension": ".py", 254 | "mimetype": "text/x-python", 255 | "name": "python", 256 | "nbconvert_exporter": "python", 257 | "pygments_lexer": "ipython3", 258 | "version": "3.8.4" 259 | } 260 | }, 261 | "nbformat": 4, 262 | "nbformat_minor": 5 263 | } 264 | -------------------------------------------------------------------------------- /examples/3.6 APP U本位合约交易-价格与数量.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "03da3f8c", 6 | "metadata": {}, 7 | "source": [ 8 | "## 1. APP U本位合约交易-价格与数量函数总览" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "d36448a2", 14 | "metadata": {}, 15 | "source": [ 16 | "|方法|解释|\n", 17 | "|:---|:---|\n", 18 | "|round_quantity|下单数量圆整|\n", 19 | "|round_price|价格圆整|\n", 20 | "|get_quantity|根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量|\n", 21 | "|quantity_to_f|将下单数量转化为字符串|\n", 22 | "|price_to_f|将价格转化为字符串|" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "id": "6790cb23", 28 | "metadata": {}, 29 | "source": [ 30 | "## 2. 模型实例化" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 1, 36 | "id": "502ee9c8", 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "from binance_interface.app import BinanceUM\n", 41 | "from binance_interface.app.utils import eprint" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 2, 47 | "id": "a9135e5c", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "# 转发:需搭建转发服务器,可参考:https://github.com/pyted/binance_resender\n", 52 | "proxy_host = None\n", 53 | "key = 'xxxx'\n", 54 | "secret = 'xxxx'\n", 55 | "\n", 56 | "binanceUM = BinanceUM(\n", 57 | " key=key, secret=secret,\n", 58 | " proxy_host=proxy_host\n", 59 | ")\n", 60 | "trade = binanceUM.trade" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "id": "c8c46a11", 66 | "metadata": {}, 67 | "source": [ 68 | "## 3. 下单数量圆整 round_quantity" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 3, 74 | "id": "dbd104eb", 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "name": "stdout", 79 | "output_type": "stream", 80 | "text": [ 81 | "{'code': 200, 'data': 0.123, 'msg': ''}\n" 82 | ] 83 | } 84 | ], 85 | "source": [ 86 | "# 以产品数量的最小精度向下取圆整\n", 87 | "quantity_result = trade.round_quantity(\n", 88 | " symbol='BTCUSDT',\n", 89 | " quantity=0.12345678912345,\n", 90 | ")\n", 91 | "print(quantity_result)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "92fc8f06", 97 | "metadata": {}, 98 | "source": [ 99 | "## 4. 价格圆整 round_price" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 4, 105 | "id": "dbe1ddd5", 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "name": "stdout", 110 | "output_type": "stream", 111 | "text": [ 112 | "{'code': 200, 'data': 12345.7, 'msg': ''}\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "# 以产品价格的最小精度取圆整\n", 118 | "price_result = trade.round_price(\n", 119 | " price=12345.67891234,\n", 120 | " symbol='BTCUSDT',\n", 121 | " type='CEIL', # 向上取圆整\n", 122 | ")\n", 123 | "print(price_result)" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 5, 129 | "id": "6b0a5450", 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "name": "stdout", 134 | "output_type": "stream", 135 | "text": [ 136 | "{'code': 200, 'data': 12345.6, 'msg': ''}\n" 137 | ] 138 | } 139 | ], 140 | "source": [ 141 | "# 以产品价格的最小精度取圆整\n", 142 | "price_result = trade.round_price(\n", 143 | " price=12345.67891234,\n", 144 | " symbol='BTCUSDT',\n", 145 | " type='FLOOR', # 向下取圆整\n", 146 | ")\n", 147 | "print(price_result)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "id": "72dfa59e", 153 | "metadata": {}, 154 | "source": [ 155 | "## 5. 根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量 get_quantity" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 6, 161 | "id": "ed4c31f1", 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "{'code': 200, 'data': 0.018, 'msg': ''}\n" 169 | ] 170 | } 171 | ], 172 | "source": [ 173 | "quantity_result = trade.get_quantity(\n", 174 | " openPrice=21212.12,\n", 175 | " openMoney=400,\n", 176 | " symbol='BTCUSDT',\n", 177 | ")\n", 178 | "print(quantity_result)" 179 | ] 180 | }, 181 | { 182 | "cell_type": "markdown", 183 | "id": "b5d1329e", 184 | "metadata": {}, 185 | "source": [ 186 | "## 6. 将下单数量转化为字符串 quantity_to_f" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": 7, 192 | "id": "28eca601", 193 | "metadata": {}, 194 | "outputs": [ 195 | { 196 | "name": "stdout", 197 | "output_type": "stream", 198 | "text": [ 199 | "{'code': 200, 'data': '0.018', 'msg': ''}\n" 200 | ] 201 | } 202 | ], 203 | "source": [ 204 | "quantity_to_f_result = trade.quantity_to_f(\n", 205 | " quantity=0.018,\n", 206 | " symbol='BTCUSDT',\n", 207 | ")\n", 208 | "print(quantity_to_f_result)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "id": "6a4fca09", 214 | "metadata": {}, 215 | "source": [ 216 | "## 7. 将价格转化为字符串 price_to_f" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 8, 222 | "id": "276a4fd3", 223 | "metadata": {}, 224 | "outputs": [ 225 | { 226 | "name": "stdout", 227 | "output_type": "stream", 228 | "text": [ 229 | "{'code': 200, 'data': '12345.1', 'msg': ''}\n" 230 | ] 231 | } 232 | ], 233 | "source": [ 234 | "price_to_f_result = trade.price_to_f(\n", 235 | " price=12345.1,\n", 236 | " symbol='BTCUSDT',\n", 237 | ")\n", 238 | "print(price_to_f_result)" 239 | ] 240 | } 241 | ], 242 | "metadata": { 243 | "kernelspec": { 244 | "display_name": "Python 3 (ipykernel)", 245 | "language": "python", 246 | "name": "python3" 247 | }, 248 | "language_info": { 249 | "codemirror_mode": { 250 | "name": "ipython", 251 | "version": 3 252 | }, 253 | "file_extension": ".py", 254 | "mimetype": "text/x-python", 255 | "name": "python", 256 | "nbconvert_exporter": "python", 257 | "pygments_lexer": "ipython3", 258 | "version": "3.8.4" 259 | } 260 | }, 261 | "nbformat": 4, 262 | "nbformat_minor": 5 263 | } 264 | -------------------------------------------------------------------------------- /examples/4.6 APP 币本位合约交易-价格与数量.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "95a3695a", 6 | "metadata": {}, 7 | "source": [ 8 | "## 1. APP 币本位合约交易-价格与数量函数总览" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "3a3715ee", 14 | "metadata": {}, 15 | "source": [ 16 | "|方法|解释|\n", 17 | "|:---|:---|\n", 18 | "|round_quantity|下单数量圆整|\n", 19 | "|round_price|价格圆整|\n", 20 | "|get_quantity|根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量|\n", 21 | "|quantity_to_f|将下单数量转化为字符串|\n", 22 | "|price_to_f|将价格转化为字符串|" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "id": "0bdaec41", 28 | "metadata": {}, 29 | "source": [ 30 | "## 2. 模型实例化" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 1, 36 | "id": "b42b3704", 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "from binance_interface.app import BinanceCM\n", 41 | "from binance_interface.app.utils import eprint" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 2, 47 | "id": "a33a6abc", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "# 转发:需搭建转发服务器,可参考:https://github.com/pyted/binance_resender\n", 52 | "proxy_host = None\n", 53 | "key = 'xxxx'\n", 54 | "secret = 'xxxx'\n", 55 | "\n", 56 | "binanceCM = BinanceCM(\n", 57 | " key=key, secret=secret,\n", 58 | " proxy_host=proxy_host\n", 59 | ")\n", 60 | "trade = binanceCM.trade" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "id": "eabade13", 66 | "metadata": {}, 67 | "source": [ 68 | "## 3. 下单数量圆整 round_quantity" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 3, 74 | "id": "6198d2c9", 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "name": "stdout", 79 | "output_type": "stream", 80 | "text": [ 81 | "{'code': 200, 'data': 10, 'msg': ''}\n" 82 | ] 83 | } 84 | ], 85 | "source": [ 86 | "# 以产品数量的最小精度向下取圆整\n", 87 | "quantity_result = trade.round_quantity(\n", 88 | " symbol='BTCUSD_PERP',\n", 89 | " quantity=10,\n", 90 | ")\n", 91 | "print(quantity_result)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "533deceb", 97 | "metadata": {}, 98 | "source": [ 99 | "## 4. 价格圆整 round_price" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 4, 105 | "id": "22e1fbd5", 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "name": "stdout", 110 | "output_type": "stream", 111 | "text": [ 112 | "{'code': 200, 'data': 12345.7, 'msg': ''}\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "# 以产品价格的最小精度取圆整\n", 118 | "price_result = trade.round_price(\n", 119 | " price=12345.67891234,\n", 120 | " symbol='BTCUSD_PERP',\n", 121 | " type='CEIL', # 向上取圆整\n", 122 | ")\n", 123 | "print(price_result)" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 5, 129 | "id": "b0393f23", 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "name": "stdout", 134 | "output_type": "stream", 135 | "text": [ 136 | "{'code': 200, 'data': 12345.6, 'msg': ''}\n" 137 | ] 138 | } 139 | ], 140 | "source": [ 141 | "# 以产品价格的最小精度取圆整\n", 142 | "price_result = trade.round_price(\n", 143 | " price=12345.67891234,\n", 144 | " symbol='BTCUSD_PERP',\n", 145 | " type='FLOOR', # 向下取圆整\n", 146 | ")\n", 147 | "print(price_result)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "id": "00de8ef4", 153 | "metadata": {}, 154 | "source": [ 155 | "## 5. 根据产品的开仓金额、杠杆倍数、开仓价格获取购买数量 get_quantity" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 6, 161 | "id": "8984b99b", 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "{'code': 200, 'data': 212, 'msg': ''}\n" 169 | ] 170 | } 171 | ], 172 | "source": [ 173 | "# openMoney为货币数量\n", 174 | "quantity_result = trade.get_quantity(\n", 175 | " openPrice=21212.12,\n", 176 | " openMoney=1,\n", 177 | " symbol='BTCUSD_PERP',\n", 178 | " leverage=1,\n", 179 | ")\n", 180 | "print(quantity_result)" 181 | ] 182 | }, 183 | { 184 | "cell_type": "markdown", 185 | "id": "86ed33f3", 186 | "metadata": {}, 187 | "source": [ 188 | "## 6. 将下单数量转化为字符串 quantity_to_f" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": 7, 194 | "id": "d705dd47", 195 | "metadata": {}, 196 | "outputs": [ 197 | { 198 | "name": "stdout", 199 | "output_type": "stream", 200 | "text": [ 201 | "{'code': 200, 'data': '10', 'msg': ''}\n" 202 | ] 203 | } 204 | ], 205 | "source": [ 206 | "quantity_to_f_result = trade.quantity_to_f(\n", 207 | " quantity=10,\n", 208 | " symbol='BTCUSD_PERP',\n", 209 | ")\n", 210 | "print(quantity_to_f_result)" 211 | ] 212 | }, 213 | { 214 | "cell_type": "markdown", 215 | "id": "2c59fe93", 216 | "metadata": {}, 217 | "source": [ 218 | "## 7. 将价格转化为字符串 price_to_f" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": 8, 224 | "id": "b3876470", 225 | "metadata": {}, 226 | "outputs": [ 227 | { 228 | "name": "stdout", 229 | "output_type": "stream", 230 | "text": [ 231 | "{'code': 200, 'data': '12345.1', 'msg': ''}\n" 232 | ] 233 | } 234 | ], 235 | "source": [ 236 | "price_to_f_result = trade.price_to_f(\n", 237 | " price=12345.1,\n", 238 | " symbol='BTCUSD_PERP',\n", 239 | ")\n", 240 | "print(price_to_f_result)" 241 | ] 242 | } 243 | ], 244 | "metadata": { 245 | "kernelspec": { 246 | "display_name": "Python 3 (ipykernel)", 247 | "language": "python", 248 | "name": "python3" 249 | }, 250 | "language_info": { 251 | "codemirror_mode": { 252 | "name": "ipython", 253 | "version": 3 254 | }, 255 | "file_extension": ".py", 256 | "mimetype": "text/x-python", 257 | "name": "python", 258 | "nbconvert_exporter": "python", 259 | "pygments_lexer": "ipython3", 260 | "version": "3.8.4" 261 | } 262 | }, 263 | "nbformat": 4, 264 | "nbformat_minor": 5 265 | } 266 | -------------------------------------------------------------------------------- /examples/5.2 APP K线服务 每日定时下载昨日历史K线.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "6e30761a", 6 | "metadata": {}, 7 | "source": [ 8 | "## 1. CandleRule中的相关配置\n", 9 | "\n", 10 | "与\"每日定时下载昨日历史K线功能\"重要相关配置为:\n", 11 | "\n", 12 | "\n", 13 | "|参数|类型|默认值|说明|\n", 14 | "|:---|:---|:---|:---|\n", 15 | "|**SERVER_WEIGHT**|float, int|0.75|服务占用权重上限的比例 现货交易权重上限1200 合约交易权重上限2400|\n", 16 | "|**SYMBOLS**|str,list|'all'|收集的产品 all表示全部正在交易的产品|\n", 17 | "|**SYMBOLS_FILTER**|list|[]|过滤的产品|\n", 18 | "|**SYMBOL_CONTAINS**|str|''|产品名称中需要包含的内容|\n", 19 | "|**SYMBOL_ENDSWITH**|str|''|产品名称必须以何内容结尾|\n", 20 | "|**BAR**|str|binance_interface.binace_lite.BINANCE_DEFAULT_BAR|时间颗粒度|\n", 21 | "|**TIMEZONE**|str|binance_interface.binace_lite.BINANCE_TIMEZONE|时区|\n", 22 | "|**CANDLE_DIR**|str|binance_interface.binace_lite.BINANCE_CANDLE_DATE_BASE_DIR|以天为单位的数据存储路径|\n", 23 | "|**DOWNLOAD_TIME**|str, None|'00:10:00'|每日下载昨日历史K线数据的时刻 格式:%H:%M:%S None表示不下载(每日定时下载K线中使用)|" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "id": "9146e771", 29 | "metadata": {}, 30 | "source": [ 31 | "## 2. 每日定时下载昨日历史K线" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": 1, 37 | "id": "9c78fc8b", 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "from binance_interface.app.candle_server import CandleRule,CandleServer\n", 42 | "import time" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 2, 48 | "id": "14ef75eb", 49 | "metadata": {}, 50 | "outputs": [ 51 | { 52 | "name": "stderr", 53 | "output_type": "stream", 54 | "text": [ 55 | "2024-01-26 01:16:25,393 [INFO] DOWNLOAD BTCUSD_PERP 1m 24/01/2024\n", 56 | "2024-01-26 01:16:26,119 [INFO] DOWNLOAD BTCUSD_240329 1m 24/01/2024\n", 57 | "2024-01-26 01:16:26,769 [INFO] DOWNLOAD BTCUSD_240628 1m 24/01/2024\n", 58 | "2024-01-26 01:16:27,562 [INFO] DOWNLOAD ETHUSD_PERP 1m 24/01/2024\n", 59 | "2024-01-26 01:16:28,389 [INFO] DOWNLOAD ETHUSD_240329 1m 24/01/2024\n", 60 | "2024-01-26 01:16:29,049 [INFO] DOWNLOAD ETHUSD_240628 1m 24/01/2024\n", 61 | "2024-01-26 01:16:29,769 [INFO] DOWNLOAD LINKUSD_PERP 1m 24/01/2024\n", 62 | "2024-01-26 01:16:30,560 [INFO] DOWNLOAD BNBUSD_PERP 1m 24/01/2024\n", 63 | "2024-01-26 01:16:31,290 [INFO] DOWNLOAD TRXUSD_PERP 1m 24/01/2024\n", 64 | "2024-01-26 01:16:32,109 [INFO] DOWNLOAD DOTUSD_PERP 1m 24/01/2024\n", 65 | "2024-01-26 01:16:32,940 [INFO] DOWNLOAD ADAUSD_PERP 1m 24/01/2024\n", 66 | "2024-01-26 01:16:33,607 [INFO] DOWNLOAD EOSUSD_PERP 1m 24/01/2024\n", 67 | "2024-01-26 01:16:34,328 [INFO] DOWNLOAD LTCUSD_PERP 1m 24/01/2024\n", 68 | "2024-01-26 01:16:35,082 [INFO] DOWNLOAD BCHUSD_PERP 1m 24/01/2024\n", 69 | "2024-01-26 01:16:35,809 [INFO] DOWNLOAD XRPUSD_PERP 1m 24/01/2024\n", 70 | "2024-01-26 01:16:36,618 [INFO] DOWNLOAD ETCUSD_PERP 1m 24/01/2024\n", 71 | "2024-01-26 01:16:37,389 [INFO] DOWNLOAD FILUSD_PERP 1m 24/01/2024\n", 72 | "2024-01-26 01:16:38,159 [INFO] DOWNLOAD EGLDUSD_PERP 1m 24/01/2024\n", 73 | "2024-01-26 01:16:38,888 [INFO] DOWNLOAD DOGEUSD_PERP 1m 24/01/2024\n", 74 | "2024-01-26 01:16:39,598 [INFO] DOWNLOAD UNIUSD_PERP 1m 24/01/2024\n", 75 | "2024-01-26 01:16:40,218 [INFO] DOWNLOAD THETAUSD_PERP 1m 24/01/2024\n", 76 | "2024-01-26 01:16:40,838 [INFO] DOWNLOAD XLMUSD_PERP 1m 24/01/2024\n", 77 | "2024-01-26 01:16:41,570 [INFO] DOWNLOAD SOLUSD_PERP 1m 24/01/2024\n", 78 | "2024-01-26 01:16:42,243 [INFO] DOWNLOAD FTMUSD_PERP 1m 24/01/2024\n", 79 | "2024-01-26 01:16:43,080 [INFO] DOWNLOAD SANDUSD_PERP 1m 24/01/2024\n", 80 | "2024-01-26 01:16:43,838 [INFO] DOWNLOAD MANAUSD_PERP 1m 24/01/2024\n", 81 | "2024-01-26 01:16:44,499 [INFO] DOWNLOAD AVAXUSD_PERP 1m 24/01/2024\n", 82 | "2024-01-26 01:16:45,160 [INFO] DOWNLOAD MATICUSD_PERP 1m 24/01/2024\n", 83 | "2024-01-26 01:16:45,830 [INFO] DOWNLOAD NEARUSD_PERP 1m 24/01/2024\n", 84 | "2024-01-26 01:16:46,549 [INFO] DOWNLOAD ATOMUSD_PERP 1m 24/01/2024\n", 85 | "2024-01-26 01:16:47,230 [INFO] DOWNLOAD AAVEUSD_PERP 1m 24/01/2024\n", 86 | "2024-01-26 01:16:47,899 [INFO] DOWNLOAD AXSUSD_PERP 1m 24/01/2024\n", 87 | "2024-01-26 01:16:48,659 [INFO] DOWNLOAD ROSEUSD_PERP 1m 24/01/2024\n", 88 | "2024-01-26 01:16:49,257 [INFO] DOWNLOAD XTZUSD_PERP 1m 24/01/2024\n", 89 | "2024-01-26 01:16:49,855 [INFO] DOWNLOAD ICXUSD_PERP 1m 24/01/2024\n", 90 | "2024-01-26 01:16:50,458 [INFO] DOWNLOAD ALGOUSD_PERP 1m 24/01/2024\n", 91 | "2024-01-26 01:16:51,187 [INFO] DOWNLOAD RUNEUSD_PERP 1m 24/01/2024\n", 92 | "2024-01-26 01:16:51,848 [INFO] DOWNLOAD APEUSD_PERP 1m 24/01/2024\n", 93 | "2024-01-26 01:16:52,507 [INFO] DOWNLOAD KNCUSD_PERP 1m 24/01/2024\n", 94 | "2024-01-26 01:16:53,207 [INFO] DOWNLOAD XMRUSD_PERP 1m 24/01/2024\n", 95 | "2024-01-26 01:16:53,927 [INFO] DOWNLOAD GMTUSD_PERP 1m 24/01/2024\n", 96 | "2024-01-26 01:16:54,729 [INFO] DOWNLOAD OPUSD_PERP 1m 24/01/2024\n", 97 | "2024-01-26 01:16:55,449 [INFO] DOWNLOAD ENSUSD_PERP 1m 24/01/2024\n", 98 | "2024-01-26 01:16:56,213 [INFO] DOWNLOAD CHZUSD_PERP 1m 24/01/2024\n", 99 | "2024-01-26 01:16:57,011 [INFO] DOWNLOAD APTUSD_PERP 1m 24/01/2024\n", 100 | "2024-01-26 01:16:57,758 [INFO] DOWNLOAD ADAUSD_240329 1m 24/01/2024\n", 101 | "2024-01-26 01:16:58,428 [INFO] DOWNLOAD LINKUSD_240329 1m 24/01/2024\n", 102 | "2024-01-26 01:16:59,049 [INFO] DOWNLOAD BCHUSD_240329 1m 24/01/2024\n", 103 | "2024-01-26 01:16:59,807 [INFO] DOWNLOAD DOTUSD_240329 1m 24/01/2024\n", 104 | "2024-01-26 01:17:00,498 [INFO] DOWNLOAD XRPUSD_240329 1m 24/01/2024\n", 105 | "2024-01-26 01:17:01,106 [INFO] DOWNLOAD LTCUSD_240329 1m 24/01/2024\n", 106 | "2024-01-26 01:17:01,739 [INFO] DOWNLOAD BNBUSD_240329 1m 24/01/2024\n", 107 | "2024-01-26 01:17:02,371 [INFO] DOWNLOAD ADAUSD_240628 1m 24/01/2024\n", 108 | "2024-01-26 01:17:02,974 [INFO] DOWNLOAD LINKUSD_240628 1m 24/01/2024\n", 109 | "2024-01-26 01:17:03,567 [INFO] DOWNLOAD BCHUSD_240628 1m 24/01/2024\n", 110 | "2024-01-26 01:17:04,217 [INFO] DOWNLOAD DOTUSD_240628 1m 24/01/2024\n", 111 | "2024-01-26 01:17:04,838 [INFO] DOWNLOAD XRPUSD_240628 1m 24/01/2024\n", 112 | "2024-01-26 01:17:05,437 [INFO] DOWNLOAD LTCUSD_240628 1m 24/01/2024\n", 113 | "2024-01-26 01:17:06,037 [INFO] DOWNLOAD BNBUSD_240628 1m 24/01/2024\n", 114 | "2024-01-26 01:17:06,039 [INFO] COMPLETE DOWNLOAD 24/01/2024 (ALL:59 SKIP:0 SUC:59 WARN:0 ERROR:0)\n" 115 | ] 116 | } 117 | ], 118 | "source": [ 119 | "# 币币交易:SPOT;U本位合约:UM;币本位合约:CM\n", 120 | "instType = 'CM'\n", 121 | "# 永续合约,默认规则\n", 122 | "candleServer = CandleServer(\n", 123 | " instType=instType,\n", 124 | " rule=CandleRule,\n", 125 | " # 使用http和https代理,proxies={'http':'xxxxx','https:':'xxxxx'},通requests中的proxies参数规则相同\n", 126 | " proxies={},\n", 127 | " # 转发:需搭建转发服务器,可参考:https://github.com/pyted/binance_resender\n", 128 | " proxy_host=None,\n", 129 | ")\n", 130 | "# 每日在CandleRule.DOWNLOAD_TIME时刻开始下载前一日的历史K线\n", 131 | "candleServer.download_daily(replace=True) # 异步方法\n", 132 | "# 等待10秒钟关闭服务\n", 133 | "time.sleep(10)\n", 134 | "candleServer.close_download_daily() # 关闭服务,并不会立刻停止,而是而等待当前正在下载的日期数据全部完成后,停止运行" 135 | ] 136 | } 137 | ], 138 | "metadata": { 139 | "kernelspec": { 140 | "display_name": "Python 3 (ipykernel)", 141 | "language": "python", 142 | "name": "python3" 143 | }, 144 | "language_info": { 145 | "codemirror_mode": { 146 | "name": "ipython", 147 | "version": 3 148 | }, 149 | "file_extension": ".py", 150 | "mimetype": "text/x-python", 151 | "name": "python", 152 | "nbconvert_exporter": "python", 153 | "pygments_lexer": "ipython3", 154 | "version": "3.8.4" 155 | } 156 | }, 157 | "nbformat": 4, 158 | "nbformat_minor": 5 159 | } 160 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Binance_interface 2.0.5 2 | 3 | 安装: 4 | 5 | ```cmd 6 | pip3 install binance_interface --upgrade 7 | ``` 8 | 9 | 10 | 11 | 使用教程请参考examples 12 | 13 | - 1.1 Binance_Interface安装与介绍 14 | - 1.2 API函数接口总览 15 | - 1.3 API 现货行情接口.ipynb 16 | - 1.4 API U本位合约行情.ipynb 17 | - 1.5 API 币本位合约行情.ipynb 18 | - 1.6 API 现货交易账户.ipynb 19 | - 1.7 API U本位合约交易账户.ipynb 20 | - 1.8 API 币本位合约交易账户.ipynb 21 | - 2.1 APP 现货交易账户.ipynb 22 | - 2.2 APP 现货行情-交易规则信息.ipynb 23 | - 2.3 APP 现货行情-实时行情.ipynb 24 | - 2.4 APP 现货行情-历史K线.ipynb 25 | - 2.5 APP 现货交易-基础订单.ipynb 26 | - 2.6 APP 现货交易-价格与数量.ipynb 27 | - 2.7 APP 现货交易-限价单开仓.ipynb 28 | - 2.8 APP 现货交易-市价单开仓.ipynb 29 | - 2.9 APP 现货交易-限单价平仓.ipynb 30 | - 2.10 APP 现货交易-市单价平仓.ipynb 31 | - 3.1 APP U本位合约交易账户.ipynb 32 | - 3.2 APP U本位合约行情-交易规则信息.ipynb 33 | - 3.3 APP U本位合约行情-实时行情.ipynb 34 | - 3.4 APP U本位合约行情-历史K线.ipynb 35 | - 3.5 APP U本位合约交易-基础订单.ipynb 36 | - 3.6 APP U本位合约交易-价格与数量.ipynb 37 | - 3.7 APP U本位合约交易-限价单开仓.ipynb 38 | - 3.8 APP U本位合约交易-市价单开仓.ipynb 39 | - 3.9 APP U本位合约交易-限单价平仓.ipynb 40 | - 3.10 APP U本位合约交易-市单价平仓.ipynb 41 | - 4.1 APP 币本位合约交易账户.ipynb 42 | - 4.2 APP 币本位合约行情-交易规则信息.ipynb 43 | - 4.3 APP 币本位合约行情-实时行情.ipynb 44 | - 4.4 APP 币本位合约行情-历史K线.ipynb 45 | - 4.5 APP 币本位合约交易-基础订单.ipynb 46 | - 4.6 APP 币本位合约交易-价格与数量.ipynb 47 | - 4.7 APP 币本位合约交易-限价单开仓.ipynb 48 | - 4.8 APP 币本位合约交易-市价单开仓.ipynb 49 | - 4.9 APP 币本位合约交易-限单价平仓.ipynb 50 | - 4.10 APP 币本位合约交易-市单价平仓.ipynb 51 | - 5.1 APP K线服务 下载历史K线.ipynb 52 | - 5.2 APP K线服务 每日定时下载昨日历史K线.ipynb 53 | - 5.3 APP K线服务 维护实时历史K线.ipynb 54 | 55 | ### v2.0.3 56 | 57 | - 更新日期:2024-02-08 58 | - 同步官方文档全部Rest接口 59 | - 添加代理IP与代理服务器转发功能 60 | 61 | ### v2.0.5 62 | 63 | - 修正candle_map实时K线服务因各个产品的最新K线数据更新时间的不同而造成的candle验证误删。 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | import sys 4 | from shutil import rmtree 5 | from setuptools import find_packages, setup, Command 6 | 7 | NAME = 'binance_interface' 8 | DESCRIPTION = "Python Binance API Interface and Advanced APP Packaging Methods" 9 | URL = "https://github.com/pyted/binance_interface" 10 | EMAIL = 'pyted@outlook.com' 11 | AUTHOR = 'pyted' 12 | REQUIRES_PYTHON = '>=3.8.0' 13 | VERSION = '2.0.5' 14 | 15 | REQUIRED = [ 16 | 'requests', 17 | 'pandas', 18 | 'numpy', 19 | 'paux>=1.0.13', 20 | 'candlelite>=1.0.10', 21 | ] 22 | 23 | EXTRAS = {} 24 | 25 | here = os.path.abspath(os.path.dirname(__file__)) 26 | try: 27 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 28 | long_description = '\n' + f.read() 29 | except FileNotFoundError: 30 | long_description = DESCRIPTION 31 | 32 | about = {} 33 | 34 | if not VERSION: 35 | project_slug = NAME.lower().replace("-", "_").replace(" ", "_") 36 | with open(os.path.join(here, project_slug, '__version__.py')) as f: 37 | exec(f.read(), about) 38 | else: 39 | about['__version__'] = VERSION 40 | 41 | 42 | class UploadCommand(Command): 43 | """Support setup.py upload.""" 44 | 45 | description = 'Build and publish the package.' 46 | user_options = [] 47 | 48 | @staticmethod 49 | def status(s): 50 | """Prints things in bold.""" 51 | print('\033[1m{0}\033[0m'.format(s)) 52 | 53 | def initialize_options(self): 54 | pass 55 | 56 | def finalize_options(self): 57 | pass 58 | 59 | def run(self): 60 | try: 61 | self.status('Removing previous builds…') 62 | rmtree(os.path.join(here, 'dist')) 63 | except OSError: 64 | pass 65 | 66 | self.status('Building Source and Wheel (universal) distribution…') 67 | os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) 68 | 69 | self.status('Uploading the package to PyPI via Twine…') 70 | os.system('twine upload dist/*') 71 | 72 | self.status('Pushing git tags…') 73 | os.system('git tag v{0}'.format(about['__version__'])) 74 | os.system('git push --tags') 75 | 76 | sys.exit() 77 | 78 | 79 | # Where the magic happens: 80 | setup( 81 | name=NAME, 82 | version=about['__version__'], 83 | description=DESCRIPTION, 84 | long_description=long_description, 85 | long_description_content_type='text/markdown', 86 | author=AUTHOR, 87 | author_email=EMAIL, 88 | python_requires=REQUIRES_PYTHON, 89 | url=URL, 90 | packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]), 91 | install_requires=REQUIRED, 92 | extras_require=EXTRAS, 93 | include_package_data=True, 94 | license='MIT', 95 | classifiers=[ 96 | 'License :: OSI Approved :: MIT License', 97 | 'Programming Language :: Python', 98 | 'Programming Language :: Python :: 3', 99 | 'Programming Language :: Python :: 3.6', 100 | 'Programming Language :: Python :: Implementation :: CPython', 101 | 'Programming Language :: Python :: Implementation :: PyPy' 102 | ], 103 | # $ setup.py publish support. 104 | cmdclass={ 105 | 'upload': UploadCommand, 106 | }, 107 | ) 108 | --------------------------------------------------------------------------------