Exemplo n.º 1
0
 async def withdraw(self, code, amount, address, tag=None, params={}):
     self.check_address(address)
     await self.load_markets()
     currency = self.currency(code)
     request = {
         'units': amount,
         'address': address,
         'currency': currency['id'],
     }
     if currency == 'XRP' or currency == 'XMR' or currency == 'EOS' or currency == 'STEEM':
         destination = self.safe_string(params, 'destination')
         if (tag is None) and (destination is None):
             raise ArgumentsRequired(
                 self.id + ' ' + code +
                 ' withdraw() requires a tag argument or an extra destination param'
             )
         elif tag is not None:
             request['destination'] = tag
     response = await self.privatePostTradeBtcWithdrawal(
         self.extend(request, params))
     return {
         'info': response,
         'id': None,
     }
Exemplo n.º 2
0
Arquivo: zb.py Projeto: priest671/ccxt
 async def fetch_orders(self, symbol=None, since=None, limit=50, params={}):
     if symbol is None:
         raise ArgumentsRequired(self.id +
                                 'fetchOrders() requires a symbol argument')
     await self.load_markets()
     market = self.market(symbol)
     request = {
         'currency': market['id'],
         'pageIndex': 1,  # default pageIndex is 1
         'pageSize': limit,  # default pageSize is 50
     }
     method = 'privateGetGetOrdersIgnoreTradeType'
     # tradeType 交易类型1/0[buy/sell]
     if 'tradeType' in params:
         method = 'privateGetGetOrdersNew'
     response = None
     try:
         response = await getattr(self,
                                  method)(self.extend(request, params))
     except Exception as e:
         if isinstance(e, OrderNotFound):
             return []
         raise e
     return self.parse_orders(response, market, since, limit)
Exemplo n.º 3
0
Arquivo: gdax.py Projeto: tameur/ccxt
 async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
     await self.load_markets()
     if code is None:
         raise ArgumentsRequired(self.id + ' fetchTransactions() requires a currency code argument')
     currency = self.currency(code)
     accountId = None
     accounts = await self.privateGetAccounts()
     for i in range(0, len(accounts)):
         account = accounts[i]
         # todo: use unified common currencies below
         if account['currency'] == currency['id']:
             accountId = account['id']
             break
     if accountId is None:
         raise ExchangeError(self.id + ' fetchTransactions() could not find account id for ' + code)
     request = {
         'id': accountId,
     }
     if limit is not None:
         request['limit'] = limit
     response = await self.privateGetAccountsIdTransfers(self.extend(request, params))
     for i in range(0, len(response)):
         response[i]['currency'] = code
     return self.parseTransactions(response)
Exemplo n.º 4
0
 def withdraw(self, code, amount, address, tag=None, params={}):
     self.check_address(address)
     self.load_markets()
     currency = self.currency(code)
     commission = self.safe_value(params, 'commission')
     if commission is None:
         raise ArgumentsRequired(
             self.id +
             ' withdraw() requires a `commission`(withdrawal fee) parameter(string)'
         )
     params = self.omit(params, commission)
     request = {
         'currency': currency['id'],
         'amount': float(amount),
         'address': address,
         'commission': commission,
     }
     if tag is not None:
         request['address'] += ':' + tag
     response = self.dwapiPostWithdrawCrypto(self.extend(request, params))
     #
     #     [
     #         {
     #             "success": 1,
     #             "return": {
     #                 "transactionId": 2863073
     #             }
     #         }
     #     ]
     #
     data = self.safe_value(response, 'return', {})
     id = self.safe_string(data, 'transactionId')
     return {
         'info': response,
         'id': id,
     }
Exemplo n.º 5
0
 async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
     ids = self.safe_string(params, 'ids')
     if (symbol is None) or (ids is None):
         raise ArgumentsRequired(self.id + " fetchOrders requires a 'symbol' argument and an extra 'ids' parameter. The 'ids' should be an array or a string of one or more order ids separated with slashes.")  # eslint-disable-line quotes
     if isinstance(ids, list):
         ids = '/'.join(ids)
     await self.load_markets()
     market = self.market(symbol)
     request = {
         'trading_pair': market['id'],
         'ids': ids,
     }
     response = await self.traderGetHistoryTradingPairIds(self.extend(request, params))
     #
     # response = {
     #         "status": {
     #             "success": 1,
     #             "message": null
     #         },
     #         "result": [
     #             {
     #                 "trading_pair": "ETPCNY",
     #                 "status": "TRADE",
     #                 "fee": 0.23,
     #                 "min_fee": 10000000,
     #                 "created_at": "2017-05-25T00:12:27.000Z",
     #                 "cost": 1152468000000,
     #                 "limit": 3600000000,
     #                 "id": 11060,
     #                 "quantity": 32013000000,
     #                 "filled_quantity": 32013000000
     #             }
     #         ]
     #     }
     #
     return self.parse_orders(response['result'], None, since, limit)
Exemplo n.º 6
0
 def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
     if symbol is None:
         raise ArgumentsRequired(
             self.id + ' fetchMyTrades requires a symbol argument')
     self.load_markets()
     market = self.market(symbol)
     # limit is required, must be in the range(0, 50)
     maxLimit = 50
     limit = maxLimit if (limit is None) else min(limit, maxLimit)
     request = {
         'symbol': market['id'],
         'offset': 0,  # current page, starts from 0
         'limit': limit,  # required
     }
     response = self.privateGetTrades(self.extend(request, params))
     #
     #     {
     #         "total_trades": 216,
     #         "total_pages": 22,
     #         "current_page": 0,
     #         "trades": [
     #             {
     #                 "symbol": "BMX_ETH",
     #                 "amount": "1.0",
     #                 "fees": "0.0005000000",
     #                 "trade_id": 2734956,
     #                 "price": "0.00013737",
     #                 "active": True,
     #                 "entrust_id": 5576623,
     #                 "timestamp": 1545292334000
     #             },
     #         ]
     #     }
     #
     trades = self.safe_value(response, 'trades', [])
     return self.parse_trades(trades, market, since, limit)
Exemplo n.º 7
0
 def fetch_ticker(self, symbol, params={}):
     apiKey = self.safe_value(params, 'apiKey', self.apiKey)
     if not apiKey:
         raise ArgumentsRequired(self.id + ' fetchTicker is a private v2 endpoint that requires an `exchange.apiKey` credential or an `apiKey` extra parameter')
     self.load_markets()
     market = self.market(symbol)
     # reversed base/quote in v2
     marketId = market['quoteId'] + '_' + market['baseId']
     request = {
         'symbol': marketId,
         'apiKey': apiKey,
     }
     response = self.v2GetTicker(self.extend(request, params))
     #
     #     {
     #         "ticker":{
     #             "btc_eth":{
     #                 "last":0.021957,
     #                 "base_vol":2249.3521732227,
     #                 "change":-0.6,
     #                 "vol":102443.5111,
     #                 "sell":0.021978,
     #                 "low":0.021791,
     #                 "buy":0.021946,
     #                 "high":0.022266
     #             }
     #         },
     #         "date":1564518452,
     #         "code":0
     #     }
     #
     date = self.safe_integer(response, 'date')
     ticker = self.safe_value(response, 'ticker', {})
     result = self.safe_value(ticker, marketId, {})
     result = self.extend({'date': date}, result)
     return self.parse_ticker(result, market)
