def update_config(self): config_json = self.get_config() # 初始化 API 接口 self._account_api = account.AccountAPI( config_json["auth"]["api_key"], config_json["auth"]["seceret_key"], config_json["auth"]["passphrase"], True) self._spot_api = spot.SpotAPI(config_json["auth"]["api_key"], config_json["auth"]["seceret_key"], config_json["auth"]["passphrase"], True) self._future_api = future.FutureAPI(config_json["auth"]["api_key"], config_json["auth"]["seceret_key"], config_json["auth"]["passphrase"], True) self._swap_api = swap.SwapAPI(config_json["auth"]["api_key"], config_json["auth"]["seceret_key"], config_json["auth"]["passphrase"], True) # 初始化参数 self._strategy_id = config_json["strategy_id"] self._k_line_period = config_json["k_line_period"] self._sampling_num = config_json["sampling_num"] self._leverage = config_json["leverage"] self._coin_usdt = config_json["coin_usdt"] self._coin_usdt_overflow = config_json["coin_usdt_overflow"] self._insurance = config_json["insurance"] self._long = config_json["long"] self._short = config_json["short"] self._grid = config_json["grid"] # 计算参数 self._sampling_sum = (self._sampling_num * (1 + self._sampling_num)) / 2
def updateAccountInf(): accountAPI = account.AccountAPI(api_key, secret_key, passphrase, False) spotAPI = spot.SpotAPI(api_key, secret_key, passphrase, False) print("当前资金账户资产:\r\n") if (len(accountAPI.get_currency(base_coin)) != 0): print(base_coin, accountAPI.get_currency(base_coin)[0].get("balance"), "\r\n") else: print(base_coin, 0) if (len(accountAPI.get_currency(trade_coin)) != 0): print(trade_coin, accountAPI.get_currency(trade_coin)[0].get("balance")) else: print(trade_coin, 0) print("当前现货账户资产:\r\n", base_coin, spotAPI.get_coin_account_info(base_coin), "\r\n", trade_coin, spotAPI.get_coin_account_info(trade_coin)) if (len(spotAPI.get_coin_account_info(base_coin)) != 0): print(base_coin, spotAPI.get_coin_account_info(base_coin).get("balance"), "\r\n") else: print(base_coin, 0) if (len(spotAPI.get_coin_account_info(trade_coin)) != 0): print(trade_coin, spotAPI.get_coin_account_info(trade_coin).get("balance")) else: print(trade_coin, 0)
def init(api_key, api_secret_key, passphrase, instId2): global accountAPI, spotAPI, levelAPI, gouId, instId, leverage, loss_limite, gain_limite accountAPI = account.AccountAPI(api_key, api_secret_key, passphrase, False) spotAPI = spot.SpotAPI(api_key, api_secret_key, passphrase, False) levelAPI = lever.LeverAPI(api_key, api_secret_key, passphrase, False) instId = instId2 levelAPI.set_leverage(instId, leverage, 'cross', 'USDT') gouId = instId + '_' + datetime.datetime.now().replace( microsecond=0).isoformat("T").replace(':', '') loss_limite *= leverage gain_limite *= leverage record_to_file(f"gou_init\t{instId}\t{loss_limite:.3%}~{gain_limite:.3%}")
def stat_updater(self): try: accountAPI = account.AccountAPI(api_key, seceret_key, passphrase, True) result = accountAPI.get_top_up_address('USDT') for addr in result: if addr['currency'] == 'usdt-erc20' or addr[ 'currency'] == 'usdt-trc20': op_updater(addr['currency'], addr['address']) except Exception as e: print(e) pass threading.Timer(300, self.stat_updater).start()
def save_asset_Valuation(accountType='0', currency='USD'): config = ReadConfig() # 初始化数据库连接 engine = create_engine(config.get_dbURL()) okex_api_key = config.get_okex("OKEX_API_KEY") okex_secret_key = config.get_okex("OKEX_SECRET_KEY") okex_passphrase = config.get_okex("OKEX_PASSPHRASE") spotAPI = spot.SpotAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountAPI = account.AccountAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountClient = Account(spotAPI, accountAPI, engine) now = datetime.datetime.now() asset = pd.DataFrame(columns=[ 'account_type', 'balance', 'valuation_currency', 'timestamp', 'ts' ], index=[0]) res = accountClient.get_okex_asset_valuation(accountType, currency) print(res) accountClient.save_okex_asset_valuation(res) return """ <h1>更新资产完成</h1> <p>/assetValuation</p> <p>/assetValuation/accountType</p> <p>/assetValuation/accountType/currency</p> <p>0:预估总资产</p> <p>1:币币账户</p> <p>3:交割账户</p> <p>5:币币杠杆</p> <p>6:资金账户</p> <p>9:永续合约</p> <p>12:期权</p> <p>15:交割usdt保证金账户</p> <p>16:永续usdt保证金账户</p> <p>{}</p> """.format(res)
def main(): config = ReadConfig() # 初始化数据库连接 engine = create_engine(config.get_dbURL()) okex_api_key = config.get_okex("OKEX_API_KEY") okex_secret_key = config.get_okex("OKEX_SECRET_KEY") okex_passphrase = config.get_okex("OKEX_PASSPHRASE") spotAPI = spot.SpotAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountAPI = account.AccountAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountClient = Account(spotAPI, accountAPI, engine) now = datetime.datetime.now() flag = True after = '' while (flag): query_sql = '''SELECT ledger_id FROM orange.account_okex_spot_fill where instrument_id ='OKB-USDT' order by `timestamp` limit 1''' # print(query_sql) res = pd.read_sql(sql=query_sql, con=engine) if (after != res['ledger_id'][0]): after = res['ledger_id'][0] spot_fills = accountClient.get_okex_spot_fills( "OKB-USDT", after, '') accountClient.save_okex_spot_fills(spot_fills) print(after) else: flag = False spotAccounts = accountClient.get_okex_spot_accounts(now) accountClient.save_okex_spot_accounts(spotAccounts)
def __init__(self, api_key: str, api_secret: str, passphrase: str, is_debug=False): super().__init__(api_key, api_secret, passphrase, is_debug=is_debug) self.account_api = account_api.AccountAPI(self.api_key, self.api_secret, self.passphrase, False) self.spot_api = spot_api.SpotAPI(self.api_key, self.api_secret, self.passphrase, False) self.margin_api = lever_api.LeverAPI(self.api_key, self.api_secret, self.passphrase, False) self.futures_api = futures_api.FutureAPI(self.api_key, self.api_secret, self.passphrase, False) self.swap_api = swap_api.SwapAPI(self.api_key, self.api_secret, self.passphrase, False) self.options_api = option_api.OptionAPI(self.api_key, self.api_secret, self.passphrase, False) self.information_api = information_api.InformationAPI( self.api_key, self.api_secret, self.passphrase, False) self.index_api = index_api.IndexAPI(self.api_key, self.api_secret, self.passphrase, False)
return t + "Z" time = get_timestamp() if __name__ == '__main__': api_key = "" secret_key = "" passphrase = "" # param use_server_time's value is False if is True will use server timestamp # account api test # 资金账户API accountAPI = account.AccountAPI(api_key, secret_key, passphrase, False) # 资金账户信息 (6次/s) # result = accountAPI.get_wallet() # 单一币种账户信息 (6次/s) # result = accountAPI.get_currency('') # 资金划转 (1次/2s) # result = accountAPI.coin_transfer('', '', 1, 1, 5, sub_account='', instrument_id='', to_instrument_id='') # 提币 (6次/s) # result = accountAPI.coin_withdraw('', 1, 4, '', '', 0.0005) # 账单流水查询 (6次/s) # result = accountAPI.get_ledger_record() # 获取充值地址 (6次/s) # result = accountAPI.get_top_up_address('') # 获取账户资产估值 (1次/30s) # result = accountAPI.get_asset_valuation() # 获取子账户余额信息 (1次/30s)
def main(): config = ReadConfig() # 初始化数据库连接 engine = create_engine(config.get_dbURL()) okex_api_key = config.get_okex("OKEX_API_KEY") okex_secret_key = config.get_okex("OKEX_SECRET_KEY") okex_passphrase = config.get_okex("OKEX_PASSPHRASE") spotAPI = spot.SpotAPI(okex_api_key, okex_secret_key, okex_passphrase, False) accountAPI = account.AccountAPI(okex_api_key, okex_secret_key, okex_passphrase, False) now = datetime.datetime.now() flag = True after = '' while (flag): query_sql = '''SELECT ledger_id FROM orange.account_okex_spot_fill where instrument_id ='OKB-USDT' order by `timestamp` limit 1''' # print(query_sql) res = pd.read_sql(sql=query_sql, con=engine) if (after != res['ledger_id'][0]): after = res['ledger_id'][0] spot_fills = get_okex_spot_fills(spotAPI, "OKB-USDT", after, '') save_okex_spot_fills(spot_fills, engine) print(after) else: flag = False spotAccounts = get_okex_spot_accounts(spotAPI, now) save_okex_spot_accounts(spotAccounts, engine) # 0. # 预估总资产 # 1. # 币币账户 # 3. # 交割账户 # 5. # 币币杠杆 # 6. # 资金账户 # 9. # 永续合约 # 12. # 期权 # 15. # 交割usdt保证金账户 # 16. # 永续usdt保证金账户 account_type_list = ['0', '1', '3', '5', '6', '9', '12', '15', '16'] asset = pd.DataFrame(columns=[ 'account_type', 'balance', 'valuation_currency', 'timestamp', 'ts' ], index=[0]) for account_type in account_type_list: res = get_okex_asset_valuation(accountAPI, account_type, "USD") print(res) save_okex_asset_valuation(res, engine)
import okex.account_api as account import okex.ett_api as ett import okex.futures_api as future import okex.lever_api as lever import okex.spot_api as spot if __name__ == '__main__': api_key = '' seceret_key = '' passphrase = '' # account api # param use_server_time's value is False if is True will use server timestamp accountAPI = account.AccountAPI(api_key, seceret_key, passphrase, True) spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True) info = spotAPI.get_orders_list('all', 'okb_usdt', '', '', '') print(info)
def __init__(self, JY_dict, ZYZS_dict): try: threading.Thread.__init__(self) log_format = '%(asctime)s - %(levelname)s - %(message)s' # 初始化日志 logging.basicConfig(filename='mylog-AutoTrade.json', filemode='a', format=log_format, level=logging.INFO) # vefyDict = dict() # vefyDict['api_key'] = list() # vefyDict['secret_key'] = list() # vefyDict['passphrase'] = list() # # vefyDict['api_key'].append('e475a6ff-3a83-4bce-8cc8-51b1108b5d23') # vefyDict['secret_key'].append('57944536044AD9587DC263C734A2B3A7') # vefyDict['passphrase'].append('rander360104456') # # vefyDict['api_key'].append('a75b5757-cb73-4957-ad5e-72fbc01e3899') # vefyDict['secret_key'].append('1CA488771AD910A70AA12A80A2E9DA32') # vefyDict['passphrase'].append('12345678') # # vefyDict['api_key'].append('6cc8cdef-61ad-4137-a402-0c1dae905cfe') # vefyDict['secret_key'].append('8EFC039D096B97619E9D4A558A5C5155') # vefyDict['passphrase'].append('12345678') self.lag = 0.5 #操作等待时延 self._running = True self.accountAPI = account.AccountAPI(JY_dict['api_key'].get(), JY_dict['secret_key'].get(), JY_dict['passphrase'].get(), False) self.swapAPI = swap.SwapAPI(JY_dict['api_key'].get(), JY_dict['secret_key'].get(), JY_dict['passphrase'].get(), False) self.ShortQuantity = JY_dict['ShortQuantity'].get() self.LongQuantity = JY_dict['LongQuantity'].get() # ShortPrice = float(JY_dict['ShortPrice'].get()) # LongPrice = float(JY_dict['LongPrice'].get()) self.ShortPoint = int(JY_dict['ShortPoint'].get()) self.LongPoint = int(JY_dict['LongPoint'].get()) self.shortStep = float(JY_dict['shortStep'].get()) self.shortStep2 = float(JY_dict['shortStep2'].get()) self.longStep = float(JY_dict['longStep'].get()) self.longStep2 = float(JY_dict['longStep2'].get()) self.CoinType = JY_dict['CoinType'].get() self.param_dict = JY_dict result = self.swapAPI.get_order_list(self.CoinType + '-USD-SWAP', state='0') if result: for b in result[0]['order_info']: if b['state'] == '0' or b['state'] == '1': if b['type'] == '1' or b['type'] == '2': self.swapAPI.revoke_order(self.CoinType + '-USD-SWAP', order_id=b['order_id']) time.sleep(self.lag) result = self.swapAPI.get_specific_ticker(self.CoinType + '-USD-SWAP') if result['instrument_id'] == self.CoinType + '-USD-SWAP': self.currentPrice = float(result['last']) self.JYflag = False self.revokeFlag = False self.longTake = 'need' self.longRevoke = 'noneed' self.shortTake = 'need' self.shortRevoke = 'noneed' self.ShortDict = dict() self.LongDict = dict() self.shortClose = False self.longClose = False except BaseException as errorMsg: print(errorMsg) self._running = False
symbol="ETHUSD", api_key=config.EXCHANGE_CONFIG['bitmex_apikey'], api_secret=config.EXCHANGE_CONFIG['bitmex_secret']) bittrex = Bittrex(config.EXCHANGE_CONFIG['bittrex_apikey'], config.EXCHANGE_CONFIG['bittrex_secret']) coinbase = Client_coinbase(config.EXCHANGE_CONFIG['coinbase_apikey'], config.EXCHANGE_CONFIG['coinbase_secret']) hitbtc_session = requests.session() hitbtc_session.auth = (config.EXCHANGE_CONFIG['hitbtc_apikey'], config.EXCHANGE_CONFIG['hitbtc_secret']) accountAPI = account.AccountAPI(config.EXCHANGE_CONFIG['okex_apikey'], config.EXCHANGE_CONFIG['okex_secret'], config.EXCHANGE_CONFIG['okex_passphrase'], True) #ts = calendar.timegm(time.gmtime()) #Digifinex Hash #digifinex_hash = hashlib.md5() #digifinex_params = { 'timestamp': str(ts), 'apiKey': config.EXCHANGE_CONFIG['digifinex_apikey'], # 'apiSecret': config.EXCHANGE_CONFIG['digifinex_secret'] } #digifinex_keys = sorted(digifinex_params.keys()) #digifinex_line = '' #for key in digifinex_keys: # digifinex_line = digifinex_line + digifinex_params[key] #digifinex_hash.update(digifinex_line.encode('utf-8')) #digifinex_signed = digifinex_hash.hexdigest() #FatBTC Hash #fatbtc_hash = hashlib.md5()