예제 #1
0
            order_info = "%s, %s, price=%s, Volume=%s" % (
                order_type, order_state, price, amount)
        else:
            order_info = "%s, %s" % (order_type, order_state)

        print(order_info)

        current = sys.stdout
        a = __Autonomy__()
        sys.stdout = a
        print(b._buff)
        print("\n===== check SUBMITTED order =====\n")
        get_orders(['eth3lusdt', 'dogeusdt', 'ethusdt'])
        sys.stdout = current

        if order_type == "sell" and order_state != "submitted" and order_state != "canceled":
            send_email("HB: " + order_info, a._buff)

        elif order_type == "buy" and order_state != "submitted" and order_state != "canceled":
            send_email("HB: " + order_info, a._buff)

        print()
    except:
        print("ExecuteError")


trade_client = TradeClient(api_key=g_api_key,
                           secret_key=g_secret_key,
                           init_log=True)
trade_client.sub_order_update("eth3lusdt,dogeusdt,ethusdt", callback)
예제 #2
0
def batch_cancel_orders(symbol, order_id_list):
    trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
    print("cancel order list:", order_id_list)
    if len(order_id_list):
        result = trade_client.cancel_orders(symbol, order_id_list)
        result.print_object()
예제 #3
0
class User:
    def __init__(self, access_key, secret_key, buy_amount, wxuid):
        self.access_key = access_key
        self.sercet_key = secret_key
        self.account_client = AccountClient(api_key=access_key, secret_key=secret_key)
        self.trade_client = TradeClient(api_key=access_key, secret_key=secret_key)
        self.account_id = next(filter(
            lambda account: account.type=='spot' and account.state =='working',
            self.account_client.get_accounts()
        )).id

        self.usdt_balance = self.get_currency_balance(['usdt'])['usdt']

        if buy_amount.startswith('/'):
            self.buy_amount =  max(math.floor(self.usdt_balance / float(buy_amount[1:])), 5)
        else:
            self.buy_amount = float(buy_amount)

        self.wxuid = wxuid.split(';')

        self.balance = {}
        self.buy_order_list = []
        self.sell_order_list = []
        self.buy_id = []
        self.sell_id = []
        self.username = wx_name(self.wxuid[0])
        self.high = True

    def buy(self, targets, amounts):
        buy_order_list = [{
            "symbol": target.symbol,
            "account_id": self.account_id,
            "order_type": OrderType.BUY_MARKET,
            "source": OrderSource.SPOT_API,
            "price": 1,
            "amount": target.check_amount(max(
                amount,
                target.min_order_value
            ))}
            for target, amount in zip(targets, amounts)
            if amount > 0
        ]
        if buy_order_list:
            self.buy_id.extend(self.trade_client.batch_create_order(buy_order_list))
            self.buy_order_list.extend(buy_order_list)
            # logger.debug(f'User {self.account_id} buy report')
            for order in buy_order_list:
                logger.debug(f'Speed {order["amount"]} USDT to buy {order["symbol"][:-4].upper()}')

    def buy_limit(self, targets, amounts, prices=None):
        if not prices:
            rate = MAX_BUY_RATE
            rate2 = 9
            buy_order_list = [{
                "symbol": target.symbol,
                "account_id": self.account_id,
                "order_type": OrderType.BUY_LIMIT,
                "source": OrderSource.SPOT_API,
                "price": target.check_price(min(
                    (1 + rate / 100) * target.init_price,
                    (1 + rate2 / 100) * target.price
                )),
                "amount": target.check_amount(max(
                    amount / min(
                        (1 + rate / 100) * target.init_price,
                        (1 + rate2 / 100) * target.price
                    ),
                    target.limit_order_min_order_amt
                ))}
                for target, amount in zip(targets, amounts)
                if amount > 0
            ]
        else:
            buy_order_list = [{
                "symbol": target.symbol,
                "account_id": self.account_id,
                "order_type": OrderType.BUY_LIMIT,
                "source": OrderSource.SPOT_API,
                "price": target.check_price(price),
                "amount": target.check_amount(max(
                    amount / price,
                    target.limit_order_min_order_amt
                ))}
                for target, amount, price in zip(targets, amounts, prices)
                if amount > 0
            ]

        if buy_order_list:
            self.buy_id.extend(self.trade_client.batch_create_order(buy_order_list))
            self.buy_order_list.extend(buy_order_list)
            # logger.debug(f'User {self.account_id} buy report')
            for order in buy_order_list:
                logger.debug(f'Speed {order["amount"]} USDT to buy {order["symbol"][:-4].upper()}')

    def sell(self, targets, amounts):
        sell_order_list = [{
            "symbol": target.symbol,
            "account_id": self.account_id,
            "order_type": OrderType.SELL_MARKET,
            "source": OrderSource.SPOT_API,
            "price": 1,
            "amount": target.check_amount(amount)}
            for target, amount in zip(targets, amounts)
        ]
        sell_order_list = [
            order for order, target in zip(sell_order_list, targets)
            if order['amount'] >= target.sell_market_min_order_amt
        ]
        
        if sell_order_list:
            self.sell_id.extend(self.trade_client.batch_create_order(sell_order_list))
            self.sell_order_list.extend(sell_order_list)
            # logger.debug(f'User {self.account_id} sell report')
            for order in sell_order_list:
                logger.debug(f'Sell {order["amount"]} {order["symbol"][:-4].upper()} with market price')


    def sell_limit(self, targets, amounts, prices=None):
        if not prices:
            rate = SELL_RATE if self.high else SECOND_SELL_RATE
            sell_order_list = [{
                "symbol": target.symbol,
                "account_id": self.account_id,
                "order_type": OrderType.SELL_LIMIT,
                "source": OrderSource.SPOT_API,
                "price": target.check_price((1 + rate / 100) * target.buy_price),
                "amount": target.check_amount(amount)}
                for target, amount in zip(targets, amounts)
            ]
        else:
            sell_order_list = [{
                "symbol": target.symbol,
                "account_id": self.account_id,
                "order_type": OrderType.SELL_LIMIT,
                "source": OrderSource.SPOT_API,
                "price": target.check_price(price),
                "amount": target.check_amount(amount)}
                for target, amount, price in zip(targets, amounts, prices)
            ]

        sell_order_list = [
            order for order, target in zip(sell_order_list, targets)
            if order['amount'] >= target.limit_order_min_order_amt
        ]

        if sell_order_list:
            self.sell_id.extend(self.trade_client.batch_create_order(sell_order_list))
            self.sell_order_list.extend(sell_order_list)
            # logger.debug(f'User {self.account_id} sell report')
            for order in sell_order_list:
                logger.debug(f'Sell {order["amount"]} {order["symbol"][:-4].upper()} with price {order["price"]}')

 
    @timeout_handle([])
    def get_open_orders(self, targets, side=OrderSide.SELL) -> 'list[huobi.model.trade.order.Order]':
        open_orders = []
        all_symbols = [target.symbol for target in targets]
        for symbols in [all_symbols[i:i+10] for i in range(0, len(all_symbols), 10)]:
            open_orders.extend(self.trade_client.get_open_orders(','.join(symbols), self.account_id, side))
        return open_orders

    def cancel_and_sell(self, targets):
        open_orders = self.get_open_orders(targets)
        if open_orders:
            all_symbols = [target.symbol for target in targets]
            for symbols in [all_symbols[i:i+10] for i in range(0, len(all_symbols), 10)]:
                self.trade_client.cancel_orders(','.join(symbols), [order.id for order in open_orders if order.symbol in symbols])
            logger.info(f'Cancel open sell orders for {", ".join(all_symbols)}')

        self.get_balance(targets)
        amounts = [self.balance[target.base_currency] for target in targets]
        self.sell(targets, amounts)

        target_currencies = [target.base_currency for target in targets]
        while True:
            frozen_balance = self.get_currency_balance(target_currencies, 'frozen')
            if not any(frozen_balance.values()):
                break
            else:
                time.sleep(0.1)
        
        self.get_balance(targets)
        amounts = [self.balance[target.base_currency] for target in targets]


    def high_cancel_and_sell(self, targets, symbol, price):
        self.high = False
        open_orders = self.get_open_orders(targets)
        if open_orders:
            all_symbols = [target.symbol for target in targets]
            for symbols in [all_symbols[i:i+10] for i in range(0, len(all_symbols), 10)]:
                self.trade_client.cancel_orders(','.join(symbols), [order.id for order in open_orders if order.symbol in symbols])
            logger.info(f'Cancel open sell orders for {", ".join(all_symbols)}')

        self.get_balance(targets)
        symbol_targets = [target for target in targets if target.symbol == symbol]
        symbol_amounts = [self.balance[target.base_currency] for target in symbol_targets]
        other_targets = [target for target in targets if target.symbol != symbol]
        other_amounts = [self.balance[target.base_currency] for target in other_targets]

        prices = [(price + target.buy_price * (1 + SELL_RATE / 100)) / 2 for target in symbol_targets]
        self.sell_limit(symbol_targets, symbol_amounts, prices=prices)
        self.sell_limit(other_targets, other_amounts)

        # target_currencies = [target.base_currency for target in targets]
        # while True:
        #     frozen_balance = self.get_currency_balance(target_currencies, 'frozen')
        #     if not any(frozen_balance.values()):
        #         break
        #     else:
        #         time.sleep(0.1)
        
        # self.get_balance(targets)
        # amounts = [self.balance[target.base_currency] for target in targets]

    def buy_and_sell(self, targets):
        self.buy_limit(targets, [self.buy_amount for _ in targets])
        self.check_balance(targets)
        sell_amounts = [self.balance[target.base_currency] for target in targets]
        self.sell_limit(targets, sell_amounts)

    def get_currency_balance(self, currencies, balance_type='trade'):
        return {
            currency.currency: float(currency.balance)
            for currency in self.account_client.get_balance(self.account_id)
            if currency.currency in currencies and currency.type == balance_type
        }

    def get_balance(self, targets):
        while self.get_open_orders(targets, side=None):
            pass

        target_currencies = [target.base_currency for target in targets]
        self.balance = self.get_currency_balance(target_currencies)

    def check_balance(self, targets):
        self.get_balance(targets)

        # logger.debug(f'User {self.account_id} balance report')
        for target in targets:
            for order_id, order in zip(self.buy_id, self.buy_order_list):
                if order['symbol'] == target.symbol:
                    break

            
            target_balance = self.balance[target.base_currency]
            if target_balance > 10 ** -target.amount_precision:
                order_detail = self.trade_client.get_order(order_id.order_id)
                buy_price = float(order_detail.filled_cash_amount) / float(order_detail.filled_amount)
                target.buy_price = buy_price
                logger.debug(f'Get {target_balance} {target.base_currency.upper()} with average price {buy_price}')
            else:
                target.buy_price = 0
                logger.debug(f'Get no {target.base_currency.upper()}')

    def report(self):
        orders = [
            self.trade_client.get_order(order.order_id)
            for order in self.buy_id + self.sell_id
            if order.order_id
        ]

        order_info = [{
            'symbol': order.symbol,
            'time': strftime(order.finished_at / 1000, fmt='%Y-%m-%d %H:%M:%S.%f'),
            'price': round(float(order.filled_cash_amount) / float(order.filled_amount), 6),
            'amount': round(float(order.filled_amount), 6),
            'fee': round(float(order.filled_fees), 6),
            'currency': order.symbol[:-4].upper(),
            'vol': float(order.filled_cash_amount),
            'direct': order.type.split('-')[0]}
            for order in orders
            if order.state == 'filled'
        ]
        buy_info = list(filter(lambda x: x['direct']=='buy', order_info))
        sell_info = list(filter(lambda x: x['direct']=='sell', order_info))

        pay = round(sum([each['vol'] for each in buy_info]), 4)
        if pay <= 0:
            logger.warning(f'NO REPORT for User {self.account_id}')
            return

        income = round(sum([each['vol'] - each['fee'] for each in sell_info]), 4)
        profit = round(income - pay, 4)
        percent = round(profit / self.usdt_balance * 100, 4)

        logger.info(f'REPORT for user {self.account_id}')
        logger.info('Buy')
        for each in buy_info:
            currency = each['currency']
            symbol_name = '/'.join([currency, 'USDT'])
            vol = each['vol']
            amount = each['amount']
            price = each['price']
            fee = round(each['fee'] * price, 6)
            each['fee'] = fee
            logger.info(f'{symbol_name}: use {vol} USDT, get {amount} {currency}, price {price}, fee {fee} {currency}, at {each["time"]}')

        logger.info('Sell')
        for each in sell_info:
            currency = each['currency']
            symbol_name = '/'.join([currency, 'USDT'])
            vol = each['vol']
            amount = each['amount']
            price = each['price']
            fee = each['fee']
            logger.info(f'{symbol_name}: use {amount} {currency}, get {vol} USDT, price {price}, fee {fee} USDT, at {each["time"]}')

        logger.info(f'Totally pay {pay} USDT, get {income} USDT, profit {profit} USDT, {percent}%')
        add_profit(self.account_id, pay, income, profit, percent)
        total_profit, month_profit = get_profit(self.account_id)
        wx_report(self.account_id, self.wxuid, self.username, pay, income, profit, percent, buy_info, sell_info, total_profit, month_profit)
