├── LICENSE ├── README.md ├── binance_api ├── api_master_rest_caller.py ├── api_master_socket_caller.py ├── api_support_tools.py ├── blvt_api.py ├── bswap_api.py ├── formatter.py ├── futures_api.py ├── margin_api.py ├── marketData_api.py ├── mining_api.py ├── savings_api.py ├── spot_api.py ├── subAccount_api.py ├── userDataStream_api.py ├── wallet_api.py └── websocket_api.py ├── requirements.txt └── tester.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 John P Lennie 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # binance_api 2 | Contains all currently availible api endpoints found at the binanace docs. 3 | 4 | ## Description 5 | This api is written with the endpoint reference of the docs found here: https://binance-docs.github.io/apidocs/spot/en/#change-log, 6 | I decided to re-do the api to as the one I was using was dated and I will update projects to use this one as well as implementing it in future projects 7 | 8 | ### Repository Contains: 9 | - binance_api 10 | - api_master_rest_caller.py : This is where the main rest api object is created "Binance_REST". 11 | - api_master_socket_caller.py : This is where the main socket api object is created "Binance_SOCK". 12 | - api_support_tools.py : Holds logic to create custom candle intervals/limits/other support toold. 13 | - formatter.py : this is used for standerdizing formats when combinding rest data with socket data to combined update and live data together. 14 | - blvt_api.py : Holds blvt api endpoint objects. 15 | - bswap_api.py : Holds bswap api endpoint objects. 16 | - futures_api.py : Holds futures api endpoint objects. 17 | - margin_api.py : Holds margin api endpoint objects. 18 | - marketData_api.py : Holds market data api endpoint objects. 19 | - mining_api.py : Holds margin api endpoint objects. 20 | - savings_api.py : Holds savings api endpoint objects. 21 | - spot_api.py : Holds spot api endpoint objects. 22 | - subAccount_api.py : Holds sub account api endpoint objects. 23 | - userDataStream_api.py : Holds user data stream api endpoint objects. 24 | - wallet_api.py : Holds wallet api endpoint objects. 25 | - websocket_api.py : Holds websocket api endpoint objects. 26 | 27 | ## Usage 28 | To quickly install all the required modules use 'pip3 install -r requirements', this should install the modules for you. 29 | 30 | ### Rest Master: 31 | To create a rest connection you need to initilise a rest object, you can do so with or without giving your api keys however some rest calls will be unavailable unlesss you provide the keys. 32 | 33 | ### Socket Master: 34 | To create a socket connection you must only create a socket obejct and it will handle everything for you, you just need to access "Binance_SOCK.socketBuffer" for the data collected. 35 | 36 | ### Contact 37 | Please if you find any bugs or issues contact me so I can improve. 38 | EMAIL: jlennie1996@gmail.com 39 | -------------------------------------------------------------------------------- /binance_api/api_master_rest_caller.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | import hmac 4 | import time 5 | import json 6 | import logging 7 | import requests 8 | from hashlib import sha256 9 | from urllib.parse import urlencode 10 | 11 | from . import formatter 12 | from . import api_support_tools 13 | 14 | ## API Object imports 15 | from . import blvt_api 16 | from . import bswap_api 17 | from . import futures_api 18 | from . import margin_api 19 | from . import marketData_api 20 | from . import mining_api 21 | from . import savings_api 22 | from . import spot_api 23 | from . import subAccount_api 24 | from . import userDataStream_api 25 | from . import wallet_api 26 | 27 | 28 | ## sets up the rest BASE for binances rest API. 29 | REST_BASE = 'https://api.binance.com' 30 | 31 | NO_REQUIREMENTS = ['NONE'] 32 | REQUIRE_KEY = ['MARKET_DATA', 'USER_STREAM'] 33 | REQUIRE_SIGNATURE = ['USER_DATA', 'TRADE', 'MARGIN'] 34 | 35 | class Binance_REST: 36 | 37 | def __init__(self, public_key=None, private_key=None, default_api_type=None): 38 | self.session = requests.Session() 39 | self.requests_made = 0 40 | self.errors = 0 41 | 42 | self.default_api_type = default_api_type 43 | self.public_key = public_key 44 | self.private_key = private_key 45 | 46 | 47 | ## ------------------ [BLVT_EXCLUSIVE] ------------------ ## 48 | def get_blvt_info(self, **kwargs): 49 | return(self.make_api_call(blvt_api.get_blvt_info, kwargs)) 50 | def subscribe_blvt(self, **kwargs): 51 | return(self.make_api_call(blvt_api.subscribe_blvt, kwargs)) 52 | def query_subscription_record(self, **kwargs): 53 | return(self.make_api_call(blvt_api.query_subscription_record, kwargs)) 54 | def redeem_blvt(self, **kwargs): 55 | return(self.make_api_call(blvt_api.redeem_blvt, kwargs)) 56 | def query_redemption_record(self, **kwargs): 57 | return(self.make_api_call(blvt_api.query_redemption_record, kwargs)) 58 | def get_blvt_userLimit(self, **kwargs): 59 | return(self.make_api_call(blvt_api.get_blvt_userLimit, kwargs)) 60 | 61 | ## ------------------ [BSWAP_EXCLUSIVE] ------------------ ## 62 | def get_swap_pools(self): 63 | return(self.make_api_call(bswap_api.get_swap_pools)) 64 | def get_liquidity_poolInfo(self, **kwargs): 65 | return(self.make_api_call(bswap_api.get_liquidity_poolInfo, kwargs)) 66 | def add_liquidity(self, **kwargs): 67 | return(self.make_api_call(bswap_api.add_liquidity, kwargs)) 68 | def remove_liquidity(self, **kwargs): 69 | return(self.make_api_call(bswap_api.remove_liquidity, kwargs)) 70 | def get_liquidity_record(self, **kwargs): 71 | return(self.make_api_call(bswap_api.get_liquidity_record, kwargs)) 72 | def get_quote(self, **kwargs): 73 | return(self.make_api_call(bswap_api.get_quote, kwargs)) 74 | def make_swap(self, **kwargs): 75 | return(self.make_api_call(bswap_api.make_swap, kwargs)) 76 | def get_swap_history(self, **kwargs): 77 | return(self.make_api_call(bswap_api.get_swap_history, kwargs)) 78 | 79 | ## ------------------ [FUTURES_EXCLUSIVE] ------------------ ## 80 | def futures_transfer(self, **kwargs): 81 | return(self.make_api_call(futures_api.futures_transfer, kwargs)) 82 | def get_futures_transactions(self, **kwargs): 83 | return(self.make_api_call(futures_api.get_futures_transactions, kwargs)) 84 | def borrow_crossCollat(self, **kwargs): 85 | return(self.make_api_call(futures_api.borrow_crossCollat, kwargs)) 86 | def get_crossCollat_borrowHist(self, **kwargs): 87 | return(self.make_api_call(futures_api.get_crossCollat_borrowHist, kwargs)) 88 | def repay_crossCollat(self, **kwargs): 89 | return(self.make_api_call(futures_api.repay_crossCollat, kwargs)) 90 | def get_crossCollat_repayHist(self, **kwargs): 91 | return(self.make_api_call(futures_api.get_crossCollat_repayHist, kwargs)) 92 | def get_crossCollat_wallet(self): 93 | return(self.make_api_call(futures_api.get_crossCollat_wallet)) 94 | def get_crossCollat_wallet_v2(self): 95 | return(self.make_api_call(futures_api.get_crossCollat_wallet_v2)) 96 | def get_crossCollat_info(self, **kwargs): 97 | return(self.make_api_call(futures_api.get_crossCollat_info, kwargs)) 98 | def get_crossCollat_info_v2(self, **kwargs): 99 | return(self.make_api_call(futures_api.get_crossCollat_info_v2, kwargs)) 100 | def get_crossCollat_rate_LTV(self, **kwargs): 101 | return(self.make_api_call(futures_api.get_crossCollat_rate_LTV, kwargs)) 102 | def get_crossCollat_rate_LTV_v2(self, **kwargs): 103 | return(self.make_api_call(futures_api.get_crossCollat_rate_LTV_v2, kwargs)) 104 | def get_crossCollat_max_LTV(self, **kwargs): 105 | return(self.make_api_call(futures_api.get_crossCollat_max_LTV, kwargs)) 106 | def get_crossCollat_max_LTV_v2(self, **kwargs): 107 | return(self.make_api_call(futures_api.get_crossCollat_max_LTV_v2, kwargs)) 108 | def adjust_crossCollat_LTV(self, **kwargs): 109 | return(self.make_api_call(futures_api.adjust_crossCollat_LTV, kwargs)) 110 | def adjust_crossCollat_LTV_v2(self, **kwargs): 111 | return(self.make_api_call(futures_api.adjust_crossCollat_LTV_v2, kwargs)) 112 | def adjust_crossCollat_LTV_history(self, **kwargs): 113 | return(self.make_api_call(futures_api.adjust_crossCollat_LTV_history, kwargs)) 114 | def adjust_crossCollat_liquidation_history(self, **kwargs): 115 | return(self.make_api_call(futures_api.adjust_crossCollat_liquidation_history, kwargs)) 116 | def get_collatRepay_limit(self, **kwargs): 117 | return(self.make_api_call(futures_api.get_collatRepay_limit, kwargs)) 118 | def get_collatRepay_quote(self, **kwargs): 119 | return(self.make_api_call(futures_api.get_collatRepay_quote, kwargs)) 120 | def collateral_repay(self, **kwargs): 121 | return(self.make_api_call(futures_api.collateral_repay, kwargs)) 122 | def get_collatRepay_result(self, **kwargs): 123 | return(self.make_api_call(futures_api.get_collatRepay_result, kwargs)) 124 | def get_crossCollat_interestHist(self, **kwargs): 125 | return(self.make_api_call(futures_api.get_crossCollat_interestHist, kwargs)) 126 | 127 | ## ------------------ [MARGIN_EXCLUSIVE] ------------------ ## 128 | def margin_transfer(self, **kwargs): 129 | return(self.make_api_call(margin_api.margin_transfer, kwargs)) 130 | def margin_accountBorrow(self, **kwargs): 131 | return(self.make_api_call(margin_api.margin_accountBorrow, kwargs)) 132 | def margin_accountRepay(self, **kwargs): 133 | return(self.make_api_call(margin_api.margin_accountRepay, kwargs)) 134 | def query_margin_asset(self, **kwargs): 135 | return(self.make_api_call(margin_api.query_margin_asset, kwargs)) 136 | def query_crossPair(self, **kwargs): 137 | return(self.make_api_call(margin_api.query_crossPair, kwargs)) 138 | def get_margin_allAssets(self): 139 | return(self.make_api_call(margin_api.get_margin_allAssets)) 140 | def get_allCrossPairs(self): 141 | return(self.make_api_call(margin_api.get_allCrossPairs)) 142 | def query_margin_priceIndex(self, **kwargs): 143 | return(self.make_api_call(margin_api.query_margin_priceIndex, kwargs)) 144 | def get_margin_crossTransferHistory(self, **kwargs): 145 | return(self.make_api_call(margin_api.get_margin_crossTransferHistory, kwargs)) 146 | def get_loanRecord(self, **kwargs): 147 | return(self.make_api_call(margin_api.get_loanRecord, kwargs)) 148 | def get_repayRecord(self, **kwargs): 149 | return(self.make_api_call(margin_api.get_repayRecord, kwargs)) 150 | def get_interestHistory(self, **kwargs): 151 | return(self.make_api_call(margin_api.get_interestHistory, kwargs)) 152 | def get_fLiquidationRecord(self, **kwargs): 153 | return(self.make_api_call(margin_api.get_fLiquidationRecord, kwargs)) 154 | def get_cross_accountDetails(self): 155 | return(self.make_api_call(margin_api.get_cross_accountDetails)) 156 | def get_maxBorrow(self, **kwargs): 157 | return(self.make_api_call(margin_api.get_maxBorrow, kwargs)) 158 | def get_maxOutAmmount(self, **kwargs): 159 | return(self.make_api_call(margin_api.get_maxOutAmmount, kwargs)) 160 | def create_isolatedMaringAccount(self, **kwargs): 161 | return(self.make_api_call(margin_api.create_isolatedMaringAccount, kwargs)) 162 | def isolated_transfer(self, **kwargs): 163 | return(self.make_api_call(margin_api.isolated_transfer, kwargs)) 164 | def get_isolated_transferHistory(self, **kwargs): 165 | return(self.make_api_call(margin_api.get_isolated_transferHistory, kwargs)) 166 | def get_isolated_accountInfo(self, **kwargs): 167 | return(self.make_api_call(margin_api.get_isolated_accountInfo, kwargs)) 168 | def get_isolated_symbol(self, **kwargs): 169 | return(self.make_api_call(margin_api.get_isolated_symbol, kwargs)) 170 | def get_isolated_symbol_all(self): 171 | return(self.make_api_call(margin_api.get_isolated_symbol_all)) 172 | def toggle_BNB_burn_ST_MI(self, **kwargs): 173 | return(self.make_api_call(margin_api.toggle_BNB_burn_ST_MI, kwargs)) 174 | def get_BNB_burn_status(self): 175 | return(self.make_api_call(margin_api.get_BNB_burn_status)) 176 | 177 | ## ------------------ [MARKET_DATA_EXCLUSIVE] ------------------ ## 178 | def test_ping(self): 179 | return(self.make_api_call(marketData_api.test_ping)) 180 | def get_serverTime(self): 181 | return(self.make_api_call(marketData_api.get_serverTime)) 182 | def get_exchangeInfo(self): 183 | return(self.make_api_call(marketData_api.get_exchangeInfo)) 184 | def get_orderBook(self, **kwargs): 185 | return(self.make_api_call(marketData_api.get_orderBook, kwargs)) 186 | def get_custom_trades(self, **kwargs): 187 | if kwargs['limit'] > 1000: 188 | kwargs.update({'pubKey':self.public_key, 'prvKey':self.private_key}) 189 | return(api_support_tools.get_custom_trades(kwargs)) 190 | def get_recentTrades(self, **kwargs): 191 | return(api_support_tools.get_custom_trades(self.make_api_call(marketData_api.get_recentTrades, kwargs))) 192 | def get_oldTrades(self, **kwargs): 193 | return(api_support_tools.get_custom_trades(self.make_api_call(marketData_api.get_oldTrades, kwargs))) 194 | def get_aggTradeList(self, **kwargs): 195 | return(self.make_api_call(marketData_api.get_aggTradeList, kwargs)) 196 | def get_custom_candles(self, **kwargs): 197 | return(api_support_tools.get_custom_candles(kwargs)) 198 | def get_candles(self, **kwargs): 199 | return(formatter.format_candles(self.make_api_call(marketData_api.get_candles, kwargs), 'REST')) 200 | def get_averagePrice(self, **kwargs): 201 | return(self.make_api_call(marketData_api.get_averagePrice, kwargs)) 202 | def get_24hTicker(self, **kwargs): 203 | return(self.make_api_call(marketData_api.get_24hTicker, kwargs)) 204 | def get_priceTicker(self, **kwargs): 205 | return(self.make_api_call(marketData_api.get_priceTicker, kwargs)) 206 | def get_orderbookTicker(self, **kwargs): 207 | return(self.make_api_call(marketData_api.get_orderbookTicker, kwargs)) 208 | 209 | ## ------------------ [MINING_EXCLUSIVE] ------------------ ## 210 | def get_algorithm(self): 211 | return(self.make_api_call(mining_api.get_algorithm)) 212 | def get_coinNames(self): 213 | return(self.make_api_call(mining_api.get_coinNames)) 214 | def get_minerList_detail(self, **kwargs): 215 | return(self.make_api_call(mining_api.get_minerList_detail, kwargs)) 216 | def get_minerList(self, **kwargs): 217 | return(self.make_api_call(mining_api.get_minerList, kwargs)) 218 | def get_earningsList(self, **kwargs): 219 | return(self.make_api_call(mining_api.get_earningsList, kwargs)) 220 | def get_extraBonusList(self, **kwargs): 221 | return(self.make_api_call(mining_api.get_extraBonusList, kwargs)) 222 | def get_hashrateResaleList(self, **kwargs): 223 | return(self.make_api_call(mining_api.get_hashrateResaleList, kwargs)) 224 | def get_hashrateResaleDetail(self, **kwargs): 225 | return(self.make_api_call(mining_api.get_hashrateResaleDetail, kwargs)) 226 | def post_hashrateResale(self, **kwargs): 227 | return(self.make_api_call(mining_api.post_hashrateResale, kwargs)) 228 | def cancel_hashrateResale(self, **kwargs): 229 | return(self.make_api_call(mining_api.cancel_hashrateResale, kwargs)) 230 | def get_statisticList(self, **kwargs): 231 | return(self.make_api_call(mining_api.get_statisticList, kwargs)) 232 | def get_accountList(self, **kwargs): 233 | return(self.make_api_call(mining_api.get_accountList, kwargs)) 234 | 235 | ## ------------------ [SAVINGS_EXCLUSIVE] ------------------ ## 236 | def get_productList(self, **kwargs): 237 | return(self.make_api_call(savings_api.get_productList, kwargs)) 238 | def get_dailyPurchaseQuota(self, **kwargs): 239 | return(self.make_api_call(savings_api.get_dailyPurchaseQuota, kwargs)) 240 | def purchase_product(self, **kwargs): 241 | return(self.make_api_call(savings_api.purchase_product, kwargs)) 242 | def get_dailyRedemptionQuota(self, **kwargs): 243 | return(self.make_api_call(savings_api.get_dailyRedemptionQuota, kwargs)) 244 | def redeem_product(self, **kwargs): 245 | return(self.make_api_call(savings_api.redeem_product, kwargs)) 246 | def get_product_position(self, **kwargs): 247 | return(self.make_api_call(savings_api.get_product_position, kwargs)) 248 | def get_FnAProject_list(self, **kwargs): 249 | return(self.make_api_call(savings_api.get_FnAProject_list, kwargs)) 250 | def purchase_FnAProject(self, **kwargs): 251 | return(self.make_api_call(savings_api.purchase_FnAProject, kwargs)) 252 | def get_FnAProject_position(self, **kwargs): 253 | return(self.make_api_call(savings_api.get_FnAProject_position, kwargs)) 254 | def get_lending(self): 255 | return(self.make_api_call(savings_api.get_lending)) 256 | def get_purchase_record(self, **kwargs): 257 | return(self.make_api_call(savings_api.get_purchase_record, kwargs)) 258 | def get_redemption_record(self, **kwargs): 259 | return(self.make_api_call(savings_api.get_redemption_record, kwargs)) 260 | def get_interest_history(self, **kwargs): 261 | return(self.make_api_call(savings_api.get_interest_history, kwargs)) 262 | def change_position(self, **kwargs): 263 | return(self.make_api_call(savings_api.change_position, kwargs)) 264 | 265 | ## ------------------ [SPOT_EXCLUSIVE] ------------------ ## 266 | def place_order_test(self, **kwargs): 267 | return(self.make_api_call(spot_api.place_order_test, kwargs)) 268 | def place_order_oco(self, **kwargs): 269 | return(self.make_api_call(spot_api.place_order_oco, kwargs)) 270 | def cancel_order_oco(self, **kwargs): 271 | return(self.make_api_call(spot_api.cancel_order_oco, kwargs)) 272 | def query_order_oco(self, **kwargs): 273 | return(self.make_api_call(spot_api.query_order_oco, kwargs)) 274 | def get_all_orders_oco(self, **kwargs): 275 | return(self.make_api_call(spot_api.get_all_orders_oco, kwargs)) 276 | def get_open_orders_oco(self): 277 | return(self.make_api_call(spot_api.get_open_orders_oco)) 278 | def get_accountInfo(self): 279 | return(self.make_api_call(spot_api.get_accountInfo)) 280 | 281 | ## ------------------ [SUB-ACCOUNT_EXCLUSIVE] ------------------ ## 282 | def get_subAccount_list(self, **kwargs): 283 | return(self.make_api_call(subAccount_api.get_subAccount_list, kwargs)) 284 | def get_subAccount_spotTransferHistory_wapi(self, **kwargs): 285 | return(self.make_api_call(subAccount_api.get_subAccount_spotTransferHistory_wapi, kwargs)) 286 | def get_subAccount_spotTransferHistory_sapi(self, **kwargs): 287 | return(self.make_api_call(subAccount_api.get_subAccount_spotTransferHistory_sapi, kwargs)) 288 | def subAccount_spotAsset_transfer(self, **kwargs): 289 | return(self.make_api_call(subAccount_api.subAccount_spotAsset_transfer, kwargs)) 290 | def get_subAccount_futuresTransferHistory(self, **kwargs): 291 | return(self.make_api_call(subAccount_api.get_subAccount_futuresTransferHistory, kwargs)) 292 | def subAccount_futuresAsset_transfer(self, **kwargs): 293 | return(self.make_api_call(subAccount_api.subAccount_futuresAsset_transfer, kwargs)) 294 | def get_subAccount_assets(self, **kwargs): 295 | return(self.make_api_call(subAccount_api.get_subAccount_assets, kwargs)) 296 | def get_subAccount_spotAssetsSummary(self, **kwargs): 297 | return(self.make_api_call(subAccount_api.get_subAccount_spotAssetsSummary, kwargs)) 298 | def get_subAccount_depositAddress(self, **kwargs): 299 | return(self.make_api_call(subAccount_api.get_subAccount_depositAddress, kwargs)) 300 | def get_subAccount_depositHistory(self, **kwargs): 301 | return(self.make_api_call(subAccount_api.get_subAccount_depositHistory, kwargs)) 302 | def get_subAccount_statusFnM(self, **kwargs): 303 | return(self.make_api_call(subAccount_api.get_subAccount_statusFnM, kwargs)) 304 | def enable_subAccount_margin(self, **kwargs): 305 | return(self.make_api_call(subAccount_api.enable_subAccount_margin, kwargs)) 306 | def get_subAccount_marginAccount(self, **kwargs): 307 | return(self.make_api_call(subAccount_api.get_subAccount_marginAccount, kwargs)) 308 | def get_subAccount_marginAccountSummary(self): 309 | return(self.make_api_call(subAccount_api.get_subAccount_marginAccountSummary)) 310 | def enable_subAccount_futures(self, **kwargs): 311 | return(self.make_api_call(subAccount_api.enable_subAccount_futures, kwargs)) 312 | def get_subAccount_futuresAccount(self, **kwargs): 313 | return(self.make_api_call(subAccount_api.get_subAccount_futuresAccount, kwargs)) 314 | def get_subAccount_futuresAccountSummary(self): 315 | return(self.make_api_call(subAccount_api.get_subAccount_futuresAccountSummary)) 316 | def get_subAccount_positionRisk(self, **kwargs): 317 | return(self.make_api_call(subAccount_api.get_subAccount_positionRisk, kwargs)) 318 | def subAccount_futures_transfer(self, **kwargs): 319 | return(self.make_api_call(subAccount_api.subAccount_futures_transfer, kwargs)) 320 | def subAccount_margin_transfer(self, **kwargs): 321 | return(self.make_api_call(subAccount_api.subAccount_margin_transfer, kwargs)) 322 | def master_sub_transfer(self, **kwargs): 323 | return(self.make_api_call(subAccount_api.master_sub_transfer, kwargs)) 324 | def sub_master_transfer(self, **kwargs): 325 | return(self.make_api_call(subAccount_api.sub_master_transfer, kwargs)) 326 | def get_subAccount_transferHistory(self, **kwargs): 327 | return(self.make_api_call(subAccount_api.get_subAccount_transferHistory, kwargs)) 328 | def make_universalTransfer(self, **kwargs): 329 | return(self.make_api_call(subAccount_api.make_universalTransfer, kwargs)) 330 | def get_universalTransferHisotry(self, **kwargs): 331 | return(self.make_api_call(subAccount_api.get_universalTransferHisotry, kwargs)) 332 | def get_subAccount_futuresAccount_v2(self, **kwargs): 333 | return(self.make_api_call(subAccount_api.get_subAccount_futuresAccount_v2, kwargs)) 334 | def get_subAccount_futuresAccountSummary_v2(self, **kwargs): 335 | return(self.make_api_call(subAccount_api.get_subAccount_futuresAccountSummary_v2, kwargs)) 336 | def get_subAccount_positionRisk_v2(self, **kwargs): 337 | return(self.make_api_call(subAccount_api.get_subAccount_positionRisk_v2, kwargs)) 338 | 339 | ## ------------------ [WALLET_EXCLUSIVE] ------------------ ## 340 | def get_systemStatus(self): 341 | return(self.make_api_call(wallet_api.get_systemStatus)) 342 | def get_allCoinsInfo(self): 343 | return(self.make_api_call(wallet_api.get_allCoinsInfo)) 344 | def get_dailySnapshot(self, **kwargs): 345 | return(self.make_api_call(wallet_api.get_dailySnapshot, kwargs)) 346 | def disable_withdrawSwitch(self): 347 | return(self.make_api_call(wallet_api.disable_withdrawSwitch)) 348 | def enable_withdrawSwitch(self): 349 | return(self.make_api_call(wallet_api.enable_withdrawSwitch)) 350 | def make_withdraw_SAPI(self, **kwargs): 351 | return(self.make_api_call(wallet_api.make_withdraw_SAPI, kwargs)) 352 | def make_withdraw(self, **kwargs): 353 | return(self.make_api_call(wallet_api.make_withdraw, kwargs)) 354 | def get_depositHistory_SN(self, **kwargs): 355 | return(self.make_api_call(wallet_api.get_depositHistory_SN, kwargs)) 356 | def get_depositHistory(self, **kwargs): 357 | return(self.make_api_call(wallet_api.get_depositHistory, kwargs)) 358 | def get_withdrawHistory_SN(self, **kwargs): 359 | return(self.make_api_call(wallet_api.get_withdrawHistory_SN, kwargs)) 360 | def get_withdrawHistory(self, **kwargs): 361 | return(self.make_api_call(wallet_api.get_withdrawHistory, kwargs)) 362 | def depositAddress_SN(self, **kwargs): 363 | return(self.make_api_call(wallet_api.depositAddress_SN, kwargs)) 364 | def depositAddress(self, **kwargs): 365 | return(self.make_api_call(wallet_api.depositAddress, kwargs)) 366 | def get_accountStatus(self): 367 | return(self.make_api_call(wallet_api.get_accountStatus)) 368 | def get_apiStatus(self): 369 | return(self.make_api_call(wallet_api.get_apiStatus)) 370 | def get_dustLog(self): 371 | return(self.make_api_call(wallet_api.get_dustLog)) 372 | def make_dustTransfer(self, **kwargs): 373 | return(self.make_api_call(wallet_api.make_dustTransfer, kwargs)) 374 | def get_dividendRecord(self, **kwargs): 375 | return(self.make_api_call(wallet_api.get_dividendRecord, kwargs)) 376 | def get_assetDetail(self): 377 | return(self.make_api_call(wallet_api.get_assetDetail)) 378 | def get_tradeFee(self, **kwargs): 379 | return(self.make_api_call(wallet_api.get_tradeFee, kwargs)) 380 | def make_universalTransfer(self, **kwargs): 381 | return(self.make_api_call(wallet_api.make_universalTransfer, kwargs)) 382 | def get_universalTransferHistory(self, **kwargs): 383 | return(self.make_api_call(wallet_api.get_universalTransferHistory, kwargs)) 384 | 385 | ## ------------------ [USER_DATA_STREAM_EXCLUSIVE] ------------------ ## 386 | def get_listenKey(self, api_type=None): 387 | if api_type == 'SPOT': return(self.make_api_call(userDataStream_api.get_listenKey_spot)) 388 | elif api_type == 'MARGIN': return(self.make_api_call(userDataStream_api.get_listenKey_margin)) 389 | elif api_type == 'FUTURES': return(self.make_api_call(userDataStream_api.send_listenKey_keepAlive_margin, kwargs)) 390 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT/FUTURES)') 391 | 392 | def send_listenKey_keepAlive(self, api_type='SPOT', **kwargs): 393 | if api_type == 'SPOT': return(self.make_api_call(userDataStream_api.send_listenKey_keepAlive_spot, kwargs)) 394 | elif api_type == 'MARGIN': return(self.make_api_call(userDataStream_api.send_listenKey_keepAlive_margin, kwargs)) 395 | elif api_type == 'FUTURES': return(self.make_api_call(userDataStream_api.send_listenKey_keepAlive_margin, kwargs)) 396 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT/FUTURES)') 397 | 398 | def close_listenKey(self, api_type='SPOT', **kwargs): 399 | if api_type == 'SPOT': return(self.make_api_call(userDataStream_api.close_listenKey_spot, kwargs)) 400 | elif api_type == 'MARGIN': return(self.make_api_call(userDataStream_api.close_listenKey_margin, kwargs)) 401 | elif api_type == 'FUTURES': return(self.make_api_call(userDataStream_api.send_listenKey_keepAlive_margin, kwargs)) 402 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT/FUTURES)') 403 | 404 | 405 | ## ------------------ [MULTI_API_ENDPOINT] ------------------ ## 406 | def get_account(self, api_type=None): 407 | if api_type == None: api_type = self.default_api_type 408 | if api_type == 'SPOT': return(self.make_api_call(spot_api.get_accountInfo)) 409 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.get_cross_accountDetails)) 410 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 411 | 412 | def place_order(self, api_type=None, **kwargs): 413 | if api_type == None: api_type = self.default_api_type 414 | if api_type == 'SPOT': return(self.make_api_call(spot_api.place_order, kwargs)) 415 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.place_order, kwargs)) 416 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 417 | 418 | def get_order(self, api_type=None, **kwargs): 419 | if api_type == None: api_type = self.default_api_type 420 | if api_type == 'SPOT': return(self.make_api_call(spot_api.get_order, kwargs)) 421 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.get_order, kwargs)) 422 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 423 | 424 | def cancel_order(self, api_type=None, **kwargs): 425 | if api_type == None: api_type = self.default_api_type 426 | if api_type == 'SPOT': return(self.make_api_call(spot_api.cancel_order, kwargs)) 427 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.cancel_order, kwargs)) 428 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 429 | 430 | def cancel_all_orders(self, api_type=None, **kwargs): 431 | if api_type == None: api_type = self.default_api_type 432 | if api_type == 'SPOT': return(self.make_api_call(spot_api.cancel_all_orders, kwargs)) 433 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.cancel_all_orders, kwargs)) 434 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 435 | 436 | def get_all_orders(self, api_type=None, **kwargs): 437 | if api_type == None: api_type = self.default_api_type 438 | if api_type == 'SPOT': return(self.make_api_call(spot_api.get_all_orders, kwargs)) 439 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.get_all_orders, kwargs)) 440 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 441 | 442 | def get_all_trades(self, api_type=None, **kwargs): 443 | if api_type == None: api_type = self.default_api_type 444 | if api_type == 'SPOT': return(self.make_api_call(spot_api.get_all_trades, kwargs)) 445 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.get_all_trades, kwargs)) 446 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 447 | 448 | def get_open_orders(self, api_type=None, **kwargs): 449 | if api_type == None: api_type = self.default_api_type 450 | if api_type == 'SPOT': return(self.make_api_call(spot_api.get_open_orders, kwargs)) 451 | elif api_type == 'MARGIN': return(self.make_api_call(margin_api.get_open_orders, kwargs)) 452 | elif api_type == None: return('PLEASE_SPECIFY_API_TYPE, api_type=(MARGIN/SPOT)') 453 | 454 | 455 | def make_api_call(self, api_info, users_passed_parameters={}): 456 | if 'symbol' in users_passed_parameters: 457 | if '-' in users_passed_parameters: 458 | base, quote = users_passed_parameters['symbol'].split('-') 459 | users_passed_parameters.update({'symbol':(quote+base).upper()}) 460 | 461 | target_endpoint, params, headers, body = api_support_tools.param_check(api_info, users_passed_parameters) 462 | 463 | if api_info.security_type in REQUIRE_SIGNATURE: 464 | req_SIG = True 465 | else: 466 | req_SIG = False 467 | 468 | if api_info.security_type in REQUIRE_KEY or req_SIG: 469 | headers = {'X-MBX-APIKEY':self.public_key} 470 | 471 | return(self.api_request(api_info.method, target_endpoint, req_SIG, params, headers, body)) 472 | 473 | 474 | def api_request(self, method, path, req_SIG, params={}, headers={}, body={}): 475 | params_encoded = urlencode(sorted(params.items())) 476 | 477 | if req_SIG: 478 | query = '{0}×tamp={1}'.format(params_encoded, int(time.time()*1000)) 479 | signature = hmac.new(bytes(self.private_key.encode('utf-8')), (query).encode('utf-8'), sha256).hexdigest() 480 | urlQuery = '{0}{1}?{2}&signature={3}'.format(REST_BASE, path, query, signature) 481 | else: 482 | if params_encoded: 483 | urlQuery = '{0}{1}?{2}'.format(REST_BASE, path, params_encoded) 484 | else: 485 | urlQuery = '{0}{1}'.format(REST_BASE, path) 486 | 487 | logging.debug('[REST_MASTER] QUERY URL {0}'.format(urlQuery)) 488 | api_resp = self.session.request(method, urlQuery, headers=headers, data=body) 489 | data = api_resp.json() 490 | logging.debug('[REST_MASTER] QUERY DATA {0}'.format(data)) 491 | 492 | if 'code' in data: 493 | logging.warning('[BINANCE_API_ERROR][CODE: "{0}"][MESSAGE: "{1}"]'.format(data['code'], data['msg'])) 494 | 495 | self.requests_made += 1 496 | 497 | return(data) -------------------------------------------------------------------------------- /binance_api/api_master_socket_caller.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | import sys 4 | import copy 5 | import time 6 | import json 7 | import hashlib 8 | import logging 9 | import websocket 10 | import threading 11 | 12 | from . import api_support_tools 13 | from . import formatter 14 | from . import websocket_api 15 | 16 | ## sets up the socket BASE for binances socket API. 17 | SOCKET_BASE = 'wss://stream.binance.com:9443' 18 | 19 | 20 | class Binance_SOCK: 21 | 22 | def __init__(self): 23 | ''' 24 | Setup the connection and setup data containers and management variables for the socket. 25 | ''' 26 | self.MAX_REQUEST_ITEMS = 10 27 | self.requested_items = {} 28 | 29 | self.last_data_recv_time = 0 30 | 31 | self.socketRunning = False 32 | self.socketBuffer = {} 33 | self.ws = None 34 | self.stream_names = [] 35 | self.query = '' 36 | self.id_counter = 0 37 | 38 | self.BASE_CANDLE_LIMIT = 200 39 | self.BASE_DEPTH_LIMIT = 20 40 | 41 | ## For locally managed data. 42 | self.live_and_historic_data = False 43 | self.candle_data = {} 44 | self.book_data = {} 45 | self.reading_books = False 46 | 47 | self.userDataStream_added = False 48 | self.listen_key = None 49 | 50 | 51 | def build_query(self): 52 | self.query = '' 53 | 54 | if len(self.stream_names) == 0 or self.stream_names == []: 55 | return('NO_STREAMS_SET') 56 | 57 | elif len(self.stream_names) == 1: 58 | query = '{0}/ws/{1}'.format(SOCKET_BASE, self.stream_names[0]) 59 | 60 | else: 61 | query = '{0}/stream?streams='.format(SOCKET_BASE) 62 | 63 | for i, stream_name in enumerate(self.stream_names): 64 | query += stream_name 65 | if i != len(self.stream_names) - 1: 66 | query+='/' 67 | 68 | self.query = query 69 | return('QUERY_BUILT_SUCCESSFULLY') 70 | 71 | 72 | def clear_query(self): 73 | self.query = '' 74 | self.stream_names = [] 75 | self.candles_markets = [] 76 | self.book_markets = [] 77 | 78 | return('QUERY_CLEARED') 79 | 80 | 81 | ## ------------------ [DATA_ACCESS_ENDPOINT] ------------------ ## 82 | def get_live_depths(self, symbol=None): 83 | got_books = False 84 | return_books = {} 85 | 86 | while not(got_books): 87 | got_books = True 88 | for key in self.book_data: 89 | try: 90 | ask_Price_List = self._orderbook_sorter_algo(copy.deepcopy(self.book_data[key]['a']), 'ask') 91 | bid_Price_List = self._orderbook_sorter_algo(copy.deepcopy(self.book_data[key]['b']), 'bid') 92 | return_books.update({key:{'a':ask_Price_List, 'b':bid_Price_List}}) 93 | except RuntimeError as error: 94 | if error == 'dictionary changed size during iteration': 95 | print('dodged book error') 96 | got_books = False 97 | break 98 | 99 | if symbol: 100 | if not symbol in return_books: 101 | print(return_books) 102 | return(return_books[symbol]) 103 | 104 | return(return_books) 105 | 106 | def get_live_candles(self, symbol=None): 107 | if symbol: 108 | return(self.candle_data[symbol]) 109 | return(self.candle_data) 110 | 111 | 112 | ## ------------------ [MANUAL_CALLS_EXCLUSIVE] ------------------ ## 113 | def subscribe_streams(self, **kwargs): 114 | return(self._send_message('SUBSCRIBE', **kwargs)) 115 | 116 | def unsubscribe_streams(self, **kwargs): 117 | return(self._send_message('UNSUBSCRIBE', **kwargs)) 118 | 119 | def get_current_streams(self): 120 | return(self._send_message('LIST_SUBSCRIPTIONS')) 121 | 122 | def set_property(self, **kwargs): 123 | ''' combined = true''' 124 | return(self._send_message('SET_PROPERTY', **kwargs)) 125 | 126 | def get_property(self): 127 | return(self._send_message('GET_PROPERTY')) 128 | 129 | 130 | ## ------------------ [WEBSOCKET_EXCLUSIVE] ------------------ ## 131 | def set_aggTrade_stream(self, **kwargs): 132 | return(self.make_api_call(websocket_api.set_aggTrade_stream, kwargs)) 133 | 134 | def set_trade_stream(self, **kwargs): 135 | return(self.make_api_call(websocket_api.set_trade_stream, kwargs)) 136 | 137 | def set_candle_stream(self, **kwargs): 138 | return(self.make_api_call(websocket_api.set_candle_stream, kwargs)) 139 | 140 | def set_miniTicker_stream(self, **kwargs): 141 | return(self.make_api_call(websocket_api.set_miniTicker_stream, kwargs)) 142 | 143 | def set_global_miniTicker_stream(self): 144 | return(self.make_api_call(websocket_api.set_global_miniTicker_stream)) 145 | 146 | def set_ticker_stream(self, **kwargs): 147 | return(self.make_api_call(websocket_api.set_ticker_stream, kwargs)) 148 | 149 | def set_gloal_ticker_stream(self): 150 | return(self.make_api_call(websocket_api.set_gloal_ticker_stream)) 151 | 152 | def set_bookTicker_stream(self, **kwargs): 153 | return(self.make_api_call(websocket_api.set_bookTicker_stream, kwargs)) 154 | 155 | def set_global_bookTicker_stream(self): 156 | return(self.make_api_call(websocket_api.set_global_bookTicker_stream)) 157 | 158 | def set_partialBookDepth_stream(self, **kwargs): 159 | return(self.make_api_call(websocket_api.set_partialBookDepth_stream, kwargs)) 160 | 161 | def set_manual_depth_stream(self, **kwargs): 162 | return(self.make_api_call(websocket_api.set_manual_depth_stream, kwargs)) 163 | 164 | 165 | ## ------------------ [FULL_DATA_EXCLUSIVE] ------------------ ## 166 | def set_live_and_historic_combo(self, rest_api): 167 | if not(self.live_and_historic_data): 168 | for stream in self.stream_names: 169 | symbol = stream.split('@')[0].upper() 170 | if 'kline' in stream: 171 | self._set_initial_candles(symbol, stream.split('_')[1], rest_api) 172 | if 'depth' in stream: 173 | self._set_initial_depth(symbol, rest_api) 174 | time.sleep(1) 175 | 176 | RETURN_MESSAGE = 'STARTED_HISTORIC_DATA' 177 | else: 178 | if self.candle_data != {}: 179 | self.candle_data = {} 180 | 181 | RETURN_MESSAGE = 'STOPPED_HISTORIC_DATA' 182 | 183 | self.live_and_historic_data = not(self.live_and_historic_data) 184 | 185 | return(RETURN_MESSAGE) 186 | 187 | 188 | ## ------------------ [USER_DATA_STREAM_EXCLUSIVE] ------------------ ## 189 | def set_userDataStream(self, AUTHENTICATED_REST, user_data_stream_type, remove_stream=False): 190 | if remove_stream: 191 | message = self.make_api_call(None, {'listenKey':self.listen_key, 'remove_stream':True}) 192 | self.listen_key = None 193 | else: 194 | if self.listen_key == None: 195 | 196 | key_auth = AUTHENTICATED_REST.get_listenKey(user_data_stream_type) 197 | listen_key = key_auth['listenKey'] 198 | 199 | message = self.make_api_call(None, {'listenKey':listen_key}) 200 | self.listen_key = listen_key 201 | 202 | logging.info('[SOCKET_MASTER] Starting local managing') 203 | lkkaT = threading.Thread(target=self.listenKey_keepAlive, args=(AUTHENTICATED_REST,user_data_stream_type)) 204 | lkkaT.start() 205 | 206 | return(message) 207 | 208 | 209 | def listenKey_keepAlive(self, AUTHENTICATED_REST, user_data_stream_type): 210 | lastUpdate = time.time() 211 | 212 | while self.listen_key != None: 213 | if (lastUpdate + 1800) < time.time(): 214 | AUTHENTICATED_REST.send_listenKey_keepAlive(user_data_stream_type, listenKey=self.listen_key) 215 | lastUpdate = time.time() 216 | 217 | time.sleep(1) 218 | 219 | 220 | def make_api_call(self, api_info, users_passed_parameters={}): 221 | if 'listenKey' not in users_passed_parameters: 222 | if 'symbol' in users_passed_parameters: 223 | if '-' in users_passed_parameters['symbol']: 224 | base, quote = users_passed_parameters['symbol'].split('-') 225 | users_passed_parameters.update({'symbol':(quote+base).lower()}) 226 | 227 | target_endpoint, params, headers, body = api_support_tools.param_check(api_info, users_passed_parameters) 228 | stream_name = target_endpoint 229 | else: 230 | stream_name = users_passed_parameters['listenKey'] 231 | 232 | if 'remove_stream' in users_passed_parameters: 233 | if users_passed_parameters['remove_stream']: 234 | if stream_name in self.stream_names: 235 | self.stream_names.remove(stream_name) 236 | return({'result':'REMOVED_STREAM_NAME', 'stream':stream_name}) 237 | 238 | if self.ws != None and self.socketRunning: 239 | self.unsubscribe_streams(params=[stream_name]) 240 | 241 | else: 242 | if stream_name in self.stream_names: 243 | return('STREAM_[{0}]_ALREADY_EXISTS'.format(stream_name)) 244 | self.stream_names.append(stream_name) 245 | 246 | if self.ws != None and self.socketRunning: 247 | self.subscribe_streams(params=[stream_name]) 248 | 249 | if self.query.split('/')[3] == 'ws': 250 | self.set_property(params=['combined',True]) 251 | 252 | return({'result':'CREATED_STREAM_NAME', 'stream':stream_name}) 253 | 254 | 255 | def start(self): 256 | ''' 257 | This is used to start the socket. 258 | ''' 259 | if self.socketRunning: 260 | return('SOCKET_STILL_RUNNING_PLEASE_RESTART') 261 | 262 | ## -------------------------------------------------------------- ## 263 | ## Here the sockets URL is set so it can be connected to.NO_STREAMS_SET 264 | logging.debug('[SOCKET_MASTER] Setting up socket stream URL.') 265 | if self.query == '': 266 | if self.build_query() == 'NO_STREAMS_SET': 267 | return('UNABLE_TO_START_NO_STREAMS_SET') 268 | self.destURL = self.query 269 | 270 | ## -------------------------------------------------------------- ## 271 | ## Here the 'create_socket' function is called to attempt a connection to the socket. 272 | logging.debug('[SOCKET_MASTER] Setting up socket connection.') 273 | self._create_socket() 274 | 275 | ## -------------------------------------------------------------- ## 276 | # This block is used to test connectivity to the socket. 277 | conn_timeout = 5 278 | while not self.ws.sock or not self.ws.sock.connected and conn_timeout: 279 | time.sleep(5) 280 | conn_timeout -= 1 281 | 282 | if not conn_timeout: 283 | ## If the timeout limit is reached then the websocket is force closed. 284 | self.ws.close() 285 | raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.') 286 | 287 | self.socketRunning = True 288 | logging.info('[SOCKET_MASTER] Sucessfully established the socket.') 289 | 290 | 291 | def stop(self): 292 | 293 | if self.ws: 294 | self.ws.close() 295 | 296 | self.socketRunning = False 297 | self.socketBuffer = {} 298 | self.ws = None 299 | 300 | 301 | def _create_socket(self): 302 | ''' 303 | This is used to initilise connection and set it up to the exchange. 304 | ''' 305 | self.ws = websocket.WebSocketApp(self.destURL, 306 | on_open = self._on_Open, 307 | on_message = self._on_Message, 308 | on_error = self._on_Error, 309 | on_close = self._on_Close, 310 | on_ping = self._on_Ping, 311 | on_pong = self._on_Pong) 312 | 313 | wsthread = threading.Thread(target=lambda: self.ws.run_forever()) 314 | wsthread.start() 315 | 316 | 317 | def _send_message(self, method, params=None): 318 | 319 | message = {'method':method, 320 | 'id':self.id_counter} 321 | 322 | if params != None and params != []: 323 | message.update({'params':params}) 324 | 325 | message = json.dumps(message) 326 | 327 | response_data = self.ws.sock.send(message) 328 | 329 | keys = self.requested_items.keys() 330 | 331 | if len(keys) > self.MAX_REQUEST_ITEMS: 332 | del self.requested_items[min(keys)] 333 | 334 | self.requested_items.update({self.id_counter:None}) 335 | self.id_counter += 1 336 | return(self.id_counter) 337 | 338 | 339 | def _on_Open(self, wsapp): 340 | ''' 341 | This is called to manually open the websocket connection. 342 | ''' 343 | logging.debug('[SOCKET_MASTER] Websocket Opened.') 344 | 345 | 346 | def _on_Message(self, wsapp, message): 347 | ''' 348 | This is used to handle any messages recived via the websocket. 349 | ''' 350 | try: 351 | raw_data = json.loads(message) 352 | except Exception as e: 353 | print('section 2') 354 | print(e) 355 | raw_data = None 356 | 357 | self.last_data_recv_time = time.time() 358 | 359 | if raw_data != None: 360 | if 'data' in raw_data: 361 | data = raw_data['data'] 362 | else: 363 | data = raw_data 364 | 365 | if 'id' in data: 366 | if int(data['id']) in self.requested_items: 367 | if data['result'] == None: 368 | self.requested_items[int(data['id'])] = True 369 | else: 370 | self.requested_items[int(data['id'])] = data['result'] 371 | 372 | if 'e' in data: 373 | if self.live_and_historic_data: 374 | if data['e'] == 'kline': 375 | self._update_candles(data) 376 | 377 | elif data['e'] == 'depthUpdate': 378 | self._update_depth(data) 379 | 380 | else: 381 | if 'outboundAccountInfo' == data['e']: 382 | self.socketBuffer.update({data['e']:data}) 383 | elif 'outboundAccountPosition' == data['e']: 384 | self.socketBuffer.update({data['e']:data}) 385 | else: 386 | if data['e'] == 'balanceUpdate': 387 | pass 388 | else: 389 | try: 390 | self.socketBuffer.update({data['s']:{data['e']:data}}) 391 | except Exception as e: 392 | print(e) 393 | print('section 1') 394 | print(raw_data) 395 | else: 396 | self.socketBuffer.update({data['e']:data}) 397 | 398 | 399 | 400 | def _on_Ping(self, wsapp, message): 401 | ''' 402 | This is called to manually open the websocket connection. 403 | ''' 404 | logging.debug('[SOCKET_MASTER] Websocket ping.') 405 | 406 | 407 | def _on_Pong(self, wsapp, message): 408 | ''' 409 | This is called to manually open the websocket connection. 410 | ''' 411 | logging.debug('[SOCKET_MASTER] Websocket pong.') 412 | 413 | 414 | def _on_Error(self, wsapp, error): 415 | ''' 416 | This is called when the socket recives an connection based error. 417 | ''' 418 | logging.warning('[SOCKET_MASTER] Socket error: {0}'.format(error)) 419 | 420 | 421 | def _on_Close(self, wsapp, close_status_code, close_msg): 422 | ''' 423 | This is called for manually closing the websocket. 424 | ''' 425 | self.socketRunning = False 426 | logging.info('[SOCKET_MASTER]: Socket closed.') 427 | 428 | 429 | def _set_initial_candles(self, symbol, interval, rest_api): 430 | try: 431 | hist_candles = rest_api.get_custom_candles(symbol=symbol, interval=interval, limit=self.BASE_CANDLE_LIMIT) 432 | except Exception as error: 433 | logging.critical('[SOCKET_MASTER] _initial_candles error {0}'.format(error)) 434 | logging.warning('[SOCKET_MASTER] _initial_candles {0}'.format(hist_candles)) 435 | self.candle_data.update({symbol:hist_candles}) 436 | 437 | 438 | def _set_initial_depth(self, symbol, rest_api): 439 | try: 440 | rest_data = rest_api.get_orderBook(symbol=symbol, limit=self.BASE_DEPTH_LIMIT) 441 | hist_books = formatter.format_depth(rest_data, 'REST') 442 | except Exception as error: 443 | logging.critical('[SOCKET_MASTER] _set_initial_depth error {0}'.format(error)) 444 | logging.warning('[SOCKET_MASTER] _set_initial_depth {0}'.format(rest_data)) 445 | self.book_data.update({symbol:hist_books}) 446 | 447 | 448 | def _update_candles(self, data): 449 | rC = data['k'] 450 | 451 | live_candle_data = formatter.format_candles(rC, 'SOCK') 452 | 453 | if live_candle_data[0] == self.candle_data[rC['s']][0][0]: 454 | self.candle_data[rC['s']][0] = live_candle_data 455 | 456 | else: 457 | if live_candle_data[0] > self.candle_data[rC['s']][0][0]: 458 | self.candle_data[rC['s']].insert(0, live_candle_data) 459 | self.candle_data[rC['s']] = self.candle_data[rC['s']][:self.BASE_CANDLE_LIMIT] 460 | 461 | 462 | def _update_depth(self, data): 463 | live_depth_data = formatter.format_depth(data, 'SOCK') 464 | 465 | for lask in live_depth_data['a']: 466 | if lask[1] in self.book_data[data['s']]['a']: 467 | if lask[2] == 0.0: 468 | del self.book_data[data['s']]['a'][lask[1]] 469 | continue 470 | 471 | if self.book_data[data['s']]['a'][lask[1]][0] >= lask[0]: 472 | continue 473 | 474 | self.book_data[data['s']]['a'].update({lask[1]:[lask[0],lask[2]]}) 475 | 476 | for lbid in live_depth_data['b']: 477 | if lbid[1] in self.book_data[data['s']]['b']: 478 | if lbid[2] == 0.0: 479 | del self.book_data[data['s']]['b'][lbid[1]] 480 | continue 481 | 482 | if self.book_data[data['s']]['b'][lbid[1]][0] >= lbid[0]: 483 | continue 484 | 485 | self.book_data[data['s']]['b'].update({lbid[1]:[lbid[0],lbid[2]]}) 486 | 487 | all_ask_prices = list(self.book_data[data['s']]['a'].keys()) 488 | all_ask_prices.sort() 489 | if len(all_ask_prices) > self.BASE_DEPTH_LIMIT+1: 490 | all_ask_prices_to_cut = all_ask_prices[self.BASE_DEPTH_LIMIT:] 491 | for aPrice in all_ask_prices_to_cut: 492 | if aPrice in self.book_data[data['s']]['a']: 493 | del self.book_data[data['s']]['a'][aPrice] 494 | 495 | all_bid_prices = list(self.book_data[data['s']]['b'].keys()) 496 | all_bid_prices.sort(reverse=True) 497 | if len(all_bid_prices) > self.BASE_DEPTH_LIMIT + 1: 498 | all_bid_prices_to_cut = all_bid_prices[self.BASE_DEPTH_LIMIT:] 499 | for bPrice in all_bid_prices_to_cut: 500 | if bPrice in self.book_data[data['s']]['b']: 501 | del self.book_data[data['s']]['b'][bPrice] 502 | 503 | 504 | def _orderbook_sorter_algo(self, books_dict_base, side): 505 | book_depth_organised = [] 506 | 507 | prices_list = list(books_dict_base.keys()) 508 | 509 | if side == 'ask': 510 | prices_list.sort() 511 | elif side == 'bid': 512 | prices_list.sort(reverse=True) 513 | 514 | prices_list = prices_list 515 | 516 | for price in prices_list: 517 | if price in books_dict_base: 518 | book_depth_organised.append([price, books_dict_base[price][1]]) 519 | 520 | return(book_depth_organised) 521 | -------------------------------------------------------------------------------- /binance_api/api_support_tools.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | import re 4 | import time 5 | import json 6 | import logging 7 | from datetime import datetime 8 | 9 | from . import api_master_rest_caller 10 | 11 | BASE_1m = (60*1000) 12 | BASE_1h = BASE_1m*60 13 | BASE_1d = BASE_1h*24 14 | BASE_1w = BASE_1d*7 15 | 16 | BASE_BINANCE_MINS = [1, 3, 5, 15, 30] 17 | BASE_BINANCE_HOURS = [1, 2, 4, 6, 8, 12] 18 | BASE_BINANAE_DAYS = [1, 3] 19 | BASE_BINANCE_WEEKS = [1] 20 | 21 | 22 | def _combined_param_list(api_info): 23 | all_params_cat = {'R':{},'O':{}} 24 | all_params_uncat = [] 25 | # Check for url parameters/url fillin parameters 26 | 27 | for param_type in ['R','O']: # Check for Required and Optional parameters. 28 | for data_type in ['P', 'H', 'B']: # Check for Parameters (url params/fillin gaps), Headers, Post Body. 29 | try: 30 | if data_type == 'P': 31 | target_data_type = api_info.params 32 | elif data_type == 'H': 33 | target_data_type = api_info.headers 34 | elif data_type == 'B': 35 | target_data_type = api_info.body 36 | except AttributeError as error: 37 | # If no data is available just set as null and pass. 38 | target_data_type = None 39 | 40 | # Check if there is data availible. 41 | if target_data_type != None: 42 | if param_type in target_data_type: 43 | all_params_cat[param_type].update({data_type:[]}) 44 | all_params_cat[param_type][data_type].extend(target_data_type[param_type]) 45 | 46 | # Get a list of all the parameters by themselves. 47 | for req_op in all_params_cat: 48 | for data_types in all_params_cat[req_op]: 49 | for key_value in all_params_cat[req_op][data_types]: 50 | if not(key_value in all_params_uncat): 51 | all_params_uncat.append(key_value) 52 | 53 | return(all_params_cat, all_params_uncat) 54 | 55 | 56 | def param_check(api_info, users_passed_parameters={}): 57 | params = {} 58 | headers = {} 59 | body = {} 60 | 61 | # Check for any URL parameters that need populated. 62 | target_endpoint = api_info.endpoint 63 | missing_url_params = [] 64 | if '<' in target_endpoint and '>' in target_endpoint: 65 | url_variables = re.findall(r'<([^>]+)>', target_endpoint) 66 | for val in url_variables: 67 | if val in users_passed_parameters: 68 | target_endpoint = target_endpoint.replace("<{0}>".format(val), users_passed_parameters[val]) 69 | del users_passed_parameters[val] 70 | else: 71 | missing_url_params.append(val) 72 | 73 | if len(missing_url_params) >= 1: 74 | return('MISSING_REQUIRED_PARAMETERS', missing_url_params) 75 | 76 | organised_params, full_params_list = _combined_param_list(api_info) 77 | 78 | ## Update parameter checks 79 | if full_params_list != []: 80 | # Check if ALL required parameters are passed and if not return a message saying what are missing. 81 | missingParameters = [] 82 | for data_type in organised_params['R']: 83 | for key_value in organised_params['R'][data_type]: 84 | if not key_value in users_passed_parameters: 85 | missingParameters.append(key_value) 86 | 87 | if len(missingParameters) >= 1: 88 | return('MISSING_REQUIRED_PARAMETERS', missingParameters) 89 | 90 | # Sort the passed data to the correct variable types (body, header, urlparams) 91 | for req_op in organised_params: 92 | for data_types in organised_params[req_op]: 93 | current_kv_required = organised_params[req_op][data_types] 94 | for key_value in users_passed_parameters: 95 | if key_value in current_kv_required: 96 | if data_types == 'P': 97 | params.update({key_value:users_passed_parameters[key_value]}) 98 | elif data_types == 'H': 99 | headers.update({key_value:users_passed_parameters[key_value]}) 100 | elif data_types == 'B': 101 | body.update({key_value:users_passed_parameters[key_value]}) 102 | 103 | else: 104 | if users_passed_parameters != None and users_passed_parameters != {}: 105 | return('ENDPOINT_TAKES_NO_PARAMETERS_BUT_SOME_WHERE_GIVEN', users_passed_parameters) 106 | 107 | return(target_endpoint, params, headers, body) 108 | 109 | 110 | 111 | def get_custom_trades(kwargs): 112 | ''' ''' 113 | trade_data = [] 114 | total_trades_left = kwargs['limit'] 115 | t_id = 0 116 | 117 | if total_trades_left > 1000: 118 | authApi = api_master_rest_caller.Binance_REST(kwargs['pubKey'], kwargs['prvKey']) 119 | 120 | while True: 121 | if total_trades_left > 1000: 122 | total_trades_left -= 1000 123 | t_limit = 1000 124 | 125 | else: 126 | if total_trades_left == 0: 127 | break 128 | else: 129 | t_limit = total_trades_left 130 | total_trades_left = 0 131 | 132 | if t_id == 0: 133 | trades = api_master_rest_caller.Binance_REST().get_recentTrades( 134 | symbol=kwargs['symbol'], 135 | limit=t_limit) 136 | else: 137 | time.sleep(0.75) 138 | trades = authApi.get_oldTrades( 139 | symbol=kwargs['symbol'], 140 | limit=t_limit, 141 | fromId=t_id) 142 | 143 | t_id = trades[-1]['id'] 144 | trade_data = trade_data + trades 145 | 146 | return(trade_data) 147 | 148 | 149 | def get_custom_candles(kwargs): 150 | ''' ''' 151 | candle_data = [] 152 | 153 | ## 154 | interval_time_type = kwargs['interval'][-1] 155 | 156 | ## 157 | interval_number_multiplier = int(kwargs['interval'][:-1]) 158 | 159 | total_candles_left = kwargs['limit'] 160 | 161 | c_limit = 0 162 | c_start_time = 0 if not 'startTime' in kwargs else kwargs['startTime'] 163 | c_end_time = 0 164 | best_interval = None 165 | 166 | if interval_time_type == 'm': 167 | best_interval = best_interval_calc(BASE_BINANCE_MINS, interval_number_multiplier, 60) 168 | elif interval_time_type == 'h': 169 | best_interval = best_interval_calc(BASE_BINANCE_HOURS, interval_number_multiplier, 24) 170 | elif interval_time_type == 'd': 171 | best_interval = best_interval_calc(BASE_BINANAE_DAYS, interval_number_multiplier, 7) 172 | else: 173 | return('INVALIDE_TIMEFRAME') 174 | 175 | if best_interval == None: 176 | return('ERROR_INVALID_INTEVAL') 177 | 178 | if best_interval == interval_number_multiplier: 179 | total_candles_left = int(kwargs['limit']) 180 | else: 181 | total_candles_left = int(kwargs['limit']*(interval_number_multiplier/best_interval)) 182 | 183 | best_interval = '{0}{1}'.format(best_interval, interval_time_type) 184 | 185 | total_sets_done = 0 186 | total_sets = total_candles_left/1000 187 | 188 | print('Total 1k sets: {0}'.format(total_sets)) 189 | 190 | while True: 191 | 192 | total_left_Time = (total_sets-total_sets_done)*1.2 193 | 194 | if total_left_Time > 60: 195 | time_min, time_sec = str(total_left_Time/60).split('.') 196 | 197 | time_sec = (int(time_sec[:2])/100)*60 198 | 199 | f_total_time = '{0}.{1:.0f}m'.format(int(time_min), time_sec) 200 | else: 201 | f_total_time = '{0}s'.format(int(total_left_Time)) 202 | 203 | 204 | print('Candle sets: {0}/{1}, ETA: {2}'.format(total_sets_done, total_sets, f_total_time)) 205 | 206 | if total_candles_left > 1000: 207 | total_candles_left -= 1000 208 | c_limit = 1000 209 | 210 | else: 211 | if total_candles_left == 0: 212 | break 213 | else: 214 | c_limit = total_candles_left 215 | total_candles_left = 0 216 | 217 | total_sets_done += c_limit/1000 218 | 219 | if c_end_time == 0: 220 | candles = api_master_rest_caller.Binance_REST().get_candles( 221 | symbol=kwargs['symbol'], 222 | interval=best_interval, 223 | limit=c_limit) 224 | else: 225 | time.sleep(0.75) 226 | candles = api_master_rest_caller.Binance_REST().get_candles( 227 | symbol=kwargs['symbol'], 228 | interval=best_interval, 229 | limit=c_limit, 230 | endTime=c_end_time) 231 | 232 | c_end_time = candles[-1][0]-1 233 | candle_data = candle_data + candles 234 | 235 | ## To be used to build custom timeframes 236 | if best_interval != kwargs['interval']: 237 | 238 | # Build the most recent candles close time into a valid timestamp. 239 | cc_time=round((candle_data[0][6]/1000)) 240 | 241 | if interval_time_type == 'm': 242 | current_time = time.localtime()[4] 243 | split_time = int(str(datetime.fromtimestamp(cc_time))[11:].split(':')[1]) 244 | elif interval_time_type == 'h': 245 | current_time = time.localtime()[3] 246 | split_time = int(str(datetime.fromtimestamp(cc_time))[11:].split(':')[0]) 247 | elif interval_time_type == 'd': 248 | current_time = time.localtime()[2] 249 | split_time = int(str(datetime.fromtimestamp(cc_time))[:10].split('-')[2]) 250 | 251 | # How many candles required for the current candle with the new timeframe. 252 | current_range = round((split_time%interval_number_multiplier)/int(best_interval[:-1])) 253 | 254 | # This holds the amount of candles will be part of 1 with the new timeframe. 255 | normal_range = round(interval_number_multiplier/int(best_interval[:-1])) 256 | 257 | # max amount of candles for new timeframe. 258 | candles_for_new_timeframe = round(len(candle_data)/normal_range)-1 259 | 260 | # New empty list where the newly built candles will be held 261 | buit_candles = [] 262 | 263 | for i in range(candles_for_new_timeframe): 264 | ccstart = i*current_range 265 | ccend = (i*current_range)+current_range 266 | 267 | otime = candle_data[ccend-1][0] 268 | copen = candle_data[ccend-1][1] 269 | chigh = 0 270 | clow = 9999 271 | cclose = candle_data[ccstart][4] 272 | cvolume = 0 273 | closetime = candle_data[ccstart][6] 274 | qavolume = 0 275 | numtrades = 0 276 | 277 | for x, candle in enumerate(candle_data[ccstart:ccend]): 278 | chigh = candle[2] if candle[2] > chigh else chigh 279 | clow = candle[3] if candle[3] < clow else clow 280 | cvolume += candle[5] 281 | qavolume += candle[7] 282 | numtrades += candle[8] 283 | 284 | buit_candles.append([otime, copen, chigh, clow, cclose, cvolume, closetime, qavolume, numtrades]) 285 | 286 | current_range = normal_range 287 | 288 | return_candles = buit_candles 289 | else: 290 | return_candles = candle_data 291 | 292 | return(return_candles) 293 | 294 | 295 | def best_interval_calc(base_intervals, target_interval, max_time): 296 | best_interval = None 297 | 298 | if max_time == 0: 299 | return(target_interval) 300 | 301 | if not(target_interval in base_intervals) and (max_time % target_interval == 0): 302 | for current_interval in base_intervals: 303 | if (current_interval < target_interval) and (target_interval % current_interval == 0): 304 | best_interval = current_interval 305 | elif current_interval > target_interval: 306 | break 307 | 308 | if target_interval in base_intervals: 309 | best_interval = target_interval 310 | 311 | return(best_interval) -------------------------------------------------------------------------------- /binance_api/blvt_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the BLVT Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#blvt-endpoints 4 | ''' 5 | 6 | # Get BLVT Info: 7 | class get_blvt_info: 8 | params = {'O':['tokenName']} 9 | method = 'GET' 10 | endpoint = '/sapi/v1/blvt/tokenInfo' 11 | security_type = 'MARKET_DATA' 12 | 13 | 14 | # Historical BLVT NAV Kline/Candlestick: 15 | class get_blvt_historic_candles: 16 | ''' 17 | Endpoint is based on binance future endpoint (fapi) 18 | ''' 19 | pass 20 | 21 | 22 | # Subscribe BLVT: 23 | class subscribe_blvt: 24 | params = {'R':['tokenName', 'cost']} 25 | method = 'POST' 26 | endpoint = '/sapi/v1/blvt/subscribe' 27 | security_type = 'USER_DATA' 28 | 29 | 30 | # Query Subscription Record: 31 | class query_subscription_record: 32 | params = {'O':['tokenName', 'id', 'startTime', 'endTime', 'limit']} 33 | method = 'GET' 34 | endpoint = '/sapi/v1/blvt/subscribe/record' 35 | security_type = 'USER_DATA' 36 | 37 | 38 | # Redeem BLVT: 39 | class redeem_blvt: 40 | params = {'R':['tokenName', 'amount']} 41 | method = 'POST' 42 | endpoint = '/sapi/v1/blvt/redeem' 43 | security_type = 'USER_DATA' 44 | 45 | 46 | # Query Redemption Record: 47 | class query_redemption_record: 48 | params = {'O':['tokenName', 'id', 'startTime', 'endTime', 'limit']} 49 | method = 'GET' 50 | endpoint = '/sapi/v1/blvt/redeem/record' 51 | security_type = 'USER_DATA' 52 | 53 | 54 | # Get BLVT User Limit Info: 55 | class get_blvt_userLimit: 56 | params = {'O':['tokenName']} 57 | method = 'GET' 58 | endpoint = '/sapi/v1/blvt/userLimit' 59 | security_type = 'USER_DATA' 60 | 61 | 62 | # Websocket BLVT Info Streams: 63 | class blvt_info_stream: 64 | ''' 65 | Endpoint is based on binance future websocket (fstream or fstream3) 66 | ''' 67 | pass 68 | 69 | 70 | # BLVT NAV Kline/Candlestick Streams: 71 | class blvt_candle_stream: 72 | ''' 73 | Endpoint is based on binance future websocket (fstream or fstream3) 74 | ''' 75 | pass -------------------------------------------------------------------------------- /binance_api/bswap_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the BSwap Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#bswap-endpoints 4 | ''' 5 | 6 | # List All Swap Pools: 7 | class get_swap_pools: 8 | params = None 9 | method = 'GET' 10 | endpoint = '/sapi/v1/bswap/pools' 11 | security_type = 'MARKET_DATA' 12 | 13 | 14 | # Get liquidity information of a pool: 15 | class get_liquidity_poolInfo: 16 | params = {'O':['poolId']} 17 | method = 'GET' 18 | endpoint = '/sapi/v1/bswap/liquidity' 19 | security_type = 'USER_DATA' 20 | 21 | 22 | # Add Liquidity: 23 | class add_liquidity: 24 | params = {'R':['poolId', 'asset', 'quantity']} 25 | method = 'POST' 26 | endpoint = '/sapi/v1/bswap/liquidityAdd' 27 | security_type = 'TRADE' 28 | 29 | 30 | # Remove Liquidity: 31 | class remove_liquidity: 32 | params = {'R':['poolId', 'type', 'asset', 'shareAmount']} 33 | method = 'POST' 34 | endpoint = '/sapi/v1/bswap/liquidityRemove' 35 | security_type = 'TRADE' 36 | 37 | 38 | # Get Liquidity Operation Record: 39 | class get_liquidity_record: 40 | params = {'O':['operationId', 'poolId', 'operation', 'startTime', 'endTime', 'limit']} 41 | method = 'GET' 42 | endpoint = '/sapi/v1/bswap/liquidityOps' 43 | security_type = 'USER_DATA' 44 | 45 | 46 | # Request Quote: 47 | class get_quote: 48 | params = {'R':['quoteAsset', 'baseAsset', 'quoteQty']} 49 | method = 'GET' 50 | endpoint = '/sapi/v1/bswap/quote' 51 | security_type = 'USER_DATA' 52 | 53 | 54 | # Swap: 55 | class make_swap: 56 | params = {'R':['quoteAsset', 'baseAsset', 'quoteQty']} 57 | method = 'POST' 58 | endpoint = '/sapi/v1/bswap/swap' 59 | security_type = 'TRADE' 60 | 61 | 62 | # Get Swap History : 63 | class get_swap_history: 64 | params = {'O':['swapId', 'startTime', 'endTime', 'status', 'quoteAsset', 'baseAsset', 'limit']} 65 | method = 'GET' 66 | endpoint = '/sapi/v1/bswap/swap' 67 | security_type = 'USER_DATA' 68 | -------------------------------------------------------------------------------- /binance_api/formatter.py: -------------------------------------------------------------------------------- 1 | 2 | def format_candles(raw_data, candleType): 3 | ''' 4 | Candle format = 5 | [Open_Time, Open, High, Low, Close, Volume, Close_Time, Quote_Asset_Volume, Num_trades] 6 | ''' 7 | if candleType == 'REST': 8 | format_data = [ 9 | [int(c[0]), 10 | float(c[1]), 11 | float(c[2]), 12 | float(c[3]), 13 | float(c[4]), 14 | float(c[5]), 15 | int(c[6]), 16 | float(c[7]), 17 | int(c[8])] 18 | for c in raw_data] 19 | 20 | format_data.reverse() 21 | 22 | elif candleType == 'SOCK': 23 | c = raw_data 24 | format_data = [int(c['t']), 25 | float(c['o']), 26 | float(c['h']), 27 | float(c['l']), 28 | float(c['c']), 29 | float(c['v']), 30 | int(c['T']), 31 | float(c['q']), 32 | int(c['n'])] 33 | 34 | return(format_data) 35 | 36 | 37 | def format_trades(raw_data): 38 | format_data = [] 39 | raw_data.reverse() 40 | for t in raw_data: 41 | t.update({'side': 'BUY' if t['isBuyerMaker'] else 'SELL'}) 42 | format_data.append(t) 43 | return(format_data) 44 | 45 | 46 | def format_depth(raw_data, candleType): 47 | ''' 48 | Candle format = 49 | [upID, price, quantity] 50 | ''' 51 | if candleType == 'REST': 52 | lastUpdateId = int(raw_data['lastUpdateId']) 53 | 54 | a = {} 55 | b = {} 56 | 57 | for row in raw_data['asks']: 58 | a.update({float(row[0]):[lastUpdateId, float(row[1])]}) 59 | 60 | for row in raw_data['bids']: 61 | b.update({float(row[0]):[lastUpdateId, float(row[1])]}) 62 | 63 | format_data ={ 64 | 'a':a, 65 | 'b':b 66 | } 67 | 68 | elif candleType == 'SOCK': 69 | lastUpdateId = int(raw_data['u']) 70 | 71 | format_data = { 72 | 'a':[[lastUpdateId, float(row[0]), float(row[1])] for row in raw_data['a']], 73 | 'b':[[lastUpdateId, float(row[0]), float(row[1])] for row in raw_data['b']] 74 | } 75 | 76 | return(format_data) 77 | -------------------------------------------------------------------------------- /binance_api/futures_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Futures Endpoint api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#futures 4 | ''' 5 | 6 | # New Future Account Transfer: 7 | class futures_transfer: 8 | params = {'R':['asset', 'amount', 'type']} 9 | method = 'POST' 10 | endpoint = '/sapi/v1/futures/transfer' 11 | security_type = 'USER_DATA' 12 | 13 | 14 | # Get Future Account Transaction History List : 15 | class get_futures_transactions: 16 | params = {'R':['asset', 'startTime'], 17 | 'O':['endTime', 'current', 'size']} 18 | method = 'GET' 19 | endpoint = '/sapi/v1/futures/transfer' 20 | security_type = 'USER_DATA' 21 | 22 | 23 | # Borrow For Cross-Collateral: 24 | class borrow_crossCollat: 25 | params = {'R':['coin', 'amount', 'collateralCoin', 'collateralAmount']} 26 | method = 'POST' 27 | endpoint = '/sapi/v1/futures/loan/borrow' 28 | security_type = 'TRADE' 29 | 30 | 31 | # Cross-Collateral Borrow History: 32 | class get_crossCollat_borrowHist: 33 | params = {'O':['coin', 'startTime', 'endTime', 'limit']} 34 | method = 'GET' 35 | endpoint = '/sapi/v1/futures/loan/borrow/history' 36 | security_type = 'USER_DATA' 37 | 38 | 39 | # Repay For Cross-Collateral: 40 | class repay_crossCollat: 41 | params = {'R':['coin', 'collateralCoin', 'amount']} 42 | method = 'POST' 43 | endpoint = '/sapi/v1/futures/loan/repay' 44 | security_type = 'USER_DATA' 45 | 46 | 47 | # Cross-Collateral Repayment History: 48 | class get_crossCollat_repayHist: 49 | params = {'R':['coin', 'startTime', 'endTime', 'limit']} 50 | method = 'GET' 51 | endpoint = '/sapi/v1/futures/loan/repay/history' 52 | security_type = 'USER_DATA' 53 | 54 | 55 | # Cross-Collateral Wallet: 56 | class get_crossCollat_wallet: 57 | params = None 58 | method = 'GET' 59 | endpoint = '/sapi/v1/futures/loan/wallet' 60 | security_type = 'USER_DATA' 61 | 62 | 63 | # Cross-Collateral Wallet V2: 64 | class get_crossCollat_wallet_v2: 65 | params = None 66 | method = 'GET' 67 | endpoint = '/sapi/v2/futures/loan/wallet' 68 | security_type = 'USER_DATA' 69 | 70 | 71 | # Cross-Collateral Information: 72 | class get_crossCollat_info: 73 | params = {'O':['collateralCoin']} 74 | method = 'GET' 75 | endpoint = '/sapi/v1/futures/loan/configs' 76 | security_type = 'USER_DATA' 77 | 78 | 79 | # Cross-Collateral Information V2: 80 | class get_crossCollat_info_v2: 81 | params = {'O':['loanCoin', 'collateralCoin']} 82 | method = 'GET' 83 | endpoint = '/sapi/v2/futures/loan/configs' 84 | security_type = 'USER_DATA' 85 | 86 | 87 | # Calculate Rate After Adjust Cross-Collateral LTV: 88 | class get_crossCollat_rate_LTV: 89 | params = {'R':['collateralCoin', 'amount', 'direction']} 90 | method = 'GET' 91 | endpoint = '/sapi/v1/futures/loan/calcAdjustLevel' 92 | security_type = 'USER_DATA' 93 | 94 | 95 | # Calculate Rate After Adjust Cross-Collateral LTV V2: 96 | class get_crossCollat_rate_LTV_v2: 97 | params = {'R':['loanCoin', 'collateralCoin', 'amount', 'direction']} 98 | method = 'GET' 99 | endpoint = '/sapi/v2/futures/loan/calcAdjustLevel' 100 | security_type = 'USER_DATA' 101 | 102 | 103 | # Get Max Amount for Adjust Cross-Collateral LTV: 104 | class get_crossCollat_max_LTV: 105 | params = {'R':['collateralCoin']} 106 | method = 'GET' 107 | endpoint = '/sapi/v1/futures/loan/calcMaxAdjustAmount' 108 | security_type = 'USER_DATA' 109 | 110 | 111 | # Get Max Amount for Adjust Cross-Collateral LTV V2: 112 | class get_crossCollat_max_LTV_v2: 113 | params = {'R':['loanCoin', 'collateralCoin']} 114 | method = 'GET' 115 | endpoint = '/sapi/v2/futures/loan/calcMaxAdjustAmount' 116 | security_type = 'USER_DATA' 117 | 118 | 119 | # Adjust Cross-Collateral LTV: 120 | class adjust_crossCollat_LTV: 121 | params = {'R':['collateralCoin', 'amount', 'direction']} 122 | method = 'POST' 123 | endpoint = '/sapi/v1/futures/loan/adjustCollateral' 124 | security_type = 'TRADE' 125 | 126 | 127 | # Adjust Cross-Collateral LTV V2: 128 | class adjust_crossCollat_LTV_v2: 129 | params = {'R':['loanCoin', 'collateralCoin', 'amount', 'direction']} 130 | method = 'POST' 131 | endpoint = '/sapi/v2/futures/loan/adjustCollateral' 132 | security_type = 'TRADE' 133 | 134 | 135 | # Adjust Cross-Collateral LTV History: 136 | class adjust_crossCollat_LTV_history: 137 | params = {'O':['loanCoin', 'collateralCoin', 'startTime', 'endTime', 'limit']} 138 | method = 'GET' 139 | endpoint = '/sapi/v1/futures/loan/adjustCollateral/history' 140 | security_type = 'USER_DATA' 141 | 142 | 143 | # Cross-Collateral Liquidation History: 144 | class adjust_crossCollat_liquidation_history: 145 | params = {'O':['loanCoin', 'collateralCoin', 'startTime', 'endTime', 'limit']} 146 | method = 'GET' 147 | endpoint = '/sapi/v1/futures/loan/liquidationHistory' 148 | security_type = 'USER_DATA' 149 | 150 | 151 | # Check Collateral Repay Limit: 152 | class get_collatRepay_limit: 153 | params = {'R':['coin', 'collateralCoin']} 154 | method = 'GET' 155 | endpoint = '/sapi/v1/futures/loan/collateralRepayLimit' 156 | security_type = 'USER_DATA' 157 | 158 | 159 | # Get Collateral Repay Quote: 160 | class get_collatRepay_quote: 161 | params = {'R':['coin', 'collateralCoin', 'amount']} 162 | method = 'GET' 163 | endpoint = '/sapi/v1/futures/loan/collateralRepay' 164 | security_type = 'USER_DATA' 165 | 166 | 167 | # Repay with Collateral: 168 | class collateral_repay: 169 | params = {'R':['quoteId']} 170 | method = 'POST' 171 | endpoint = '/sapi/v1/futures/loan/collateralRepay' 172 | security_type = 'USER_DATA' 173 | 174 | 175 | # Collateral Repayment Result: 176 | class get_collatRepay_result: 177 | params = {'R':['quoteId']} 178 | method = 'GET' 179 | endpoint = '/sapi/v1/futures/loan/collateralRepayResult' 180 | security_type = 'USER_DATA' 181 | 182 | 183 | # Cross-Collateral Interest History: 184 | class get_crossCollat_interestHist: 185 | params = {'O':['collateralCoin', 'startTime', 'endTime', 'current', 'limit']} 186 | method = 'GET' 187 | endpoint = '/sapi/v1/futures/loan/interestHistory' 188 | security_type = 'USER_DATA' -------------------------------------------------------------------------------- /binance_api/margin_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Margin Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#margin-account-trade 4 | ''' 5 | 6 | # Cross Margin Account Transfer: 7 | class margin_transfer: 8 | params = {'R':['asset', 'amount', 'type']} 9 | method = 'POST' 10 | endpoint = '/sapi/v1/margin/transfer' 11 | security_type = 'MARGIN' 12 | 13 | 14 | # Margin Account Borrow: 15 | class margin_accountBorrow: 16 | params = {'R':['asset', 'amount'], 17 | 'O':['isIsolated', 'symbol']} 18 | method = 'POST' 19 | endpoint = '/sapi/v1/margin/loan' 20 | security_type = 'MARGIN' 21 | 22 | 23 | # Margin Account Repay: 24 | class margin_accountRepay: 25 | params = {'R':['asset', 'amount'], 26 | 'O':['isIsolated', 'symbol']} 27 | method = 'POST' 28 | endpoint = '/sapi/v1/margin/repay' 29 | security_type = 'MARGIN' 30 | 31 | 32 | # Query Margin Asset: 33 | class query_margin_asset: 34 | params = {'R':['asset']} 35 | method = 'GET' 36 | endpoint = '/sapi/v1/margin/asset' 37 | security_type = 'MARKET_DATA' 38 | 39 | 40 | # Query Cross Margin Pair: 41 | class query_crossPair: 42 | params = {'R':['symbol']} 43 | method = 'GET' 44 | endpoint = '/sapi/v1/margin/pair' 45 | security_type = 'MARKET_DATA' 46 | 47 | # Get All Margin Assets: 48 | class get_margin_allAssets: 49 | params = None 50 | method = 'GET' 51 | endpoint = '/sapi/v1/margin/allAssets' 52 | security_type = 'MARKET_DATA' 53 | 54 | 55 | # Get All Cross Margin Pairs: 56 | class get_allCrossPairs: 57 | params = None 58 | method = 'GET' 59 | endpoint = '/sapi/v1/margin/allPairs' 60 | security_type = 'MARKET_DATA' 61 | 62 | 63 | # Query Margin PriceIndex: 64 | class query_margin_priceIndex: 65 | params = {'R':['symbol']} 66 | method = 'GET' 67 | endpoint = '/sapi/v1/margin/priceIndex' 68 | security_type = 'MARKET_DATA' 69 | 70 | 71 | # Margin Account New Order: 72 | class place_order: 73 | params = {'R':['symbol', 'side', 'type'], 74 | 'O':['isIsolated', 'quantity', 'quoteOrderQty', 'price', 'stopPrice', 'newClientOrderId', 'icebergQty', 'newOrderRespType', 'sideEffectType', 'timeInForce']} 75 | method = 'POST' 76 | endpoint = '/sapi/v1/margin/order' 77 | security_type = 'TRADE' 78 | 79 | 80 | # Margin Account Cancel Order: 81 | class cancel_order: 82 | params = {'R':['symbol'], 83 | 'O':['isIsolated', 'orderId', 'origClientOrderId', 'newClientOrderId']} 84 | method = 'DELETE' 85 | endpoint = '/sapi/v1/margin/order' 86 | security_type = 'TRADE' 87 | 88 | 89 | # Margin Account Cancel all Open Orders on a Symbol: 90 | class cancel_all_orders: 91 | params = {'R':['symbol'], 92 | 'O':['isIsolated']} 93 | method = 'DELETE' 94 | endpoint = '/sapi/v1/margin/openOrders' 95 | security_type = 'TRADE' 96 | 97 | 98 | # Get Cross Margin Transfer History: 99 | class get_margin_crossTransferHistory: 100 | params = {'O':['asset', 'type', 'startTime', 'endTime', 'current', 'size', 'archived']} 101 | method = 'GET' 102 | endpoint = '/sapi/v1/margin/transfer' 103 | security_type = 'USER_DATA' 104 | 105 | 106 | # Query Loan Record: 107 | class get_loanRecord: 108 | params = {'R':['asset'], 109 | 'O':['isolatedSymbol', 'txId', 'startTime', 'endTime', 'current', 'size', 'archived']} 110 | method = 'GET' 111 | endpoint = '/sapi/v1/margin/loan' 112 | security_type = 'USER_DATA' 113 | 114 | 115 | # Query Repay Record: 116 | class get_repayRecord: 117 | params = {'R':['asset'], 118 | 'O':['isolatedSymbol', 'txId', 'startTime', 'endTime', 'current', 'size', 'archived']} 119 | method = 'GET' 120 | endpoint = '/sapi/v1/margin/repay' 121 | security_type = 'USER_DATA' 122 | 123 | 124 | # Get Interest History: 125 | class get_interestHistory: 126 | params = {'O':['asset', 'isolatedSymbol', 'startTime', 'endTime', 'current', 'size', 'archived']} 127 | method = 'GET' 128 | endpoint = '/sapi/v1/margin/interestHistory' 129 | security_type = 'USER_DATA' 130 | 131 | 132 | # Get Force Liquidation Record: 133 | class get_fLiquidationRecord: 134 | params = {'O':['startTime', 'endTime', 'isolatedSymbol', 'current', 'size']} 135 | method = 'GET' 136 | endpoint = '/sapi/v1/margin/forceLiquidationRec' 137 | security_type = 'USER_DATA' 138 | 139 | 140 | # Query Cross Margin Account Details: 141 | class get_cross_accountDetails: 142 | params = None 143 | method = 'GET' 144 | endpoint = '/sapi/v1/margin/account' 145 | security_type = 'USER_DATA' 146 | 147 | 148 | # Query Margin Account's Order: 149 | class get_order: 150 | params = {'R':['symbol'], 151 | 'O':['isIsolated', 'orderId', 'origClientOrderId']} 152 | method = 'GET' 153 | endpoint = '/sapi/v1/margin/order' 154 | security_type = 'USER_DATA' 155 | 156 | 157 | # Query Margin Account's Open Orders: 158 | class get_open_orders: 159 | params = {'O':['symbol', 'isIsolated']} 160 | method = 'GET' 161 | endpoint = '/sapi/v1/margin/openOrders' 162 | security_type = 'USER_DATA' 163 | 164 | 165 | # Query Margin Account's All Orders: 166 | class get_all_orders: 167 | params = {'R':['symbol'], 168 | 'O':['isIsolated', 'orderId', 'startTime', 'endTime', 'limit']} 169 | method = 'GET' 170 | endpoint = '/sapi/v1/margin/allOrders' 171 | security_type = 'USER_DATA' 172 | 173 | 174 | # Query Margin Account's Trade List: 175 | class get_all_trades: 176 | params = {'R':['symbol'], 177 | 'O':['isIsolated', 'startTime', 'endTime', 'fromId', 'limit']} 178 | method = 'GET' 179 | endpoint = '/sapi/v1/margin/myTrades' 180 | security_type = 'USER_DATA' 181 | 182 | 183 | # Query Max Borrow: 184 | class get_maxBorrow: 185 | params = {'R':['asset'], 186 | 'O':['isolatedSymbol']} 187 | method = 'GET' 188 | endpoint = '/sapi/v1/margin/maxBorrowable' 189 | security_type = 'USER_DATA' 190 | 191 | 192 | # Query Max Transfer-Out Amount: 193 | class get_maxOutAmmount: 194 | params = {'R':['asset'], 195 | 'O':['isolatedSymbol']} 196 | method = 'GET' 197 | endpoint = '/sapi/v1/margin/maxTransferable' 198 | security_type = 'USER_DATA' 199 | 200 | 201 | # Create Isolated Margin Account: 202 | class create_isolatedMaringAccount: 203 | params = {'R':['base', 'quote']} 204 | method = 'POST' 205 | endpoint = '/sapi/v1/margin/isolated/create' 206 | security_type = 'MARGIN' 207 | 208 | 209 | # Isolated Margin Account Transfer: 210 | class isolated_transfer: 211 | params = {'R':['asset', 'symbol', 'transFrom', 'transTo', 'amount']} 212 | method = 'POST' 213 | endpoint = '/sapi/v1/margin/isolated/transfer' 214 | security_type = 'MARGIN' 215 | 216 | 217 | # Get Isolated Margin Transfer History: 218 | class get_isolated_transferHistory: 219 | params = {'R':['symbol'], 220 | 'O':['asset', 'symbol', 'transFrom', 'transTo', 'startTime', 'endTime', 'current', 'size']} 221 | method = 'GET' 222 | endpoint = '/sapi/v1/margin/isolated/transfer' 223 | security_type = 'USER_DATA' 224 | 225 | 226 | # Query Isolated Margin Account Info 227 | class get_isolated_accountInfo: 228 | params = {'O':['symbols']} 229 | method = 'GET' 230 | endpoint = '/sapi/v1/margin/isolated/account' 231 | security_type = 'USER_DATA' 232 | 233 | 234 | # Query Isolated Margin Symbol: 235 | class get_isolated_symbol: 236 | params = {'R':['symbol'], 237 | 'O':['price']} 238 | method = 'GET' 239 | endpoint = '/sapi/v1/margin/isolated/pair' 240 | security_type = 'USER_DATA' 241 | 242 | 243 | # Get All Isolated Margin Symbol: 244 | class get_isolated_symbol_all: 245 | params = None 246 | method = 'GET' 247 | endpoint = '/sapi/v1/margin/isolated/allPairs' 248 | security_type = 'USER_DATA' 249 | 250 | 251 | # Toggle BNB Burn On Spot Trade And Margin Interest: 252 | class toggle_BNB_burn_ST_MI: 253 | params = {'O':['spotBNBBurn', 'interestBNBBurn']} 254 | method = 'POST' 255 | endpoint = '/sapi/v1/bnbBurn' 256 | security_type = 'USER_DATA' 257 | 258 | 259 | # Get BNB Burn Status: 260 | class get_BNB_burn_status: 261 | params = None 262 | method = 'GET' 263 | endpoint = '/sapi/v1/bnbBurn' 264 | security_type = 'USER_DATA' 265 | 266 | -------------------------------------------------------------------------------- /binance_api/marketData_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Market Data Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#market-data-endpoints 4 | ''' 5 | 6 | # Test Connectivity: 7 | class test_ping: 8 | params = None 9 | method = 'GET' 10 | endpoint = '/api/v3/ping' 11 | security_type = 'None' 12 | 13 | 14 | # Check Server Time: 15 | class get_serverTime: 16 | params = None 17 | method = 'GET' 18 | endpoint = '/api/v3/time' 19 | security_type = 'None' 20 | 21 | 22 | # Exchange Information: 23 | class get_exchangeInfo: 24 | params = None 25 | method = 'GET' 26 | endpoint = '/api/v3/exchangeInfo' 27 | security_type = 'None' 28 | 29 | 30 | # Order Book: 31 | class get_orderBook: 32 | params = {'R':['symbol'], 33 | 'O':['limit']} 34 | method = 'GET' 35 | endpoint = '/api/v3/depth' 36 | security_type = 'None' 37 | 38 | 39 | # Recent Trades List: 40 | class get_recentTrades: 41 | params = {'R':['symbol'], 42 | 'O':['limit']} 43 | method = 'GET' 44 | endpoint = '/api/v3/trades' 45 | security_type = 'None' 46 | 47 | 48 | # Old Trade Lookup: 49 | class get_oldTrades: 50 | params = {'R':['symbol'], 51 | 'O':['limit', 'fromId']} 52 | method = 'GET' 53 | endpoint = '/api/v3/historicalTrades' 54 | security_type = 'None' 55 | 56 | 57 | # Compressed/Aggregate Trades List: 58 | class get_aggTradeList: 59 | params = {'R':['symbol'], 60 | 'O':['limit', 'fromId', 'startTime', 'endTime', 'limit']} 61 | method = 'GET' 62 | endpoint = '/api/v3/aggTrades' 63 | security_type = 'None' 64 | 65 | 66 | # Kline/Candlestick Data: 67 | class get_candles: 68 | params = {'R':['symbol', 'interval'], 69 | 'O':['startTime', 'endTime', 'limit']} 70 | method = 'GET' 71 | endpoint = '/api/v3/klines' 72 | security_type = 'None' 73 | 74 | 75 | # Current Average Price: 76 | class get_averagePrice: 77 | params = {'R':['symbol']} 78 | method = 'GET' 79 | endpoint = '/api/v3/avgPrice' 80 | security_type = 'None' 81 | 82 | 83 | # 24hr Ticker Price Change Statistics: 84 | class get_24hTicker: 85 | params = {'O':['symbol']} 86 | method = 'GET' 87 | endpoint = '/api/v3/ticker/24hr' 88 | security_type = 'None' 89 | 90 | 91 | # Symbol Price Ticker: 92 | class get_priceTicker: 93 | params = {'O':['symbol']} 94 | method = 'GET' 95 | endpoint = '/api/v3/ticker/price' 96 | security_type = 'None' 97 | 98 | 99 | # Symbol Order Book Ticker: 100 | class get_orderbookTicker: 101 | params = {'O':['symbol']} 102 | method = 'GET' 103 | endpoint = '/api/v3/ticker/bookTicker' 104 | security_type = 'None' -------------------------------------------------------------------------------- /binance_api/mining_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Mining Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#mining-endpoints 4 | ''' 5 | 6 | # Acquiring Algorithm: 7 | class get_algorithm: 8 | params = None 9 | method = 'GET' 10 | endpoint = '/sapi/v1/mining/pub/algoList' 11 | security_type = 'USER_DATA' 12 | 13 | 14 | # Acquiring CoinName: 15 | class get_coinNames: 16 | params = None 17 | method = 'GET' 18 | endpoint = '/sapi/v1/mining/pub/coinList' 19 | security_type = 'USER_DATA' 20 | 21 | 22 | # Request for Detail Miner List: 23 | class get_minerList_detail: 24 | params = {'R':['algo', 'userName', 'workerName']} 25 | method = 'GET' 26 | endpoint = '/sapi/v1/mining/worker/detail' 27 | security_type = 'USER_DATA' 28 | 29 | 30 | # Request for Miner List: 31 | class get_minerList: 32 | params = {'R':['algo', 'userName'], 33 | 'O':['pageIndex', 'sort', 'sortColumn', 'worderStatus']} 34 | method = 'GET' 35 | endpoint = '/sapi/v1/mining/worker/list' 36 | security_type = 'USER_DATA' 37 | 38 | 39 | # Earnings List: 40 | class get_earningsList: 41 | params = {'R':['algo', 'userName'], 42 | 'O':['coin', 'startDate', 'endDate', 'pageIndex', 'pageSize']} 43 | method = 'GET' 44 | endpoint = '/sapi/v1/mining/payment/list' 45 | security_type = 'USER_DATA' 46 | 47 | 48 | # Extra Bonus List: 49 | class get_extraBonusList: 50 | params = {'R':['algo', 'userName'], 51 | 'O':['coin', 'startDate', 'endDate', 'pageIndex', 'pageSize']} 52 | method = 'GET' 53 | endpoint = '/sapi/v1/mining/payment/other' 54 | security_type = 'USER_DATA' 55 | 56 | 57 | # Hashrate Resale List: 58 | class get_hashrateResaleList: 59 | params = {'O':['pageIndex', 'pageSize']} 60 | method = 'GET' 61 | endpoint = '/sapi/v1/mining/hash-transfer/config/details/list' 62 | security_type = 'USER_DATA' 63 | 64 | 65 | # Hashrate Resale Detail: 66 | class get_hashrateResaleDetail: 67 | params = {'R':['configId', 'userName'], 68 | 'O':['pageIndex', 'pageSize']} 69 | method = 'GET' 70 | endpoint = '/sapi/v1/mining/hash-transfer/profit/details' 71 | security_type = 'USER_DATA' 72 | 73 | 74 | # Hashrate Resale Request: 75 | class post_hashrateResale: 76 | params = {'R':['userName', 'algo', 'endDate', 'startDate', 'toPoolUser', 'hashRate']} 77 | method = 'POST' 78 | endpoint = '/sapi/v1/mining/hash-transfer/config' 79 | security_type = 'USER_DATA' 80 | 81 | 82 | # Cancel hashrate resale configuration: 83 | class cancel_hashrateResale: 84 | params = {'R':['configId', 'userName']} 85 | method = 'POST' 86 | endpoint = '/sapi/v1/mining/hash-transfer/config/cancel' 87 | security_type = 'USER_DATA' 88 | 89 | 90 | # Statistic List: 91 | class get_statisticList: 92 | params = {'R':['algo', 'userName']} 93 | method = 'GET' 94 | endpoint = '/sapi/v1/mining/statistics/user/status' 95 | security_type = 'USER_DATA' 96 | 97 | 98 | # Account List: 99 | class get_accountList: 100 | params = {'R':['algo', 'userName']} 101 | method = 'GET' 102 | endpoint = '/sapi/v1/mining/statistics/user/list' 103 | security_type = 'USER_DATA' -------------------------------------------------------------------------------- /binance_api/savings_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Saving Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#savings-endpoints 4 | ''' 5 | 6 | # Get Flexible Product List: 7 | class get_productList: 8 | params = {'O':['status', 'featured']} 9 | method = 'GET' 10 | endpoint = '/sapi/v1/lending/daily/product/list' 11 | security_type = 'USER_DATA' 12 | 13 | 14 | # Get Left Daily Purchase Quota of Flexible Product: 15 | class get_dailyPurchaseQuota: 16 | params = {'R':['productId']} 17 | method = 'GET' 18 | endpoint = '/sapi/v1/lending/daily/userLeftQuota' 19 | security_type = 'USER_DATA' 20 | 21 | 22 | # Purchase Flexible Product: 23 | class purchase_product: 24 | params = {'R':['productId', 'amount']} 25 | method = 'POST' 26 | endpoint = '/sapi/v1/lending/daily/purchase' 27 | security_type = 'USER_DATA' 28 | 29 | 30 | # Get Left Daily Redemption Quota of Flexible Product: 31 | class get_dailyRedemptionQuota: 32 | params = {'R':['productId', 'type']} 33 | method = 'GET' 34 | endpoint = '/sapi/v1/lending/daily/userRedemptionQuota' 35 | security_type = 'USER_DATA' 36 | 37 | 38 | # Redeem Flexible Product 39 | class redeem_product: 40 | params = {'R':['productId', 'amount', 'type']} 41 | method = 'POST' 42 | endpoint = '/sapi/v1/lending/daily/redeem' 43 | security_type = 'USER_DATA' 44 | 45 | 46 | # Get Flexible Product Position: 47 | class get_product_position: 48 | params = {'R':['asset']} 49 | method = 'GET' 50 | endpoint = '/sapi/v1/lending/daily/token/position' 51 | security_type = 'USER_DATA' 52 | 53 | 54 | # Get Fixed and Activity Project List: 55 | class get_FnAProject_list: 56 | params = {'R':['type'], 57 | 'O':['asset', 'status', 'isSortAsc', 'sortBy', 'current', 'size']} 58 | method = 'GET' 59 | endpoint = '/sapi/v1/lending/project/list' 60 | security_type = 'USER_DATA' 61 | 62 | 63 | # Purchase Fixed/Activity Project: 64 | class purchase_FnAProject: 65 | params = {'R':['projectId', 'lot']} 66 | method = 'POST' 67 | endpoint = '/sapi/v1/lending/customizedFixed/purchase' 68 | security_type = 'USER_DATA' 69 | 70 | 71 | # Get Fixed/Activity Project Position: 72 | class get_FnAProject_position: 73 | params = {'R':['asset'], 74 | 'O':['projectId', 'status']} 75 | method = 'GET' 76 | endpoint = '/sapi/v1/lending/project/position/list' 77 | security_type = 'USER_DATA' 78 | 79 | 80 | # Lending Account: 81 | class get_lending: 82 | params = None 83 | method = 'GET' 84 | endpoint = '/sapi/v1/lending/union/account' 85 | security_type = 'USER_DATA' 86 | 87 | 88 | # Get Purchase Record: 89 | class get_purchase_record: 90 | params = {'R':['lendingType'], 91 | 'O':['asset', 'startTime', 'endTime', 'current', 'size']} 92 | method = 'GET' 93 | endpoint = '/sapi/v1/lending/union/purchaseRecord' 94 | security_type = 'USER_DATA' 95 | 96 | 97 | # Get Redemption Record: 98 | class get_redemption_record: 99 | params = {'R':['lendingType'], 100 | 'O':['asset', 'startTime', 'endTime', 'current', 'size']} 101 | method = 'GET' 102 | endpoint = '/sapi/v1/lending/union/redemptionRecord' 103 | security_type = 'USER_DATA' 104 | 105 | 106 | # Get Interest History: 107 | class get_interest_history: 108 | params = {'R':['lendingType'], 109 | 'O':['asset', 'startTime', 'endTime', 'current', 'size']} 110 | method = 'GET' 111 | endpoint = '/sapi/v1/lending/union/interestHistory' 112 | security_type = 'USER_DATA' 113 | 114 | 115 | # Change Fixed/Activity Position to Daily Position: 116 | class change_position: 117 | params = {'R':['productId', 'lot', 'positionId']} 118 | method = 'POST' 119 | endpoint = '/sapi/v1/lending/positionChanged' 120 | security_type = 'USER_DATA' -------------------------------------------------------------------------------- /binance_api/spot_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Spot Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#spot-account-trade 4 | ''' 5 | 6 | # Test New Order: 7 | class place_order_test: 8 | params = {'R':['symbol', 'side', 'type'], 9 | 'O':['timeInForce', 'quantity', 'quoteOrderQty', 'price', 'newClientOrderId', 'stopPrice', 'icebergQty', 'newOrderRespType']} 10 | method = 'POST' 11 | endpoint = '/api/v3/order/test' 12 | security_type = 'TRADE' 13 | 14 | 15 | # New Order: 16 | class place_order: 17 | params = {'R':['symbol', 'side', 'type'], 18 | 'O':['timeInForce', 'quantity', 'quoteOrderQty', 'price', 'newClientOrderId', 'stopPrice', 'icebergQty', 'newOrderRespType']} 19 | method = 'POST' 20 | endpoint = '/api/v3/order' 21 | security_type = 'TRADE' 22 | 23 | 24 | # Cancel Order: 25 | class cancel_order: 26 | params = {'R':['symbol'], 27 | 'O':['orderId', 'origClientOrderId', 'newClientOrderId']} 28 | method = 'DELETE' 29 | endpoint = '/api/v3/order' 30 | security_type = 'TRADE' 31 | 32 | 33 | # Cancel all Open Orders on a Symbol: 34 | class cancel_all_orders: 35 | params = {'R':['symbol']} 36 | method = 'DELETE' 37 | endpoint = '/api/v3/openOrders' 38 | security_type = 'TRADE' 39 | 40 | 41 | # Query Order: 42 | class get_order: 43 | params = {'R':['symbol'], 44 | 'O':['orderId', 'origClientOrderId']} 45 | method = 'GET' 46 | endpoint = '/api/v3/order' 47 | security_type = 'USER_DATA' 48 | 49 | 50 | # Current Open Orders: 51 | class get_open_orders: 52 | params = {'R':['symbol']} 53 | method = 'GET' 54 | endpoint = '/api/v3/openOrders' 55 | security_type = 'USER_DATA' 56 | 57 | 58 | # All Orders: 59 | class get_all_orders: 60 | params = {'R':['symbol'], 61 | 'O':['orderId', 'startTime', 'endTime', 'limit']} 62 | method = 'GET' 63 | endpoint = '/api/v3/allOrders' 64 | security_type = 'USER_DATA' 65 | 66 | 67 | # New OCO: 68 | class place_order_oco: 69 | params = {'R':['symbol', 'side', 'quantity', 'price', 'stopPrice'], 70 | 'O':['listClientOrderId', 'limitClientOrderId', 'limitIcebergQty', 'stopClientOrderId', 'stopLimitPrice', 'stopIcebergQty', 'stopLimitTimeInForce', 'newOrderRespType']} 71 | method = 'POST' 72 | endpoint = '/api/v3/order/oco' 73 | security_type = 'TRADE' 74 | 75 | 76 | # Cancel OCO: 77 | class cancel_order_oco: 78 | params = {'R':['symbol'], 79 | 'O':['orderListId', 'listClientOrderId', 'newClientOrderId']} 80 | method = 'DELETE' 81 | endpoint = '/api/v3/orderList' 82 | security_type = 'TRADE' 83 | 84 | 85 | # Query OCO: 86 | class query_order_oco: 87 | params = {'O':['orderListId', 'origClientOrderId']} 88 | method = 'GET' 89 | endpoint = '/api/v3/orderList' 90 | security_type = 'USER_DATA' 91 | 92 | 93 | # Query all OCO: 94 | class get_all_orders_oco: 95 | params = {'O':['fromId', 'startTime', 'endTime', 'limit']} 96 | method = 'GET' 97 | endpoint = '/api/v3/allOrderList' 98 | security_type = 'USER_DATA' 99 | 100 | 101 | # Query Open OCO: 102 | class get_open_orders_oco: 103 | params = None 104 | method = 'GET' 105 | endpoint = '/api/v3/openOrderList' 106 | security_type = 'USER_DATA' 107 | 108 | 109 | # Account Information: 110 | class get_accountInfo: 111 | params = None 112 | method = 'GET' 113 | endpoint = '/api/v3/account' 114 | security_type = 'USER_DATA' 115 | 116 | 117 | # Account Trade List: 118 | class get_all_trades: 119 | params = {'R':['symbol'], 120 | 'O':['startTime', 'endTime', 'fromId', 'limit']} 121 | method = 'GET' 122 | endpoint = '/api/v3/myTrades' 123 | security_type = 'USER_DATA' -------------------------------------------------------------------------------- /binance_api/subAccount_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Sub-Account Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#sub-account-endpoints 4 | ''' 5 | 6 | # Query Sub-account List (For Master Account): 7 | class get_subAccount_list: 8 | params = {'O':['email', 'status', 'page', 'limit']} 9 | method = 'GET' 10 | endpoint = '/wapi/v3/sub-account/list.html' 11 | security_type = 'NONE' 12 | 13 | 14 | # Query Sub-account Spot Asset Transfer History (For Master Account): 15 | class get_subAccount_spotTransferHistory_wapi: 16 | params = {'R':['email'], 17 | 'O':['startTime', 'endTime', 'page', 'limit']} 18 | method = 'GET' 19 | endpoint = '/wapi/v3/sub-account/transfer/history.html' 20 | security_type = 'NONE' 21 | 22 | 23 | # Query Sub-account Spot Asset Transfer History (SAPI For Master Account): 24 | class get_subAccount_spotTransferHistory_sapi: 25 | params = {'O':['fromEmail', 'toEmail', 'startTime', 'endTime', 'page', 'limit']} 26 | method = 'GET' 27 | endpoint = '/sapi/v1/sub-account/sub/transfer/history' 28 | security_type = 'USER_DATA' 29 | 30 | 31 | # Sub-account Spot Asset Transfer (For Master Account): 32 | class subAccount_spotAsset_transfer: 33 | params = {'R':['fromEmail', 'toEmail', 'asset', 'amount']} 34 | method = 'POST' 35 | endpoint = '/wapi/v3/sub-account/transfer.html' 36 | security_type = 'NONE' 37 | 38 | 39 | # Query Sub-account Futures Asset Transfer History (For Master Account): 40 | class get_subAccount_futuresTransferHistory: 41 | params = {'R':['email', 'futuresType'], 42 | 'O':['startTime', 'endTime', 'page', 'limit']} 43 | method = 'GET' 44 | endpoint = '/sapi/v1/sub-account/futures/internalTransfer' 45 | security_type = 'USER_DATA' 46 | 47 | 48 | # Sub-account Futures Asset Transfer (For Master Account): 49 | class subAccount_futuresAsset_transfer: 50 | params = {'R':['fromEmail', 'toEmail', 'futuresType', 'asset', 'amount']} 51 | method = 'POST' 52 | endpoint = '/sapi/v1/sub-account/futures/internalTransfer' 53 | security_type = 'USER_DATA' 54 | 55 | 56 | # Query Sub-account Assets (For Master Account): 57 | class get_subAccount_assets: 58 | params = {'R':['email']} 59 | method = 'GET' 60 | endpoint = '/wapi/v3/sub-account/assets.html' 61 | security_type = 'NONE' 62 | 63 | 64 | # Query Sub-account Spot Assets Summary (For Master Account): 65 | class get_subAccount_spotAssetsSummary: 66 | params = {'O':['email', 'page', 'size']} 67 | method = 'GET' 68 | endpoint = '/sapi/v1/sub-account/spotSummary' 69 | security_type = 'USER_DATA' 70 | 71 | 72 | # Get Sub-account Deposit Address (For Master Account): 73 | class get_subAccount_depositAddress: 74 | params = {'R':['email', 'coin'], 75 | 'O':['network']} 76 | method = 'GET' 77 | endpoint = '/sapi/v1/capital/deposit/subAddress' 78 | security_type = 'USER_DATA' 79 | 80 | 81 | # Get Sub-account Deposit History (For Master Account): 82 | class get_subAccount_depositHistory: 83 | params = {'R':['email'], 84 | 'O':['coin', 'status', 'startTime', 'endTime', 'limit', 'offset']} 85 | method = 'GET' 86 | endpoint = '/sapi/v1/capital/deposit/subHisrec' 87 | security_type = 'USER_DATA' 88 | 89 | 90 | # Get Sub-account's Status on Margin/Futures (For Master Account): 91 | class get_subAccount_statusFnM: 92 | params = {'O':['email']} 93 | method = 'GET' 94 | endpoint = '/sapi/v1/sub-account/status' 95 | security_type = 'USER_DATA' 96 | 97 | 98 | # Enable Margin for Sub-account (For Master Account): 99 | class enable_subAccount_margin: 100 | params = {'R':['email']} 101 | method = 'POST' 102 | endpoint = '/sapi/v1/sub-account/margin/enable' 103 | security_type = 'USER_DATA' 104 | 105 | 106 | # Get Detail on Sub-account's Margin Account (For Master Account): 107 | class get_subAccount_marginAccount: 108 | params = {'R':['email']} 109 | method = 'GET' 110 | endpoint = '/sapi/v1/sub-account/margin/account' 111 | security_type = 'USER_DATA' 112 | 113 | 114 | # Get Summary of Sub-account's Margin Account (For Master Account): 115 | class get_subAccount_marginAccountSummary: 116 | params = None 117 | method = 'GET' 118 | endpoint = '/sapi/v1/sub-account/margin/accountSummary' 119 | security_type = 'USER_DATA' 120 | 121 | 122 | # Enable Futures for Sub-account (For Master Account): 123 | class enable_subAccount_futures: 124 | params = {'R':['email']} 125 | method = 'POST' 126 | endpoint = '/sapi/v1/sub-account/futures/enable' 127 | security_type = 'USER_DATA' 128 | 129 | 130 | # Get Detail on Sub-account's Futures Account (For Master Account): 131 | class get_subAccount_futuresAccount: 132 | params = {'R':['email']} 133 | method = 'GET' 134 | endpoint = '/sapi/v1/sub-account/futures/account' 135 | security_type = 'USER_DATA' 136 | 137 | 138 | # Get Summary of Sub-account's Futures Account (For Master Account): 139 | class get_subAccount_futuresAccountSummary: 140 | params = None 141 | method = 'GET' 142 | endpoint = '/sapi/v1/sub-account/futures/accountSummary' 143 | security_type = 'USER_DATA' 144 | 145 | 146 | # Get Futures Position-Risk of Sub-account (For Master Account) 147 | class get_subAccount_positionRisk: 148 | params = {'R':['email']} 149 | method = 'GET' 150 | endpoint = '/sapi/v1/sub-account/futures/positionRisk' 151 | security_type = 'USER_DATA' 152 | 153 | 154 | # Futures Transfer for Sub-account (For Master Account): 155 | class subAccount_futures_transfer: 156 | params = {'R':['email', 'asset']} 157 | method = 'POST' 158 | endpoint = '/sapi/v1/sub-account/futures/transfer' 159 | security_type = 'USER_DATA' 160 | 161 | 162 | # Margin Transfer for Sub-account (For Master Account): 163 | class subAccount_margin_transfer: 164 | params = {'R':['email', 'asset', 'amount', 'type']} 165 | method = 'POST' 166 | endpoint = '/sapi/v1/sub-account/margin/transfer' 167 | security_type = 'USER_DATA' 168 | 169 | 170 | # Transfer to Sub-account of Same Master (For Sub-account): 171 | class master_sub_transfer: 172 | params = {'R':['toEmail', 'asset', 'amount']} 173 | method = 'POST' 174 | endpoint = '/sapi/v1/sub-account/transfer/subToSub' 175 | security_type = 'USER_DATA' 176 | 177 | 178 | # Transfer to Master (For Sub-account): 179 | class sub_master_transfer: 180 | params = {'R':['asset', 'amount']} 181 | method = 'POST' 182 | endpoint = '/sapi/v1/sub-account/transfer/subToMaster' 183 | security_type = 'USER_DATA' 184 | 185 | 186 | # Sub-account Transfer History (For Sub-account) 187 | class get_subAccount_transferHistory: 188 | params = {'O':['asset', 'type', 'startTime', 'endTime', 'limit']} 189 | method = 'GET' 190 | endpoint = '/sapi/v1/sub-account/transfer/subUserHistory' 191 | security_type = 'USER_DATA' 192 | 193 | 194 | # Universal Transfer (For Master Account): 195 | class make_universalTransfer: 196 | params = {'R':['fromAccountType', 'toAccountType', 'asset', 'amount'], 197 | 'O':['toEmail', 'fromEmail']} 198 | method = 'POST' 199 | endpoint = '/sapi/v1/sub-account/universalTransfer' 200 | security_type = 'NONE' 201 | 202 | 203 | # Query Universal Transfer History: 204 | class get_universalTransferHisotry: 205 | params = {'O':['fromEmail', 'toEmail', 'startTime', 'endTime', 'page', 'limit']} 206 | method = 'GET' 207 | endpoint = '/sapi/v1/sub-account/universalTransfer' 208 | security_type = 'USER_DATA' 209 | 210 | 211 | # Get Detail on Sub-account's Futures Account V2 (For Master Account): 212 | class get_subAccount_futuresAccount_v2: 213 | params = {'R':['email', 'futuresType']} 214 | method = 'GET' 215 | endpoint = '/sapi/v2/sub-account/futures/account' 216 | security_type = 'USER_DATA' 217 | 218 | 219 | # Get Summary of Sub-account's Futures Account V2 (For Master Account): 220 | class get_subAccount_futuresAccountSummary_v2: 221 | params = {'R':['futuresType'], 222 | 'O':['page', 'type']} 223 | method = 'GET' 224 | endpoint = '/sapi/v2/sub-account/futures/accountSummary' 225 | security_type = 'USER_DATA' 226 | 227 | 228 | # Get Futures Position-Risk of Sub-account V2 (For Master Account): 229 | class get_subAccount_positionRisk_v2: 230 | params = {'R':['email', 'futuresType']} 231 | method = 'GET' 232 | endpoint = '/sapi/v2/sub-account/futures/positionRisk' 233 | security_type = 'USER_DATA' -------------------------------------------------------------------------------- /binance_api/userDataStream_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the User Data Stream Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#user-data-streams 4 | 5 | Account Update Event: outboundAccountPosition 6 | Order Update Event: executionReport (Also ListStatus if OCO) 7 | 8 | ''' 9 | 10 | ### SPOT ENDPOINTS ### 11 | 12 | # Create a ListenKey: 13 | class get_listenKey_spot: 14 | params = None 15 | method = 'POST' 16 | endpoint = '/api/v3/userDataStream' 17 | security_type = 'USER_STREAM' 18 | 19 | 20 | # Ping/Keep-alive a ListenKey: 21 | class send_listenKey_keepAlive_spot: 22 | params = {'R':['listenKey']} 23 | method = 'PUT' 24 | endpoint = '/api/v3/userDataStream' 25 | security_type = 'USER_STREAM' 26 | 27 | 28 | # Close a ListenKey: 29 | class close_listenKey_spot: 30 | params = {'R':['listenKey']} 31 | method = 'DELETE' 32 | endpoint = '/api/v3/userDataStream' 33 | security_type = 'USER_STREAM' 34 | 35 | 36 | ### MARGIN ENDPOINTS ### 37 | 38 | # Create a ListenKey: 39 | class get_listenKey_margin: 40 | params = None 41 | method = 'POST' 42 | endpoint = '/sapi/v1/userDataStream' 43 | security_type = 'USER_STREAM' 44 | 45 | 46 | # Ping/Keep-alive a ListenKey: 47 | class send_listenKey_keepAlive_margin: 48 | params = {'R':['listenKey']} 49 | method = 'PUT' 50 | endpoint = '/sapi/v1/userDataStream' 51 | security_type = 'USER_STREAM' 52 | 53 | 54 | # Close a ListenKey: 55 | class close_listenKey_margin: 56 | params = {'R':['listenKey']} 57 | method = 'DELETE' 58 | endpoint = '/sapi/v1/userDataStream' 59 | security_type = 'USER_STREAM' 60 | 61 | 62 | ### ISOLATED MARGIN ENDPOINTS ### 63 | 64 | # Create a ListenKey: 65 | class get_listenKey_isolatedMargin: 66 | params = None 67 | method = 'POST' 68 | endpoint = '/sapi/v1/userDataStream/isolated' 69 | security_type = 'USER_STREAM' 70 | 71 | 72 | # Ping/Keep-alive a ListenKey: 73 | class send_listenKey_keepAlive_isolatedMargin: 74 | params = {'R':['symbol', 'listenKey']} 75 | method = 'PUT' 76 | endpoint = '/sapi/v1/userDataStream/isolated' 77 | security_type = 'USER_STREAM' 78 | 79 | 80 | # Close a ListenKey: 81 | class close_listenKey_isolatedMargin: 82 | params = {'R':['symbol', 'listenKey']} 83 | method = 'DELETE' 84 | endpoint = '/sapi/v1/userDataStream/isolated' 85 | security_type = 'USER_STREAM' -------------------------------------------------------------------------------- /binance_api/wallet_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Wallet Endpoints api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#wallet-endpoints 4 | ''' 5 | 6 | # System Status: 7 | class get_systemStatus: 8 | params = None 9 | method = 'GET' 10 | endpoint = '/wapi/v3/systemStatus.html' 11 | security_type = 'System' 12 | 13 | 14 | # All Coins' Information: 15 | class get_allCoinsInfo: 16 | params = None 17 | method = 'GET' 18 | endpoint = '/sapi/v1/capital/config/getall' 19 | security_type = 'USER_DATA' 20 | 21 | 22 | #Daily Account Snapshot: 23 | class get_dailySnapshot: 24 | params = {'R':['type'], 25 | 'O':['startTime', 'endTime', 'limit']} 26 | method = 'GET' 27 | endpoint = '/sapi/v1/accountSnapshot' 28 | security_type = 'USER_DATA' 29 | 30 | 31 | # Disable Fast Withdraw Switch: 32 | class disable_withdrawSwitch: 33 | params = None 34 | method = 'POST' 35 | endpoint = '/sapi/v1/account/disableFastWithdrawSwitch' 36 | security_type = 'USER_DATA' 37 | 38 | 39 | # Enable Fast Withdraw Switch: 40 | class enable_withdrawSwitch: 41 | params = None 42 | method = 'POST' 43 | endpoint = '/sapi/v1/account/enableFastWithdrawSwitch' 44 | security_type = 'USER_DATA' 45 | 46 | 47 | # Withdraw [SAPI]: 48 | class make_withdraw_SAPI: 49 | params = {'R':['coin', 'address', 'amount'], 50 | 'O':['withdrawOrderId', 'network', 'addressTag', 'transactionFeeFlag', 'name']} 51 | method = 'POST' 52 | endpoint = '/sapi/v1/capital/withdraw/apply' 53 | security_type = 'USER_DATA' 54 | 55 | 56 | # Withdraw: 57 | class make_withdraw: 58 | params = {'R':['asset', 'address', 'amount'], 59 | 'O':['withdrawOrderId', 'network', 'addressTag', 'transactionFeeFlag', 'name']} 60 | method = 'POST' 61 | endpoint = '/wapi/v3/withdraw.html' 62 | security_type = 'USER_DATA' 63 | 64 | 65 | # Deposit History(supporting network): 66 | class get_depositHistory_SN: 67 | params = {'O':['coin', 'status', 'startTime', 'endTime', 'offest', 'limit']} 68 | method = 'GET' 69 | endpoint = '/sapi/v1/capital/deposit/hisrec' 70 | security_type = 'USER_DATA' 71 | 72 | 73 | # Deposit History: 74 | class get_depositHistory: 75 | params = {'O':['asset', 'status', 'startTime', 'endTime']} 76 | method = 'GET' 77 | endpoint = '/wapi/v3/depositHistory.html' 78 | security_type = 'USER_DATA' 79 | 80 | 81 | # Withdraw History (supporting network): 82 | class get_withdrawHistory_SN: 83 | params = {'O':['coin', 'status', 'offset', 'limit', 'startTime', 'endTime']} 84 | method = 'GET' 85 | endpoint = '/sapi/v1/capital/withdraw/history' 86 | security_type = 'USER_DATA' 87 | 88 | 89 | # Withdraw History: 90 | class get_withdrawHistory: 91 | params = {'O':['asset', 'status', 'startTime', 'endTime']} 92 | method = 'GET' 93 | endpoint = '/wapi/v3/withdrawHistory.html' 94 | security_type = 'USER_DATA' 95 | 96 | 97 | # Deposit Address (supporting network): 98 | class depositAddress_SN: 99 | params = {'R':['coin'], 100 | 'O':['network']} 101 | method = 'GET' 102 | endpoint = '/sapi/v1/capital/deposit/address' 103 | security_type = 'USER_DATA' 104 | 105 | 106 | # Deposit Address: 107 | class depositAddress: 108 | params = {'R':['asset'], 109 | 'O':['status']} 110 | method = 'GET' 111 | endpoint = '/wapi/v3/depositAddress.html' 112 | security_type = 'USER_DATA' 113 | 114 | 115 | # Account Status: 116 | class get_accountStatus: 117 | params = None 118 | method = 'GET' 119 | endpoint = '/wapi/v3/accountStatus.html' 120 | security_type = 'USER_DATA' 121 | 122 | 123 | # Account API Trading Status: 124 | class get_apiStatus: 125 | params = None 126 | method = 'GET' 127 | endpoint = '/wapi/v3/apiTradingStatus.html' 128 | security_type = 'USER_DATA' 129 | 130 | 131 | # DustLog: 132 | class get_dustLog: 133 | params = None 134 | method = 'GET' 135 | endpoint = '/wapi/v3/userAssetDribbletLog.html' 136 | security_type = 'USER_DATA' 137 | 138 | 139 | # Dust Transfer: 140 | class make_dustTransfer: 141 | params = {'R':['asset']} 142 | method = 'POST' 143 | endpoint = '/sapi/v1/asset/dust' 144 | security_type = 'USER_DATA' 145 | 146 | 147 | # Asset Dividend Record: 148 | class get_dividendRecord: 149 | params = {'O':['asset', 'startTime', 'endTime', 'limit']} 150 | method = 'GET' 151 | endpoint = '/sapi/v1/asset/assetDividend' 152 | security_type = 'USER_DATA' 153 | 154 | 155 | # Asset Detail: 156 | class get_assetDetail: 157 | params = None 158 | method = 'GET' 159 | endpoint = '/wapi/v3/assetDetail.html' 160 | security_type = 'USER_DATA' 161 | 162 | 163 | # Trade Fee: 164 | class get_tradeFee: 165 | params = {'O':['symbol']} 166 | method = 'GET' 167 | endpoint = '/wapi/v3/tradeFee.html' 168 | security_type = 'USER_DATA' 169 | 170 | 171 | # User Universal Transfer: 172 | class make_universalTransfer: 173 | params = {'R':['type', 'asset', 'amount']} 174 | method = 'POST' 175 | endpoint = '/sapi/v1/asset/transfer' 176 | security_type = 'USER_DATA' 177 | 178 | 179 | # Query User Universal Transfer History 180 | class get_universalTransferHistory: 181 | params = {'R':['type'], 182 | 'O':['startTime', 'endTime', 'current', 'size']} 183 | method = 'GET' 184 | endpoint = '/sapi/v1/asset/transfer' 185 | security_type = 'USER_DATA' -------------------------------------------------------------------------------- /binance_api/websocket_api.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Endpoints are collected from the Websocket api section under the official binance api docs: 3 | https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams 4 | ''' 5 | 6 | # Aggregate Trade Streams: 7 | class set_aggTrade_stream: 8 | params = None 9 | endpoint = '@aggTrade' 10 | 11 | 12 | # Trade Streams: 13 | class set_trade_stream: 14 | params = None 15 | endpoint = '@trade' 16 | 17 | # Kline/Candlestick Streams: 18 | class set_candle_stream: 19 | params = {'O':['local_manager']} 20 | data_type = 'CANDLE' 21 | endpoint = '@kline_' 22 | 23 | 24 | # Individual Symbol Mini Ticker Stream: 25 | class set_miniTicker_stream: 26 | params = None 27 | endpoint = '@miniTicker' 28 | 29 | 30 | # All Market Mini Tickers Stream: 31 | class set_global_miniTicker_stream: 32 | params = None 33 | endpoint = '!miniTicker@arr' 34 | 35 | 36 | # Individual Symbol Ticker Streams: 37 | class set_ticker_stream: 38 | params = None 39 | endpoint = '@ticker' 40 | 41 | 42 | # All Market Tickers Stream: 43 | class set_gloal_ticker_stream: 44 | params = None 45 | endpoint = '!ticker@arr' 46 | 47 | 48 | # Individual Symbol Book Ticker Streams: 49 | class set_bookTicker_stream: 50 | params = None 51 | endpoint = '@bookTicker' 52 | 53 | 54 | # All Book Tickers Stream: 55 | class set_global_bookTicker_stream: 56 | params = None 57 | endpoint = '!bookTicker' 58 | 59 | 60 | # Partial Book Depth Streams: 61 | class set_partialBookDepth_stream: 62 | params = None 63 | endpoint = '@depth@' 64 | 65 | 66 | # Diff. Depth Stream: 67 | class set_manual_depth_stream: 68 | params = None 69 | data_type = 'BOOKS' 70 | endpoint = '@depth@' -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | requests 3 | websocket-client 4 | -------------------------------------------------------------------------------- /tester.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | from binance_api import rest_master 4 | 5 | rest_api = rest_master.Binance_REST(public_key='', private_key='') 6 | 7 | # Rest endpoints to test: 8 | def test_rest(): 9 | print('Testing... [get_blvt_info]') 10 | rest_api.get_blvt_info(IS_TEST=True) 11 | print('Testing... [subscribe_blvt]') 12 | rest_api.subscribe_blvt(IS_TEST=True) 13 | print('Testing... [query_subscription_record]') 14 | rest_api.query_subscription_record(IS_TEST=True) 15 | print('Testing... [redeem_blvt]') 16 | rest_api.redeem_blvt(IS_TEST=True) 17 | print('Testing... [query_redemption_record]') 18 | rest_api.query_redemption_record(IS_TEST=True) 19 | print('Testing... [get_blvt_userLimit]') 20 | rest_api.get_blvt_userLimit(IS_TEST=True) 21 | print('Testing... [get_swap_pools]') 22 | rest_api.get_swap_pools() 23 | print('Testing... [get_liquidity_poolInfo]') 24 | rest_api.get_liquidity_poolInfo(IS_TEST=True) 25 | print('Testing... [add_liquidity]') 26 | rest_api.add_liquidity(IS_TEST=True) 27 | print('Testing... [remove_liquidity]') 28 | rest_api.remove_liquidity(IS_TEST=True) 29 | print('Testing... [get_liquidity_record]') 30 | rest_api.get_liquidity_record(IS_TEST=True) 31 | print('Testing... [get_quote]') 32 | rest_api.get_quote(IS_TEST=True) 33 | print('Testing... [make_swap]') 34 | rest_api.make_swap(IS_TEST=True) 35 | print('Testing... [get_swap_history]') 36 | rest_api.get_swap_history(IS_TEST=True) 37 | print('Testing... [futures_transfer]') 38 | rest_api.futures_transfer(IS_TEST=True) 39 | print('Testing... [get_futures_transactions]') 40 | rest_api.get_futures_transactions(IS_TEST=True) 41 | print('Testing... [borrow_crossCollat]') 42 | rest_api.borrow_crossCollat(IS_TEST=True) 43 | print('Testing... [get_crossCollat_borrowHist]') 44 | rest_api.get_crossCollat_borrowHist(IS_TEST=True) 45 | print('Testing... [repay_crossCollat]') 46 | rest_api.repay_crossCollat(IS_TEST=True) 47 | print('Testing... [get_crossCollat_repayHist]') 48 | rest_api.get_crossCollat_repayHist(IS_TEST=True) 49 | print('Testing... [get_crossCollat_wallet]') 50 | rest_api.get_crossCollat_wallet() 51 | print('Testing... [get_crossCollat_wallet_v2]') 52 | rest_api.get_crossCollat_wallet_v2() 53 | print('Testing... [get_crossCollat_info]') 54 | rest_api.get_crossCollat_info(IS_TEST=True) 55 | print('Testing... [get_crossCollat_info_v2]') 56 | rest_api.get_crossCollat_info_v2(IS_TEST=True) 57 | print('Testing... [get_crossCollat_rate_LTV]') 58 | rest_api.get_crossCollat_rate_LTV(IS_TEST=True) 59 | print('Testing... [get_crossCollat_rate_LTV_v2]') 60 | rest_api.get_crossCollat_rate_LTV_v2(IS_TEST=True) 61 | print('Testing... [get_crossCollat_max_LTV]') 62 | rest_api.get_crossCollat_max_LTV(IS_TEST=True) 63 | print('Testing... [get_crossCollat_max_LTV_v2]') 64 | rest_api.get_crossCollat_max_LTV_v2(IS_TEST=True) 65 | print('Testing... [adjust_crossCollat_LTV]') 66 | rest_api.adjust_crossCollat_LTV(IS_TEST=True) 67 | print('Testing... [adjust_crossCollat_LTV_v2]') 68 | rest_api.adjust_crossCollat_LTV_v2(IS_TEST=True) 69 | print('Testing... [adjust_crossCollat_LTV_history]') 70 | rest_api.adjust_crossCollat_LTV_history(IS_TEST=True) 71 | print('Testing... [adjust_crossCollat_liquidation_history]') 72 | rest_api.adjust_crossCollat_liquidation_history(IS_TEST=True) 73 | print('Testing... [get_collatRepay_limit]') 74 | rest_api.get_collatRepay_limit(IS_TEST=True) 75 | print('Testing... [get_collatRepay_quote]') 76 | rest_api.get_collatRepay_quote(IS_TEST=True) 77 | print('Testing... [collateral_repay]') 78 | rest_api.collateral_repay(IS_TEST=True) 79 | print('Testing... [get_collatRepay_result]') 80 | rest_api.get_collatRepay_result(IS_TEST=True) 81 | print('Testing... [get_crossCollat_interestHist]') 82 | rest_api.get_crossCollat_interestHist(IS_TEST=True) 83 | print('Testing... [margin_transfer]') 84 | rest_api.margin_transfer(IS_TEST=True) 85 | print('Testing... [margin_accountBorrow]') 86 | rest_api.margin_accountBorrow(IS_TEST=True) 87 | print('Testing... [margin_accountRepay]') 88 | rest_api.margin_accountRepay(IS_TEST=True) 89 | print('Testing... [query_margin_asset]') 90 | rest_api.query_margin_asset(IS_TEST=True) 91 | print('Testing... [query_crossPair]') 92 | rest_api.query_crossPair(IS_TEST=True) 93 | print('Testing... [get_margin_allAssets]') 94 | rest_api.get_margin_allAssets() 95 | print('Testing... [get_allCrossPairs]') 96 | rest_api.get_allCrossPairs() 97 | print('Testing... [query_margin_priceIndex]') 98 | rest_api.query_margin_priceIndex(IS_TEST=True) 99 | print('Testing... [get_margin_crossTransferHistory]') 100 | rest_api.get_margin_crossTransferHistory(IS_TEST=True) 101 | print('Testing... [get_loanRecord]') 102 | rest_api.get_loanRecord(IS_TEST=True) 103 | print('Testing... [get_repayRecord]') 104 | rest_api.get_repayRecord(IS_TEST=True) 105 | print('Testing... [get_interestHistory]') 106 | rest_api.get_interestHistory(IS_TEST=True) 107 | print('Testing... [get_fLiquidationRecord]') 108 | rest_api.get_fLiquidationRecord(IS_TEST=True) 109 | print('Testing... [get_cross_accountDetails]') 110 | rest_api.get_cross_accountDetails() 111 | print('Testing... [get_maxBorrow]') 112 | rest_api.get_maxBorrow(IS_TEST=True) 113 | print('Testing... [get_maxOutAmmount]') 114 | rest_api.get_maxOutAmmount(IS_TEST=True) 115 | print('Testing... [create_isolatedMaringAccount]') 116 | rest_api.create_isolatedMaringAccount(IS_TEST=True) 117 | print('Testing... [isolated_transfer]') 118 | rest_api.isolated_transfer(IS_TEST=True) 119 | print('Testing... [get_isolated_transferHistory]') 120 | rest_api.get_isolated_transferHistory(IS_TEST=True) 121 | print('Testing... [get_isolated_accountInfo]') 122 | rest_api.get_isolated_accountInfo(IS_TEST=True) 123 | print('Testing... [get_isolated_symbol]') 124 | rest_api.get_isolated_symbol(IS_TEST=True) 125 | print('Testing... [get_isolated_symbol_all]') 126 | rest_api.get_isolated_symbol_all() 127 | print('Testing... [toggle_BNB_burn_ST_MI]') 128 | rest_api.toggle_BNB_burn_ST_MI(IS_TEST=True) 129 | print('Testing... [get_BNB_burn_status]') 130 | rest_api.get_BNB_burn_status() 131 | print('Testing... [test_ping]') 132 | rest_api.test_ping() 133 | print('Testing... [get_serverTime]') 134 | rest_api.get_serverTime() 135 | print('Testing... [get_ExchangeInfo]') 136 | rest_api.get_ExchangeInfo() 137 | print('Testing... [get_orderBook]') 138 | rest_api.get_orderBook(IS_TEST=True) 139 | print('Testing... [get_aggTradeList]') 140 | rest_api.get_aggTradeList(IS_TEST=True) 141 | print('Testing... [get_averagePrice]') 142 | rest_api.get_averagePrice(IS_TEST=True) 143 | print('Testing... [get_24hTicker]') 144 | rest_api.get_24hTicker(IS_TEST=True) 145 | print('Testing... [get_priceTicker]') 146 | rest_api.get_priceTicker(IS_TEST=True) 147 | print('Testing... [get_orderbookTicker]') 148 | rest_api.get_orderbookTicker(IS_TEST=True) 149 | print('Testing... [get_algorithm]') 150 | rest_api.get_algorithm() 151 | print('Testing... [get_coinNames]') 152 | rest_api.get_coinNames() 153 | print('Testing... [get_minerList_detail]') 154 | rest_api.get_minerList_detail(IS_TEST=True) 155 | print('Testing... [get_minerList]') 156 | rest_api.get_minerList(IS_TEST=True) 157 | print('Testing... [get_earningsList]') 158 | rest_api.get_earningsList(IS_TEST=True) 159 | print('Testing... [get_extraBonusList]') 160 | rest_api.get_extraBonusList(IS_TEST=True) 161 | print('Testing... [get_hashrateResaleList]') 162 | rest_api.get_hashrateResaleList(IS_TEST=True) 163 | print('Testing... [get_hashrateResaleDetail]') 164 | rest_api.get_hashrateResaleDetail(IS_TEST=True) 165 | print('Testing... [post_hashrateResale]') 166 | rest_api.post_hashrateResale(IS_TEST=True) 167 | print('Testing... [cancel_hashrateResale]') 168 | rest_api.cancel_hashrateResale(IS_TEST=True) 169 | print('Testing... [get_statisticList]') 170 | rest_api.get_statisticList(IS_TEST=True) 171 | print('Testing... [get_accountList]') 172 | rest_api.get_accountList(IS_TEST=True) 173 | print('Testing... [get_productList]') 174 | rest_api.get_productList(IS_TEST=True) 175 | print('Testing... [get_dailyPurchaseQuota]') 176 | rest_api.get_dailyPurchaseQuota(IS_TEST=True) 177 | print('Testing... [purchase_product]') 178 | rest_api.purchase_product(IS_TEST=True) 179 | print('Testing... [get_dailyRedemptionQuota]') 180 | rest_api.get_dailyRedemptionQuota(IS_TEST=True) 181 | print('Testing... [redeem_product]') 182 | rest_api.redeem_product(IS_TEST=True) 183 | print('Testing... [get_product_position]') 184 | rest_api.get_product_position(IS_TEST=True) 185 | print('Testing... [get_FnAProject_list]') 186 | rest_api.get_FnAProject_list(IS_TEST=True) 187 | print('Testing... [purchase_FnAProject]') 188 | rest_api.purchase_FnAProject(IS_TEST=True) 189 | print('Testing... [get_FnAProject_position]') 190 | rest_api.get_FnAProject_position(IS_TEST=True) 191 | print('Testing... [get_lending]') 192 | rest_api.get_lending() 193 | print('Testing... [get_purchase_record]') 194 | rest_api.get_purchase_record(IS_TEST=True) 195 | print('Testing... [get_redemption_record]') 196 | rest_api.get_redemption_record(IS_TEST=True) 197 | print('Testing... [get_interest_history]') 198 | rest_api.get_interest_history(IS_TEST=True) 199 | print('Testing... [change_position]') 200 | rest_api.change_position(IS_TEST=True) 201 | print('Testing... [place_order_test]') 202 | rest_api.place_order_test(IS_TEST=True) 203 | print('Testing... [place_order_oco]') 204 | rest_api.place_order_oco(IS_TEST=True) 205 | print('Testing... [cancel_order_oco]') 206 | rest_api.cancel_order_oco(IS_TEST=True) 207 | print('Testing... [query_order_oco]') 208 | rest_api.query_order_oco(IS_TEST=True) 209 | print('Testing... [get_all_orders_oco]') 210 | rest_api.get_all_orders_oco(IS_TEST=True) 211 | print('Testing... [get_open_orders_oco]') 212 | rest_api.get_open_orders_oco() 213 | print('Testing... [get_accountInfo]') 214 | rest_api.get_accountInfo() 215 | print('Testing... [get_subAccount_list]') 216 | rest_api.get_subAccount_list(IS_TEST=True) 217 | print('Testing... [get_subAccount_spotTransferHistory_wapi]') 218 | rest_api.get_subAccount_spotTransferHistory_wapi(IS_TEST=True) 219 | print('Testing... [get_subAccount_spotTransferHistory_sapi]') 220 | rest_api.get_subAccount_spotTransferHistory_sapi(IS_TEST=True) 221 | print('Testing... [subAccount_spotAsset_transfer]') 222 | rest_api.subAccount_spotAsset_transfer(IS_TEST=True) 223 | print('Testing... [get_subAccount_futuresTransferHistory]') 224 | rest_api.get_subAccount_futuresTransferHistory(IS_TEST=True) 225 | print('Testing... [subAccount_futuresAsset_transfer]') 226 | rest_api.subAccount_futuresAsset_transfer(IS_TEST=True) 227 | print('Testing... [get_subAccount_assets]') 228 | rest_api.get_subAccount_assets(IS_TEST=True) 229 | print('Testing... [get_subAccount_spotAssetsSummary]') 230 | rest_api.get_subAccount_spotAssetsSummary(IS_TEST=True) 231 | print('Testing... [get_subAccount_depositAddress]') 232 | rest_api.get_subAccount_depositAddress(IS_TEST=True) 233 | print('Testing... [get_subAccount_depositHistory]') 234 | rest_api.get_subAccount_depositHistory(IS_TEST=True) 235 | print('Testing... [get_subAccount_statusFnM]') 236 | rest_api.get_subAccount_statusFnM(IS_TEST=True) 237 | print('Testing... [enable_subAccount_margin]') 238 | rest_api.enable_subAccount_margin(IS_TEST=True) 239 | print('Testing... [get_subAccount_marginAccount]') 240 | rest_api.get_subAccount_marginAccount(IS_TEST=True) 241 | print('Testing... [get_subAccount_marginAccountSummary]') 242 | rest_api.get_subAccount_marginAccountSummary() 243 | print('Testing... [enable_subAccount_futures]') 244 | rest_api.enable_subAccount_futures(IS_TEST=True) 245 | print('Testing... [get_subAccount_futuresAccount]') 246 | rest_api.get_subAccount_futuresAccount(IS_TEST=True) 247 | print('Testing... [get_subAccount_futuresAccountSummary]') 248 | rest_api.get_subAccount_futuresAccountSummary() 249 | print('Testing... [get_subAccount_positionRisk]') 250 | rest_api.get_subAccount_positionRisk(IS_TEST=True) 251 | print('Testing... [subAccount_futures_transfer]') 252 | rest_api.subAccount_futures_transfer(IS_TEST=True) 253 | print('Testing... [subAccount_margin_transfer]') 254 | rest_api.subAccount_margin_transfer(IS_TEST=True) 255 | print('Testing... [master_sub_transfer]') 256 | rest_api.master_sub_transfer(IS_TEST=True) 257 | print('Testing... [sub_master_transfer]') 258 | rest_api.sub_master_transfer(IS_TEST=True) 259 | print('Testing... [get_subAccount_transferHistory]') 260 | rest_api.get_subAccount_transferHistory(IS_TEST=True) 261 | print('Testing... [make_universalTransfer]') 262 | rest_api.make_universalTransfer(IS_TEST=True) 263 | print('Testing... [get_universalTransferHisotry]') 264 | rest_api.get_universalTransferHisotry(IS_TEST=True) 265 | print('Testing... [get_subAccount_futuresAccount_v2]') 266 | rest_api.get_subAccount_futuresAccount_v2(IS_TEST=True) 267 | print('Testing... [get_subAccount_futuresAccountSummary_v2]') 268 | rest_api.get_subAccount_futuresAccountSummary_v2(IS_TEST=True) 269 | print('Testing... [get_subAccount_positionRisk_v2]') 270 | rest_api.get_subAccount_positionRisk_v2(IS_TEST=True) 271 | print('Testing... [get_systemStatus]') 272 | rest_api.get_systemStatus() 273 | print('Testing... [get_allCoinsInfo]') 274 | rest_api.get_allCoinsInfo() 275 | print('Testing... [get_dailySnapshot]') 276 | rest_api.get_dailySnapshot(IS_TEST=True) 277 | print('Testing... [disable_withdrawSwitch]') 278 | rest_api.disable_withdrawSwitch() 279 | print('Testing... [enable_withdrawSwitch]') 280 | rest_api.enable_withdrawSwitch() 281 | print('Testing... [make_withdraw_SAPI]') 282 | rest_api.make_withdraw_SAPI(IS_TEST=True) 283 | print('Testing... [make_withdraw]') 284 | rest_api.make_withdraw(IS_TEST=True) 285 | print('Testing... [get_depositHistory_SN]') 286 | rest_api.get_depositHistory_SN(IS_TEST=True) 287 | print('Testing... [get_depositHistory]') 288 | rest_api.get_depositHistory(IS_TEST=True) 289 | print('Testing... [get_withdrawHistory_SN]') 290 | rest_api.get_withdrawHistory_SN(IS_TEST=True) 291 | print('Testing... [get_withdrawHistory]') 292 | rest_api.get_withdrawHistory(IS_TEST=True) 293 | print('Testing... [depositAddress_SN]') 294 | rest_api.depositAddress_SN(IS_TEST=True) 295 | print('Testing... [depositAddress]') 296 | rest_api.depositAddress(IS_TEST=True) 297 | print('Testing... [get_accountStatus]') 298 | rest_api.get_accountStatus() 299 | print('Testing... [get_apiStatus]') 300 | rest_api.get_apiStatus() 301 | print('Testing... [get_dustLog]') 302 | rest_api.get_dustLog() 303 | print('Testing... [make_dustTransfer]') 304 | rest_api.make_dustTransfer(IS_TEST=True) 305 | print('Testing... [get_dividendRecord]') 306 | rest_api.get_dividendRecord(IS_TEST=True) 307 | print('Testing... [get_assetDetail]') 308 | rest_api.get_assetDetail() 309 | print('Testing... [get_tradeFee]') 310 | rest_api.get_tradeFee(IS_TEST=True) 311 | print('Testing... [make_universalTransfer]') 312 | rest_api.make_universalTransfer(IS_TEST=True) 313 | print('Testing... [get_universalTransferHistory]') 314 | rest_api.get_universalTransferHistory(IS_TEST=True) 315 | print('Testing... [get_account]') 316 | rest_api.get_account() 317 | print('Testing... [place_order]') 318 | rest_api.place_order(IS_TEST=True) 319 | print('Testing... [get_order]') 320 | rest_api.get_order(IS_TEST=True) 321 | print('Testing... [cancel_order]') 322 | rest_api.cancel_order(IS_TEST=True) 323 | print('Testing... [cancel_all_orders]') 324 | rest_api.cancel_all_orders(IS_TEST=True) 325 | print('Testing... [get_all_orders]') 326 | rest_api.get_all_orders(IS_TEST=True) 327 | print('Testing... [get_all_trades]') 328 | rest_api.get_all_trades(IS_TEST=True) 329 | print('Testing... [get_open_orders]') 330 | rest_api.get_open_orders(IS_TEST=True) 331 | 332 | test_rest() --------------------------------------------------------------------------------