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'
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.leverage = config['leverage'] self.size = config['size'] self.depth = config['depth'] self.market = Market(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.tick_size = 0 self.best_ask = 0 self.best_bid = 0 self.diff = 0 self.max_ask = 0 self.max_bid = 0 self.precision = 0 self.ask_list = {} self.bid_list = {}
def get_prices(self): try: client = Market(key=self.api_key, secret=self.api_secret, is_sandbox=self.debug_mode) prices = client.get_all_tickers() return [{"price": item.get("buy"), "symbol": item.get("symbol")} for item in prices.get("ticker")] except Exception as ex: logger.error(ex, exc_info=True) raise Exception(ex) return self.client.get_all_tickers()
def get_symbol_info(self, coin_name, pair_base="BTC"): try: client = Market(key=self.api_key, secret=self.api_secret, is_sandbox=self.debug_mode) info = client.get_currency_detail(currency=coin_name) logger.info(f"currency info: {coin_name} > {self.name}") return info except Exception as ex: logger.error(ex, exc_info=True) raise Exception(ex)
def get_price(self, symbol): try: client = Market(key=self.api_key, secret=self.api_secret, is_sandbox=self.debug_mode) price_info = client.get_ticker(symbol=symbol) logger.info(f"price info: {price_info}") return float(price_info.get("price")) except Exception as ex: logger.error(ex, exc_info=True) raise Exception(ex)
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 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]
class Avg(object): 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' def get_symbol_precision(self): s = self.market.get_symbol_list() sd = {} for item in s: if item.get('symbol') and item.get('symbol') == self.symbol_trade: sd = item return int(1 / Decimal(sd['baseMinSize']))
def returnPrice(symbol): ''' :param symbol: a trading pair ('BTC-USDT',...) :return: the last deal price of a trading pair ''' account = Market.get_ticker(symbol) return account['price']
def returnIncrementSize(symbol): ''' :param symbol: a trading pair ('BTC-USDT',...) :return: The increment of the order size. ''' liste = Market.get_symbol_list() element = list(filter(lambda item: item['symbol'] == symbol, liste)) return Decimal(element[0]['baseIncrement'])
def returnBaseMin(symbol): ''' :param symbol: a trading pair ('BTC-USDT',...) :return: The minimum order quantity required to place an order ''' liste = Market.get_symbol_list() element = list(filter(lambda item: item['symbol'] == symbol, liste)) return element[0]['baseMinSize']
def __init__(self): # read configuration from json file with open(c.CONFIG_FILE, 'r') as file: config = json.load(file) self.api_key = config['kucoin_api_key'] self.secret_key = config['kucoin_secret_key'] self.pass_phrase = config['kucoin_pass_phrase'] self.is_sandbox = config['is_sandbox'] self.kucoin_symbol = config['kucoin_symbol'] self.category = config['category'] self.maker_number = config['maker_number'] self.taker_number = config['taker_number'] self.side = config['side'] self.sizeMin = 100 self.sizeMax = 10000 self.buy_list = {} self.sell_list = {} self.best_ask = 0 self.best_bid = 0 self.market_price = 0 self.trade_sandbox = Trade(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=self.is_sandbox) self.market_sandbox = Market(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=self.is_sandbox) self.trade = Trade(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=False) self.market = Market(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=False)
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
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
import time from threading import Thread from random import seed from random import randint import math from decimal import Decimal seed(2) medianBuy = #upper limit price to execute buying orders medianSell = #lower limit price to execute selling orders # MarketData from kucoin.client import Market client = Market(url='https://api.kucoin.com') #client = Market() # or connect to Sandbox #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
from kucoin.client import Market from kucoin.client import Trade # Sandbox Market client = Market(url='https://openapi-sandbox.kucoin.com') # Sandbox Trade client = Trade(api_key, api_secret, api_passphrase, is_sandbox=True) time = client.get_timestamp() print(time)
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)
class Kucoin(object): def __init__(self): # read configuration from json file with open(c.CONFIG_FILE, 'r') as file: config = json.load(file) self.api_key = config['kucoin_api_key'] self.secret_key = config['kucoin_secret_key'] self.pass_phrase = config['kucoin_pass_phrase'] self.is_sandbox = config['is_sandbox'] self.kucoin_symbol = config['kucoin_symbol'] self.category = config['category'] self.maker_number = config['maker_number'] self.taker_number = config['taker_number'] self.side = config['side'] self.sizeMin = 100 self.sizeMax = 10000 self.buy_list = {} self.sell_list = {} self.best_ask = 0 self.best_bid = 0 self.market_price = 0 self.trade_sandbox = Trade(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=self.is_sandbox) self.market_sandbox = Market(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=self.is_sandbox) self.trade = Trade(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=False) self.market = Market(self.api_key, self.secret_key, self.pass_phrase, is_sandbox=False) def get_market_price(self): r = {} # 根据类型调用对应的合约API try: if self.category == c.BTC_USDT: r = self.market.get_ticker(self.kucoin_symbol) elif self.category == c.ETH_USDT: r = self.market.get_ticker(self.kucoin_symbol) elif self.category == c.ETH_BTC: r = self.market.get_ticker(self.kucoin_symbol) except Exception as e: logging.error(e) time.sleep(5) self.best_ask = int(float(r['bestAsk'])) self.best_bid = int(float(r['bestBid'])) self.market_price = int((self.best_ask + self.best_bid) / 2) logging.info('最新盘口价格 = %s' % self.market_price) def taker(self): try: t = self.market_sandbox.get_ticker(self.kucoin_symbol) logging.info(t) best_bid_size = t['bestBidSize'] best_ask_size = t['bestAskSize'] max_size = 100000 if best_bid_size > max_size: best_bid_size = max_size if best_ask_size > max_size: best_ask_size = max_size if best_ask_size > 0: try: sell = self.trade_sandbox.create_market_order( self.kucoin_symbol, 'sell', size=best_ask_size, type='market') logging.info( '在交易对 %s 以数量= %s, 吃卖单,订单ID = %s' % (self.kucoin_symbol, best_ask_size, sell['orderId'])) except Exception as e: logging.error(e) if best_bid_size > 0: try: buy = self.trade_sandbox.create_market_order( self.kucoin_symbol, 'buy', size=best_bid_size, type='market') logging.info( '在交易对 %s 以数量= %s, 吃买单,订单ID = %s' % (self.kucoin_symbol, best_bid_size, buy['orderId'])) except Exception as e: logging.error(e) except Exception as e: logging.error(e) return def ask_maker(self, p): try: m = random.randint(self.sizeMin, self.sizeMax) ask = self.trade_sandbox.create_limit_order( self.kucoin_symbol, 'sell', m, p) logging.info( '当前盘口价格 = %s,在交易对 %s 以数量= %s,价格= %s,创建了卖单,卖单ID = %s' % (self.market_price, self.kucoin_symbol, m, p, ask['orderId'])) self.sell_list[p] = { 'price': p, 'side': 'sell', 'size': m, 'order_id': ask['orderId'] } except Exception as e: logging.error(e) def bid_maker(self, p): try: m = random.randint(self.sizeMin, self.sizeMax) bid = self.trade_sandbox.create_limit_order( self.kucoin_symbol, 'buy', m, p) logging.info( '当前盘口价格 = %s,在交易对 %s 以数量= %s,价格= %s,创建了买单,卖单ID = %s' % (self.market_price, self.kucoin_symbol, m, p, bid['orderId'])) self.sell_list[p] = { 'price': p, 'side': 'buy', 'size': m, 'order_id': bid['orderId'] } except Exception as e: logging.error(e) def cancel_order(self, order_id, key, side): try: self.trade_sandbox.cancel_order(order_id) logging.info('当前盘口价 = %s,撤单 id = %s, key = %s' % (self.market_price, order_id, key)) if side == 'sell': del self.sell_list[key] elif side == 'buy': del self.buy_list[key] except Exception as e: logging.info('撤单时发生错误, order_id = %s, key = %s' % (order_id, key)) logging.error(e) def get_order_info(self, order_id): try: o = self.trade_sandbox.get_order_details(order_id) except Exception as e: logging.error(e) o = {} return o def get_active_orders(self): try: o = self.trade_sandbox.get_order_list(symbol=self.kucoin_symbol, status='active', type='limit') os = o['items'] except Exception as e: logging.error(e) os = [] if len(os) > 0: self.sell_list.clear() self.buy_list.clear() for n in os: # print(json.dumps(n)) if n['side'] == 'sell': self.sell_list[int(n['price'])] = { 'price': int(n['price']), 'side': 'sell', 'size': n['size'], 'order_id': n['id'] } elif n['side'] == 'buy': self.buy_list[int(n['price'])] = { 'price': int(n['price']), 'side': 'buy', 'size': n['size'], 'order_id': n['id'] }
def __init__(self, key='', secret='', passphrase='') -> None: self.user = User(key, secret, passphrase) self.client = Market() pass
from kucoin.client import Market, User from typing import Dict, List client = Market() 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
btc3l_acc = '' asset = 'BTC' fiat = 'USDT' import time import numpy as np import pandas as pd import datetime as DT print('----TIME-------------PRICE--RSI---STRATEGY') while True: try: from kucoin.client import Market client = Market(api_key, api_secret, api_passphrase, url='https://api.kucoin.com') price = client.get_ticker(asset+'-'+fiat) price = price['price'] orders = client.get_aggregated_orderv3(asset+'-'+fiat) klines = client.get_kline(asset+'-'+fiat, '1min') server_time = time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(client.get_server_timestamp()/1000.)) from kucoin.client import User client = User(api_key, api_secret, api_passphrase) fiat_balance = client.get_account('612a5bd4fdacf4000769936e') fiat_balance = fiat_balance['available'] coin_balance = client.get_account(kcs_acc) coin_balance = coin_balance['available']
c.execute( "INSERT INTO Orders VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ("Kucoin", order['clientOid'], order_id, order['id'], order['symbol'], order['type'], order['side'], order['timeInForce'], order['createdAt'], symbol, price, order['fee'], order['size'], order['dealFunds'])) conn.commit() 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
c.execute("INSERT INTO Orders VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ("Kucoin", order['clientOrderId'], order['orderId'], order['fills'][0]['tradeId'], order['symbol'], order['type'], order['side'], order['timeInForce'], 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']
class Grid(object): 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.leverage = config['leverage'] self.size = config['size'] self.depth = config['depth'] self.market = Market(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.tick_size = 0 self.best_ask = 0 self.best_bid = 0 self.diff = 0 self.max_ask = 0 self.max_bid = 0 self.precision = 0 self.ask_list = {} self.bid_list = {} def get_symbol(self): symbols = self.market.get_symbol_list() ks = {} for s in symbols: if s.get('symbol') and s.get('symbol') == self.symbol: ks = s if ks: self.tick_size = Decimal(ks['priceIncrement']) self.diff = Decimal(self.tick_size * self.depth) self.precision = int(1 / Decimal(ks['baseIncrement'])) logging.debug('tick_size = %s, precision = %s', self.tick_size, self.precision) def get_market_price(self): try: r = self.market.get_ticker(self.symbol) if 'bestAsk' in r.keys(): self.best_ask = Decimal(r['bestAsk']) self.max_ask = Decimal(self.best_ask + self.diff).quantize( Decimal("0.00")) else: return if 'bestBid' in r.keys(): self.best_bid = Decimal(r['bestBid']) self.max_bid = Decimal(self.best_bid - self.diff).quantize( Decimal("0.00")) else: return logging.debug('最新卖价格 = %s' % self.best_ask) logging.debug('最新买价格 = %s' % self.best_bid) except Exception as e: logging.error(e) time.sleep(5) def cancel_order(self, order_id, side): try: oi = self.trade.get_order_details(order_id) if oi['isActive']: self.trade.cancel_order(order_id) if side == 'sell': del self.ask_list[order_id] elif side == 'buy': del self.bid_list[order_id] except Exception as e: logging.error('该订单状态不可撤回 side = %s, order_id = %s' % (side, order_id)) logging.error(e) def ask_maker(self, p): try: price = int(p * 100) / 100 ask = self.trade.create_limit_order(self.symbol, 'sell', self.size, float(price)) logging.debug( '当前盘口价格 = %s,在交易对 %s 以数量= %s,价格= %s,创建了卖单,卖单ID = %s' % (self.best_ask, self.symbol, self.size, float(price), ask['orderId'])) self.ask_list[ask['orderId']] = {'price': p} except Exception as e: logging.error(e) def bid_maker(self, p): try: price = int(p * 100) / 100 bid = self.trade.create_limit_order(self.symbol, 'buy', self.size, float(price)) logging.debug( '当前盘口价格 = %s,在交易对 %s 以数量= %s,价格= %s,创建了买单,卖单ID = %s' % (self.best_ask, self.symbol, self.size, float(price), bid['orderId'])) self.bid_list[bid['orderId']] = {'price': p} except Exception as e: logging.error(e)