コード例 #1
0
    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
コード例 #2
0
ファイル: market.py プロジェクト: Xing-Huang/ok-strategy
    def __init__(self, pair, api_key, secret_key, passphrase):
        self.pair = pair
        self.swap_api = swap.SwapAPI(api_key, secret_key, passphrase, False)
        self.sell_trigger_status = False
        self.buy_trigger_status = False

        self.buy_client_oid = None
        self.sell_client_oid = None
        self.buy_stop_loss_id = None
        self.sell_stop_loss_id = None

        self.id = 0
        self.leverage = None
コード例 #3
0
 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)
コード例 #4
0
    # 公共-获取预估交割价 (20次/2s)
    # result = futureAPI.get_estimated_price('')
    # 公共-获取平台总持仓量 (20次/2s)
    # result = futureAPI.get_holds('')
    # 公共-获取当前限价 (20次/2s)
    # result = futureAPI.get_limit('')
    # 公共-获取标记价格 (20次/2s)
    # result = futureAPI.get_mark_price('')
    # 公共-获取强平单 (20次/2s)
    # result = futureAPI.get_liquidation('', '')
    # 公共-获取历史结算/交割记录 (1次/60s)
    # result = futureAPI.get_history_settlement('')

    # swap api test
    # 永续合约API
    swapAPI = swap.SwapAPI(api_key, secret_key, passphrase, False)
    # 所有合约持仓信息 (1次/10s)
    # result = swapAPI.get_position()
    # 单个合约持仓信息 (20次/2s)
    # result = swapAPI.get_specific_position('')
    # 所有币种合约账户信息 (1次/10s)
    # result = swapAPI.get_accounts()
    # 单个币种合约账户信息 (20次/2s)
    # result = swapAPI.get_coin_account('')
    # 获取某个合约的用户配置 (5次/2s)
    # result = swapAPI.get_settings('')
    # 设定某个合约的杠杆 (5次/2s)
    # result = swapAPI.set_leverage('', '', '')
    # 账单流水查询 (5次/2s)
    # result = swapAPI.get_ledger('')
    # 下单 (40次/2s)
コード例 #5
0
ファイル: premiumQuant.py プロジェクト: sparrowlsb/btcQuant

    dictRealizedFutureCoin = {}
    dictAvailableFutureCoin = {}
    dictPriceDifference = {}
    coinSTDList = {}
    coinAVGList = {}
    coinBigPriceList = {}
    priceList = {}

    api_key = API_KEY
    seceret_key = SECERET_KEY
    passphrase = PASSPARASE

    futureAPI = future.FutureAPI(api_key, seceret_key, passphrase, True)  #登陆期货合约
    swapAPI = swap.SwapAPI(api_key, seceret_key, passphrase, True) #登陆永续期货合约
    db = pymysql.connect(host=HOST, user=USER, passwd=PASSWORD, db=DBNAME) #连接数据库

    count = 0
    type = 0  #0未开单,1已开单

    while True:
        try:
            # 定义
            dictRealizedFutureCoin = {}
            dictAvailableFutureCoin = {}
            dictPriceDifference = {}
            message = ""
            timestamp = {}
            coinAVGList = {}
            coinBigPriceList = {}