Exemplo n.º 8
0
 def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
     if symbol is None:
         raise ArgumentsRequired(
             self.id + ' fetchMyTrades requires a symbol argument')
     self.load_markets()
     market = self.market(symbol)
     size = limit if (limit) else 200
     response = self.privatePostOrderpending({
         'cmd':
         'orderpending/orderHistoryList',
         'body':
         self.extend(
             {
                 'pair': market['id'],
                 'account_type': 0,  # 0 - regular, 1 - margin
                 'page': 1,
                 'size': size,
                 'coin_symbol': market['baseId'],
                 'currency_symbol': market['quoteId'],
             },
             params),
     })
     trades = self.safe_value(response['result'], 'items', [])
     return self.parse_trades(trades, market, since, limit)
Exemplo n.º 9
0
 async def fetch_my_trades(self,
                           symbol=None,
                           since=None,
                           limit=None,
                           params={}):
     # todo: self method is deprecated and to be deleted shortly
     # it improperly mimics fetchMyTrades with closed orders
     # kucoin does not have any means of fetching personal trades at all
     # self will effectively simplify current convoluted implementations of parseOrder and parseTrade
     if symbol is None:
         raise ArgumentsRequired(
             self.id +
             ' fetchMyTrades is deprecated and requires a symbol argument')
     await self.load_markets()
     market = self.market(symbol)
     request = {
         'symbol': market['id'],
     }
     if limit is not None:
         request['limit'] = limit
     response = await self.privateGetDealOrders(self.extend(
         request, params))
     return self.parse_trades(response['data']['datas'], market, since,
                              limit)
Exemplo n.º 10
0
 async def cancel_order(self, id, symbol=None, params={}):
     if symbol is None:
         raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
     await self.load_markets()
     market = self.market(symbol)
     request = {
         'coin_pair': market['id'],
         'order_id': id,
     }
     response = await self.privatePostCancelOrder(self.extend(request, params))
     #
     #     {
     #         response_data: {
     #             order: {
     #                 order_id: 2176769,
     #                 coin_pair: 'BRLBCH',
     #                 order_type: 2,
     #                 status: 3,
     #                 has_fills: False,
     #                 quantity: '0.10000000',
     #                 limit_price: '1996.15999',
     #                 executed_quantity: '0.00000000',
     #                 executed_price_avg: '0.00000',
     #                 fee: '0.00000000',
     #                 created_timestamp: '1536956488',
     #                 updated_timestamp: '1536956499',
     #                 operations: []
     #             }
     #         },
     #         status_code: 100,
     #         server_unix_timestamp: '1536956499'
     #     }
     #
     responseData = self.safe_value(response, 'response_data', {})
     order = self.safe_value(responseData, 'order', {})
     return self.parse_order(order, market)
Exemplo n.º 11
0
 async def fetch_order(self, id, symbol=None, params={}):
     if symbol is None:
         raise ArgumentsRequired(self.id + ' fetchOrder requires a `symbol` argument')
     await self.load_markets()
     request = {
         'symbol': self.market_id(symbol),
         'trust_id': id,
     }
     response = await self.privatePostApiOrderOrderInfo(self.extend(request, params))
     order = self.safe_value(response, 'data')
     timestamp = self.safe_timestamp(order, 'created')
     status = self.parse_order_status(self.safe_string(order, 'status'))
     side = self.safe_string(order, 'flag')
     if side == 'sale':
         side = 'sell'
     # Can't use parseOrder because the data format is different btw endpoint for fetchOrder and fetchOrders
     return {
         'info': order,
         'id': id,
         'timestamp': timestamp,
         'datetime': self.iso8601(timestamp),
         'lastTradeTimestamp': None,
         'symbol': symbol,
         'type': None,
         'side': side,
         'price': self.safe_float(order, 'price'),
         'cost': None,
         'average': self.safe_float(order, 'avg_price'),
         'amount': self.safe_float(order, 'number'),
         'filled': self.safe_float(order, 'numberdeal'),
         'remaining': self.safe_float(order, 'numberover'),
         'status': status,
         'fee': None,
         'clientOrderId': None,
         'trades': None,
     }
Exemplo n.º 12
0
 async def fetch_orders(self,
                        symbol=None,
                        since=None,
                        limit=None,
                        params={}):
     if 'fetchOrdersRequiresSymbol' in self.options:
         if self.options['fetchOrdersRequiresSymbol']:
             if symbol is None:
                 raise ArgumentsRequired(
                     self.id + ' fetchOrders requires a `symbol` argument')
     await self.load_markets()
     request = {}
     market = None
     if symbol is not None:
         market = self.market(symbol)
         request['pair'] = market['id']
     response = await self.privatePostActiveOrders(
         self.extend(request, params))
     # it can only return 'open' orders(i.e. no way to fetch 'closed' orders)
     orders = self.safe_value(response, 'return', [])
     openOrders = self.parse_orders(orders, market)
     allOrders = self.update_cached_orders(openOrders, symbol)
     result = self.filter_by_symbol(allOrders, symbol)
     return self.filter_by_since_limit(result, since, limit)
Exemplo n.º 13
0
 async def fetch_withdrawals(self,
                             code=None,
                             since=None,
                             limit=None,
                             params={}):
     if code is None:
         raise ArgumentsRequired(
             self.id + ' fetchWithdrawals() requires a code argument')
     if limit is None or limit > 100:
         limit = 100
     await self.load_markets()
     currency = self.currency(code)
     request = {
         'currency': currency['id'],
         'type': 'withdraw',
         'from':
         0,  # From 'id' ... if you want to get results after a particular transaction id, pass the id in params.from
     }
     if limit is not None:
         request['size'] = limit  # max 100
     response = await self.privateGetQueryDepositWithdraw(
         self.extend(request, params))
     # return response
     return self.parseTransactions(response['data'], currency, since, limit)
Exemplo n.º 14
0
 async def fetch_ledger(self, code=None, since=None, limit=None, params={}):
     await self.load_markets()
     await self.load_accounts()
     currency = None
     id = self.safe_string(params, 'id')  # account id
     min_row = self.safe_value(params, 'min_row')
     max_row = self.safe_value(params, 'max_row')
     if id is None:
         if code is None:
             raise ArgumentsRequired(self.id + ' fetchLedger() requires a currency code argument if no account id specified in params')
         currency = self.currency(code)
         accountsByCurrencyCode = self.index_by(self.accounts, 'currency')
         account = self.safe_value(accountsByCurrencyCode, code)
         if account is None:
             raise ExchangeError(self.id + ' fetchLedger() could not find account id for ' + code)
         id = account['id']
     if min_row is None and max_row is None:
         max_row = 0  # Default to most recent transactions
         min_row = -1000  # Maximum number of records supported
     elif min_row is None or max_row is None:
         raise ExchangeError(self.id + " fetchLedger() require both params 'max_row' and 'min_row' or neither to be defined")
     if limit is not None and max_row - min_row > limit:
         if max_row <= 0:
             min_row = max_row - limit
         elif min_row > 0:
             max_row = min_row + limit
     if max_row - min_row > 1000:
         raise ExchangeError(self.id + " fetchLedger() requires the params 'max_row' - 'min_row' <= 1000")
     request = {
         'id': id,
         'min_row': min_row,
         'max_row': max_row,
     }
     response = await self.privateGetAccountsIdTransactions(self.extend(params, request))
     entries = self.safe_value(response, 'transactions', [])
     return self.parse_ledger(entries, currency, since, limit)
