예제 #1
0
    def __init__(self,
                 model,
                 quote_asset,
                 base_asset,
                 api_key,
                 api_secret,
                 passphrase,
                 annualization=365 * 24 * 60,
                 max_leverage=4,
                 **kwargs):
        super(LiveMarginTradingEnv, self).__init__()

        self.model = model
        self.base_asset = base_asset
        self.quote_asset = quote_asset
        self.instrument_id = "-".join(self.base_asset, self.quote_asset)
        self.api_key = api_key
        self.api_secret = api_secret
        self.passphrase = passphrase
        self.spotAPI = spot.SpotAPI(api_key, api_secret, passphrase, True)
        self.leverAPI = lever.LeverAPI(api_key, api_secret, passphrase, True)

        self.window_size = window_size
        self.max_leverage = max_leverage
        self.reward_func = reward_func
        self.annualization = annualization
예제 #2
0
def bd():
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print('现货量化检测:' + '\033[0;34;40m\t' + nowtime + ': \033[0m')

    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
    result = spotAPI.get_orders_list(state='2', instrument_id='BTC-USDT')

    # side	String	buy 或 sell
    # price_avg	String	成交均价
    # created_at 时间

    mail_text = ''  # 邮件内容
    my_last_spot1 = result[0][0]  # 我的最新一次下单数据
    my_last_spot2 = result[0][1]  # 我的最新二次下单数据

    mail_text = '最新一次时间:{0},动作:{1},成交均价{2};'.format(
        my_last_spot1['created_at'], my_last_spot1['side'],
        my_last_spot1['price_avg'])
    mail_text += '上两次时间:{0},动作:{1},成交均价{2};'.format(
        my_last_spot2['created_at'], my_last_spot2['side'],
        my_last_spot2['price_avg'])

    get_last_text = "select top 1 mail_text from tab_send_email where type=1 order by create_time desc"
    last_text = ms.ExecQueryOne(get_last_text)

    # 如果邮件内容不为空,并且和上次不同,插入数据库,以发送提醒邮件
    if mail_text != '' and mail_text != last_text[0]:
        send_mail_sql = "insert into tab_send_email (address_to,mail_subject,mail_text,type) values('*****@*****.**','现货开单','" + mail_text + "','1')"
        print(mail_text)
        ms.ExecNonQuery(send_mail_sql)
    else:
        print('相同')
예제 #3
0
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)
예제 #4
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
예제 #5
0
def get_k_line_info(api_key_, seceret_key_, passphrase_, symbol_, start_time,
                    end_time, period_):  # 单次请求最多获取200条数据
    spot_api = spot.SpotAPI(api_key_, seceret_key_, passphrase_, True)  # 请求连接
    kline = spot_api.get_kline(symbol_, start_time, end_time, period_)  # 获取数据
    if len(kline) > 0:
        return kline
    else:
        return ''
예제 #6
0
def save_kline(instrumentId="OKB-USDT"):
    app.logger.info('instrument_id:{}'.format(instrumentId))

    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)

    kline = Kline(spotAPI, engine)

    now = datetime.datetime.now().replace(hour=0,
                                          minute=0,
                                          second=0,
                                          microsecond=0)
    end = now
    start = now - datetime.timedelta(days=1)

    for i in range(5):

        kline900 = kline.get_okex_spot_kline(instrumentId, start, end, 900)
        try:
            kline.save_okex_spot_kline(kline900, "kline_okex_15", True)
        except Exception:
            app.logger.error(traceback.format_exc())  # 用法

        end = end - datetime.timedelta(days=i)
        start = start - datetime.timedelta(days=1)

    end = now
    start = end - datetime.timedelta(days=200)

    for i in range(5):

        print(i, end, start)

        kline86400 = kline.get_okex_spot_kline(instrumentId, start, end, 86400)
        kline.save_okex_spot_kline(kline86400, "kline_okex_1d", True)

        end = end - datetime.timedelta(days=200)
        start = start - datetime.timedelta(days=200)

    return """
    <h1>{}</h1>
    <p>15分钟和1日线kline搜集完成。</p>
    <p>/kline/DOT-USDT</p>
    """.format(instrumentId)
예제 #7
0
def clear():
    for i in zip(api_key_list, secret_key_list):
        spotAPI = spot.SpotAPI(i[0], i[1], passphrase, False)
        trade_status()
        if lasthold:
            try:
                stop_check()
            except:
                pass

        if selllist:
            sell_all()
