コード例 #1
0
ファイル: bid.py プロジェクト: ljmljz/trader
    def __init__(self, symbol):
        Thread.__init__(self, name=symbol + '_Bid_Policy')

        if symbol not in store.hbsymbols:
            self._symbol = None
        else:
            self._symbol = store.hbsymbols[symbol]

        self._name = symbol
        self._buy_in_price = 0.0
        self._buy_in = False
        self._sell_out = True
        self._money = 0
        self._amount = 0
        self._price = {"value": None, "timestamp": None}
        self._queue = Queue()
        self._account_client = AccountClient(
            url=settings.config['COMMON']['host'],
            api_key=settings.config['ACCOUNT']['api_key'],
            secret_key=settings.config['ACCOUNT']['secret_key'])
        self._trade_client = TradeClient(
            url=settings.config['COMMON']['host'],
            api_key=settings.config['ACCOUNT']['api_key'],
            secret_key=settings.config['ACCOUNT']['secret_key'])

        self.daemon = True
        self.start()
コード例 #2
0
    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
コード例 #3
0
def get_usdt_trade_balance():
    try:
        account_client = AccountClient(api_key=g_api_key,
                                       secret_key=g_secret_key)
        list_obj = account_client.get_balance(account_id=account_id)
        for balance_obj in list_obj:
            if float(balance_obj.balance
                     ) > 0.1:  # only show account with balance
                order_type = []
                a = __Autonomy__()
                current = sys.stdout
                sys.stdout = a
                balance_obj.print_object("\t")
                sys.stdout = current
                order_type = get_value("usdt", a._buff)
                if order_type:
                    #print(order_type)
                    #print(a._buff)
                    order_type = get_value("trade", a._buff)
                    if order_type:
                        #print(order_type)
                        #print(a._buff)
                        order_type = get_value("Balance", a._buff)
                        if order_type:
                            #print(order_type[1])
                            return order_type[1]
    except:
        print("ExecuteError:", inspect.stack()[1][4])
    return 0.0
コード例 #4
0
def get_eth3l_trade_balance():
    account_id = 23455585
    account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
    list_obj = account_client.get_balance(account_id=account_id)
    for balance_obj in list_obj:
        if float(balance_obj.balance) > 0.1:  # only show account with balance
            order_type = []
            a = __Autonomy__()
            current = sys.stdout
            sys.stdout = a
            balance_obj.print_object("\t")
            sys.stdout = current
            order_type = get_value("eth3l", a._buff)
            if order_type:
                #print(order_type)
                #print(a._buff)
                order_type = get_value("trade", a._buff)
                if order_type:
                    #print(order_type)
                    #print(a._buff)
                    order_type = get_value("Balance", a._buff)
                    if order_type:
                        #print(order_type[1])
                        return order_type[1]
    return 0.0
コード例 #5
0
ファイル: app.py プロジェクト: ljmljz/trader
def get_account():
    try:
        account_client = AccountClient(url=settings.config['COMMON']['host'], api_key=settings.config['ACCOUNT']['api_key'], secret_key=settings.config['ACCOUNT']['secret_key'])
        accounts = account_client.get_accounts()
        
        for account in accounts:
            if account.type == "spot":
                store.account = account
    except Exception as e:
        print(e)
コード例 #6
0
 def __init__(self):
     self.api_key = "db8f342a-3540b528-hrf5gdfghe-5e793"
     self.secret_key = "366684d9-94c5fdf7-ad3b02a0-446bf"
     self.account_client = AccountClient(api_key=self.api_key,
                                         secret_key=self.secret_key)
     self.margin_client = MarginClient(api_key=self.api_key,
                                       secret_key=self.secret_key)
     self.accounts = []
     self.asset = {}
     self.balance = pd.DataFrame(
         columns=['account', 'currency', 'type', 'balance'])
     self.margin = {}
     self.th = TradeHandler()
     self.conn = sqlite3.connect('market.db', timeout=10)
     self.open_order = 0
コード例 #7
0
ファイル: trader.py プロジェクト: 3Dori/huobi_trader
 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
コード例 #8
0
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="dogeusdt",
                                account_id=account_spot.id,
                                callback=callback,
                                order_states=OrderState.CANCELED,
                                client_req_id="xxx-01-1")