Exemplo n.º 15
0
Arquivo: zb.py Projeto: yogch/ccxt
 async def fetch_order(self, id, symbol=None, params={}):
     if symbol is None:
         raise ArgumentsRequired(self.id +
                                 ' fetchOrder() requires a symbol argument')
     await self.load_markets()
     request = {
         'id': str(id),
         'currency': self.market_id(symbol),
     }
     response = await self.privateGetGetOrder(self.extend(request, params))
     #
     #     {
     #         'total_amount': 0.01,
     #         'id': '20180910244276459',
     #         'price': 180.0,
     #         'trade_date': 1536576744960,
     #         'status': 2,
     #         'trade_money': '1.96742',
     #         'trade_amount': 0.01,
     #         'type': 0,
     #         'currency': 'eth_usdt'
     #     }
     #
     return self.parse_order(response, None)
 def fetch_balance(self, params={}):
     self.load_markets()
     market = None
     query = params
     symbol = self.safe_string(params, 'symbol')
     if symbol is not None:
         market = self.market(params['symbol'])
         query = self.omit(params, 'symbol')
     marketId = self.safe_string(params, 'id')
     if marketId in self.markets_by_id:
         market = self.markets_by_id[marketId]
     if market is None:
         raise ArgumentsRequired(self.id + ' fetchBalance requires a symbol param')
     request = {
         'id': market['id'],
     }
     response = self.privatePostIdBalance(self.extend(request, query))
     result = {
         'info': response,
     }
     # base/quote used for keys e.g. "xbt_reserved"
     base = market['base']
     quote = market['quote']
     baseIdLower = self.safe_string_lower(market, 'baseId')
     quoteIdLower = self.safe_string_lower(market, 'quoteId')
     result[base] = {
         'free': self.safe_float(response, baseIdLower + '_available'),
         'used': self.safe_float(response, baseIdLower + '_reserved'),
         'total': self.safe_float(response, baseIdLower + '_balance'),
     }
     result[quote] = {
         'free': self.safe_float(response, quoteIdLower + '_available'),
         'used': self.safe_float(response, quoteIdLower + '_reserved'),
         'total': self.safe_float(response, quoteIdLower + '_balance'),
     }
     return self.parse_balance(result)
Exemplo n.º 17
0
 def create_order(self, symbol, type, side, amount, price=None, params={}):
     self.load_markets()
     market = self.market(symbol)
     request = {
         'marketId': market['id'],
         # 'price': self.price_to_precision(symbol, price),
         'amount': self.amount_to_precision(symbol, amount),
         # 'type': 'Limit',  # "Limit", "Market", "Stop Limit", "Stop", "Take Profit"
         'side': 'Bid' if (side == 'buy') else 'Ask',
         # 'triggerPrice': self.price_to_precision(symbol, triggerPrice),  # required for Stop, Stop Limit, Take Profit orders
         # 'targetAmount': self.amount_to_precision(symbol, targetAmount),  # target amount when a desired target outcome is required for order execution
         # 'timeInForce': 'GTC',  # GTC, FOK, IOC
         # 'postOnly': False,  # boolean if self is a post-only order
         # 'selfTrade': 'A',  # A = allow, P = prevent
         # 'clientOrderId': self.uuid(),
     }
     lowercaseType = type.lower()
     orderTypes = self.safe_value(
         self.options, 'orderTypes', {
             'limit': 'Limit',
             'market': 'Market',
             'stop': 'Stop',
             'stop limit': 'Stop Limit',
             'take profit': 'Take Profit',
         })
     request['type'] = self.safe_string(orderTypes, lowercaseType, type)
     priceIsRequired = False
     triggerPriceIsRequired = False
     if lowercaseType == 'limit':
         priceIsRequired = True
     # elif lowercaseType == 'market':
     #     ...
     # }
     elif lowercaseType == 'stop limit':
         triggerPriceIsRequired = True
         priceIsRequired = True
     elif lowercaseType == 'take profit':
         triggerPriceIsRequired = True
     elif lowercaseType == 'stop':
         triggerPriceIsRequired = True
     if priceIsRequired:
         if price is None:
             raise ArgumentsRequired(
                 self.id +
                 ' createOrder() requires a price argument for a ' + type +
                 'order')
         else:
             request['price'] = self.price_to_precision(symbol, price)
     if triggerPriceIsRequired:
         triggerPrice = self.safe_float(params, 'triggerPrice')
         params = self.omit(params, 'triggerPrice')
         if triggerPrice is None:
             raise ArgumentsRequired(
                 self.id +
                 ' createOrder() requires a triggerPrice parameter for a ' +
                 type + 'order')
         else:
             request['triggerPrice'] = self.price_to_precision(
                 symbol, triggerPrice)
     clientOrderId = self.safe_string(params, 'clientOrderId')
     if clientOrderId is not None:
         request['clientOrderId'] = clientOrderId
     params = self.omit(params, 'clientOrderId')
     response = self.privatePostOrders(self.extend(request, params))
     #
     #     {
     #         "orderId": "7524",
     #         "marketId": "BTC-AUD",
     #         "side": "Bid",
     #         "type": "Limit",
     #         "creationTime": "2019-08-30T11:08:21.956000Z",
     #         "price": "100.12",
     #         "amount": "1.034",
     #         "openAmount": "1.034",
     #         "status": "Accepted",
     #         "clientOrderId": "1234-5678",
     #         "timeInForce": "IOC",
     #         "postOnly": False,
     #         "selfTrade": "P",
     #         "triggerAmount": "105",
     #         "targetAmount": "1000"
     #     }
     #
     return self.parse_order(response, market)
Exemplo n.º 18
0
 async def fetch_orders_by_type(self,
                                type,
                                symbol=None,
                                since=None,
                                limit=None,
                                params={}):
     if symbol is None:
         raise ArgumentsRequired(self.id +
                                 ' fetchOrders requires a symbol argument')
     await self.load_markets()
     market = self.market(symbol)
     request = {
         # 'from_id': 'b2a2d379-f9b6-418b-9414-cbf8330b20d1',  # string(uuid), fetchOrders(all orders) only
         # 'page': 0,  # different pagination in fetchOpenOrders and fetchClosedOrders
         # 'limit': 50,  # optional, max = default = 50
         'symbol': market['id'],  # required
     }
     if limit is not None:
         request['limit'] = limit  # max = default = 50
     method = 'tradePostOrderList' + type
     response = await getattr(self, method)(self.extend(request, params))
     #
     # fetchOrders, fetchClosedOrders
     #
     #     [{      hex_id: "5c192784330fe51149f556bb",
     #             order_id: "5e46e1b1-93d5-4656-9b43-a5635b08eae9",
     #           account_id: "a0c20128-b9e0-484e-9bc8-b8bb86340e5b",
     #         order_symbol: "COSS_ETH",
     #           order_side: "BUY",
     #               status: "filled",
     #           createTime:  1545152388019,
     #                 type: "limit",
     #         timeMatching:  0,
     #          order_price: "0.00065900",
     #           order_size: "10",
     #             executed: "10",
     #           stop_price: "0.00000000",
     #                  avg: "0.00065900",
     #                total: "0.00659000 ETH"                        }  ]
     #
     # fetchOpenOrders
     #
     #     {
     #         "total": 2,
     #         "list": [
     #             {
     #                 "order_id": "9e5ae4dd-3369-401d-81f5-dff985e1c4ty",
     #                 "account_id": "9e5ae4dd-3369-401d-81f5-dff985e1c4a6",
     #                 "order_symbol": "eth-btc",
     #                 "order_side": "BUY",
     #                 "status": "OPEN",
     #                 "createTime": 1538114348750,
     #                 "type": "limit",
     #                 "order_price": "0.12345678",
     #                 "order_size": "10.12345678",
     #                 "executed": "0",
     #                 "stop_price": "02.12345678",
     #                 "avg": "1.12345678",
     #                 "total": "2.12345678"
     #             }
     #         ]
     #     }
     #
     # the following code is to handle the above difference in response formats
     orders = None
     if isinstance(response, list):
         orders = response
     else:
         orders = self.safe_value(response, 'list', [])
     return self.parse_orders(orders, market, since, limit)