예제 #8
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%}")
예제 #9
0
def yijia():
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print('\033[0;34;40m\t' + nowtime + ': \033[0m')

    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)

    # get_ticker 获取全部ticker信息
    # type(bb_get_ticker): list
    bb_get_ticker = spotAPI.get_ticker()
    # type(ticker) : dict
    instrument_id_list = ['BTC-USDT', 'LTC-USDT', 'ETH-USDT', 'EOS-USDT', 'XRP-USDT', 'ETC-USDT', 'BCH-USDT',
                          'BSV-USDT']
    ticker_list = []
    for bb_ticker in bb_get_ticker:
        if bb_ticker['instrument_id'] in instrument_id_list:
            ticker_list.insert(len(ticker_list), {'name': bb_ticker['instrument_id'][0:-1],
                                                  bb_ticker['instrument_id'][0:-1]: bb_ticker['last']})
    # best_ask 卖一价  last 最新成交价

    futureAPI = future.FutureAPI(api_key, seceret_key, passphrase, True)

    future_get_ticker = futureAPI.get_ticker()
    mail_text = ''
    for ticket in ticker_list:
        for future_ticker in future_get_ticker:
            if ticket['name'] in future_ticker['instrument_id']:
                ticket[future_ticker['instrument_id']] = future_ticker['last']
                rate = (float(future_ticker['last']) / float(ticket[ticket['name']]) * 100 - 100)
                ticket[future_ticker['instrument_id'] + '溢价'] = '%.2f' % rate + '%'
                if (rate > 3 or rate < -3) and ('190628' in future_ticker['instrument_id']):
                    mail_text = mail_text + '\r\n' + future_ticker['instrument_id'] + '季度溢价:' + str('%.2f' % rate + '%')
                elif (rate > 1 or rate < -1) and ('190628' not in future_ticker['instrument_id']):
                    mail_text = mail_text + '\r\n' + future_ticker['instrument_id'] + '周溢价:' + str('%.2f' % rate + '%')
    # [{'name': 'ETH-USD', 'ETH-USD': '171.78', 'ETH-USD-190517': '170.476', 'ETH-USD-190517溢价': '-0.76%', 'ETH-USD-190628': '171.191', 'ETH-USD-190628溢价': '-0.34%', 'ETH-USD-190510': '170.634', 'ETH-USD-190510溢价': '-0.67%'}]
    # print(ticker_list)
    # print(mail_text)
    # sys.exit(0)
    # 判断上一次时间在2小时之前 并且时间在8点到晚上12点 则插入信息
    today = datetime.datetime.today()
    get_last_time = "select * from tab_send_email where create_time > '" + (
                datetime.datetime.now() - datetime.timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S') + "'"
    last_time = ms.ExecQueryOne(get_last_time)
    bl1=nowtime>datetime.datetime(today.year, today.month, today.day,8, 30, 0).strftime('%Y-%m-%d %H:%M:%S')
    bl2=nowtime<datetime.datetime(today.year, today.month, today.day, 23, 59, 59).strftime('%Y-%m-%d %H:%M:%S')
    bl3 =(last_time is None)
    if bl1 and bl2 and bl3 and mail_text != '':
        send_mail_sql = "insert into tab_send_email (address_to,mail_subject,mail_text) values('*****@*****.**','okex期货出现溢价'+'" + nowtime + "','" + mail_text + "')"
        print(mail_text)
        ms.ExecNonQuery(send_mail_sql)
    else:
        # print(bl1,bl2,bl3)
        pass
예제 #10
0
def okb():
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print('\033[0;34;40m\t' + nowtime + ': \033[0m')

    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)

    # get_currency 获取单一币种持仓信息
    usdt_dict = spotAPI.get_coin_account_info('USDT')

    if (float(usdt_dict['balance']) == 0):
        # 获取某个ticker信息 get_specific_ticker
        okb_dict = spotAPI.get_specific_ticker('OKB-USDT')
        # best_ask 卖一价  last 最新成交价
        print(okb_dict['best_bid'])
예제 #11
0
 def account_info(self):
     spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
     result = spotAPI.get_account_info()
     balance = {"btc": '', 'eth': '', 'usdt': '', 'krw': ''}
     for coin in result:
         if coin['currency'] == 'BTC':
             balance['btc'] = coin["balance"]
         elif coin['currency'] == 'ETH':
             balance['eth'] = coin["balance"]
         elif coin['currency'] == 'USDT':
             balance['usdt'] = coin["balance"]
         elif coin['currency'] == 'KRW':
             balance['krw'] = coin["balance"]
     return balance