コード例 #9
0
ファイル: get_my_balance.py プロジェクト: everschen/tools
#!/usr/bin/python3

from huobi.client.account import AccountClient, AccountBalance, get_default_server_url, AccountType
from huobi.privateconfig import *
from huobi.client.wallet import WalletClient
from huobi.service.wallet.get_deposit_withdraw import GetDepositWithdrawService
from huobi.constant.definition import *
from huobi.constant import *
from huobi.utils import *

g_api_key = "XXXXXXX"
g_secret_key = "XXXXXXX"

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
account_balance_list = account_client.get_account_balance()
if account_balance_list and len(account_balance_list):
    for account_balance_obj in account_balance_list:
        if account_balance_obj and len(account_balance_obj.list):
            PrintBasic.print_basic(account_balance_obj.id, "ID")
            PrintBasic.print_basic(account_balance_obj.type, "Account Type")
            PrintBasic.print_basic(account_balance_obj.state, "Account State")
            PrintBasic.print_basic(account_balance_obj.subtype, "Subtype")
            for balance_obj in account_balance_obj.list:
                if float(balance_obj.balance
                         ) > 0.1:  # only show account with balance
                    balance_obj.print_object("\t")
                    print()
        print()
コード例 #10
0
class AccountHandler:
    def __init__(self):
        self.api_key = "db8f342a-3540b528-hrf5gdfghe-5e793"
        self.secret_key = "366684d9-94c5fdf7-ad3b02a0-446bf"
        self.account_client = AccountClient(api_key=self.api_key,
                                            secret_key=self.secret_key)
        self.margin_client = MarginClient(api_key=self.api_key,
                                          secret_key=self.secret_key)
        self.accounts = []
        self.asset = {}
        self.balance = pd.DataFrame(
            columns=['account', 'currency', 'type', 'balance'])
        self.margin = {}
        self.th = TradeHandler()
        self.conn = sqlite3.connect('market.db', timeout=10)
        self.open_order = 0

    def get_accounts(self):
        self.accounts = self.account_client.get_accounts()
        # LogInfo.output_list(self.accounts)

    def get_account_asset(self, account_type, currency):
        asset_valuation = self.account_client.get_account_asset_valuation(
            account_type=account_type, valuation_currency=currency)
        return float(asset_valuation.balance)

    def update_asset(self):
        for item in self.accounts:
            self.asset[item.type] = self.get_account_asset(item.type, 'usd')

    def get_balance(self, account_id):
        list_obj = self.account_client.get_balance(account_id=account_id)
        for item in list_obj:
            if float(item.balance) != 0:
                self.balance = self.balance.append(pd.Series(
                    [
                        account_id, item.currency, item.type,
                        float(item.balance)
                    ],
                    index=['account', 'currency', 'type', 'balance']),
                                                   ignore_index=True)
        self.balance = self.balance.drop_duplicates()

    def update_balance(self):
        self.balance = pd.DataFrame(
            columns=['account', 'currency', 'type', 'balance'])
        for item in self.accounts:
            self.get_balance(item.id)
        self.balance = self.balance.loc[
            self.balance['balance'] != 0].reset_index(drop=True)

    def get_cross_margin_account(self):
        account_balance = self.margin_client.get_cross_margin_account_balance()
        self.margin['balance'] = float(account_balance.acct_balance_sum)
        self.margin['debt'] = float(account_balance.debt_balance_sum)
        # account_balance.print_object()

    def get_account_ledger(self, account_id):
        list_obj = self.account_client.get_account_ledger(
            account_id=account_id)
        LogInfo.output_list(list_obj)

    def update_history_trades(self, symbol):
        table = symbol + "_trade_log"
        self.th.get_match_result(symbol)
        data = self.th.trade_log.copy()
        c = self.conn.cursor()
        # get the count of tables with the name
        c.execute(
            "SELECT count(name) FROM sqlite_master WHERE type='table' AND name='"
            + table + "'")
        # #if the count is 1, then table exists
        if c.fetchone()[0] == 1:
            last_data = pd.read_sql('select * from ' + table, self.conn)
            last_data = last_data.append(data).drop_duplicates().sort_values(
                by='Time', ascending=True)
            last_data.sort_values(by='Time',
                                  ascending=True).to_sql(table,
                                                         self.conn,
                                                         if_exists='replace',
                                                         index=False)
        else:
            data.sort_values(by='Time',
                             ascending=True).to_sql(table,
                                                    self.conn,
                                                    if_exists='replace',
                                                    index=False)

    def adjust_position(self, account, currency, target, last_price):
        balance = self.balance
        current_balance = balance[(balance['account'] == account)
                                  & (balance['currency'] == currency)]
        if len(current_balance):
            current_position = current_balance['balance'].values[0]
        else:
            current_position = 0.0

        if current_position < target * 0.95:
            od = OrderType.BUY_MARKET
            amt = (target - current_position) * last_price
            if amt < 5:
                return
            else:
                self.place_market_order(currency, account, od, amt)
        elif current_position > target * 1.05 + 0.00005:
            amt = round(current_position - target - 0.00001, 5)
            od = OrderType.SELL_MARKET
            if amt < 0.0001:
                return
            else:
                self.place_market_order(currency, account, od, amt)

    def place_market_order(self, currency, account, od, amt):
        try:
            self.th.batch_cancel(account)
            order_id = self.th.create_order_market(currency + "usdt", account,
                                                   od, round(amt, 6))
            self.open_order = order_id
        except Exception as error:
            print(error)
            print(od)
            print(amt)
            print("CANNOT PLACE ORDER!!!!!")

    def check_latest_order(self):
        if self.open_order > 0:
            return self.th.get_order(self.open_order)