Exemplo n.º 19
0
 async def fetch_withdrawals(self,
                             code=None,
                             since=None,
                             limit=None,
                             params={}):
     if code is None:
         raise ArgumentsRequired(
             self.id +
             ' fetchWithdrawals requires a currency code argument')
     await self.load_markets()
     currency = self.currency(code)
     request = {
         'coin_type': currency['id'],
     }
     if limit is not None:
         request['Limit'] = limit
     response = await self.privateGetBalanceCoinWithdraw(
         self.extend(request, params))
     #
     #     {
     #         "code": 0,
     #         "data": [
     #             {
     #                 "actual_amount": "1.00000000",
     #                 "amount": "1.00000000",
     #                 "coin_address": "1KAv3pazbTk2JnQ5xTo6fpKK7p1it2RzD4",
     #                 "coin_type": "BCH",
     #                 "coin_withdraw_id": 206,
     #                 "confirmations": 0,
     #                 "create_time": 1524228297,
     #                 "status": "audit",
     #                 "tx_fee": "0",
     #                 "tx_id": ""
     #             },
     #             {
     #                 "actual_amount": "0.10000000",
     #                 "amount": "0.10000000",
     #                 "coin_address": "15sr1VdyXQ6sVLqeJUJ1uPzLpmQtgUeBSB",
     #                 "coin_type": "BCH",
     #                 "coin_withdraw_id": 203,
     #                 "confirmations": 11,
     #                 "create_time": 1515806440,
     #                 "status": "finish",
     #                 "tx_fee": "0",
     #                 "tx_id": "896371d0e23d64d1cac65a0b7c9e9093d835affb572fec89dd4547277fbdd2f6"
     #             },
     #             {
     #                 "actual_amount": "0.00100000",
     #                 "amount": "0.00100000",
     #                 "coin_address": "1GVVx5UBddLKrckTprNi4VhHSymeQ8tsLF",
     #                 "coin_type": "BCH",
     #                 "coin_withdraw_id": 27,
     #                 "confirmations": 0,
     #                 "create_time": 1513933541,
     #                 "status": "cancel",
     #                 "tx_fee": "0",
     #                 "tx_id": ""
     #             }
     #         ],
     #         "message": "Ok"
     #     }
     #
     return self.parseTransactions(response['data'], currency, since, limit)
Exemplo n.º 20
0
 async def fetch_my_trades(self,
                           symbol=None,
                           since=None,
                           limit=None,
                           params={}):
     if symbol is None:
         raise ArgumentsRequired(
             self.id + ' fetchOrders() requires a symbol argument')
     await self.load_markets()
     market = self.market(symbol)
     request = {
         'symbol': market['id'],
         'page': 0,
     }
     if since is not None:
         request['since'] = self.iso8601(since)
     response = await self.v1PostListExecutedOrdersSymbol(
         self.extend(request, params))
     #
     #     {
     #         "data": [
     #             {
     #                 "type": "BTC Sell order executed",
     #                 "typeI": 6,
     #                 "crypto": 5000,
     #                 "amount": 35.4,
     #                 "rate": 709800,
     #                 "date": "2020-05-22T15:05:34.000Z",
     #                 "unit": "INR",
     #                 "factor": 100000000,
     #                 "fee": 0.09,
     #                 "delh_btc": -5000,
     #                 "delh_inr": 0,
     #                 "del_btc": 0,
     #                 "del_inr": 35.4,
     #                 "id": "2938823"
     #             },
     #             {
     #                 "type": "BTC Sell order executed",
     #                 "typeI": 6,
     #                 "crypto": 195000,
     #                 "amount": 1380.58,
     #                 "rate": 709765.5,
     #                 "date": "2020-05-22T15:05:34.000Z",
     #                 "unit": "INR",
     #                 "factor": 100000000,
     #                 "fee": 3.47,
     #                 "delh_btc": -195000,
     #                 "delh_inr": 0,
     #                 "del_btc": 0,
     #                 "del_inr": 1380.58,
     #                 "id": "2938823"
     #             }
     #         ],
     #         "status": 1,
     #         "error": null,
     #         "code": 200
     #     }
     #
     data = self.safe_value(response, 'data', [])
     return self.parse_trades(data, market, since, limit)
Exemplo n.º 21
0
 def create_order(self, symbol, type, side, amount, price=None, params={}):
     self.load_markets()
     market = self.market(symbol)
     uppercaseType = type.upper()
     uppercaseSide = side.upper()
     request = {
         'symbol': market['id'],
         'side': uppercaseSide,  # or SELL
         # 'amount': self.amount_to_precision(symbol, amount),
         # "price": "1234.5678",  # required for LIMIT and STOP orders
         # 'operator': ''  # for stop orders, can be found in order introduction
         # 'stopPrice': self.price_to_precision(symbol, stopPrice),
         # 'accountId': '...',  # subaccount id, optional
     }
     stopPrice = self.safe_number(params, 'stopPrice')
     if stopPrice is None:
         if (uppercaseType == 'STOP_LIMIT') or (uppercaseType
                                                == 'STOP_MARKET'):
             raise ArgumentsRequired(
                 self.id +
                 ' createOrder() requires a stopPrice parameter for ' +
                 uppercaseType + ' orders')
     else:
         if uppercaseType == 'LIMIT':
             uppercaseType = 'STOP_LIMIT'
         elif uppercaseType == 'MARKET':
             uppercaseType = 'STOP_MARKET'
         defaultOperator = 'LTE' if (uppercaseSide == 'BUY') else 'GTE'
         request['operator'] = self.safe_string(params, 'operator',
                                                defaultOperator)
         request['stopPrice'] = self.price_to_precision(symbol, stopPrice)
         params = self.omit(params, 'stopPrice')
     if (uppercaseType == 'LIMIT') or (uppercaseType == 'STOP_LIMIT'):
         request['price'] = self.price_to_precision(symbol, price)
         request['amount'] = self.amount_to_precision(symbol, amount)
     elif (uppercaseType == 'MARKET') or (uppercaseType == 'STOP_MARKET'):
         if uppercaseSide == 'SELL':
             request['amount'] = self.amount_to_precision(symbol, amount)
         elif uppercaseSide == 'BUY':
             value = self.safe_number(params, 'value')
             createMarketBuyOrderRequiresPrice = self.safe_value(
                 self.options, 'createMarketBuyOrderRequiresPrice', True)
             if createMarketBuyOrderRequiresPrice:
                 if price is not None:
                     if value is None:
                         value = amount * price
                 elif value is None:
                     raise InvalidOrder(
                         self.id +
                         " createOrder() requires the price argument with market buy orders to calculate total order cost(amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = False and supply the total cost value in the 'amount' argument or in the 'value' extra parameter(the exchange-specific behaviour)"
                     )
             else:
                 value = amount if (value is None) else value
             precision = market['precision']['price']
             request['value'] = self.decimal_to_precision(
                 value, TRUNCATE, precision, self.precisionMode)
     request['type'] = uppercaseType
     response = self.privatePostOrdersCreate(self.extend(request, params))
     #
     #     {
     #         "code": "A10000",
     #         "data": {
     #             "amount": "0.001",
     #             "averagePrice": null,
     #             "filledAmount": "0",
     #             "filledFee": "0",
     #             "filledValue": "0",
     #             "id": "870613508008464384",
     #             "operator": "GTE",
     #             "price": "210000",
     #             "side": "BUY",
     #             "status": "SUBMITTED",
     #             "stopPrice": "211000",
     #             "symbol": "BTC_BRL",
     #             "timestamp": 1627612035528,
     #             "type": "STOP_LIMIT",
     #             "value": "210"
     #         },
     #         "message": "Success"
     #     }
     #
     data = self.safe_value(response, 'data', {})
     return self.parse_order(data, market)