예제 #12
0
def skyrocketing():
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print('\033[0;34;40m\t' + nowtime + ': \033[0m')

    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)

    # get_ticker 获取全部ticker信息
    # type(bb_get_ticker): list
    bb_get_ticker = spotAPI.get_ticker()
    # type(ticker) : dict
    instrument_id_list1 = [
        'BTC-USDT', 'LTC-USDT', 'ETH-USDT', 'EOS-USDT', 'XRP-USDT', 'ETC-USDT',
        'BCH-USDT'
    ]
    instrument_id_list2 = ('BTC-USDT', 'LTC-USDT', 'ETH-USDT', 'EOS-USDT',
                           'XRP-USDT', 'ETC-USDT', 'BCH-USDT')
    ticker_dict = dict.fromkeys(instrument_id_list2)
    for bb_ticker in bb_get_ticker:
        if bb_ticker['instrument_id'] in ticker_dict:
            ticker_dict[bb_ticker['instrument_id']] = bb_ticker['last']

    # best_ask 卖一价  last 最新成交价

    # 将前一分钟的数据取出数据库
    history_list_sql = "select top 1 token_price from tab_minutes_price order by create_time desc"
    history_list_ms = ms.ExecQueryOne(history_list_sql)
    history_list_dict = eval(history_list_ms[0])
    print(history_list_dict)

    # 将这一分钟的数据存进数据库
    print(ticker_dict)
    string1 = str(ticker_dict).replace('\'', '\'\'').replace('{',
                                                             '\'{').replace(
                                                                 '}', '}\'')
    send_mail_sql1 = "insert into tab_minutes_price (token_price) values(%s)" % (
        string1)
    ms.ExecNonQuery(send_mail_sql1)

    for item in instrument_id_list1:
        price_change = (float(ticker_dict[item]) - float(
            history_list_dict[item])) / float(ticker_dict[item])
        if (price_change > 0.005 or price_change < -0.005):
            print(price_change)
            # 将这一分钟的数据暴涨暴跌存进数据库
            send_mail_sql2 = "insert into tab_price_change (before_price,now_price,change) values(%s,%s,%s)" % (
                str(history_list_dict[item]), str(
                    ticker_dict[item]), str(price_change))
            ms.ExecNonQuery(send_mail_sql2)
예제 #13
0
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)
예제 #14
0
def connect_context(context, ws_flag=True, restapi_flag=True):
    """
    set up context object
    :param context: context is the object to hold all trade stats across functions
    :return: context
    """
    logger.info('Connect to websocket and restapi')
    if restapi_flag:
        context.futureAPI = future.FutureAPI(context.api_key,
                                             context.secret_key,
                                             context.passphrase, True)
        context.spotAPI = spot.SpotAPI(context.api_key, context.secret_key,
                                       context.passphrase, True)
    if ws_flag:
        context.ws = websocket.WSSubscription(context.instrument_id,
                                              context.instrument_type)
        context.ws_spot = websocket.WSSubscription(context.spot_inst_id,
                                                   context.spot_inst_type)
        time.sleep(3)
    return context
예제 #15
0
    def open_api(self):
        SQLog.info("open_api,quote already open=", self.is_open())
        self.spot_api = spot.SpotAPI(self.ApiKey, self.SeceretKey,
                                     self.PassPhrase, True)

        for stockcode in self.get_stockcode_pools():
            cc_coin = stockcode.split('.')
            instrument_id = cc_coin[1].upper() + '-USDT'
            result = self.spot_api.get_orders_pending(
                froms='', to='', limit='100', instrument_id=instrument_id)
            for op in result[0]:
                self.order_handler(
                    'CC.' + cc_coin[1].upper() + '.' + op.get('order_id'),
                    'CC.' + cc_coin[1].upper(), False,
                    'buy' == op.get('side').lower(),
                    float(op.get('price_avg'))
                    if op.get('price_avg') else None,
                    float(op.get('filled_size')), float(op.get('size')),
                    float(op.get('price')))
        return True