예제 #4
0
def myEventHandle():
    #trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key, init_log=True)
    trade_client = TradeClient(api_key=g_api_key,
                               secret_key=g_secret_key,
                               init_log=False)
    trade_client.sub_order_update(symbol, handle_order_update)
예제 #5
0
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
list_obj = trade_client.get_match_result(symbol="trxusdt",
                                         size=5,
                                         direct=QueryDirection.NEXT)
LogInfo.output_list(list_obj)

list_obj = trade_client.get_match_result(symbol="eosusdt", size=5)
LogInfo.output_list(list_obj)
예제 #6
0
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *

order_id = 113717254174681
trade_client = TradeClient(api_key='ghxertfvbf-300cc64c-05cc3126-79874',
                           secret_key='30ca5dcd-48f1cceb-d770f579-92cec')
orderObj = trade_client.get_order(order_id=113717254174681)
LogInfo.output("======= get order by order id : {order_id} =======".format(
    order_id=113717254174681))
orderObj.print_object()
from huobi.client.account import AccountClient
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *


def callback(order_req_obj: 'OrderListRequest'):
    print("---- order list:  ----")
    order_req_obj.print_object()
    print()

# for test, get spot account
account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
account_spot = account_client.get_account_by_type_and_symbol(account_type=AccountType.SPOT, symbol=None)