Exemplo n.º 22
0
 def fetch_orders_with_method(self, method, symbol=None, since=None, limit=None, params={}):
     if symbol is None:
         raise ArgumentsRequired(self.id + ' fetchOpenOrders requires a symbol argument')
     self.load_markets()
     market = self.market(symbol)
     request = {
         'coinFrom': market['baseId'],
         'coinTo': market['quoteId'],
         # 'type': 1,  # optional integer, 1 = buy, 2 = sell
         # 'page': 1,  # optional integer
         # 'pageSize': 100,  # optional integer, max 100
         # 'startTime': 1510235730,  # optional integer timestamp in seconds
         # 'endTime': 1510235730,  # optional integer timestamp in seconds
     }
     if limit is not None:
         request['page'] = 1
         request['pageSize'] = limit
     if since is not None:
         request['startTime'] = int(since / 1000)
         # request['endTime'] = int(since / 1000)
     response = getattr(self, method)(self.extend(request, params))
     #
     #     {
     #         "status": 200,
     #         "msg": "",
     #         "data": {
     #             "data": [
     #                 {
     #                     "id": "693248739",
     #                     "uid": "2074056",
     #                     "price": "100.00000000",
     #                     "number": "10.0000",
     #                     "total": "0.00000000",
     #                     "numberOver": "0.0000",
     #                     "numberDeal": "0.0000",
     #                     "flag": "sale",
     #                     "status": "3",  # 0:unfilled, 1:partial deal, 2:all transactions, 3:already cancelled
     #                     "isNew": "N",
     #                     "coinFrom": "vtc",
     #                     "coinTo": "dkkt",
     #                     "created": "1533035300",
     #                 },
     #                 {
     #                     "id": "723086996",
     #                     "uid": "2074056",
     #                     "price": "100.00000000",
     #                     "number": "10.0000",
     #                     "total": "0.00000000",
     #                     "numberOver": "0.0000",
     #                     "numberDeal": "0.0000",
     #                     "flag": "sale",
     #                     "status": "3",
     #                     "isNew": "N",
     #                     "coinFrom": "bz",
     #                     "coinTo": "usdt",
     #                     "created": "1533523568",
     #                 },
     #             ],
     #             "pageInfo": {
     #                 "limit": "10",
     #                 "offest": "0",
     #                 "current_page": "1",
     #                 "page_size": "10",
     #                 "total_count": "17",
     #                 "page_count": "2",
     #             }
     #         },
     #         "time": "1533279329",
     #         "microtime": "0.15305300 1533279329",
     #         "source": "api"
     #     }
     #
     orders = self.safe_value(response['data'], 'data', [])
     return self.parse_orders(orders, None, since, limit)
Exemplo n.º 23
0
Arquivo: dsx.py Projeto: zilveer/ccxt
 async def create_order(self, symbol, type, side, amount, price=None, params={}):
     await self.load_markets()
     market = self.market(symbol)
     if type == 'market' and price is None:
         raise ArgumentsRequired(self.id + ' createOrder requires a price argument even for market orders, that is the worst price that you agree to fill your order for')
     request = {
         'pair': market['id'],
         'type': side,
         'volume': self.amount_to_precision(symbol, amount),
         'rate': self.price_to_precision(symbol, price),
         'orderType': type,
     }
     price = float(price)
     amount = float(amount)
     response = await self.privatePostOrderNew(self.extend(request, params))
     #
     #     {
     #       "success": 1,
     #       "return": {
     #         "received": 0,
     #         "remains": 10,
     #         "funds": {
     #           "BTC": {
     #             "total": 100,
     #             "available": 95
     #           },
     #           "USD": {
     #             "total": 10000,
     #             "available": 9995
     #           },
     #           "EUR": {
     #             "total": 1000,
     #             "available": 995
     #           },
     #           "LTC": {
     #             "total": 1000,
     #             "available": 995
     #           }
     #         },
     #         "orderId": 0,  # https://github.com/ccxt/ccxt/issues/3677
     #       }
     #     }
     #
     status = 'open'
     filled = 0.0
     remaining = amount
     responseReturn = self.safe_value(response, 'return')
     id = self.safe_string_2(responseReturn, 'orderId', 'order_id')
     if id == '0':
         id = self.safe_string(responseReturn, 'initOrderId', 'init_order_id')
         status = 'closed'
     filled = self.safe_float(responseReturn, 'received', 0.0)
     remaining = self.safe_float(responseReturn, 'remains', amount)
     timestamp = self.milliseconds()
     return {
         'info': response,
         'id': id,
         'timestamp': timestamp,
         'datetime': self.iso8601(timestamp),
         'lastTradeTimestamp': None,
         'status': status,
         'symbol': symbol,
         'type': type,
         'side': side,
         'price': price,
         'cost': price * filled,
         'amount': amount,
         'remaining': remaining,
         'filled': filled,
         'fee': None,
         # 'trades': self.parse_trades(order['trades'], market),
     }
Exemplo n.º 24
0
 def fetch_ohlcv(self,
                 symbol,
                 timeframe='1m',
                 since=None,
                 limit=None,
                 params={}):
     self.load_markets()
     market = self.market(symbol)
     interval = self.timeframes[timeframe]
     limit = 100 if (limit is None) else limit
     requestLimit = self.sum(limit, 1)
     requestLimit = min(1000, requestLimit)  # max 1000
     request = {
         'market_ids': market['id'],
         'interval': interval,
         'sort':
         'asc',  # 'asc' will always include the start_time, 'desc' will always include end_time
         'limit': requestLimit,  # max 1000
     }
     now = self.milliseconds()
     duration = self.parse_timeframe(timeframe)
     startTime = since
     endTime = now
     if since is None:
         if limit is None:
             raise ArgumentsRequired(
                 self.id +
                 ' fetchOHLCV() requires either a since argument or a limit argument'
             )
         else:
             startTime = now - limit * duration * 1000
     else:
         if limit is None:
             endTime = now
         else:
             endTime = self.sum(since, self.sum(limit, 1) * duration * 1000)
     startTimeNormalized = self.normalize_ohlcv_timestamp(
         startTime, timeframe)
     endTimeNormalized = self.normalize_ohlcv_timestamp(
         endTime, timeframe, True)
     request['start_time'] = startTimeNormalized
     request['end_time'] = endTimeNormalized
     response = self.publicGetCandle(self.extend(request, params))
     #
     #     {
     #         "data":[
     #             {
     #                 "market_id":"ETH-BTC",
     #                 "open":"0.02811",
     #                 "close":"0.02811",
     #                 "low":"0.02811",
     #                 "high":"0.02811",
     #                 "base_volume":"0.0005",
     #                 "quote_volume":"0.000014055",
     #                 "start_time":"2018-11-30T18:19:00.000Z",
     #                 "end_time":"2018-11-30T18:20:00.000Z"
     #             },
     #         ]
     #     }
     #
     data = self.safe_value(response, 'data', [])
     return self.parse_ohlcvs(data, market, timeframe, since, limit)