def get_and_store_btc_data():
    """
        This script pulls OI, funding and mark price from bitmex, bybit, binance and okex
    """

    client = bitmex.bitmex(test=False)
    instrument_data = client.Instrument.Instrument_get(
        symbol='XBTUSD').result()

    mex_mark = round(instrument_data[0][0]["markPrice"], 1)  # [USD]
    mex_oi = round(instrument_data[0][0]["openInterest"] / 10**6,
                   3)  # [mil USD]
    mex_funding = round(instrument_data[0][0]["fundingRate"] * 100, 3)  # [%]
    # -----------------------------------------------------------

    # get data from bybit
    client = bybit.bybit(test=False, api_key="", api_secret="")

    info = client.Market.Market_symbolInfo(symbol="BTCUSD").result()
    info_dict = info[0]["result"][0]

    bybit_mark = round(float(info_dict["mark_price"]), 1)  # [USD]
    bybit_oi = round(int(info_dict["open_interest"]) / 10**6, 3)  # [mil USD]
    bybit_funding = round(float(info_dict["funding_rate"]) * 100, 3)  # [%]
    # -----------------------------------------------------------

    # get data from binance
    request_client = RequestClient(api_key="None",
                                   secret_key="None",
                                   url="https://fapi.binance.com")

    binance_oi_api = request_client.get_open_interest(symbol="BTCUSDT")
    binance_mark_api = request_client.get_mark_price(symbol="BTCUSDT")

    binance_mark = round(binance_mark_api.markPrice, 1)  # [USD]
    binance_funding = round(binance_mark_api.lastFundingRate * 100,
                            3)  # [mil USD]
    binance_oi = round(binance_oi_api.openInterest * binance_mark / 10**6,
                       3)  # [%]
    # -----------------------------------------------------------

    # get data from okex
    api_key = ""
    secret_key = ""
    passphrase = ""
    swap_contract = "BTC-USD-SWAP"

    swapAPI = swap.SwapAPI(api_key, secret_key, passphrase)
    mark_price_api = swapAPI.get_mark_price(swap_contract)
    okex_mark = round(float(mark_price_api["mark_price"]), 1)  # [USD]

    funding_api = swapAPI.get_funding_time(swap_contract)
    okex_funding = round(float(funding_api["funding_rate"]) * 100, 3)  # [%]

    oi = swapAPI.get_holds(swap_contract)
    okex_oi = round(int(oi["amount"]) * 100 / 10**6, 3)  # [mil USD]
    # -----------------------------------------------------------

    # time
    time = datetime.datetime.now().strftime(
        "%Y-%d-%m %H:%M")  # year-day-month hours-minutes-seconds

    # -----------------------------------------------------------

    # avg mark, cum OI, oi weighted funding
    avg_mark = round(
        np.average([mex_mark, bybit_mark, binance_mark, okex_mark]),
        2)  # [USD]
    cum_OI = round(np.sum([mex_oi, bybit_oi, binance_oi, okex_oi]),
                   3)  # [mil USD 1000mil => 1bil]
    oi_w_funding = round(
        (mex_oi * mex_funding + bybit_oi * bybit_funding +
         binance_oi * binance_funding + okex_oi * okex_funding) /
        (mex_oi + bybit_oi + binance_oi + okex_oi),
        3)  # [%] => (-) bears are paying, (+) bulls are paying

    dis_msg = f"```BTC: mark price: {avg_mark} $ || cum OI: {cum_OI} mil USD || OI w funding {oi_w_funding} %```"
    hook.send(dis_msg)
コード例 #7
0
 def LogIn(self):
     # self.spot = spot.SpotAPI(self.api_key, self.seceret_key, self.passphrase, True)
     self.swap = swap.SwapAPI(self.api_key, self.seceret_key,
                              self.passphrase, True)
