예제 #1
0
    def get_msg(cls, exchange, base_coin, quote_coin, size=5):
        # 组合symbol值
        symbol = ut.get_symbol(exchange, base_coin, quote_coin)
        msg = ''
        if ut.okex_exchange.lower() == exchange.lower():
            i = 1
            while True:
                try:
                    msg = okexcoinSpot.depth(str.lower(symbol), size)
                    keys = list(msg.keys())
                    if cls.get_bids_field_name() in keys and \
                            cls.get_asks_field_name() in keys:
                        return msg
                    else:
                        i = i + 1
                        time.sleep(1)
                except Exception as e:
                    Logger.error(cls.__class__.__name__,
                                 "Error in get_msg: %s" % e)
                    i = i + 1
                    time.sleep(1)
                if i > ut.RE_TRY_TIMES:
                    return None
        else:
            Logger.error(cls.__class__.__name__, 'no support exchange')

        return msg
예제 #2
0
    def insert(self, table, columns, types, values, primary_key_index=[], is_orreplace=False, is_commit=True):
        """
        Insert into the table
        :param table: Table name
        :param columns: Column array
        :param types: Type array
        :param values: Value array
        :param primary_key_index: An array of indices of primary keys in columns,
                          e.g. [0] means the first column is the primary key
        :param is_orreplace: Indicate if the query is "INSERT OR REPLACE"
        """
        if len(columns) != len(values):
            return False

        column_names = ','.join(columns)
        value_string = ','.join([SqlClient.convert_str(e) for e in values])
        if is_orreplace:
            sql = "%s %s (%s) values (%s)" % (self.replace_keyword(), table, column_names, value_string)
        else:
            sql = "insert into %s (%s) values (%s)" % (table, column_names, value_string)

        self.lock.acquire()
        try:
            self.execute(sql)
            if is_commit:
                self.commit()
        except Exception as e:
            Logger.info(self.__class__.__name__, "SQL error: %s\nSQL: %s" % (e, sql))
        self.lock.release()
        return True
예제 #3
0
 def connect(self, **kwargs):
     """
     Connect
     :param path: sqlite file to connect
     """
     addr = kwargs['addr']
     Logger.info(self.__class__.__name__,
                 'Zmq client is connecting to %s' % addr)
     self.conn.bind(addr)
     return self.conn is not None
예제 #4
0
    def do_liquidate_future_trade(self, position):
        return_msg = ut.OKEX_NO
        try:
            res = okcoinFuture.future_trade(
                position.symbol, position.contract_type, '',
                position.get_amount(), position.get_liquidate_trade_type(),
                '1', position.lever_rate)
            result = res["result"]
            #print('do_liquidate_future_trade result:%s' % result)

            if result == True:
                return_msg = ut.OKEX_YES
        except Exception as e:
            Logger.error('FutureTradeService',
                         "do_liquidate_future_trade: %s" % e)

        return return_msg
예제 #5
0
    def create(self, table, columns, types, is_ifnotexists=True):
        """
        Create table in the database
        :param table: Table name
        :param columns: Column array
        :param types: Type array
        :param is_ifnotexists: Create table if not exists keyword
        """
        file_path = os.path.join(self.file_directory, table + ".csv")
        columns = [e.split(' ')[0] for e in columns]
        if len(columns) != len(types):
            return False

        self.lock.acquire()
        if os.path.isfile(file_path):
            Logger.info(self.__class__.__name__,
                        "File (%s) has been created already." % file_path)
        else:
            with open(file_path, 'w+') as csvfile:
                csvfile.write(','.join(["\"" + e + "\""
                                        for e in columns]) + '\n')

        self.lock.release()
        return True
예제 #6
0
                greedmark.liquidation_complete = trade_service.do_liquidate_future_trade(
                    position)
                greedmark.liquidation_complete_time = datetime.now().strftime(
                    "%Y%m%d %H:%M:%S")
                if greedmark.liquidation_complete == ut.OKEX_YES:
                    #将position插入到数据库表中记录起来
                    trade_service.record_liquidate_4fix_position(position)

            # add and update greedmark
            self.greed_marks.insert_greedmark_to_database(greedmark)
            greedmark.print_detail(i)
            i = i + 1

        return ''

    #对满足强平标志的进行强平
    def do_liuqdation(self):

        return


if __name__ == "__main__":

    greed_strategy_service = GreedStrategyOkexFutureService()
    while True:
        try:
            greed_strategy_service.do_liquidation_mark()
        except Exception as e:
            Logger.error('greed_strategy_service',
                         "do_liquidation_mark: %s" % e)
        time.sleep(10)
예제 #7
0
               isFetchAll=True):
        """
        Select rows from the table
        :param table: Table name
        :param columns: Selected columns
        :param condition: Where condition
        :param orderby: Order by condition
        :param limit: Rows limit
        :param isFetchAll: Indicator of fetching all
        :return Result rows
        """
        return []

    def delete(self, table, condition='1==1'):
        """
        Delete rows from the table
        :param table: Table name
        :param condition: Where condition
        """
        return True


if __name__ == '__main__':
    Logger.init_log()
    db_client = ZmqClient()
    db_client.connect(addr='ipc://test')
    for i in range(1, 100):
        db_client.insert('test', ['c1', 'c2', 'c3', 'c4'], [],
                         ['abc', i, 1.1, 5])
        time.sleep(1)