Exemplo n.º 25
0
 async def create_order(self,
                        symbol,
                        type,
                        side,
                        amount,
                        price=None,
                        params={}):
     await self.load_markets()
     market = self.market(symbol)
     accountId = None
     if market['margin']:
         accountId = self.safe_integer(params, 'accountId')
         if accountId is None:
             raise ArgumentsRequired(
                 self.id +
                 ' createOrder() requires an accountId parameter for ' +
                 market['type'] + ' market ' + symbol)
     uppercaseType = type.upper()
     newOrderRespType = self.safe_value(self.options['newOrderRespType'],
                                        type, 'RESULT')
     request = {
         'symbol': market['id'],
         'quantity': self.amount_to_precision(symbol, amount),
         'type': uppercaseType,
         'side': side.upper(),
         'newOrderRespType':
         newOrderRespType,  # 'RESULT' for full order or 'FULL' for order with fills
         # 'leverage': 1,
         # 'accountId': 5470306579272968,  # required for leverage markets
         # 'takeProfit': '123.45',
         # 'stopLoss': '54.321'
         # 'guaranteedStopLoss': '54.321',
     }
     if uppercaseType == 'LIMIT':
         request['price'] = self.price_to_precision(symbol, price)
         request['timeInForce'] = self.options[
             'defaultTimeInForce']  # 'GTC' = Good To Cancel(default), 'IOC' = Immediate Or Cancel, 'FOK' = Fill Or Kill
     elif uppercaseType == 'STOP':
         request['price'] = self.price_to_precision(symbol, price)
     response = await self.privatePostOrder(self.extend(request, params))
     #
     #     {
     #         "symbol": "BTC/USD",
     #         "orderId": "00000000-0000-0000-0000-0000000c0263",
     #         "clientOrderId": "00000000-0000-0000-0000-0000000c0263",
     #         "transactTime": 1589878206426,
     #         "price": "9825.66210000",
     #         "origQty": "0.01",
     #         "executedQty": "0.01",
     #         "status": "FILLED",
     #         "timeInForce": "FOK",
     #         "type": "MARKET",
     #         "side": "BUY",
     #         "fills": [
     #             {
     #                 "price": "9807.05",
     #                 "qty": "0.01",
     #                 "commission": "0",
     #                 "commissionAsset": "dUSD"
     #             }
     #         ]
     #     }
     #
     return self.parse_order(response, market)
Exemplo n.º 26
0
 async def fetch_tickers(self, symbols=None, params={}):
     await self.load_markets()
     ids = self.ids
     if symbols is None:
         numIds = len(ids)
         ids = '-'.join(ids)
         maxLength = self.safe_integer(self.options,
                                       'fetchTickersMaxLength', 2048)
         # max URL length is 2048 symbols, including http schema, hostname, tld, etc...
         if len(ids) > self.options['fetchTickersMaxLength']:
             raise ArgumentsRequired(
                 self.id + ' has ' + str(numIds) +
                 ' markets exceeding max URL length for self endpoint(' +
                 str(maxLength) +
                 ' characters), please, specify a list of symbols of interest in the first argument to fetchTickers'
             )
     else:
         ids = self.market_ids(symbols)
         ids = '-'.join(ids)
     request = {
         'pair': ids,
     }
     tickers = await self.publicGetTickerPair(self.extend(request, params))
     #
     #     {
     #         "bchbtc" : {
     #             "high" : 0.02989,
     #             "low" : 0.02736,
     #             "avg" : 33.90585,
     #             "vol" : 0.65982205,
     #             "vol_cur" : 0.0194604180960,
     #             "last" : 0.03000,
     #             "buy" : 0.02980,
     #             "sell" : 0.03001,
     #             "updated" : 1568104614,
     #             "pair" : "bchbtc"
     #         },
     #         "ethbtc" : {
     #             "high" : 0.01772,
     #             "low" : 0.01742,
     #             "avg" : 56.89082,
     #             "vol" : 229.247115044,
     #             "vol_cur" : 4.02959737298943,
     #             "last" : 0.01769,
     #             "buy" : 0.01768,
     #             "sell" : 0.01776,
     #             "updated" : 1568104614,
     #             "pair" : "ethbtc"
     #         }
     #     }
     #
     result = {}
     keys = list(tickers.keys())
     for k in range(0, len(keys)):
         id = keys[k]
         ticker = tickers[id]
         symbol = id
         market = None
         if id in self.markets_by_id:
             market = self.markets_by_id[id]
             symbol = market['symbol']
         result[symbol] = self.parse_ticker(ticker, market)
     return result