# request the order list info
if account_spot and account_spot.id:
    trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
    PrintBasic.print_basic(account_spot.id, "Account ID")
    trade_client.req_order_list(symbol="eosusdt", account_id=account_spot.id, callback=callback, order_states = OrderState.CANCELED, client_req_id = "xxx-01-1")


from huobi.client.account import AccountClient
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *

symbol_test = "eosusdt"

account_id = g_account_id

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
order_id = trade_client.create_order(symbol=symbol_test,
                                     account_id=account_id,
                                     order_type=OrderType.BUY_LIMIT,
                                     source=OrderSource.API,
                                     amount=4.0,
                                     price=1.292)
LogInfo.output("created order id : {id}".format(id=order_id))

canceled_order_id = trade_client.cancel_order(symbol_test, order_id)
if canceled_order_id == order_id:
    LogInfo.output("cancel order {id} done".format(id=canceled_order_id))
else:
    LogInfo.output("cancel order {id} fail".format(id=canceled_order_id))

order_id = trade_client.create_order(symbol=symbol_test,
                                     account_id=account_id,
                                     order_type=OrderType.BUY_MARKET,
                                     source=OrderSource.API,
                                     amount=5.0,
                                     price=1.292)
LogInfo.output("created order id : {id}".format(id=order_id))
예제 #9
0
class Trader(BaseTrader):
    def __init__(self, api_key, secret_key, account_id, verbose=False):
        super().__init__()
        self.account_id = account_id
        self.trade_client = TradeClient(api_key=api_key, secret_key=secret_key)
        self.account_client = AccountClient(api_key=api_key,
                                            secret_key=secret_key)
        self.algo_client = AlgoClient(api_key=api_key, secret_key=secret_key)
        self.market_client = MarketClient()
        self.holds = {}
        self.total_fee = 0
        self.stop_loss_threads = []
        self.long_order_threads = []
        self.latest_timestamp = 0
        self.client_id_counter = 0
        self.verbose = verbose
        self.subscription = None

    def add_trade_clearing_subscription(self,
                                        symbol,
                                        callback,
                                        error_handler=None):
        self.subscription = self.trade_client.sub_trade_clearing(
            symbol, callback, error_handler)
        return self.subscription

    def remove_trade_clearing_subscription(self, subscription):
        self.subscription.unsubscribe_all()

    def get_balance(self, symbol='usdt'):
        balances = self.account_client.get_balance(self.account_id)
        for balance in balances:
            if balance.currency == symbol:
                return float(balance.balance)

    def get_balance_pair(self, symbol):
        pair = transaction_pairs[symbol]
        target, base = pair.target, pair.base
        balances = self.account_client.get_balance(self.account_id)
        target_balance, base_balance = None, None
        for balance in balances:
            if balance.currency == target and target_balance is None:
                target_balance = float(balance.balance)
            elif balance.currency == base and base_balance is None:
                base_balance = float(balance.balance)
        return target_balance, base_balance

    def get_newest_price(self, symbol):
        newest_trade = self.market_client.get_market_trade(symbol=symbol)[0]
        return newest_trade.price

    def submit_orders(self, symbol, prices, amounts, order_type):
        """Submit a series of orders to the trader and return their ids.

        symbol -- symbol of trading pair
        prices -- list of prices of limit orders
        amounts -- list of amounts of limit orders
        order_type -- OrderType.BUY_LIMIT or OrderType.SELL_LIMIT
        """
        client_order_id_header = str(int(time.time()))
        order_ids = [
            f'{client_order_id_header}{symbol}{i:02d}'
            for i in range(len(prices))
        ]
        pair = transaction_pairs[symbol]
        price_scale, amount_scale = pair.price_scale, pair.amount_scale
        orders = [{
            'account_id': self.account_id,
            'symbol': symbol,
            'order_type': order_type,
            'source': OrderSource.API,
            'amount':
            f'{self.correct_amount(amount, symbol):.{amount_scale}f}',
            'price': f'{price:.{price_scale}f}',
            'client_order_id': order_id
        } for amount, price, order_id in zip(amounts, prices, order_ids)]
        results = []
        for i in range(0, len(orders), MAX_ORDER_NUM):
            create_results = self.trade_client.batch_create_order(
                order_config_list=orders[i:i + MAX_ORDER_NUM])
            results += create_results
        LogInfo.output_list(results)
        return results

    @staticmethod
    def get_normalized_amounts_with_eagerness(num_orders, eagerness=1.0):
        amounts = np.geomspace(eagerness**num_orders, 1, num_orders)
        return amounts / np.sum(amounts)

    @staticmethod
    def get_normalized_amounts_with_normal_distr(num_orders, skewness=1.0):
        amounts = np.linspace(-skewness, skewness, num_orders)
        amounts = stats.norm.pdf(amounts, 0, 1)
        amounts += amounts.min()
        return amounts / np.sum(amounts)

    @staticmethod
    def get_normalized_amounts_with_distr(num_orders, distr):
        if distr is None:
            return Trader.get_normalized_amounts_with_eagerness(
                num_orders, 1.0)
        elif distr['distr'] == 'geometry':
            return Trader.get_normalized_amounts_with_eagerness(
                num_orders, distr.get('eagerness', 1.0))
        elif distr['distr'] == 'normal':
            return Trader.get_normalized_amounts_with_normal_distr(
                num_orders, distr.get('skewness', 1.0))

    @staticmethod
    def get_price_interval(lower_price, upper_price, num_orders, order_type):
        if order_type == OrderType.BUY_LIMIT:
            prices = np.linspace(upper_price, lower_price, num_orders)
        elif order_type == OrderType.SELL_LIMIT:
            prices = np.linspace(lower_price, upper_price, num_orders)
        else:
            raise ValueError(f'Unknown order type {order_type}')
        return prices

    def generate_buy_queue_orders(self,
                                  symbol,
                                  lower_price,
                                  upper_price,
                                  num_orders,
                                  total_amount=None,
                                  total_amount_fraction=None,
                                  distr=None):
        prices = self.get_price_interval(lower_price, upper_price, num_orders,
                                         OrderType.BUY_LIMIT)
        normalized_amounts = self.get_normalized_amounts_with_distr(
            num_orders, distr)
        if total_amount is not None:
            amounts = normalized_amounts * total_amount
        elif total_amount_fraction is not None:
            balance = self.get_balance(
                transaction_pairs[symbol].base) * total_amount_fraction
            amounts = normalized_amounts * (balance / prices *
                                            normalized_amounts).sum()
        else:
            raise ValueError(
                'One of total_amount or total_amount_fraction should be given')
        return self.submit_orders(symbol, prices, amounts, OrderType.BUY_LIMIT)

    def create_smart_buy_queue(self,
                               symbol,
                               lower_price,
                               upper_price,
                               num_orders,
                               profit=1.05,
                               total_amount=None,
                               total_amount_fraction=None,
                               distr=None):
        orders = self.generate_buy_queue_orders(symbol, lower_price,
                                                upper_price, num_orders,
                                                total_amount,
                                                total_amount_fraction, distr)
        client_order_id_header = str(int(time.time()))
        price_scale = transaction_pairs[symbol].price_scale
        algo_order_ids = []
        for i, order in enumerate(orders):
            client_order_id = f'{client_order_id_header}{symbol}{i:02d}'
            order_price = float(order['price']) * profit
            stop_price = order_price * 0.999
            self.algo_client.create_order(
                account_id=self.account_id,
                symbol=symbol,
                order_side=OrderSide.SELL,
                order_type=AlgoOrderType.LIMIT,
                order_size=order['amount'],
                order_price=f'{order_price:.{price_scale}f}',
                stop_price=f'{stop_price:.{price_scale}f}',
                client_order_id=client_order_id)
            algo_order_ids.append(client_order_id)
        return results, orders, algo_order_ids

    def cancel_all_algo_orders(self, order_ids):
        results = [
            self.algo_client.cancel_orders(order_id) for order_id in order_ids
        ]
        return results

    def update_timestamp(self):
        now = int(time.time())
        if now == self.latest_timestamp:
            self.client_id_counter += 1
        else:
            self.latest_timestamp = now
            self.client_id_counter = 0

    def get_order(self, order_id):
        return self.trade_client.get_order(order_id)

    def create_order(self,
                     symbol,
                     price,
                     order_type,
                     amount=None,
                     amount_fraction=None):
        pair = transaction_pairs[symbol]
        if amount is None:
            if order_type is OrderType.SELL_LIMIT or order_type is OrderType.SELL_MARKET:
                amount = self.get_balance(pair.target) * amount_fraction
            else:
                amount = self.get_balance(pair.base) * amount_fraction
        amount = f'{float(amount):.{pair.amount_scale}f}'
        if price is not None:
            price = f'{float(price):.{pair.price_scale}f}'
        self.update_timestamp()
        client_order_id = f'{self.latest_timestamp}{symbol}{self.client_id_counter:02d}'
        order_id = self.trade_client.create_order(
            symbol=symbol,
            account_id=self.account_id,
            order_type=order_type,
            price=price,
            amount=amount,
            source=OrderSource.API,
            client_order_id=client_order_id)
        return order_id

    @staticmethod
    def get_time():
        return int(time.time())

    def get_previous_prices(self, symbol, window_type, window_size):
        candlesticks = self.market_client.get_candlestick(
            symbol, window_type, window_size)
        return [(cs.id, (cs.open + cs.close) / 2)
                for cs in sorted(candlesticks, key=lambda cs: cs.id)]

    def create_buy_queue(self,
                         symbol,
                         lower_price,
                         upper_price,
                         num_orders,
                         total_amount=None,
                         total_amount_fraction=None,
                         distr=None):
        newest_price = self.get_newest_price(symbol)
        if upper_price > newest_price:
            raise ValueError(
                'Unable to buy at a price higher the the market price')
        if lower_price >= upper_price:
            raise ValueError('lower_price should be less than upper_price')
        orders = self.generate_buy_queue_orders(symbol, lower_price,
                                                upper_price, num_orders,
                                                total_amount,
                                                total_amount_fraction, distr)
        return orders

    def create_sell_queue(self,
                          symbol,
                          lower_price,
                          upper_price,
                          num_orders,
                          total_amount=None,
                          total_amount_fraction=None,
                          distr=None):
        newest_price = self.get_newest_price(symbol)
        if lower_price < newest_price:
            raise ValueError(
                'Unable to sell at a price lower the the market price')
        if lower_price >= upper_price:
            raise ValueError('lower_price should be less than upper_price')
        prices = self.get_price_interval(lower_price, upper_price, num_orders,
                                         OrderType.SELL_LIMIT)
        normalized_amounts = self.get_normalized_amounts_with_distr(
            num_orders, distr)
        if total_amount is not None:
            amounts = normalized_amounts * total_amount
        elif total_amount_fraction is not None:
            balance = self.get_balance(
                transaction_pairs[symbol].target) * total_amount_fraction
            amounts = normalized_amounts * balance
        else:
            raise ValueError(
                'One of total_amount or total_amount_fraction should be given')
        return self.submit_orders(symbol, prices, amounts,
                                  OrderType.SELL_LIMIT)

    def cancel_orders(self, symbol, order_ids):
        cancel_results = []
        for i in range(0, len(order_ids), MAX_CANCEL_ORDER_NUM):
            cancel_result = self.trade_client.cancel_orders(
                symbol, order_ids[i:i + MAX_CANCEL_ORDER_NUM])
            cancel_results.append(cancel_result)
        return cancel_results

    def cancel_all_orders_with_type(self, symbol, order_type):
        account_spot = self.account_client.get_account_by_type_and_symbol(
            AccountType.SPOT, symbol=None)
        orders = self.trade_client.get_open_orders(symbol=symbol,
                                                   account_id=account_spot.id,
                                                   direct=QueryDirection.NEXT)
        sell_order_ids = [
            str(order.id) for order in orders if order.type == order_type
        ]
        if len(sell_order_ids) == 0:
            return
        return self.cancel_orders(symbol, sell_order_ids)

    def cancel_all_buy_orders(self, symbol):
        return self.cancel_all_orders_with_type(symbol, OrderType.BUY_LIMIT)

    def cancel_all_sell_orders(self, symbol):
        return self.cancel_all_orders_with_type(symbol, OrderType.SELL_LIMIT)

    def sell_all_at_market_price(self, symbol):
        return self.create_order(symbol=symbol,
                                 price=None,
                                 order_type=OrderType.SELL_MARKET,
                                 amount_fraction=0.999)

    def start_new_stop_loss_thread(self,
                                   symbol,
                                   stop_loss_price,
                                   interval=10,
                                   trailing_order=None):
        from stop_loss import StopLoss
        thread = StopLoss(symbol, self, stop_loss_price, interval,
                          trailing_order)
        self.stop_loss_threads.append(thread)

    def start_long_order_thread(self,
                                symbol,
                                buy_price,
                                profit,
                                amount=None,
                                amount_fraction=None,
                                stop_loss=0.9,
                                interval=10):
        from long_order import LongOrder
        thread = LongOrder(symbol, self, buy_price, profit, amount,
                           amount_fraction, stop_loss, interval)
        self.long_order_threads.append(thread)