예제 #16
0
파일: 18.py 프로젝트: alexfordc/Tkinter
def animate(i): # i for interval
    subjectName = 'EOS-USDT'
    granularity = 60
    s_Time = '2018-11-18T00:00:00.081Z'
    e_Time = '2018-11-19T18:00:00.081Z'

    api_key = 'd921914b-0693-4ed1-b27e-1f5679e612f5'
    seceret_key = 'CD7F96CD31ADB4CB5B3D8200EA20745A'
    passphrase = '111111'

    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
    data = spotAPI.get_deal(subjectName, froms=1, to=60, limit=100)
    data = pd.DataFrame(data)
    

    buys = data.loc[data['side']=='buy', 'time'] 
    data.loc[data['side']=='buy', 'time'] = pd.to_datetime(buys.values,  utc=True).tz_convert('Asia/Shanghai')
    buyDates = data.loc[data['side']=='buy', 'time'].tolist()


    sells = data.loc[data['side']=='sell', 'time'] 
    data.loc[data['side']=='sell', 'time'] = pd.to_datetime(sells.values,  utc=True).tz_convert('Asia/Shanghai')
    sellDates = data.loc[data['side']=='sell', 'time'].tolist()


    buyPrice = data.loc[data['side']=='buy', 'price'].tolist()  
    sellPrice = data.loc[data['side']=='sell', 'price'].tolist()



    a.clear()

    a.plot_date(buyDates, buyPrice, '#00A3E0', label='buys')
    a.plot_date(sellDates, sellPrice, '#183A54', label='sells')

    title = "OKex "+subjectName+" Prices: "+str(data['price'][0])
    a.set_title(title)
    a.yaxis.set_major_locator(mticker.MaxNLocator(nbins=8, prune='lower'))
    
    a.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc=3, ncol=2, borderaxespad=0)
예제 #17
0
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)
예제 #18
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)
예제 #19
0
    # 查询所有币种的提币记录 (6次/s)
    # result = accountAPI.get_coins_withdraw_record()
    # 查询单个币种提币记录 (6次/s)
    # result = accountAPI.get_coin_withdraw_record('')
    # 获取所有币种充值记录 (6次/s)
    # result = accountAPI.get_top_up_records()
    # 获取单个币种充值记录 (6次/s)
    # result = accountAPI.get_top_up_record('')
    # 获取币种列表 (6次/s)
    # result = accountAPI.get_currencies()
    # 提币手续费 (6次/s)
    # result = accountAPI.get_coin_fee('')

    # spot api test
    # 币币API
    spotAPI = spot.SpotAPI(api_key, secret_key, passphrase, False)
    # 币币账户信息 (20次/2s)
    # result = spotAPI.get_account_info()
    # 单一币种账户信息 (20次/2s)
    # result = spotAPI.get_coin_account_info('')
    # 账单流水查询 (10次/2s)
    # result = spotAPI.get_ledger_record('')
    # 下单 (100次/2s)
    # result = spotAPI.take_order('', '', client_oid='', type='', price='', order_type='0', notional='', size='')

    # take orders
    # 批量下单 (50次/2s)
    # result = spotAPI.take_orders([
    #   {"instrument_id": "", "side": "", "type": "", "price": "", "size": ""},
    #   {"instrument_id": "", "side": "", "type": "", "price": "", "size": ""}
    # ])
예제 #20
0
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)
예제 #21
0
def animate(i): # i for interval
    global refreshRate
    global DatCounter

    if chartLoad:
        if paneCount == 1:
            if DataPace == "tick":
                try:
                    a = plt.subplot2grid((6,4), (0,0), rowspan=5, colspan=4)
                    a2 = plt.subplot2grid((6,4), (5,0), rowspan=1, colspan=4, sharex=a)


                    subjectName = 'EOS-USDT'
                    granularity = 60
                    s_Time = '2018-11-18T00:00:00.081Z'
                    e_Time = '2018-11-19T18:00:00.081Z'

                    api_key = 'd921914b-0693-4ed1-b27e-1f5679e612f5'
                    seceret_key = 'CD7F96CD31ADB4CB5B3D8200EA20745A'
                    passphrase = '111111'

                    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
                    data = spotAPI.get_deal(subjectName, froms=1, to=60, limit=100)
                    data = pd.DataFrame(data)


                    

                    buys = data.loc[data['side']=='buy', 'time'] 
                    data.loc[data['side']=='buy', 'time'] = pd.to_datetime(buys.values,  utc=True).tz_convert('Asia/Shanghai')
                    buyDates = data.loc[data['side']=='buy', 'time'].tolist()


                    sells = data.loc[data['side']=='sell', 'time'] 
                    data.loc[data['side']=='sell', 'time'] = pd.to_datetime(sells.values,  utc=True).tz_convert('Asia/Shanghai')
                    sellDates = data.loc[data['side']=='sell', 'time'].tolist()


                    buyPrice = data.loc[data['side']=='buy', 'price'].tolist()  
                    sellPrice = data.loc[data['side']=='sell', 'price'].tolist()

                    allDates = data['time'].tolist()

                    volume = data['size']



                    a.clear()

                    a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                    a.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                    a.yaxis.set_major_locator(mticker.MaxNLocator(8))
                    # a.yaxis.set_major_locator(mticker.MaxNLocator(3))





                    a.plot_date(buyDates, buyPrice, '#00A3E0', label='buys')
                    a.plot_date(sellDates, sellPrice, '#183A54', label='sells')





                    a2.fill_between(allDates, 0, volume, facecolor='#183A54')
                    a2.yaxis.set_major_locator(mticker.MaxNLocator(5))
                    




                    title = "OKex "+subjectName+" Prices: "+str(data['price'][0])
                    a.set_title(title)
                    
                    
                    a.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc=3, ncol=2, borderaxespad=0)
                except Exception as e:
                    print("Exception: "+str(e))