コード例 #11
0
from huobi.client.account import AccountClient
from huobi.constant import *

# get accounts
from huobi.utils import *

account_client = AccountClient(api_key='ghxertfvbf-300cc64c-05cc3126-79874',
                               secret_key='30ca5dcd-48f1cceb-d770f579-92cec')

list_obj = account_client.get_accounts()
LogInfo.output_list(list_obj)
コード例 #12
0
 def __init__(self):
     account_client = AccountClient(api_key=Config.api_key, secret_key=Config.secret_key)
     self.account_balance_list = account_client.get_account_balance()
from huobi.client.account import AccountClient
from huobi.constant import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

point_transfer_result = account_client.post_point_transfer(from_uid=111859319,
                                                           to_uid=124409916,
                                                           group_id=0,
                                                           amount=10)
point_transfer_result.print_object()
コード例 #14
0
from huobi.client.account import AccountClient
from huobi.constant import *


def callback(account_balance_req: 'AccountBalanceReq'):
    account_balance_req.print_object()


account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
account_client.req_account_balance(callback=callback, client_req_id=None)
コード例 #15
0
from huobi.client.account import AccountClient
from huobi.constant import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

account_point_result = account_client.get_account_point()
account_point_result.print_object()
from huobi.client.account import AccountClient
from huobi.constant import *


def callback(account_change_event: 'AccountChangeEvent'):
    account_change_event.print_object()
    print()


account_client = AccountClient(api_key=g_api_key,
                               secret_key=g_secret_key,
                               init_log=True)
# account_client.sub_account_update(AccountBalanceMode.TOTAL, callback)
account_client.sub_account_update(AccountBalanceMode.BALANCE, callback)
コード例 #17
0
from huobi.client.account import AccountClient
from huobi.constant import *

account_client = AccountClient(api_key="db8f342a-3540b528-hrf5gdfghe-5e793",
                               secret_key="366684d9-94c5fdf7-ad3b02a0-446bf")

account_type = "spot"
asset_valuation = account_client.get_account_asset_valuation(account_type=account_type, valuation_currency="usd")
asset_valuation.print_object()
from huobi.client.account import AccountClient
from huobi.constant import *

# get accounts
account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

ret = account_client.post_sub_uid_management(sub_uid=g_sub_uid,
                                             action=SubUidAction.LOCK)
ret.print_object()

ret = account_client.post_sub_uid_management(sub_uid=g_sub_uid,
                                             action=SubUidAction.UNLOCK)
ret.print_object()
from huobi.client.account import AccountClient
from huobi.constant import *
from huobi.utils import *
import time

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
transfer_order_id = account_client.transfer_between_futures_and_pro(
    currency="trx", amount=200, transfer_type=TransferFuturesPro.TO_FUTURES)
LogInfo.output(
    "transfer from pro to future Order Id : {id}".format(id=transfer_order_id))