예제 #10
0
from huobi.client.trade import TradeClient
from huobi.constant import *

# cancel all the open orders under account
trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
result = trade_client.cancel_open_orders(account_id=g_account_id)
result.print_object()
예제 #11
0
class TradeHandler:
    def __init__(self):
        self.api_key = "db8f342a-3540b528-hrf5gdfghe-5e793"
        self.secret_key = "366684d9-94c5fdf7-ad3b02a0-446bf"
        self.trade_client = TradeClient(api_key=self.api_key,
                                        secret_key=self.secret_key)
        self.algo_client = AlgoClient(api_key=self.api_key,
                                      secret_key=self.secret_key)
        self.trade_log = pd.DataFrame(
            columns=['Time', 'Amount', 'Fee', 'Price', 'Symbol', 'OrderType'])

    def get_feerate(self, symbol):
        list_obj = self.trade_client.get_feerate(symbols=symbol)
        LogInfo.output_list(list_obj)

    def get_history_orders(self, symbol_list):
        for symbol in symbol_list:
            list_obj = self.trade_client.get_history_orders(symbol=symbol,
                                                            start_time=None,
                                                            end_time=None,
                                                            size=20,
                                                            direct=None)
            LogInfo.output_list(list_obj)

    def get_match_result(self, symbol):
        list_obj = self.trade_client.get_match_result(symbol=symbol, size=100)
        for obj in list_obj:
            self.trade_log = self.trade_log.append(pd.Series(
                [
                    obj.created_at, obj.filled_amount, obj.filled_fees,
                    obj.price, obj.symbol, obj.type
                ],
                index=[
                    'Time', 'Amount', 'Fee', 'Price', 'Symbol', 'OrderType'
                ]),
                                                   ignore_index=True)
        # LogInfo.output_list(list_obj)
        self.trade_log = self.trade_log.drop_duplicates()

    def get_open_orders(self, id, symbol):
        list_obj = self.trade_client.get_open_orders(
            symbol=symbol, account_id=id, direct=QueryDirection.NEXT)
        LogInfo.output_list(list_obj)
        # list_obj = self.trade_client.get_open_orders(symbol=symbol, account_id=id, direct=QueryDirection.PREV)
        # LogInfo.output_list(list_obj)

    def get_order(self, order_id):
        order_obj = self.trade_client.get_order(order_id=order_id)
        # LogInfo.output("======= get order by order id : {order_id} =======".format(order_id=order_id))
        # order_obj.print_object()
        return order_obj

    def batch_cancel(self, account_id):
        # cancel all the open orders under account
        result = self.trade_client.cancel_open_orders(account_id=account_id)

    def create_order_limit(self, symbol, account_id, order_type, amount,
                           price):
        order_id = self.trade_client.create_order(symbol=symbol,
                                                  account_id=account_id,
                                                  order_type=order_type,
                                                  source=OrderSource.API,
                                                  amount=amount,
                                                  price=price)
        LogInfo.output("created order id : {id}".format(id=order_id))

    def create_order_market(self, symbol, account_id, order_type, value):
        order_id = self.trade_client.create_order(symbol=symbol,
                                                  account_id=account_id,
                                                  order_type=order_type,
                                                  source=OrderSource.API,
                                                  amount=value,
                                                  price=None)
        return order_id

    def cancel_order(self, symbol, order_id):
        canceled_order_id = self.trade_client.cancel_order(symbol, order_id)
        if canceled_order_id == order_id:
            LogInfo.output(
                "cancel order {id} done".format(id=canceled_order_id))
        else:
            LogInfo.output(
                "cancel order {id} fail".format(id=canceled_order_id))