예제 #8
0
 def execute(self, sql):
     """
     Execute the sql command
     :param sql: SQL command
     """
     Logger.info(self.__class__.__name__, "Execute command = %s" % sql)
    def get_positions_okex(self, symbol, contractType, type1):
        '''
        # Request
        POST https://www.okex.com/api/v1/future_position_4fix.do
        # Response
        {'result': True, 'holding': [
            {'buy_price_avg': 0, 'symbol': 'eth_usd', 'lever_rate': 10, 'buy_available': 0, 'contract_id': 201809210020060,
             'sell_risk_rate': '104.79', 'buy_amount': 0, 'buy_risk_rate': '1,000,000.00', 'profit_real': 0.00786862,
             'contract_type': 'next_week', 'sell_flatprice': '186.566', 'buy_bond': 0, 'sell_profit_lossratio': '4.79',
             'buy_flatprice': '0.000', 'buy_profit_lossratio': '0.00', 'sell_amount': 16, 'sell_bond': 0.09424238,
             'sell_price_cost': 169.775, 'buy_price_cost': 0, 'create_date': 1536571738000, 'sell_price_avg': 169.775,
             'sell_available': 16}]}
        '''

        try:
            res = okcoinFuture.future_position_4fix(symbol, contractType, type1)
            #print(res)
            result = res["result"]

            if not result:
                return None
        except Exception as e:
            Logger.error('FuturePositionFixService', "get_positions_okex: %s" % e)

        msg_holdings = res["holding"]


        positions = fut_position.Positions()

        for i in range(len(msg_holdings)):
            msg_holding = msg_holdings[i]

            position = fut_position.Position()
            position.buy_amount = float(msg_holding["buy_amount"])                                  # 多仓数量
            #有则添加,持仓中,有可能多空有其一,或者两者都有,则各分别添加,多空都有的情况下变为两条position加入
            if position.buy_amount > 0:
                position.exchange = ut.okex_exchange                                                    # 此账号所属交易所,如果是所有交易所总和统计,以ALL表示
                position.time = datetime.now().strftime("%Y%m%d %H:%M:%S")                           # 统计时点时间
                position.symbol = msg_holding['symbol']                                                 # btc_usd ltc_usd eth_usd etc_usd bch_usd
                position.lever_rate = msg_holding['lever_rate']                                         # 杠杆倍数
                position.contract_id = msg_holding['contract_id']                                       # 合约id
                position.contract_type = msg_holding['contract_type']                                   # 合约类型
                create_date = float(msg_holding["create_date"]) / 1000
                position.create_date = datetime.fromtimestamp(create_date).strftime("%Y%m%d %H:%M:%S")  # 创建日期
                position.profit_real = float(msg_holding["profit_real"])                                # 已实现盈余

                position.buy_profit_lossratio = float(msg_holding["buy_profit_lossratio"])              # 多仓盈亏比
                position.buy_available = float(msg_holding["buy_available"])                            # 多仓可平仓数量
                position.buy_bond = float(msg_holding["buy_bond"])                                      # 多仓保证金
                position.buy_price_avg = float(msg_holding["buy_price_avg"])                            # 多仓开仓平均价
                position.buy_flatprice = float(msg_holding["buy_flatprice"])                            # 多仓强平价格
                position.buy_price_cost = float(msg_holding["buy_price_cost"])                          # 多仓结算基准价
                position.buy_risk_rate = msg_holding["buy_risk_rate"]                           #

                positions.add_position(position)

            position_sell = fut_position.Position()
            position_sell.sell_amount = float(msg_holding["sell_amount"])                                # 空仓数量
            #有则添加,持仓中,有可能多空有其一,或者两者都有,则各分别添加,多空都有的情况下变为两条position加入
            if position_sell.sell_amount > 0:
                position_sell.exchange = ut.okex_exchange                                                    # 此账号所属交易所,如果是所有交易所总和统计,以ALL表示
                position_sell.time = datetime.now().strftime("%Y%m%d %H:%M:%S")                           # 统计时点时间
                position_sell.symbol = msg_holding['symbol']                                                 # btc_usd ltc_usd eth_usd etc_usd bch_usd
                position_sell.lever_rate = msg_holding['lever_rate']                                         # 杠杆倍数
                position_sell.contract_id = msg_holding['contract_id']                                       # 合约id
                position_sell.contract_type = msg_holding['contract_type']                                   # 合约类型
                create_date = float(msg_holding["create_date"]) / 1000
                position_sell.create_date = datetime.fromtimestamp(create_date).strftime("%Y%m%d %H:%M:%S")  # 创建日期
                position_sell.profit_real = float(msg_holding["profit_real"])                                # 已实现盈余

                position_sell.sell_profit_lossratio = float(msg_holding["sell_profit_lossratio"])            # 空仓盈亏比
                position_sell.sell_available = float(msg_holding["sell_available"])                          # 空仓可平仓数量
                position_sell.sell_bond = float(msg_holding["sell_bond"])                                    # 空仓保证金
                position_sell.sell_price_avg = float(msg_holding["sell_price_avg"])                          # 空仓开仓平均价
                position_sell.sell_flatprice = float(msg_holding["sell_flatprice"])                          # 空仓强平价格
                position_sell.sell_price_cost = float(msg_holding["sell_price_cost"])                        # 空仓结算基准价
                position_sell.sell_risk_rate = msg_holding["sell_risk_rate"]                          #

                positions.add_position(position_sell)

        return positions