コード例 #8
0
ファイル: ok510.py プロジェクト: waifwaif/okex-quantification
def okex():
    try:
        nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print('\033[0;34;40m\t' + nowtime + ': \033[0m')
        zh = ms.ExecQueryALL(
                "  select keyvalue from tab_accounts where status =1")

        if __name__ == '__main__':
            for i in zh:
                keyvalue = list(i)[0]
                account = ms.ExecQueryOne(
                    "  select api_key,seceret_key,passphrase from tab_accounts where  keyvalue='" + keyvalue + "' ")
                if (account is not None):
                    api_key = str(account[0])
                    seceret_key = str(account[1])
                    passphrase = str(account[2])
                    row = ms.ExecQueryOne(
                        "select top 1 * from okex where  name='" + keyvalue + "' and DateDiff(dd,create_time,getdate())=1 order by create_time asc ")
                    # print(row)
                    lastday = '0'
                    lastday_btc='0.0'
                    lastday_eth='0.0'
                    lastday_eos='0.0'
                    lastday_etc='0.0'
                    if (row is not None):
                        lastday = str(row[1])
                        lastday_btc = str(row[4])
                        lastday_eth = str(row[5])
                        lastday_eos = str(row[6])
                        lastday_etc = str(row[7])


                    # sys.exit(0)
                    # print('\033[0;34;40m\t' + lastday + ': \033[0m')
                    print('' + keyvalue + ': ')
                    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
                    spotresult = spotAPI.get_coin_account_info('USDT')
                    # future api test
                    futureAPI = future.FutureAPI(api_key, seceret_key, passphrase, True)
                    # futureresult_get_accounts = futureAPI.get_accounts()
                    # # print('当前合约账户'+json.dumps(futureresult_get_accounts.info))
                    # if(futureresult_get_accounts['info'].__contains__('btc')):
                    #     print('当前合约账户btc: '+futureresult_get_accounts['info']['btc']['equity'])
                    # if (futureresult_get_accounts['info'].__contains__('etc')):
                    #     print('当前合约账户etc: '+futureresult_get_accounts['info']['etc']['equity'])
                    # if (futureresult_get_accounts['info'].__contains__('eth')):
                    #     print('当前合约账户eth: '+futureresult_get_accounts['info']['eth']['equity'])
                    # if (futureresult_get_accounts['info'].__contains__('eos')):
                    #     print('当前合约账户eos: '+futureresult_get_accounts['info']['eos']['equity'])

                    btc_amunt = futureAPI.get_coin_account('btc')
                    etc_amunt = futureAPI.get_coin_account('etc')
                    eth_amunt = futureAPI.get_coin_account('eth')
                    eos_amunt = futureAPI.get_coin_account('eos')

                    # futureresult_get_position = futureAPI.get_position()
                    # print('当前合约账户持仓:' + json.dumps(futureresult_get_position['holding'][0][0]))

                    ####
                    # futureresult_get_order_list1 = futureAPI.get_order_list(6, '', '', '', 'ETH-USD-190329')
                    # futureresult_get_order_list2 = futureAPI.get_order_list(7, '', '', '', 'ETH-USD-190329')
                    #
                    # print('未完成:' + json.dumps(futureresult_get_order_list1))
                    # print('已完成:' + json.dumps(futureresult_get_order_list2))
                    # sys.exit(0)
                    #
                    ####
                    # print('当前合约账户持仓'+json.dumps(futureresult_get_position['holding'][0][0]))

                    # swap api test
                    swapAPI = swap.SwapAPI(api_key, seceret_key, passphrase, True)
                    btc_price = swapAPI.get_mark_price('BTC-USD-SWAP')['mark_price']
                    etc_price = swapAPI.get_mark_price('ETC-USD-SWAP')['mark_price']
                    eth_price = swapAPI.get_mark_price('ETH-USD-SWAP')['mark_price']
                    eos_price = swapAPI.get_mark_price('EOS-USD-SWAP')['mark_price']
                    btc = float(str(btc_price)) * float(str(btc_amunt['equity']))
                    etc = float(str(etc_price)) * float(str(etc_amunt['equity']))
                    eth = float(str(eth_price)) * float(str(eth_amunt['equity']))
                    eos = float(str(eos_price)) * float(str(eos_amunt['equity']))
                    all = str(eos + eth + btc + etc + float(str(spotresult['balance'])))

                    # ms.ExecNonQuery(newsql.encode('utf-8'))
                    # newsql = "insert into okex (usdt,name) values('" + all + "','" + keyvalue + "')"
                    # print(newsql)
                    #
                    # ms.ExecNonQuery(newsql)
                    # newsql = "insert into okex (usdt,name,btc,eth,eos,etc) values('" + all + "','" + keyvalue + "','" + btc_amunt['equity'] + ",'" + eth_amunt['equity'] + ",'" + eos_amunt['equity'] + ",'" + etc_amunt['equity'] + "')"



                    newsql = "insert into okex (usdt,name,btc,eth,eos,etc) values('" + all + "','" + keyvalue + "','" + btc_amunt[
                        'equity'] + "','" + eth_amunt['equity'] + "','" + eos_amunt['equity'] + "','" + etc_amunt['equity'] + "')"
                    ms.ExecNonQuery(newsql)

                    bfb = '%.2f%%' % ((float(all) - float(lastday)) / float(all) * 100)
                    if (lastday == '0'):
                        bfb = '0%'

                    res = keyvalue + ':\n当前币币账户USDT:' + spotresult['balance'] + '\n' + '当前合约账户btc:' + btc_amunt[
                        'equity'] + ';昨日'+lastday_btc+'\n' + '当前合约账户etc: ' + etc_amunt['equity']
                    res = res +';昨日'+lastday_etc+ '\n' + '当前合约账户eth: ' + eth_amunt['equity'] +';昨日'+lastday_eth+  '\n' + '当前合约账户eos: ' + eos_amunt[
                        'equity'] +';昨日'+lastday_eos+ '\n账户总计USDT约: ' + all + ';昨日: ' + lastday + '\n' + '今日USDT本位盈利率' + bfb

                    print(res)
                    time.sleep(10)
    except Exception as e:
        newsql = "insert into tab_send_email (address_to,mail_subject,mail_text) values('*****@*****.**','okex脚本出现问题'+'"+nowtime+"','"+str(e)+"')"
        ms.ExecNonQuery(newsql)
        time.sleep(10)