# need wait a minute
time.sleep(2)

transfer_order_id = account_client.transfer_between_futures_and_pro(
    currency="trx", amount=200, transfer_type=TransferFuturesPro.TO_PRO)
LogInfo.output(
    "transfer from future to pro Order Id : {id}".format(id=transfer_order_id))
コード例 #20
0
ファイル: bid.py プロジェクト: ljmljz/trader
class BidPolicy(Thread):
    def __init__(self, symbol):
        Thread.__init__(self, name=symbol + '_Bid_Policy')

        if symbol not in store.hbsymbols:
            self._symbol = None
        else:
            self._symbol = store.hbsymbols[symbol]

        self._name = symbol
        self._buy_in_price = 0.0
        self._buy_in = False
        self._sell_out = True
        self._money = 0
        self._amount = 0
        self._price = {"value": None, "timestamp": None}
        self._queue = Queue()
        self._account_client = AccountClient(
            url=settings.config['COMMON']['host'],
            api_key=settings.config['ACCOUNT']['api_key'],
            secret_key=settings.config['ACCOUNT']['secret_key'])
        self._trade_client = TradeClient(
            url=settings.config['COMMON']['host'],
            api_key=settings.config['ACCOUNT']['api_key'],
            secret_key=settings.config['ACCOUNT']['secret_key'])

        self.daemon = True
        self.start()

    def push_data(self, price):
        self._queue.put(price)

    def _get_balance(self, currency):
        balance = self._account_client.get_balance(store.account.id)
        for b in balance:
            if b.currency == currency and b.type == 'trade':
                return float(b.balance)

        return 0

    def run(self):
        while True:
            if not self._queue.empty():
                cur_time = datetime.now()
                cur_bid = self._queue.get()

                # print(self._name, cur_bid)

                if self._price['value'] is None:
                    self._price['value'] = cur_bid
                    self._price['timestamp'] = cur_time

                # print(datetime.now(), cur_bid, self._price['value'])

                diff = cur_time - self._price['timestamp']

                if not self._buy_in:
                    if diff.seconds < int(
                            settings.config['COMMON']['interval']) * 60:
                        self._price['value'] = min(self._price['value'],
                                                   cur_bid)
                    else:
                        if cur_bid <= self._price['value']:
                            # buy in
                            self._money = self._get_balance('usdt') / len(
                                store.symbol_policies)
                            print(self._money)
                            if self._money > 0:
                                self._amount = self._money / cur_bid

                                try:
                                    result = self._trade_client.create_spot_order(
                                        symbol=self.name,
                                        account_id=store.account.id,
                                        order_type=OrderType.BUY_MARKET,
                                        amount=self._amount,
                                        price=None)

                                    if result != '':
                                        self._buy_in_price = cur_bid
                                        self._buy_in = True
                                        self._sell_out = False

                                        print(datetime.now(), 'buy in',
                                              cur_bid, self._amount,
                                              self._money)
                                        log.info("Buy in " + str(cur_bid) +
                                                 ', ' + str(self._amount) +
                                                 ', ' + str(self._money))
                                    else:
                                        print('Failed to buy in')
                                        log.info('Failed to buy in')
                                except Exception as e:
                                    print(e)
                        else:
                            self._price['value'] = min(self._price['value'],
                                                       cur_bid)
                            self._price['timestamp'] = cur_time + timedelta(
                                minutes=-int(settings.config['COMMON']
                                             ['interval']))
                else:
                    stop_profit = float(
                        settings.config['COMMON']['stop_profit'])
                    if cur_bid > (self._buy_in_price *
                                  stop_profit) and self._amount > 0:
                        # sell out
                        self._amount = self._get_balance(
                            self._symbol.base_currency)
                        if self._amount > 0:
                            result = self._trade_client.create_spot_order(
                                symbol=self.name,
                                account_id=store.account.id,
                                order_type=OrderType.SELL_MARKET,
                                amount=self._amount,
                                # price=cur_bid
                            )

                            if result != '':
                                self._buy_in = False
                                self._sell_out = True
                                self._price['value'] = cur_bid
                                self._price['timestamp'] = cur_time

                                print(datetime.now(), 'Sell out', cur_bid,
                                      self._amount, self._money)
                                log.info("Sell out " + str(cur_bid) + ', ' +
                                         str(self._amount) + ', ' +
                                         str(self._money))
            else:
                time.sleep(0.1)