예제 #12
0
#!/usr/bin/python3

from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
symbol = "eth3lusdt"
list_obj = trade_client.get_orders(symbol=symbol,
                                   order_state=OrderState.SUBMITTED,
                                   order_type=OrderType.BUY_LIMIT,
                                   start_date=None,
                                   end_date=None,
                                   start_id=None,
                                   size=None,
                                   direct=QueryDirection.PREV)

LogInfo.output("===== step 1 ==== {symbol} {count} orders found".format(
    symbol=symbol, count=len(list_obj)))
if len(list_obj):
    LogInfo.output_list(list_obj)
예제 #13
0
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *

client_order_id_test = "xxxxxx"  # unique id in 24hours

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
orderObj = trade_client.get_order_by_client_order_id(
    client_order_id=client_order_id_test)
LogInfo.output(
    "======= get order by client order id : {client_id} =======".format(
        client_id=client_order_id_test))
orderObj.print_object()
예제 #14
0
def myEventHandle():
        #trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key, init_log=True)
        trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key, init_log=False)
        trade_client.sub_order_update("eth3lusdt,dogeusdt,ethusdt", handle_order_update)
예제 #15
0
파일: money.py 프로젝트: lxm065/tools-1
    #火币处理
    hb_balance = {}
    account_client = AccountClient(api_key=hb_api_key,
                                   secret_key=hb_secret_key)
    account_balance_list = account_client.get_account_balance()
    for account_balance_obj in account_balance_list:
        for balance_obj in account_balance_obj.list:
            if float(balance_obj.balance
                     ) > 0.01 and balance_obj.currency not in hb_iglist:
                hb_balance[balance_obj.currency] = float(
                    balance_obj.balance
                ) if balance_obj.currency not in hb_balance else hb_balance[
                    balance_obj.currency] + float(balance_obj.balance)

    trade_client = TradeClient(api_key=hb_api_key, secret_key=hb_secret_key)
    for symbol, bcount in hb_balance.items():
        x, order_bcount = 0, 0
        hb_border = []
        while abs(order_bcount - bcount) > 0.1 and x < 30:
            list_obj = trade_client.get_orders(
                symbol=f'{symbol}usdt',
                start_date=(datetime.now() -
                            timedelta(days=2 * x + 1)).strftime('%Y-%m-%d'),
                end_date=(datetime.now() -
                          timedelta(days=2 * x)).strftime('%Y-%m-%d'),
                order_state="partial-filled,filled,partial-canceled")
            if len(list_obj) != 0:
                for order in list_obj:
                    hb_border.append({
                        "orderId":
예제 #16
0
def has_buy_order(symbol, buy_price, sell_price, check_partial):
    try:
        trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
        list_obj = trade_client.get_orders(symbol=symbol,
                                           order_state=OrderState.SUBMITTED,
                                           order_type=None,
                                           start_date=None,
                                           end_date=None,
                                           start_id=None,
                                           size=None,
                                           direct=QueryDirection.PREV)
        count = len(list_obj)
        order_type = []
        for obj in list_obj:
            a = __Autonomy__()
            current = sys.stdout
            sys.stdout = a
            obj.print_object()
            sys.stdout = current
            order_type = get_value("Order Type", a._buff)
            order_id = get_value("Order Id", a._buff)
            amount = get_value("Amount", a._buff)
            price = get_value("Price", a._buff)
            current_price = float(price[0])
            if (order_type[0] == "buy-limit"):
                if current_price == buy_price:
                    return True, True, int(order_id[0]), float(amount[0])
            else:
                if current_price == sell_price:
                    return True, False, int(order_id[0]), float(amount[0])
    except:
        print("ExecuteError")

    if check_partial:
        try:
            list_obj = trade_client.get_orders(
                symbol=symbol,
                order_state=OrderState.PARTIAL_FILLED,
                order_type=None,
                start_date=None,
                end_date=None,
                start_id=None,
                size=None,
                direct=QueryDirection.PREV)
            count = len(list_obj)
            order_type = []
            for obj in list_obj:
                a = __Autonomy__()
                current = sys.stdout
                sys.stdout = a
                obj.print_object()
                sys.stdout = current
                order_type = get_value("Order Type", a._buff)
                order_id = get_value("Order Id", a._buff)
                amount = get_value("Amount", a._buff)
                price = get_value("Price", a._buff)
                current_price = float(price[0])
                if (order_type[0] == "buy-limit"):
                    if current_price == buy_price:
                        return True, True, int(order_id[0]), float(amount[0])
                else:
                    if current_price == sell_price:
                        return True, False, int(order_id[0]), float(amount[0])
        except:
            print("ExecuteError")
    return False, False, 0, 0
예제 #17
0
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *

order_id = 25943298415466
trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
orderObj = trade_client.get_order(order_id=order_id)
LogInfo.output("======= get order by order id : {order_id} =======".format(
    order_id=order_id))
orderObj.print_object()