Esempio n. 1
0
 def __init__(self):
     super().__init__()
     self.__api_key = os.getenv('KUCOIN_API_KEY')
     self.__api_secret = os.getenv('KUCOIN_API_SECRET')
     self.__api_passphrase = os.getenv('KUCOIN_API_PASSPHRASE')
     self.__valid = self.__api_key and self.__api_secret and self.__api_passphrase
     if self.__valid:
         logging.info(f"Initialized {self.name()} Exchange")
         self.__user = User(self.__api_key, self.__api_secret,
                            self.__api_passphrase)
         self.__market = Market()
     else:
         logging.warning(f"{self.name()} Is Missing Configuration")
Esempio n. 2
0
def returnAccountAvailable(currency):
    '''
    :param currency: a symbol of a currency ('BTC', 'ETH',...)
    :return: Funds available to withdraw or trade
    '''
    account = User.get_account_list(currency, "trade")
    return account[0]['available']
Esempio n. 3
0
    def __init__(self):
        # read configuration from json file
        with open('config.json', 'r') as file:
            config = json.load(file)

        self.api_key = config['api_key']
        self.api_secret = config['api_secret']
        self.api_passphrase = config['api_passphrase']
        self.sandbox = config['is_sandbox']
        self.symbol = config['symbol']
        self.min_param = float(config['min_param'])
        self.price_param = float(config['price_param'])
        self.market = Market(self.api_key,
                             self.api_secret,
                             self.api_passphrase,
                             is_sandbox=self.sandbox)
        self.user = User(self.api_key,
                         self.api_secret,
                         self.api_passphrase,
                         is_sandbox=self.sandbox)
        self.trade = Trade(self.api_key,
                           self.api_secret,
                           self.api_passphrase,
                           is_sandbox=self.sandbox)
        self.symbol_trade = self.symbol + '-USDT'
Esempio n. 4
0
class Kucoin:
    def __init__(self, key='', secret='', passphrase='') -> None:
        self.user = User(key, secret, passphrase)
        self.client = Market()
        pass

    def __get_asset(self) -> Dict[str, float]:
        result = {}
        balances = self.user.get_account_list()
        for i in balances:
            coin_name = i['currency']
            if coin_name in result:
                result[coin_name] = result[coin_name] + float(i['balance'])
            else:
                result.update({coin_name: float(i['balance'])})
        return result

    def __get_price_usdt(self) -> Dict[str, float]:
        tickers = self.client.get_all_tickers()
        result: Dict[str, float] = {}
        for i in tickers['ticker']:
            if i['symbol'].endswith("USDT"):
                coin_name = i['symbol'].replace("-USDT", "")
                result.update({coin_name: float(i['averagePrice'])})
        return result

    def asset_report(self,
                     buy_price: Dict[str, any] = {}) -> List[Dict[str, any]]:
        result = []
        price = self.__get_price_usdt()
        asset = self.__get_asset()
        for coin_name, coin_unit in asset.items():
            profit = 0.00
            worth_usdt = 0.00
            if coin_name in price:
                worth_usdt = coin_unit * price[coin_name]
            if coin_name in buy_price:
                profit = worth_usdt - (coin_unit * buy_price[coin_name])
            result.append({
                'asset':
                coin_name,
                'current_price':
                round(price[coin_name] if coin_name in price else 0, 4),
                'vol':
                round(coin_unit, 3),
                'worth_usdt':
                round(worth_usdt, 3),
                'profit':
                round(profit, 3)
            })
        return result
Esempio n. 5
0
    def __init__(self, config: AccountConfiguration) -> None:
        self.config = config

        self.user_client = UserClient(key=self.config.api_key,
                                      secret=self.config.api_secret,
                                      passphrase=self.config.api_passphrase,
                                      is_sandbox=False,
                                      url=self.config.base_url)

        self.margin_client = MarginClient(
            key=self.config.api_key,
            secret=self.config.api_secret,
            passphrase=self.config.api_passphrase,
            is_sandbox=False,
            url=self.config.base_url)