예제 #22
0
 def __init__(self, apikey, secretkey, password):
     self.last_pending_order_time = None
     self.last_pending_orders = None
     self.spot_api = spot_api.SpotAPI(apikey, secretkey, password, True)
예제 #23
0
def animate(i):  # i for interval
    global refreshRate
    global DatCounter
    global spotAPI
    global periods

    def rsiIndicator(priceData, location="top"):
        if location == "top":
            values = {
                'key': 1,
                "prices": priceData,
                "periods": topIndicator[1]
            }
        if location == "bottom":
            values = {
                'key': 1,
                "prices": priceData,
                "periods": bottomIndicator[1]
            }

    if chartLoad:
        if paneCount == 1:

            if DataPace == "tick":
                try:
                    if exchange == "BTC-e":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        subjectName = 'EOS-USDT'
                        granularity = 60
                        s_Time = '2018-11-18T00:00:00.081Z'
                        e_Time = '2018-11-19T18:00:00.081Z'

                        api_key = 'd921914b-0693-4ed1-b27e-1f5679e612f5'
                        seceret_key = 'CD7F96CD31ADB4CB5B3D8200EA20745A'
                        passphrase = '111111'

                        spotAPI = spot.SpotAPI(api_key, seceret_key,
                                               passphrase, True)
                        data = spotAPI.get_deal(subjectName,
                                                froms=1,
                                                to=60,
                                                limit=100)
                        data = pd.DataFrame(data)

                        buys = data.loc[data['side'] == 'buy', 'time']
                        data.loc[data['side'] == 'buy',
                                 'time'] = pd.to_datetime(
                                     buys.values,
                                     utc=True).tz_convert('Asia/Shanghai')
                        buyDates = data.loc[data['side'] == 'buy',
                                            'time'].tolist()

                        sells = data.loc[data['side'] == 'sell', 'time']
                        data.loc[data['side'] == 'sell',
                                 'time'] = pd.to_datetime(
                                     sells.values,
                                     utc=True).tz_convert('Asia/Shanghai')
                        sellDates = data.loc[data['side'] == 'sell',
                                             'time'].tolist()

                        buyPrice = data.loc[data['side'] == 'buy',
                                            'price'].tolist()
                        sellPrice = data.loc[data['side'] == 'sell',
                                             'price'].tolist()

                        allDates = data['time'].tolist()

                        volume = data['size']

                        a.clear()

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False)

                        a.yaxis.set_major_locator(mticker.MaxNLocator(8))

                        # a.yaxis.set_major_locator(mticker.MaxNLocator(3))

                        a.plot_date(buyDates,
                                    buyPrice,
                                    lightColor,
                                    label='buys')
                        a.plot_date(sellDates,
                                    sellPrice,
                                    darkColor,
                                    label='sells')

                        a2.fill_between(allDates,
                                        0,
                                        volume,
                                        facecolor=darkColor)
                        a2.yaxis.set_major_locator(mticker.MaxNLocator(5))

                        title = "OKex " + subjectName + " Prices: " + str(
                            data['price'][0])
                        a.set_title(title)

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                    if exchange == "Bitstamp":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = "https://www.bitstamp.net/api/transactions/"
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        data = pd.DataFrame(data)

                        data['date'] = pd.to_datetime(data['date'], unit='s')
                        dateStamp = data['date'].tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False)

                        # a.yaxis.set_major_locator(mticker.MaxNLocator(8))

                        a.plot_date(dateStamp,
                                    data["price"],
                                    lightColor,
                                    label='buys')

                        a2.fill_between(dateStamp,
                                        0,
                                        volume,
                                        facecolor=darkColor)
                        a2.yaxis.set_major_locator(mticker.MaxNLocator(5))

                        title = "BTCUSD BTC-USD Prices:\nLastprice: " + str(
                            data['price'][0])
                        a.set_title(title)

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                    if exchange == "Bitfinex":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = "https://api.bitfinex.com/v1/trades/btcusd?limit=2000"
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        data = pd.DataFrame(data)

                        data["timestamp"] = pd.to_datetime(data["timestamp"],
                                                           unit='s')
                        dateStamp = data["timestamp"].tolist()

                        buys = data[(data["type"] == "buy")]
                        buyDates = (buys["timestamp"]).tolist()

                        sells = data[(data["type"] == "sell")]
                        sellDates = (sells["timestamp"]).tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        a.yaxis.set_major_locator(mticker.MaxNLocator(8))

                        plt.setp(a.get_xticklabels(), visible=False)

                        a.plot_date(buyDates,
                                    buys["price"],
                                    lightColor,
                                    label='buy')
                        a.plot_date(sellDates,
                                    sells["price"],
                                    darkColor,
                                    label='sell')

                        a2.fill_between(dateStamp,
                                        0,
                                        volume,
                                        facecolor=darkColor)
                        a2.yaxis.set_major_locator(mticker.MaxNLocator(5))

                        title = "Bitfinex BTC-USD Prices:\nLastprice: " + str(
                            data['price'][0])
                        a.set_title(title)

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                except Exception as e:
                    print("Exception: " + str(e))

            else:
                if DatCounter > 12:
                    try:
                        if exchange == "Huobi":
                            if topIndicator != "none":
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=5,
                                                     colspan=4)
                                a2 = plt.subplot2grid((6, 4), (0, 0),
                                                      shareex=a,
                                                      rowspan=5,
                                                      colspan=4)
                            else:
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=6,
                                                     colspan=4)
                        else:
                            if topIndicator != "none" and bottomIndicator != "none":
                                # main graph
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # bottom indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # top indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif topIndicator != "none":
                                # main graph
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                # top indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif bottomIndicator != "none":
                                # main graph
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                # bottom indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            else:
                                # main graph
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                        ohlcData = spotAPI.get_kline('EOS-USDT',
                                                     granularity=86400)
                        for oneDict in ohlcData:
                            t = oneDict['time']
                            parsed_t = dp.parse(t)
                            time = parsed_t.strftime("%Y-%m-%d-%H-%M-%S")
                            oneDict['time'] = time

                        OHLC = pd.DataFrame(ohlcData,
                                            columns=[
                                                'time', 'open', 'high', 'low',
                                                'close', 'volume'
                                            ])
                        OHLC['time'] = pd.to_datetime(OHLC['time'])
                        OHLC.loc[:,
                                 ['open', 'high', 'low', 'close', 'volume'
                                  ]] = OHLC.loc[:, [
                                      'open', 'high', 'low', 'close', 'volume'
                                  ]].astype(float)

                        OHLC['MPLDates'] = mdates.date2num(OHLC['time'])
                        volumeData = OHLC['volume'].tolist()
                        OHLC.set_index('time', inplace=True)
                        priceData = OHLC["close"].tolist()

                        a.clear()

                        if middleIndicator != "none":
                            for eachMA in middleIndicator:
                                #ewma = pd.stats.moments.ewma
                                if eachMA[0] == 'sma':
                                    sma = OHLC['close'].rolling(10).mean()
                                    label = str(eachMA[1]) + "SMA"
                                    a.plot(OHLC["MPLDates"], sma, label=label)

                                if eachMA[0] == 'ema':
                                    ewma = pd.stats.moments.ewma
                                    label = str(eachMA[1]) + "EMA"
                                    a.plot(OHLC["MPLDates"],
                                           ewma(OHLC["close"], eachMA[1]),
                                           label=label)

                            a.legend(loc=0)

                        if topIndicator[0] == "rsi":
                            rsiIndicator(priceData, "top")

                        elif topIndicator == "macd":
                            try:
                                computeMACD(priceData, location="top")
                            except Exception as e:
                                print(str(e))

                        if bottomIndicator[0] == "rsi":
                            rsiIndicator(priceData, "bottom")

                        elif bottomIndicator == "macd":
                            try:
                                computeMACD(priceData, location="bottom")
                            except Exception as e:
                                print(str(e))

                        csticks = candlestick_ohlc(
                            a,
                            OHLC[["MPLDates", "open", "high", "low",
                                  "close"]].values,
                            width=candleWidth,
                            colorup=lightColor,
                            colordown=darkColor)
                        a.set_ylabel("Price")
                        if exchange != "Huobi":
                            a2.fill_between(OHLC["MPLDates"],
                                            0,
                                            OHLC['volume'],
                                            facecolor=darkColor)
                            a2.set_ylabel("Volume")

                        a.xaxis.set_major_locator(mticker.MaxNLocator(3))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter('%Y-%m-%d %H:%M'))

                        if exchange != "Huobi":
                            plt.setp(a.get_xticklabels(), visible=False)

                        if topIndicator != "none":
                            plt.setp(a0.get_xticklabels(), visible=False)

                        if bottomIndicator != "none":
                            plt.setp(a2.get_xticklabels(), visible=False)

                        x = (len(OHLC["close"])) - 1

                        if DataPace == "1d":
                            title = exchange + " 1 Day Data with" + resampleSize + " Bars\nLast Price: " + str(
                                OHLC["close"][0])
                        if DataPace == "3d":
                            title = exchange + " 3 Day Data with" + resampleSize + " Bars\nLast Price: " + str(
                                OHLC["close"][0])
                        if DataPace == "7d":
                            title = exchange + " 7 Day Data with" + resampleSize + " Bars\nLast Price: " + str(
                                OHLC["close"][0])

                        if topIndicator != "none":
                            a0.set_title(title)

                        else:
                            a.set_title(title)
                        print("New Graph")
                        DatCounter = 0

                    except Exception as e:
                        print("failed in the non-tick animate: ", str(e))
                        DatCounter = 9000
                else:
                    DatCounter += 1