Exemplo n.º 27
0
 def transfer(self, code, amount, address, params={}):
     self.check_required_dependencies()
     if self.apiKey is None:
         raise ArgumentsRequired('transfer requires self.apiKey')
     self.load_markets()
     currency = self.currency(code)
     amountTruncate = self.decimal_to_precision(amount, TRUNCATE, currency['info']['transferPrecision'], DECIMAL_PLACES, NO_PADDING)
     amountChain = self.toWei(amountTruncate, 'ether', currency['precision']['amount'])
     assetType = int(currency['id'])
     now = self.milliseconds()
     expiration = now
     datetime = self.iso8601(now)
     datetime = datetime.split('.')[0]
     expirationDatetime = self.iso8601(expiration)
     expirationDatetime = expirationDatetime.split('.')[0]
     feeAmount = '300000000000000'
     chainName = 'Sagittarius'
     eightBytes = self.integer_pow('2', '64')
     byteStringArray = [
         self.numberToBE(1, 32),
         self.numberToLE(int(math.floor(now / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(int(math.floor(expiration / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(0, 1),
         self.numberToLE(0, 8),
         self.numberToLE(feeAmount, 8),  # string for 32 bit php
         self.numberToLE(len(self.apiKey), 1),
         self.encode(self.apiKey),
         self.numberToLE(len(address), 1),
         self.encode(address),
         self.numberToLE(assetType, 4),
         self.numberToLE(self.integer_divide(amountChain, eightBytes), 8),
         self.numberToLE(self.integer_modulo(amountChain, eightBytes), 8),
         self.numberToLE(0, 1),
         self.numberToLE(1, 1),
         self.numberToLE(len(chainName), 1),
         self.encode(chainName),
         self.numberToLE(0, 1),
     ]
     bytestring = self.binary_concat_array(byteStringArray)
     hash = self.hash(bytestring, 'sha256', 'hex')
     signature = self.ecdsa(hash, self.secret, 'secp256k1', None, True)
     recoveryParam = self.decode(base64.b16encode(self.numberToLE(self.sum(signature['v'], 31), 1)))
     mySignature = recoveryParam + signature['r'] + signature['s']
     operation = {
         'fee': '300000000000000',
         'from': self.apiKey,
         'to': address,
         'asset_type': int(currency['id']),
         'amount': str(amountChain),
     }
     fatty = {
         'timestamp': datetime,
         'expiration': expirationDatetime,
         'operations': [
             [
                 0,
                 operation,
             ],
         ],
         'validate_type': 0,
         'dapp': 'Sagittarius',
         'signatures': [
             mySignature,
         ],
     }
     request = {
         'trObj': self.json(fatty),
     }
     response = self.publicPostTransactionTransfer(request)
     timestamp = self.milliseconds()
     statusCode = self.safe_string(response, 'code')
     status = ''
     if statusCode == '0':
         status = 'submit success'
     else:
         status = 'submit fail'
     return {
         'info': response,
         'id': '',
         'timestamp': timestamp,
         'datetime': self.iso8601(timestamp),
         'lastTradeTimestamp': None,
         'status': status,
         'symbol': None,
         'type': None,
         'side': None,
         'price': None,
         'amount': None,
         'filled': None,
         'remaining': None,
         'cost': None,
         'fee': None,
     }
Exemplo n.º 28
0
 def cancel_order(self, id, symbol=None, params={}):
     if self.apiKey is None:
         raise ArgumentsRequired('cancelOrder requires hasAlreadyAuthenticatedSuccessfully')
     if symbol is None:
         raise ArgumentsRequired(self.id + ' cancelOrder requires a symbol argument')
     self.load_markets()
     market = self.market(symbol)
     baseId = market['baseId']
     quoteId = market['quoteId']
     normalSymbol = market['normalSymbol']
     feeAmount = '300000000000000'
     now = self.milliseconds()
     expiration = 0
     datetime = self.iso8601(now)
     datetime = datetime.split('.')[0]
     expirationDatetime = self.iso8601(expiration)
     expirationDatetime = expirationDatetime.split('.')[0]
     chainName = 'Sagittarius'
     byteStringArray = [
         self.numberToBE(1, 32),
         self.numberToLE(int(math.floor(now / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(expiration, 4),
         self.numberToLE(1, 1),
         self.numberToLE(33, 1),
         self.numberToLE(0, 8),
         self.numberToLE(feeAmount, 8),  # string for 32 bit php
         self.numberToLE(len(self.apiKey), 1),
         self.encode(self.apiKey),
         self.numberToLE(len(normalSymbol), 1),
         self.encode(normalSymbol),
         self.base16_to_binary(id),
         self.numberToLE(int(quoteId), 4),
         self.numberToLE(int(baseId), 4),
         self.numberToLE(0, 1),
         self.numberToLE(1, 1),
         self.numberToLE(len(chainName), 1),
         self.encode(chainName),
         self.numberToLE(0, 1),
     ]
     bytestring = self.binary_concat_array(byteStringArray)
     hash = self.hash(bytestring, 'sha256', 'hex')
     signature = self.ecdsa(hash, self.secret, 'secp256k1', None, True)
     recoveryParam = self.decode(base64.b16encode(self.numberToLE(self.sum(signature['v'], 31), 1)))
     mySignature = recoveryParam + signature['r'] + signature['s']
     operation = {
         'fee': feeAmount,
         'creator': self.apiKey,
         'order_id': id,
         'market_name': normalSymbol,
         'money_id': int(quoteId),
         'stock_id': int(baseId),
     }
     fatty = {
         'timestamp': datetime,
         'expiration': expirationDatetime,
         'operations': [
             [
                 33,
                 operation,
             ],
         ],
         'validate_type': 0,
         'dapp': 'Sagittarius',
         'signatures': [
             mySignature,
         ],
     }
     request = {
         'trObj': self.json(fatty),
     }
     response = self.publicPostTransactionCancelorder(request)
     timestamp = self.milliseconds()
     statusCode = self.safe_string(response, 'code')
     status = 'canceled' if (statusCode == '0') else 'failed'
     return {
         'info': response,
         'id': None,
         'timestamp': timestamp,
         'datetime': self.iso8601(timestamp),
         'lastTradeTimestamp': None,
         'status': status,
         'symbol': None,
         'type': None,
         'side': None,
         'price': None,
         'amount': None,
         'filled': None,
         'remaining': None,
         'cost': None,
         'trades': None,
         'fee': None,
     }
Exemplo n.º 29
0
 def create_order(self, symbol, type, side, amount, price=None, params={}):
     self.check_required_dependencies()
     if self.apiKey is None:
         raise ArgumentsRequired('createOrder requires self.apiKey or userid in params')
     self.load_markets()
     market = self.market(symbol)
     sideNum = None
     typeNum = None
     if side == 'sell':
         sideNum = 1
     else:
         sideNum = 2
     if type == 'limit':
         typeNum = 1
     else:
         typeNum = 2
     normalSymbol = market['normalSymbol']
     baseId = market['baseId']
     baseCurrency = self.currency(market['base'])
     amountTruncated = self.amount_to_precision(symbol, amount)
     amountChain = self.toWei(amountTruncated, 'ether', baseCurrency['precision']['amount'])
     quoteId = market['quoteId']
     quoteCurrency = self.currency(market['quote'])
     priceRounded = self.price_to_precision(symbol, price)
     priceChain = self.toWei(priceRounded, 'ether', quoteCurrency['precision']['amount'])
     now = self.milliseconds()
     expiration = self.milliseconds()
     datetime = self.iso8601(now)
     datetime = datetime.split('.')[0]
     expirationDatetime = self.iso8601(expiration)
     expirationDatetime = expirationDatetime.split('.')[0]
     chainName = 'Sagittarius'
     defaultFee = self.safe_string(self.options, 'fee', '300000000000000')
     fee = self.safe_string(params, 'fee', defaultFee)
     eightBytes = self.integer_pow('2', '64')
     allByteStringArray = [
         self.numberToBE(1, 32),
         self.numberToLE(int(math.floor(now / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(int(math.floor(expiration / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(32, 1),
         self.numberToLE(0, 8),
         self.numberToLE(fee, 8),  # string for 32 bit php
         self.numberToLE(len(self.apiKey), 1),
         self.encode(self.apiKey),
         self.numberToLE(sideNum, 1),
         self.numberToLE(typeNum, 1),
         self.numberToLE(len(normalSymbol), 1),
         self.encode(normalSymbol),
         self.numberToLE(self.integer_divide(amountChain, eightBytes), 8),
         self.numberToLE(self.integer_modulo(amountChain, eightBytes), 8),
         self.numberToLE(self.integer_divide(priceChain, eightBytes), 8),
         self.numberToLE(self.integer_modulo(priceChain, eightBytes), 8),
         self.numberToLE(0, 2),
         self.numberToLE(int(math.floor(now / 1000)), 4),
         self.numberToLE(int(math.floor(expiration / 1000)), 4),
         self.numberToLE(0, 2),
         self.numberToLE(int(quoteId), 4),
         self.numberToLE(int(baseId), 4),
         self.numberToLE(0, 1),
         self.numberToLE(1, 1),
         self.numberToLE(len(chainName), 1),
         self.encode(chainName),
         self.numberToLE(0, 1),
     ]
     txByteStringArray = [
         self.numberToLE(int(math.floor(now / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(int(math.floor(expiration / 1000)), 4),
         self.numberToLE(1, 1),
         self.numberToLE(32, 1),
         self.numberToLE(0, 8),
         self.numberToLE(fee, 8),  # string for 32 bit php
         self.numberToLE(len(self.apiKey), 1),
         self.encode(self.apiKey),
         self.numberToLE(sideNum, 1),
         self.numberToLE(typeNum, 1),
         self.numberToLE(len(normalSymbol), 1),
         self.encode(normalSymbol),
         self.numberToLE(self.integer_divide(amountChain, eightBytes), 8),
         self.numberToLE(self.integer_modulo(amountChain, eightBytes), 8),
         self.numberToLE(self.integer_divide(priceChain, eightBytes), 8),
         self.numberToLE(self.integer_modulo(priceChain, eightBytes), 8),
         self.numberToLE(0, 2),
         self.numberToLE(int(math.floor(now / 1000)), 4),
         self.numberToLE(int(math.floor(expiration / 1000)), 4),
         self.numberToLE(0, 2),
         self.numberToLE(int(quoteId), 4),
         self.numberToLE(int(baseId), 4),
         self.numberToLE(0, 1),
         self.numberToLE(1, 1),
         self.numberToLE(len(chainName), 1),
         self.encode(chainName),
         self.numberToLE(0, 1),
     ]
     txbytestring = self.binary_concat_array(txByteStringArray)
     txidhash = self.hash(txbytestring, 'sha256', 'hex')
     txid = txidhash[0:40]
     orderidByteStringArray = [
         self.numberToLE(len(txid), 1),
         self.encode(txid),
         self.numberToBE(0, 4),
     ]
     orderidbytestring = self.binary_concat_array(orderidByteStringArray)
     orderidhash = self.hash(orderidbytestring, 'sha256', 'hex')
     orderid = orderidhash[0:40]
     bytestring = self.binary_concat_array(allByteStringArray)
     hash = self.hash(bytestring, 'sha256', 'hex')
     signature = self.ecdsa(hash, self.secret, 'secp256k1', None, True)
     recoveryParam = self.decode(base64.b16encode(self.numberToLE(self.sum(signature['v'], 31), 1)))
     mySignature = recoveryParam + signature['r'] + signature['s']
     operation = {
         'now': datetime,
         'expiration': expirationDatetime,
         'fee': fee,
         'creator': self.apiKey,
         'side': sideNum,
         'order_type': typeNum,
         'market_name': normalSymbol,
         'amount': amountChain,
         'price': priceChain,
         'use_btt_as_fee': False,
         'money_id': int(quoteId),
         'stock_id': int(baseId),
     }
     fatty = {
         'timestamp': datetime,
         'expiration': expirationDatetime,
         'operations': [
             [
                 32,
                 operation,
             ],
         ],
         'validate_type': 0,
         'dapp': 'Sagittarius',
         'signatures': [
             mySignature,
         ],
     }
     request = {
         'trObj': self.json(fatty),
     }
     response = self.publicPostTransactionCreateorder(request)
     timestamp = self.milliseconds()
     statusCode = self.safe_string(response, 'code')
     status = 'open' if (statusCode == '0') else 'failed'
     return {
         'info': response,
         'id': orderid,
         'timestamp': timestamp,
         'datetime': self.iso8601(timestamp),
         'lastTradeTimestamp': None,
         'status': status,
         'symbol': None,
         'type': None,
         'side': None,
         'price': None,
         'amount': None,
         'filled': None,
         'remaining': None,
         'cost': None,
         'trades': None,
         'fee': None,
     }
Exemplo n.º 30
0
 def withdraw(self, code, amount, address, tag=None, params={}):
     self.check_required_dependencies()
     self.check_address(address)
     self.load_markets()
     if self.apiKey is None:
         raise ArgumentsRequired('withdraw requires self.apiKey')
     addressResponse = self.fetch_deposit_address(code)
     middleAddress = self.safe_string(addressResponse, 'address')
     chainTypeString = self.safe_string(addressResponse, 'chainType')
     chainType = 0
     operationId = 18
     if chainTypeString == 'ethereum':
         chainType = 1
     elif chainTypeString == 'bitcoin':
         chainType = 2
         operationId = 26
     elif chainTypeString == 'cmt':
         chainType = 3
     elif chainTypeString == 'naka':
         chainType = 4
     else:
         raise ExchangeError(self.id + ' ' + code + ' is not supported.')
     now = self.milliseconds()
     expiration = 0
     datetime = self.iso8601(now)
     datetime = datetime.split('.')[0]
     expirationDatetime = self.iso8601(expiration)
     expirationDatetime = expirationDatetime.split('.')[0]
     chainName = 'Sagittarius'
     feeAmount = '300000000000000'
     currency = self.currency(code)
     coinId = currency['id']
     amountTruncate = self.decimal_to_precision(amount, TRUNCATE, currency['info']['transferPrecision'], DECIMAL_PLACES, NO_PADDING)
     amountChain = self.toWei(amountTruncate, 'ether', currency['info']['externalPrecision'])
     eightBytes = self.integer_pow('2', '64')
     assetFee = 0
     byteStringArray = []
     if chainTypeString == 'bitcoin':
         assetFee = currency['info']['fee']
         byteStringArray = [
             self.numberToBE(1, 32),
             self.numberToLE(int(math.floor(now / 1000)), 4),
             self.numberToLE(1, 1),
             self.numberToLE(int(math.floor(expiration / 1000)), 4),
             self.numberToLE(1, 1),
             self.numberToLE(operationId, 1),
             self.numberToLE(0, 8),
             self.numberToLE(feeAmount, 8),  # string for 32 bit php
             self.numberToLE(len(self.apiKey), 1),
             self.encode(self.apiKey),
             self.numberToLE(len(address), 1),
             self.encode(address),
             self.numberToLE(int(coinId), 4),
             self.numberToLE(int(math.floor(int(float(self.integer_divide(amountChain, eightBytes))))), 8),
             self.numberToLE(self.integer_modulo(amountChain, eightBytes), 8),
             self.numberToLE(1, 1),
             self.numberToLE(self.integer_divide(assetFee, eightBytes), 8),
             self.numberToLE(self.integer_modulo(assetFee, eightBytes), 8),
             self.numberToLE(0, 1),
             self.numberToLE(1, 1),
             self.numberToLE(len(chainName), 1),
             self.encode(chainName),
             self.numberToLE(0, 1),
         ]
     else:
         byteStringArray = [
             self.numberToBE(1, 32),
             self.numberToLE(int(math.floor(now / 1000)), 4),
             self.numberToLE(1, 1),
             self.numberToLE(int(math.floor(expiration / 1000)), 4),
             self.numberToLE(1, 1),
             self.numberToLE(operationId, 1),
             self.numberToLE(0, 8),
             self.numberToLE(feeAmount, 8),  # string for 32 bit php
             self.numberToLE(len(self.apiKey), 1),
             self.encode(self.apiKey),
             self.numberToLE(int(math.floor(now / 1000)), 4),
             self.numberToLE(1, 1),
             self.numberToLE(4, 1),
             self.numberToLE(0, 8),
             self.numberToLE(feeAmount, 8),
             self.numberToLE(len(self.apiKey), 1),
             self.encode(self.apiKey),
             self.numberToLE(len(middleAddress), 1),
             self.encode(middleAddress),
             self.numberToLE(int(coinId), 4),
             self.numberToLE(int(math.floor(int(float(self.integer_divide(amountChain, eightBytes))))), 8),
             self.numberToLE(self.integer_modulo(amountChain, eightBytes), 8),
             self.numberToLE(0, 1),
             self.numberToLE(1, 1),
             self.numberToLE(len(chainName), 1),
             self.encode(chainName),
             self.numberToLE(0, 1),
         ]
     bytestring = self.binary_concat_array(byteStringArray)
     hash = self.hash(bytestring, 'sha256', 'hex')
     signature = self.ecdsa(hash, self.secret, 'secp256k1', None, True)
     recoveryParam = self.decode(base64.b16encode(self.numberToLE(self.sum(signature['v'], 31), 1)))
     mySignature = recoveryParam + signature['r'] + signature['s']
     fatty = None
     request = None
     operation = None
     chainContractAddress = self.safe_string(currency['info'], 'chainContractAddress')
     if chainTypeString == 'bitcoin':
         operation = {
             'fee': feeAmount,
             'from': self.apiKey,
             'to_external_address': address,
             'asset_type': int(coinId),
             'amount': amountChain,
             'asset_fee': assetFee,
         }
         fatty = {
             'timestamp': datetime,
             'expiration': expirationDatetime,
             'operations': [
                 [
                     operationId,
                     operation,
                 ],
             ],
             'validate_type': 0,
             'dapp': 'Sagittarius',
             'signatures': [
                 mySignature,
             ],
         }
         request = {
             'chainType': chainType,
             'trObj': self.json(fatty),
             'chainContractAddresss': chainContractAddress,
         }
     else:
         operation = {
             'fee': feeAmount,
             'from': self.apiKey,
             'to_external_address': middleAddress,
             'asset_type': int(coinId),
             'amount': amountChain,
             'asset_fee': assetFee,
         }
         middle = {
             'fee': feeAmount,
             'proposaler': self.apiKey,
             'expiration_time': datetime,
             'proposed_ops': [{
                 'op': [4, operation],
             }],
         }
         fatty = {
             'timestamp': datetime,
             'expiration': expirationDatetime,
             'operations': [
                 [
                     operationId,
                     middle,
                 ],
             ],
             'validate_type': 0,
             'dapp': 'Sagittarius',
             'signatures': [
                 mySignature,
             ],
         }
         request = {
             'chainType': chainType,
             'toExternalAddress': address,
             'trObj': self.json(fatty),
             'chainContractAddresss': chainContractAddress,
         }
     response = self.publicPostTransactionWithdraw(request)
     return {
         'info': response,
         'id': self.safe_string(response, 'id'),
     }