Esempio n. 6
0
class KuCoin(Exchange):
    def __init__(self):
        super().__init__()
        self.__api_key = os.getenv('KUCOIN_API_KEY')
        self.__api_secret = os.getenv('KUCOIN_API_SECRET')
        self.__api_passphrase = os.getenv('KUCOIN_API_PASSPHRASE')
        self.__valid = self.__api_key and self.__api_secret and self.__api_passphrase
        if self.__valid:
            logging.info(f"Initialized {self.name()} Exchange")
            self.__user = User(self.__api_key, self.__api_secret,
                               self.__api_passphrase)
            self.__market = Market()
        else:
            logging.warning(f"{self.name()} Is Missing Configuration")

    def name(self) -> str:
        return "KUCOIN"

    def get_positions(self) -> Dict[str, Position]:
        if not self.__valid:
            return {}
        ret = {}
        accounts = self.__user.get_account_list()
        prices = self.__market.get_fiat_price(base=self.fiat)
        for account in accounts:
            symbol = account['currency']
            account_type = account['type']
            account_balance = float(account['balance'])
            symbol_to_fiat = float(prices[symbol])
            if account_balance <= self.DUST_THRESHOLD:
                continue
            position = ret.get(symbol, Position(symbol, self.fiat))
            if account_type == TRADE or account_type == MAIN:
                position.spot_amount += account_balance
            elif account_type == MARGIN:
                position.margin_amount += account_balance
            position.spot_amount_in_fiat = position.spot_amount * symbol_to_fiat
            position.margin_amount_in_fiat = position.margin_amount * symbol_to_fiat
            ret[symbol] = position
        return ret
                order['transactTime'], order['fills'][0]['commissionAsset'], 
                order['fills'][0]['price'], order['fills'][0]['commission'],
                order['fills'][0]['qty'], order['cummulativeQuoteQty']))
    
    conn.commit()


if __name__ == '__main__':

    show_header()

    client = Market(url='https://openapi-sandbox.kucoin.com')
    # client = Client(config["api_key"], config["api_secret"])

    trade = Trade(config['api_key'], config['api_secret'], config['api_passphrase'], is_sandbox=True)
    user_client = User(config['api_key'], config['api_secret'], config['api_passphrase'], is_sandbox=True)

    if config['debug_mode']:
        debug_mode(client=client)
        print('\n')

    print(Fore.GREEN + '-- Kucoin Edition --\n' + Fore.RESET)

    #Question1
    answer1 = Inquirer.prompt(question1)
    selected_config = answer1['trade_conf']

    #Retrieve current coin balance here
    balance = acct_balance()

    #Question2
Esempio n. 8
0
#market = Market(url='https://openapi-sandbox.kucoin.com')
#market = Market(is_sandbox=True)
api_key = ''
api_secret = ''
api_passphrase = ''
def returnBid(symbol):
    '''
    :param symbol: a trading pair ('BTC-USDT',...)
    :return:  the second bid in the order book
    '''
    book = Market.get_aggregated_order(symbol)
    return book['bids'][1][0]

# User
from kucoin.client import User
client = User(api_key, api_secret, api_passphrase)

# or connect to Sandbox
#user = User(api_key, api_secret, api_passphrase, is_sandbox=True)

def returnAccountAvailable(currency):
    '''
    :param currency: a symbol of a currency ('BTC', 'ETH',...)
    :return: Funds available to withdraw or trade
    '''
    account = User.get_account_list(currency, "trade")
    return account[0]['available']