예제 #24
0
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)
예제 #25
0
    # result = accountAPI.get_currencies()
    # result = accountAPI.get_wallet()
    # result = accountAPI.get_currency('btc')
    # result = accountAPI.get_currency('btc')
    # result = accountAPI.get_coin_fee('btc')
    # result = accountAPI.get_coin_fee('btc')
    # result = accountAPI.get_coins_withdraw_record()
    # result = accountAPI.get_coin_withdraw_record('BTC')
    # result = accountAPI.get_ledger_record()
    # result = accountAPI.get_top_up_address('BTC')
    # result = accountAPI.get_top_up_address('BTC')
    # result = accountAPI.get_top_up_records()
    # result = accountAPI.get_top_up_record('BTC')

    # spot api test 币币交易
    spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True)
    # result = spotAPI.get_account_info()
    # result = spotAPI.get_coin_account_info('BTC')
    # result = spotAPI.get_ledger_record('BTC', limit=1)
    # result = spotAPI.take_order('limit', 'sell', 'BTC-USDT', 2, price='3')

    # take orders
    # params = [
    #   {"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"market"," size ":"0.001"," notional ":"10001","margin_trading ":"1"},
    #   {"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit"," size ":"0.001","notional":"10002","margin_trading ":"1"}
    # ]
    # result = spotAPI.take_orders(params)

    # result = spotAPI.revoke_order(2229535858593792, 'BTC-USDT')
    # revoke orders
    # params = [{'instrument_id': 'btc-usdt', 'orders_ids':[2233702496112640, 2233702479204352]}]