from huobi.client.account import AccountClient
from huobi.constant import *

# get accounts
from huobi.utils import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
list_obj = account_client.get_account_balance_by_subuid(sub_uid=g_sub_uid)
LogInfo.output_list(list_obj)
from huobi.client.account import AccountClient
from huobi.constant import *

# get accounts
from huobi.utils import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
list_obj = account_client.get_aggregated_subuser_balance()
LogInfo.output_list(list_obj)
コード例 #23
0
from enum import IntEnum

from huobi.exception.huobi_api_exception import HuobiApiException
from my.lesscfg import LESS_SYMBOL, LESS_INTERVAL, LESS_BASE, LESS_MAX_COUNT, LESS_LEAST_PROFIT, LESS_ADD_DIFF, \
    LESS_PEAK_DIFF
from my.lessdb import Lessdb, BTC_OPS_TABLE, Operation
from my.organized import Organized
from my.upath import UPath

from huobi.client.market import MarketClient
from huobi.client.account import AccountClient
from huobi.client.trade import TradeClient
from huobi.constant import *
from my.utils import Utils

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
market_client = MarketClient(init_log=True)
trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)


class LessTradeDirection(IntEnum):
    LONG = 0,
    SHORT = 1,
    INVALID = 2,


symbol = LESS_SYMBOL
interval = LESS_INTERVAL
LOG_THROTTLE_COUNT = 1
LESSDB_FILE = "less_{0}.db".format(symbol)
コード例 #24
0
from huobi.client.account import AccountClient
from huobi.constant import *

# get accounts
from huobi.utils import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

account_history = account_client.get_account_history(account_id=g_account_id,
                                                     start_time=1600827872000,
                                                     size=4)
LogInfo.output_list(account_history["data"])
LogInfo.output('Next Id: %s' % (account_history["next_id"]))
from huobi.client.account import AccountClient
from huobi.constant import *
from huobi.utils import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

list_obj = account_client.get_account_ledger(account_id=g_account_id)
LogInfo.output_list(list_obj)
コード例 #26
0
ファイル: trader.py プロジェクト: 3Dori/huobi_trader
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)
コード例 #27
0
#!/usr/bin/python3

from huobi.client.account import AccountClient
from huobi.constant import *

# get accounts
from huobi.utils import *
from configparser import ConfigParser

ini_file = "hunter.ini"
cfg = ConfigParser()
cfg.read(ini_file)

general_cfg = dict(cfg.items('general'))
g_api_key = general_cfg['g_api_key']
g_secret_key = general_cfg['g_secret_key']

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

list_obj = account_client.get_accounts()
LogInfo.output_list(list_obj)
コード例 #28
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)
コード例 #29
0
ファイル: huobi_ex.py プロジェクト: notechats/notestock
from huobi.client.trade import TradeClient

generic_client = GenericClient()
list_symbol = generic_client.get_exchange_symbols()
list_currency = generic_client.get_reference_currencies()
print(list_symbol[0])
print(list_currency[0].print_object())

a = c
access_key = " "
secret_key = " "

# Create generic client instance and get the timestamp
generic_client = GenericClient()
timestamp = generic_client.get_exchange_timestamp()
print(timestamp)

# Create the market client instance and get the latest btcusdt‘s candlestick
market_client = MarketClient()
list_obj = market_client.get_candlestick("btcusdt", CandlestickInterval.MIN5,
                                         10)
LogInfo.output_list(list_obj)

# // Create an AccountClient instance with APIKey
account_client = AccountClient(api_key=access_key, secret_key=secret_key)

# // Create a TradeClient instance with API Key and customized host
trade_client = TradeClient(api_key=access_key,
                           secret_key=secret_key,
                           url="https://api-aws.huobi.pro")
コード例 #30
0
from huobi.client.account import AccountClient
from huobi.constant import *
from keys import *

# get accounts
from huobi.utils import *

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
list_obj = account_client.get_balance(account_id=g_account_id)
#LogInfo.output_list(list_obj)

for index in list_obj:
    if index.currency == "ht" and index.type == "trade":
        print(index.balance)