コード例 #9
0
def get_and_store_data():
    # get data from bitmex
    ws_btc = BitMEXWebsocket(endpoint="https://www.bitmex.com", symbol="XBTUSD", api_key=None, api_secret=None)

    data_btc = ws_btc.get_instrument()

    mex_mark = round(data_btc["markPrice"], 1)                      # [USD]
    mex_oi = round(data_btc["openInterest"] / 10 ** 6, 3)           # [mil USD]
    mex_funding = round(data_btc["fundingRate"] * 100, 3)           # [%]
    # -----------------------------------------------------------

    # get data from bybit 
    client = bybit.bybit(test=False, api_key="", api_secret="")

    info = client.Market.Market_symbolInfo(symbol="BTCUSD").result()
    info_dict = info[0]["result"][0]

    bybit_mark = round(float(info_dict["mark_price"]), 1)               # [USD]
    bybit_oi = round(int(info_dict["open_interest"]) / 10 ** 6, 3)      # [mil USD]
    bybit_funding = round(float(info_dict["funding_rate"]) * 100, 3)    # [%]
    # -----------------------------------------------------------

    # get data from binance
    request_client = RequestClient(api_key="None", secret_key="None", url="https://fapi.binance.com")

    binance_oi_api = request_client.get_open_interest(symbol="BTCUSDT")
    binance_mark_api = request_client.get_mark_price(symbol="BTCUSDT")

    binance_mark = round(binance_mark_api.markPrice , 1)                            # [USD]
    binance_funding = round(binance_mark_api.lastFundingRate * 100, 3)              # [mil USD]
    binance_oi = round(binance_oi_api.openInterest * binance_mark / 10 ** 6, 3)     # [%]
    # -----------------------------------------------------------   

    # get data from okex
    api_key = ""
    secret_key = ""
    passphrase = ""
    swap_contract = "BTC-USD-SWAP"

    swapAPI = swap.SwapAPI(api_key, secret_key, passphrase)
    mark_price_api = swapAPI.get_mark_price(swap_contract)
    okex_mark = round(float(mark_price_api["mark_price"]), 1)               # [USD]

    funding_api = swapAPI.get_funding_time(swap_contract)
    okex_funding = round(float(funding_api["funding_rate"]) * 100, 3)       # [%]

    oi = swapAPI.get_holds(swap_contract)
    okex_oi = round(int(oi["amount"]) * 100 / 10 ** 6, 3)                   # [mil USD]
    # -----------------------------------------------------------

    # time 
    time = datetime.datetime.now().strftime("%Y-%d-%m %H:%M") # year-day-month hours-minutes-seconds


    # -----------------------------------------------------------
    # print outs
    print("-" * 200)
    print(f"{mex_mark}[USD] - {mex_funding}[%] - {mex_oi}[mil USD] => Bitmex")
    print(f"{bybit_mark}[USD] - {bybit_funding}[%] - {bybit_oi}[mil USD] => Bybit")
    print(f"{binance_mark}[USD] - {binance_funding}[%] - {binance_oi}[mil USD] => Binance")
    print(f"{okex_mark}[USD] - {okex_funding}[%] - {okex_oi}[mil USD] => Okex")
    print("-" * 200)


    # data storage

    # all data
    all_swap_data = [mex_mark, mex_funding, mex_oi, bybit_mark, bybit_funding, bybit_oi, binance_mark, binance_funding, binance_oi, okex_mark, okex_funding, okex_oi, time]
    all_swap_data_txt = f"{mex_mark};{mex_funding};{mex_oi};{bybit_mark};{bybit_funding};{bybit_oi};{binance_mark};{binance_funding};{binance_oi};{okex_mark};{okex_funding};{okex_oi};{time}\n"


    with open("YOUR FILE PATH/oi-funding-mark-data/data storage/all_swap_data_storage.txt", "a") as store_swap_data: 
        store_swap_data.write(all_swap_data_txt)
        store_swap_data.close()

    # print(all_swap_data_txt)
    # print(all_swap_data)
    # -----------------------------------------------------------

    # avg mark, cum OI, oi weighted funding
    avg_mark = round(np.average([mex_mark, bybit_mark, binance_mark, okex_mark]), 3)    # [USD]
    cum_OI = round(np.sum([mex_oi, bybit_oi, binance_oi, okex_oi]), 3)                  # [mil USD 1000mil => 1bil]
    oi_w_funding = round((mex_oi*mex_funding + bybit_oi*bybit_funding + binance_oi*binance_funding + okex_oi*okex_funding)/(mex_oi + bybit_oi + binance_oi + okex_oi), 3)   # [%] => (-) bears are paying, (+) bulls are paying

    avgMark_cumOI_oiWfunding = [avg_mark, cum_OI, oi_w_funding, time]
    avgMark_cumOI_oiWfunding_txt = f"{avg_mark};{cum_OI};{oi_w_funding};{time}\n"   # [USD] - [mil USD] - [%]

    with open("YOUR FILE PATH/oi-funding-mark-data/data storage/avgMark_cumOI_oiWfunding_storage.txt", "a") as store_avgM_cumOi_oiWfund:
        store_avgM_cumOi_oiWfund.write(avgMark_cumOI_oiWfunding_txt)
        store_avgM_cumOi_oiWfund.close()

    # print(avgMark_cumOI_oiWfunding_txt)
    # print(avgMark_cumOI_oiWfunding)
    # print(avg_mark)
    # print(cum_OI)
    # print(oi_w_funding)
    # -----------------------------------------------------------


    # mark prices
    mark_prices = [mex_mark, bybit_mark, binance_mark, okex_mark, time]
    mark_prices_txt = f"{mex_mark};{bybit_mark};{binance_mark};{okex_mark};{time}\n"    # [USD]

    with  open("YOUR FILE PATH/oi-funding-mark-data/data storage/mark_prices_storage.txt", "a") as store_mark_prices:
        store_mark_prices.write(mark_prices_txt)
        store_mark_prices.close()

    # print(mark_prices_txt)
    # print(mark_prices)
    # -----------------------------------------------------------

    # fundings
    fundings = [mex_funding, bybit_funding, binance_funding, okex_funding, time]
    fundings_txt = f"{mex_funding};{bybit_funding};{binance_funding};{okex_funding};{time}\n"   # [%]

    with open("YOUR FILE PATH/oi-funding-mark-data/data storage/fundings_storage.txt", "a") as store_fundings:
        store_fundings.write(fundings_txt)
        store_fundings.close()

    # print(fundings_txt)
    # print(fundings)
    # -----------------------------------------------------------

    # open interests
    open_interests = [mex_oi, bybit_oi, binance_oi, okex_oi, time]
    open_interests_txt = f"{mex_oi};{bybit_oi};{binance_oi};{okex_oi};{time}\n"     # [mil USD]

    with open("YOUR FILE PATH/oi-funding-mark-data/data storage/open_interests_storage.txt", "a") as store_open_interests:
        store_open_interests.write(open_interests_txt)
        store_open_interests.close()