예제 #26
0
def animate(i):  # i for interval
    global refreshRate
    global DatCounter

    if chartLoad:
        if paneCount == 1:

            if DataPace == "tick":
                try:
                    if exchange == "BTC-e":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        subjectName = 'EOS-USDT'
                        granularity = 60
                        s_Time = '2018-11-18T00:00:00.081Z'
                        e_Time = '2018-11-19T18:00:00.081Z'

                        api_key = 'd921914b-0693-4ed1-b27e-1f5679e612f5'
                        seceret_key = 'CD7F96CD31ADB4CB5B3D8200EA20745A'
                        passphrase = '111111'

                        spotAPI = spot.SpotAPI(api_key, seceret_key,
                                               passphrase, True)
                        data = spotAPI.get_deal(subjectName,
                                                froms=1,
                                                to=60,
                                                limit=100)
                        data = pd.DataFrame(data)

                        buys = data.loc[data['side'] == 'buy', 'time']
                        data.loc[data['side'] == 'buy',
                                 'time'] = pd.to_datetime(
                                     buys.values,
                                     utc=True).tz_convert('Asia/Shanghai')
                        buyDates = data.loc[data['side'] == 'buy',
                                            'time'].tolist()

                        sells = data.loc[data['side'] == 'sell', 'time']
                        data.loc[data['side'] == 'sell',
                                 'time'] = pd.to_datetime(
                                     sells.values,
                                     utc=True).tz_convert('Asia/Shanghai')
                        sellDates = data.loc[data['side'] == 'sell',
                                             'time'].tolist()

                        buyPrice = data.loc[data['side'] == 'buy',
                                            'price'].tolist()
                        sellPrice = data.loc[data['side'] == 'sell',
                                             'price'].tolist()

                        allDates = data['time'].tolist()

                        volume = data['size']

                        a.clear()

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False)

                        a.yaxis.set_major_locator(mticker.MaxNLocator(8))

                        # a.yaxis.set_major_locator(mticker.MaxNLocator(3))

                        a.plot_date(buyDates,
                                    buyPrice,
                                    lightColor,
                                    label='buys')
                        a.plot_date(sellDates,
                                    sellPrice,
                                    darkColor,
                                    label='sells')

                        a2.fill_between(allDates,
                                        0,
                                        volume,
                                        facecolor=darkColor)
                        a2.yaxis.set_major_locator(mticker.MaxNLocator(5))

                        title = "OKex " + subjectName + " Prices: " + str(
                            data['price'][0])
                        a.set_title(title)

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                    if exchange == "Bitstamp":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = "https://www.bitstamp.net/api/transactions/"
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        data = pd.DataFrame(data)

                        data['date'] = pd.to_datetime(data['date'], unit='s')
                        dateStamp = data['date'].tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False)

                        # a.yaxis.set_major_locator(mticker.MaxNLocator(8))

                        a.plot_date(dateStamp,
                                    data["price"],
                                    lightColor,
                                    label='buys')

                        a2.fill_between(dateStamp,
                                        0,
                                        volume,
                                        facecolor=darkColor)
                        a2.yaxis.set_major_locator(mticker.MaxNLocator(5))

                        title = "BTCUSD BTC-USD Prices:\nLastprice: " + str(
                            data['price'][0])
                        a.set_title(title)

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                    if exchange == "Bitfinex":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = "https://api.bitfinex.com/v1/trades/btcusd?limit=2000"
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        data = pd.DataFrame(data)

                        data["timestamp"] = pd.to_datetime(data["timestamp"],
                                                           unit='s')
                        dateStamp = data["timestamp"].tolist()

                        buys = data[(data["type"] == "buy")]
                        buyDates = (buys["timestamp"]).tolist()

                        sells = data[(data["type"] == "sell")]
                        sellDates = (sells["timestamp"]).tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        a.yaxis.set_major_locator(mticker.MaxNLocator(8))

                        plt.setp(a.get_xticklabels(), visible=False)

                        a.plot_date(buyDates,
                                    buys["price"],
                                    lightColor,
                                    label='buy')
                        a.plot_date(sellDates,
                                    sells["price"],
                                    darkColor,
                                    label='sell')

                        a2.fill_between(dateStamp,
                                        0,
                                        volume,
                                        facecolor=darkColor)
                        a2.yaxis.set_major_locator(mticker.MaxNLocator(5))

                        title = "Bitfinex BTC-USD Prices:\nLastprice: " + str(
                            data['price'][0])
                        a.set_title(title)

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                except Exception as e:
                    print("Exception: " + str(e))

            else:
                if DatCounter > 12:
                    try:
                        if exchange == "Huobi":
                            if topIndicator != "none":
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=5,
                                                     colspan=4)
                                a2 = plt.subplot2grid((6, 4), (0, 0),
                                                      shareex=a,
                                                      rowspan=5,
                                                      colspan=4)
                            else:
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=6,
                                                     colspan=4)
                        else:
                            if topIndicator != "none" and bottomIndicator != "none":
                                # main graph
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # bottom indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # top indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif topIndicator != "none":
                                # main graph
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                # top indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif bottomIndicator != "none":
                                # main graph
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                # bottom indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            else:
                                # main graph
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                    except Exception as e:
                        print("failed in the non-tick animate: ", str(e))
예제 #27
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('查询口令错误')