def returnPrice(symbol):
    '''
    :param symbol: a trading pair ('BTC-USDT',...)
Esempio n. 9
0
# or connect to Sandbox
#market = Market(url='https://openapi-sandbox.kucoin.com')
#market = Market(is_sandbox=True)
api_key = ''
api_secret = ''


def returnBid(symbol):
    book = market.get_aggregated_order(symbol)
    return book['bids'][1][0]


# User
from kucoin.client import User
user = User(api_key, api_secret, api_passphrase)

# or connect to Sandbox
#user = User(api_key, api_secret, api_passphrase, is_sandbox=True)


def returnPrice(token):
    account = market.get_ticker(token)
    return account['price']


# Trade
from kucoin.client import Trade
client = Trade(api_key, api_secret, api_passphrase)

# or connect to Sandbox
    balance2 = acct_balance2()
    pump_duration(start_time, end_time)


if __name__ == '__main__':

    show_header()

    client = Market(url='https://api.kucoin.com')
    trade = Trade(key=config['api_key'],
                  secret=config['api_secret'],
                  passphrase=config['api_passphrase'],
                  is_sandbox=False,
                  url='')
    user_client = User(config['api_key'], config['api_secret'],
                       config['api_passphrase'])

    if config['debug_mode']:
        debug_mode(client=client)
        print('\n')

    print(Fore.GREEN + '-- Kucoin Edition --\n' + Fore.RESET)

    #Question1
    answer1 = Inquirer.prompt(question1)
    selected_config = answer1['trade_conf']

    #Retrieve current coin balance here
    balance = acct_balance()

    #Question2
Esempio n. 11
0
from kucoin.client import Market, User, Trade

if __name__ == '__main__':
    # read configuration from json file
    with open('config.json', 'r') as file:
        config = json.load(file)

    api_key = config['api_key']
    api_secret = config['api_secret']
    api_passphrase = config['api_passphrase']
    symbol = config['symbol']
    min_param = config['min_param']
    price_param = config['price_param']
    sandbox = config['is_sandbox']
    market = Market(api_key, api_secret, api_passphrase, is_sandbox=sandbox)
    user = User(api_key, api_secret, api_passphrase, is_sandbox=sandbox)
    trade = Trade(api_key, api_secret, api_passphrase, is_sandbox=sandbox)
    init_ticker = market.get_ticker(symbol+'-USDT')
    init_price = float(init_ticker['price'])
    print('init_price =', init_price)

    while 1:
        time.sleep(1)
        # account balance
        symbol_balance = user.get_account_list(symbol, 'trade')
        available_symbol = float(symbol_balance[0]['available'])
        print('symbol_balance =', available_symbol)
        usdt_balance = user.get_account_list('USDT', 'trade')
        available_usdt = float(usdt_balance[0]['available'])
        print('usdt_balance =', available_usdt)
        now_symbol = market.get_ticker(symbol+'-USDT')
Esempio n. 12
0
 def get_account(self):
     client = User(self.api_key, self.api_secret,
                   passphrase="chimera", is_sandbox=self.debug_mode)
     return client
Esempio n. 13
0
 def __init__(self, key='', secret='', passphrase='') -> None:
     self.user = User(key, secret, passphrase)
     self.client = Market()
     pass
Esempio n. 14
0
class BaseBot:

    EPOCH_PER_HOUR = 60 * 60
    EPOCH_PER_DAY = EPOCH_PER_HOUR * 24

    config: AccountConfiguration
    user_client: UserClient
    margin_client: MarginClient

    response_log: list = None

    all_unsettled_orders: list = None

    def __init__(self, config: AccountConfiguration) -> None:
        self.config = config

        self.user_client = UserClient(key=self.config.api_key,
                                      secret=self.config.api_secret,
                                      passphrase=self.config.api_passphrase,
                                      is_sandbox=False,
                                      url=self.config.base_url)

        self.margin_client = MarginClient(
            key=self.config.api_key,
            secret=self.config.api_secret,
            passphrase=self.config.api_passphrase,
            is_sandbox=False,
            url=self.config.base_url)

    @abstractmethod
    def execute(self, should_execute: bool) -> None:
        ...

    def log(self, message) -> None:
        print(message)
        if self.response_log is not None:
            self.response_log.append(message)

    def get_account_balance(self) -> dict:
        account_response = self.user_client.get_account_list(
            self.config.currency, "main")

        total_balance = Decimal(account_response[0]["balance"])
        available_balance = Decimal(account_response[0]["available"])
        total_accrued_interest = Decimal(0)
        culumative_weighted_interest_rate = Decimal(0)
        culumative_unsettled_size = Decimal(0)

        all_unsettled_orders = self.get_all_unsettled_orders()

        for order in all_unsettled_orders:
            order_total_size = Decimal(order["size"])
            order_remaining_size = order_total_size - Decimal(order["repaid"])
            total_balance += order_remaining_size
            total_accrued_interest += Decimal(order["accruedInterest"])

            order_daily_interest_rate = Decimal(order["dailyIntRate"])
            culumative_weighted_interest_rate += order_remaining_size * order_daily_interest_rate
            culumative_unsettled_size += order_remaining_size

        unrealized_accrued_interest = total_accrued_interest * (
            100 - self.config.lending_fee_rate) / 100

        reserved_balance = self.config.reserved_balance
        if reserved_balance > 0:
            reserved_percentage = utils.round_down_to_decimal_places(
                reserved_balance / total_balance * 100, 2)
            if reserved_percentage > 100:
                reserved_percentage = 100
            self.log(
                f"ReservedBalance=[{reserved_balance}] ReservedPercentage=[{reserved_percentage}%]"
            )
            total_balance -= reserved_balance
            available_balance -= reserved_balance

        if culumative_weighted_interest_rate and culumative_unsettled_size > 0:
            average_daily_interest_rate = culumative_weighted_interest_rate / culumative_unsettled_size * 100
        else:
            average_daily_interest_rate = Decimal(0)

        if culumative_weighted_interest_rate and total_balance > 0:
            effective_daily_interest_rate_on_total_balance = culumative_weighted_interest_rate / total_balance * (
                100 - self.config.lending_fee_rate)
        else:
            effective_daily_interest_rate_on_total_balance = Decimal(0)

        result = {
            "Balance":
            total_balance,
            "Available":
            available_balance,
            "UnrealizedAccruedInterest":
            unrealized_accrued_interest,
            "AverageDailyInterestRate":
            average_daily_interest_rate,
            "EffectiveDailyInterestRateOnTotalBalance":
            effective_daily_interest_rate_on_total_balance,
        }

        return result

    def get_unsettled_orders(self, current_page: int) -> list:
        return self.margin_client.get_active_list(
            currency=self.config.currency,
            currentPage=current_page,
            pageSize=50)

    def get_all_unsettled_orders(self):
        if self.all_unsettled_orders is not None:
            return self.all_unsettled_orders

        self.all_unsettled_orders = list()

        active_order_list_current_page = 1
        while True:
            unsettled_orders_response = self.get_unsettled_orders(
                current_page=active_order_list_current_page)

            if unsettled_orders_response["totalNum"] == 0:
                break

            self.all_unsettled_orders += unsettled_orders_response["items"]

            if unsettled_orders_response[
                    "totalPage"] == active_order_list_current_page:
                break

            active_order_list_current_page += 1

        return self.all_unsettled_orders

    def get_my_active_open_orders(self) -> list:
        active_open_orders_response = self.margin_client.get_active_order(
            currency=self.config.currency)

        if active_open_orders_response["totalNum"] == 0:
            return list()

        result = list()
        for order in active_open_orders_response["items"]:
            order_info = {
                "OrderId":
                order["orderId"],
                "DailyInterestRate":
                Decimal(
                    utils.round_down_to_decimal_places_string(
                        Decimal(order["dailyIntRate"]) * 100, 3)),
                "Size":
                Decimal(order["size"]),
                "FilledSize":
                Decimal(order["filledSize"]),
            }
            result.append(order_info)

        return result

    def get_lending_market_data(self) -> list:
        return self.margin_client.get_lending_market(self.config.currency)

    def create_lend_order(self, daily_interest_rate: Decimal, size: Decimal,
                          term: int) -> None:
        daily_interest_rate_str = utils.round_down_to_decimal_places_string(
            daily_interest_rate / 100, 5)

        try:
            self.margin_client.create_lend_order(self.config.currency,
                                                 str(size),
                                                 daily_interest_rate_str, term)
            effective_daily_interest_rate = self.calculate_effective_daily_interest_rate(
                daily_interest_rate)
            effective_yeary_interest_rate = effective_daily_interest_rate * 365
            self.log(
                f"Created lend order: DailyInterestRate=[{daily_interest_rate}%] Size=[{size}] Term=[{term}] EffectiveDailyInterestRate=[{utils.round_down_to_decimal_places_string(effective_daily_interest_rate, 3)}%] EffectiveYearlyInterestRate=[{utils.round_down_to_decimal_places_string(effective_yeary_interest_rate, 3)}%]"
            )
        except Exception as ex:
            self.log(
                f"Failed to create lend order: DailyInterestRate=[{daily_interest_rate}%] Size=[{size}] Term=[{term}] Error:[{repr(ex)}]"
            )

    def cancel_lend_order(self, order_id: str):
        self.margin_client.cancel_lend_order(order_id)

    def calculate_effective_daily_interest_rate(
            self, daily_interest_rate: Decimal) -> Decimal:
        return daily_interest_rate * (100 - self.config.lending_fee_rate) / 100