def huobi_usdt_price(coin_type): API_KEY = 'd0ece565-9908ceb4-3a1fae05-7a813' API_SECRET = 'ebd261e6-222d8e94-f058cd95-1524c' client = ApiClient(API_KEY, API_SECRET) trade = client.get('/market/trade', symbol=coin_type + 'usdt') return trade['tick']['data'][0]['price']
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ .. moduleauthor:: Gabriel Martin Becedillas Ruiz <*****@*****.**> """ from liveUtils import * from hbsdk import ApiClient, ApiError client = ApiClient('API_KEY', 'API_SECRET') def getKLineBar(identifier, endTimestamp, period, length = 1): print('-------getKLine:%s %s %s %s'%(identifier, endTimestamp, period, length)) length = length + 1 if length < 2000 else 2000 klines = client.mget('/market/history/kline', symbol=identifier.getSymbol(), period='%dmin'%period, size=length) if len(klines) != length: return None if timestamp() - endTimestamp > period*60+30 and length < 100: del klines[1] else: del klines[0] x = klines[0] f = timestamp_to_DateTimeLocal print('cur: %s recv: %s ecpect: %s'%(f(timestamp()), f(x.id), f(endTimestamp)))
import pandas as pd import json import time from hbsdk import ApiClient, ApiError API_KEY = "API_KEY" API_SECRET = "API_SECRET" SYMBOL = 'btcusdt' PREIOD = 60 client = ApiClient(API_KEY, API_SECRET) history = client.mget('/market/history/kline', symbol=SYMBOL, period='%dmin' % PREIOD, size=2000) print(len(history)) def dtf(x): time_local = time.localtime(x) return time.strftime("%Y-%m-%d %H:%M:%S", time_local) def rf(x): return [dtf(x.id), x.open, x.high, x.low, x.close, x.vol, x.close] def redf(x, y): return x + [rf(y)]
from liveApi.liveUtils import * from hbsdk import ApiClient, ApiError from ApiKey import API_KEY from ApiKey import API_SECRET client = ApiClient(API_KEY, API_SECRET) oid = 840419149 orderInfo = client.get('/v1/order/orders/%s' % oid) print orderInfo
def main(): client = ApiClient(API_KEY, API_SECRET) # get symbol: symbols = client.get('/v1/common/symbols') print(symbols) # get user info: userinfo = client.get('/v1/users/user') print(userinfo) # get all accounts: accs = client.get('/v1/account/accounts') print(accs) account_id = accs[0].id for acc in accs: subaccs = client.get('/v1/account/accounts/%s/balance' % acc.id) print(subaccs) time.sleep(2.0) # create order: order_id = client.post('/v1/order/orders', { 'account-id': account_id, 'amount': '0.02', 'price': '1020.21', 'symbol': 'ethcny', 'type': 'buy-limit', 'source': 'api' }) print(order_id) # place order: client.post('/v1/order/orders/%s/place' % order_id) # get order details: order_info = client.get('/v1/order/orders/%s' % order_id) print(order_info) # cancel order: client.post('/v1/order/orders/%s/submitcancel' % order_id) # query order details: time.sleep(5.0) order_info = client.get('/v1/order/orders/%s' % order_id) print(order_info)
def __init__(self, instrument): self.__coinType = instrument self.__client = ApiClient(API_KEY, API_SECRET) self.__accountid = self.getAccountId()
class hbTradeClient(TradeClientBase): def __init__(self, instrument): self.__coinType = instrument self.__client = ApiClient(API_KEY, API_SECRET) self.__accountid = self.getAccountId() @tryForever def getAccountId(self): accs = self.__client.get('/v1/account/accounts') for x in accs: if x.type == 'spot' and x.state == 'working': return x.id raise Exception('no active account ID!') # -- #@exceDebug def getAccountBalance(self): balances = self.__client.get('/v1/account/accounts/%s/balance' % self.__accountid) acc = hbAccountBalance(self.__coinType, balances) return hbTradeAccountBalance({ 'usdt': acc.getCash(), 'coin': acc.getCoin() }) # -- #@exceDebug def getOpenOrders(self): print('--getOpenOrders:') return [] ''' return [hbTradeOrder({ 'id': ID(), 'isBuy' : True, 'price' : 13990.99, 'amount' : 1.1234, 'time' : datetime.datetime.utcnow(), })] ''' # -- #@exceDebug def cancelOrder(self, orderId): print('--cancelOrder:%s' % orderId) self.__client.post('/v1/order/orders/%s/submitcancel' % orderId) self.checkOrderState( orderId, [hbOrderState.OrderCanceled, hbOrderState.OrderFilled]) # -- #@exceDebug def buyLimit(self, limitPrice, quantity): print('--buyLimit:%s %s' % (limitPrice, quantity)) orderInfo = self.postOrder(limitPrice, quantity, hbOrderType.BuyLimit) return hbTradeOrder(orderInfo) # -- #@exceDebug def sellLimit(self, limitPrice, quantity): print('--sellLimit:%s %s' % (limitPrice, quantity)) orderInfo = self.postOrder(limitPrice, quantity, hbOrderType.SellLimit) return hbTradeOrder(orderInfo) # -- #@exceDebug def getUserTransactions(self, ordersId): if len(ordersId): print('--getUserTransactions:%s' % ordersId) ret = [] for oid in ordersId: orderInfo = self.__client.get('/v1/order/orders/%s' % oid) ret.append(hbTradeUserTransaction(orderInfo)) return ret def postOrder(self, limitPrice, quantity, orderType): price = str(PriceRound(limitPrice)) amount = str(CoinRound(quantity)) order_id = self.__client.post( '/v1/order/orders', { 'account-id': self.__accountid, 'amount': amount, 'price': price, 'symbol': self.__coinType.getSymbol(), 'type': orderType, 'source': 'api' }) self.activeOrder(order_id) orderInfo = self.checkOrderState( order_id, [hbOrderState.OrderSubmited, hbOrderState.OrderFilled]) return orderInfo @tryForever def checkOrderState(self, orderid, states): orderInfo = self.__client.get('/v1/order/orders/%s' % orderid) if orderInfo.state in states: return orderInfo raise Exception('wait state:%s => %s' % (orderInfo.state, states)) @tryForever def activeOrder(self, orderid): return self.__client.post('/v1/order/orders/%s/place' % orderid)
import pandas as pd import time import config from hbsdk import ApiClient API_KEY = "API_KEY" API_SECRET = "API_SECRET" headList=["Date Time","Open","High","Low","Close","Volume","Adj Close"] client = ApiClient(API_KEY, API_SECRET) file_path = "2000.csv" # load history of k-line def load_kline(period = config.DEFAULT_PREIOD, symbol = config.DEFAULT_PREIOD): print "start load data, symbol:%s, period: %s minutes" % (symbol, period) history = client.mget('/market/history/kline', symbol=symbol, period='%dmin' % period, size=2000) print "total raw data count: %d" % len(history) jdict= reduce(redf, history, []) print "total data of reduce count: %d" % len(history) df = pd.DataFrame.from_dict(jdict) df.to_csv(generate_file_path(period, symbol), index=False, header=headList) def dtf(x): time_local = time.localtime(x) return time.strftime("%Y-%m-%d %H:%M:%S",time_local) def rf(x): return [dtf(x.id), x.open, x.high, x.low, x.close, x.vol, x.close]
def __init__(self): self.__client = ApiClient(API_KEY, API_SECRET) self.__accountid = self.getAccountId()
class hbTradeClient(TradeClientBase): def __init__(self): self.__client = ApiClient(API_KEY, API_SECRET) self.__accountid = self.getAccountId() def getClient(self): return self.__client @tryForever def getAccountId(self): accs = self.__client.get('/v1/account/accounts') for x in accs: if x.type == 'spot' and x.state == 'working': return x.id raise Exception('no active account ID!') @tryForever def getAccountBalance(self, coinType): balances = self.__client.get('/v1/account/accounts/%s/balance' % self.__accountid) return hbAccountBalance(balances) @tryForever def cancelOrder(self, orderId): logger.info('cancelOrder:%s'%orderId) try: self.__client.post('/v1/order/orders/%s/submitcancel' % orderId) except: self.__checkOrderState(orderId, [hbOrderState.OrderCanceled, hbOrderState.OrderFilled]) def buyLimit(self, symbol, limitPrice, quantity): logger.info('buyLimit: %s %s %s'%(symbol, limitPrice, quantity)) orderInfo = self.__postOrder(symbol, limitPrice, quantity, hbOrderType.BuyLimit) return hbTradeOrder(orderInfo) def sellLimit(self, symbol, limitPrice, quantity): logger.info('sellLimit: %s %s %s'%(symbol, limitPrice, quantity)) orderInfo = self.__postOrder(symbol, limitPrice, quantity, hbOrderType.SellLimit) return hbTradeOrder(orderInfo) @tryForever def getUserTransactions(self, ordersId): if len(ordersId): logger.info('getUserTransactions:%s'%ordersId) ret = [] for oid in ordersId: orderInfo = self.__client.get('/v1/order/orders/%s' % oid) ret.append(hbTradeUserTransaction(orderInfo)) return ret @tryForever def __postOrder(self, symbol, limitPrice, quantity, orderType): order_id = self.__client.post('/v1/order/orders', { 'account-id': self.__accountid, 'amount': quantity, 'price': limitPrice, 'symbol': symbol, 'type': orderType, 'source': 'api' }) self.__activeOrder(order_id) while True: try: orderInfo = self.__checkOrderState(order_id, [hbOrderState.OrderSubmited, hbOrderState.OrderFilled]) break except: continue return orderInfo def __checkOrderState(self, orderid, states): orderInfo = self.__client.get('/v1/order/orders/%s' % orderid) if orderInfo.state in states: return orderInfo raise Exception('wait state:%s => %s'%(orderInfo.state, states)) @tryForever def __activeOrder(self, orderid): return self.__client.post('/v1/order/orders/%s/place' % orderid) def getMinAmount(self, symbol, minAmount): order_id = self.__client.post('/v1/order/orders', { 'account-id': self.__accountid, 'amount': minAmount, 'price': 1, 'symbol': symbol, 'type': hbOrderType.BuyLimit, 'source': 'api' })