コード例 #10
0
def job():
    inputval = input("请输入查询:")
    key = inputval.split('询')
    # key=msg['Text'].split('询')

    if (len(key) == 2 and key[0] == '查'):
        keyvalue = key[1]
        account = ms.ExecQueryOne(
            "  select api_key,seceret_key,passphrase from tab_accounts where  keyvalue='"
            + keyvalue + "' ")
        if (account is not None):
            api_key = str(account[0])
            seceret_key = str(account[1])
            passphrase = str(account[2])

            row = ms.ExecQueryOne(
                "select top 1 * from okex where  name='" + keyvalue +
                "' and DateDiff(dd,create_time,getdate())<=1 order by create_time asc "
            )
            lastday = '0'
            lastday_btc = '0.0'
            lastday_eth = '0.0'
            lastday_eos = '0.0'
            lastday_etc = '0.0'

            sys.exit(0)
            if (row is not None):
                lastday = str(row[1])
                lastday_btc = str(row[4])
                lastday_eth = str(row[5])
                lastday_eos = str(row[6])
                lastday_etc = str(row[7])

                print('' + keyvalue + ': ')

                spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
                spotresult = spotAPI.get_coin_account_info('USDT')

                futureAPI = future.FutureAPI(api_key, seceret_key, passphrase,
                                             True)
                btc_amunt = futureAPI.get_coin_account('btc')
                etc_amunt = futureAPI.get_coin_account('etc')
                eth_amunt = futureAPI.get_coin_account('eth')
                eos_amunt = futureAPI.get_coin_account('eos')

                swapAPI = swap.SwapAPI(api_key, seceret_key, passphrase, True)
                btc_price = swapAPI.get_mark_price(
                    'BTC-USD-SWAP')['mark_price']
                etc_price = swapAPI.get_mark_price(
                    'ETC-USD-SWAP')['mark_price']
                eth_price = swapAPI.get_mark_price(
                    'ETH-USD-SWAP')['mark_price']
                eos_price = swapAPI.get_mark_price(
                    'EOS-USD-SWAP')['mark_price']

                # 查询价格
                btc = float(str(btc_price)) * float(str(btc_amunt['equity']))
                etc = float(str(etc_price)) * float(str(etc_amunt['equity']))
                eth = float(str(eth_price)) * float(str(eth_amunt['equity']))
                eos = float(str(eos_price)) * float(str(eos_amunt['equity']))
                all = str(eos + eth + btc + etc +
                          float(str(spotresult['balance'])))

                # 盈利比率
                bfb = '%.2f%%' % (
                    (float(all) - float(lastday)) / float(all) * 100)
                if (lastday == '0'):
                    bfb = '0%'

                res = keyvalue + ':\n当前币币账户USDT:' + spotresult[
                    'balance'] + '\n' + '当前合约账户btc:' + btc_amunt[
                        'equity'] + ';\n昨日' + lastday_btc + '\n' + '当前合约账户etc: ' + etc_amunt[
                            'equity']
                res = res + ';\n昨日' + lastday_etc + '\n' + '当前合约账户eth: ' + eth_amunt[
                    'equity'] + ';\n昨日' + lastday_eth + '\n' + '当前合约账户eos: ' + eos_amunt[
                        'equity'] + ';\n昨日' + lastday_eos + '\n账户总计USDT约: ' + all + ';\n昨日: ' + lastday + '\n' + '今日USDT本位盈利率' + bfb

                # return res
                print(res)
        else:
            print('查询口令错误')
コード例 #11
0
    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