astro-perp-ccxt-dev
Version:
842 lines (839 loc) • 35.6 kB
JavaScript
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// EDIT THE CORRESPONDENT .ts FILE INSTEAD
// ---------------------------------------------------------------------------
import astrosRest from '../astros.js';
import { ArgumentsRequired } from '../base/errors.js';
import { Precise } from '../base/Precise.js';
import { ArrayCache, ArrayCacheBySymbolById, ArrayCacheBySymbolBySide, ArrayCacheByTimestamp } from '../base/ws/Cache.js';
import { sha256 } from '../static_dependencies/noble-hashes/sha256.js';
// ---------------------------------------------------------------------------
/**
* @class astros
* @augments Exchange
* @description watching delivery future markets is not yet implemented (perpertual future & swap is implemented)
*/
export default class astros extends astrosRest {
describe() {
return this.deepExtend(super.describe(), {
'has': {
'ws': true,
'createOrderWs': false,
'editOrderWs': false,
'fetchOpenOrdersWs': false,
'fetchOrderWs': false,
'cancelOrderWs': false,
'cancelOrdersWs': false,
'cancelAllOrdersWs': false,
'watchBalance': true,
'watchMyTrades': true,
'watchOHLCV': true,
'watchOHLCVForSymbols': false,
'watchOrderBook': true,
'watchOrderBookForSymbols': false,
'watchOrders': true,
'watchTicker': false,
'watchTickers': false,
'watchBidsAsks': false,
'watchTrades': true,
'watchTradesForSymbols': false,
'watchPositions': true,
},
'urls': {
'api': {
'ws': 'wss://dasprkkzjjkl7.cloudfront.net/api/market/ws',
},
},
'options': {
'tradesLimit': 1000,
'OHLCVLimit': 1000,
'timeframes': {
'1m': '1MIN',
'3m': '3MIN',
'5m': '5MIN',
'15m': '15MIN',
'30m': '30MIN',
'1h': '1HOUR',
// '2h': '2H',
'4h': '4HOUR',
// '6h': '6H',
'8h': '8HOUR',
'12h': '12HOUR',
'1d': '1DAY',
// '3d': '3D',
// '1w': '1W',
// '1M': '1M',
},
'watchOrderBook': {
'checksum': true,
},
'watchTrades': {
'ignoreDuplicates': true,
},
},
'streaming': {},
'exceptions': {
'ws': {
'exact': {},
'broad': {},
},
},
});
}
async subscribe(event, messageHash, subscriptionHash, params = {}) {
// const requestId = this.requestId ().toString ();
const url = this.urls['api']['ws'];
// const timestamp = String (Date.now ());
const timestamp = String(await this.fetchTime());
const secret = this.secret || '';
const signature = this.hmac(timestamp, secret, sha256);
const request = {
'method': 'SUBSCRIBE',
'apiKey': this.apiKey,
'signType': '1',
'signature': signature,
'event': event,
'timestamp': timestamp,
};
const message = this.extend(request, params);
return await this.watch(url, messageHash, message, subscriptionHash);
}
requestId() {
const requestId = this.sum(this.safeInteger(this.options, 'requestId', 0), 1);
this.options['requestId'] = requestId;
return requestId;
}
ping(client) {
return 'ping';
}
handlePong(client, message) {
client.lastPong = this.milliseconds();
}
handleErrorMessage(client, message) {
// {
// method: 'SUBSCRIBE',
// msg: 'The timestamp is valid for 1 minute',
// success: false
// }
const data = this.safeString(message, 'msg', '');
this.handleErrors(undefined, undefined, client.url, undefined, undefined, data, message, undefined, undefined);
}
handleMessage(client, message) {
let event = this.safeString(message, 'event', 'other');
if (event.endsWith('_res')) {
// Subscription success returns
return;
}
const success = this.safeBool(message, 'success', true);
if (!success) {
event = 'error';
}
if (message === 'pong' || message === 'PONG') {
event = 'pong';
}
const methods = {
// 'heartbeat': this.handleHeartbeat,
// 'welcome': this.handleSystemStatus,
// 'ack': this.handleSubscriptionStatus,
// 'message': this.handleSubject,
'pong': this.handlePong,
'error': this.handleErrorMessage,
'api_entrust': this.handleOrders,
'api_position': this.handlePositions,
'api_kline': this.handleOHLCV,
'api_depth': this.handleOrderBook,
// 'api_trade': this.handleTrades,
'api_account': this.handleBalance,
'api_spot_deals': this.handleTrades,
'api_deal_user': this.handleMyTrade,
};
const method = this.safeValue(methods, event);
if (method !== undefined) {
method.call(this, client, message);
}
}
handleBalance(client, message) {
// {
// "data": {
// "availableAmount": "999757.863799",
// "coinId": 4,
// "frozenAmount": "241.506568",
// "logId": 0,
// "operateAmount": "0.00",
// "symbol": "USD"
// },
// "event": "api_account",
// "success": true,
// "symbol": "USD"
// }
const event = 'api_account';
const data = this.safeValue(message, 'data', {});
const symbol = this.safeString(data, 'symbol');
const timestamp = Date.now();
this.balance['timestamp'] = timestamp;
this.balance['datetime'] = this.iso8601(timestamp);
this.balance['info'] = data;
const currencyId = this.safeString(data, 'symbol');
const code = this.safeCurrencyCode(currencyId);
const account = this.account();
const available = this.safeString(data, 'availableAmount');
const frozen = this.safeString(data, 'frozenAmount');
account['free'] = available;
account['used'] = frozen;
account['total'] = String(Number(available) + Number(frozen));
this.balance[code] = account;
this.balance = this.safeBalance(this.balance);
const messageHash = event + '.' + symbol;
client.resolve(this.balance, messageHash);
}
/**
* @method
* @name astros#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure}
*/
async watchBalance(params = {}) {
// await this.loadMarkets ();
const event = 'api_account';
let symbol = this.safeString(params, 'symbol');
if (symbol === undefined) {
symbol = 'USD';
params['symbol'] = symbol;
}
const messageHash = event + '.' + symbol;
const subscribeHash = messageHash;
return await this.subscribe(event, messageHash, subscribeHash, params);
}
/**
* @method
* @name astros#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, close price, and the volume of a market
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
async watchOHLCV(symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets();
const event = 'api_kline';
const market = this.market(symbol);
const interval = this.safeString(this.timeframes, timeframe, timeframe);
const messageHash = 'api_kline.' + market['id'] + '.kline.' + interval;
params['pair'] = market['info']['symbol'];
params['period'] = interval;
const ohlcv = await this.subscribe(event, messageHash, messageHash, params);
if (this.newUpdates) {
limit = ohlcv.getLimit(symbol, limit);
}
return this.filterBySinceLimit(ohlcv, since, limit, 0, true);
}
handleOHLCV(client, message) {
// {
// "contractPairId": 1,
// "data": {
// "amount": 0,
// "close": 2322.53,
// "contractPairId": 1,
// "count": 0,
// "hight": 2322.53,
// "low": 2322.53,
// "open": 2322.53,
// "period": "1MIN",
// "quantity": 0,
// "time": 1725870900000
// },
// "event": "api_kline",
// "period": "1MIN",
// "success": true
// }
const data = this.safeValue(message, 'data', {});
const marketId = this.safeString(data, 'contractPairId');
const market = this.safeMarket(marketId);
const symbol = market['symbol'];
const interval = this.safeString(data, 'period');
const timeframe = this.findTimeframe(interval);
this.ohlcvs[symbol] = this.safeValue(this.ohlcvs, symbol, {});
let stored = this.safeValue(this.ohlcvs[symbol], timeframe);
if (stored === undefined) {
const limit = this.safeInteger(this.options, 'OHLCVLimit', 1000);
stored = new ArrayCacheByTimestamp(limit);
this.ohlcvs[symbol][timeframe] = stored;
}
const parsed = this.parseOHLCV(data, market);
const messageHash = 'api_kline.' + market['id'] + '.kline.' + interval;
stored.append(parsed);
client.resolve(stored, messageHash);
}
parseOHLCV(ohlcv, market = undefined) {
// {
// "amount": 0,
// "close": 2322.53,
// "contractPairId": 1,
// "count": 0,
// "hight": 2322.53,
// "low": 2322.53,
// "open": 2322.53,
// "period": "1MIN",
// "quantity": 0,
// "time": 1725870900000
// }
return [
this.safeTimestamp(ohlcv, 'time'),
this.safeNumber(ohlcv, 'open'),
this.safeNumber(ohlcv, 'hight'),
this.safeNumber(ohlcv, 'low'),
this.safeNumber(ohlcv, 'close'),
this.safeNumber(ohlcv, 'amount'),
];
}
/**
* @method
* @name astros#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols
*/
async watchOrderBook(symbol, limit = undefined, params = {}) {
await this.loadMarkets();
const event = 'api_depth';
const market = this.market(symbol);
const messageHash = event + '.' + symbol;
params['pair'] = market['info']['symbol'];
const orderbook = await this.subscribe(event, messageHash, messageHash, params);
return orderbook.limit();
}
handleOrderBook(client, message) {
// {
// "data": {
// "asks": [
// {
// "price": "2341.78",
// "quantity": "13.673"
// },
// {
// "price": "2345.03",
// "quantity": "2.456"
// }
// ],
// "bids": [
// {
// "price": "2311.4",
// "quantity": "7.043"
// },
// {
// "price": "2289.71",
// "quantity": "10.261"
// }
// ]
// },
// "event": "api_depth",
// "pair": "ETH-USD",
// "success": true
// }
const remoteSymbol = this.safeString(message, 'pair');
const symbol = this.convert2MarketSymbol(remoteSymbol);
const event = 'api_depth';
const messageHash = event + '.' + symbol;
const timestamp = Date.now();
if (!(symbol in this.orderbooks)) {
this.orderbooks[symbol] = this.orderBook({});
}
const orderbook = this.orderbooks[symbol];
orderbook.reset({});
let bids = [];
let asks = [];
const data = this.safeValue(message, 'data', {});
const asks_res = this.safeValue(data, 'asks', []);
const bids_res = this.safeValue(data, 'bids', []);
for (let i = 0; i < asks_res.length; i++) {
const entry = asks_res[i];
const price = this.safeFloat(entry, 'price');
const quantity = this.safeFloat(entry, 'quantity');
asks.push([price, quantity]);
}
for (let i = 0; i < bids_res.length; i++) {
const entry = bids_res[i];
const price = this.safeFloat(entry, 'price');
const quantity = this.safeFloat(entry, 'quantity');
bids.push([price, quantity]);
}
bids = this.sortBy(bids, 0, true);
asks = this.sortBy(asks, 0);
orderbook['bids'].storeArray(bids);
orderbook['asks'].storeArray(asks);
const datetime = this.iso8601(timestamp);
orderbook['symbol'] = symbol;
orderbook['timestamp'] = timestamp;
orderbook['datetime'] = datetime;
orderbook['nonce'] = timestamp;
client.resolve(orderbook, messageHash);
}
/**
* @method
* @name astros#watchTrades
* @description get the list of most recent trades for a particular symbol
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades}
*/
async watchTrades(symbol, since = undefined, limit = undefined, params = {}) {
const event = 'api_spot_deals';
await this.loadMarkets();
const market = this.market(symbol);
params['pair'] = market['info']['symbol'];
const messageHash = 'trades.' + symbol;
const trades = await this.subscribe(event, messageHash, messageHash, params);
if (this.newUpdates) {
limit = trades.getLimit(symbol, limit);
}
return this.filterBySinceLimit(trades, since, limit, 'timestamp', true);
}
handleTrades(client, message) {
// {
// "contractPairId": 1,
// "data": {
// "amount": 2530.3042,
// "contractMatchPairId": 19868235,
// "contractPairId": 1,
// "direction": false,
// "pair": "ETH-USD",
// "price": 2321.38,
// "quantity": 1.09,
// "time": "08:40:47",
// "timestamp": 1725871247000
// },
// "event": "api_spot_deals",
// "pair": "ETH-USD",
// "success": true
// }
const data = this.safeDict(message, 'data', {});
const marketId = this.safeString(data, 'contractPairId');
const market = this.safeMarket(marketId);
const symbol = market['symbol'];
if (!(symbol in this.trades)) {
const limit = this.safeInteger(this.options, 'tradesLimit', 1000);
const stored = new ArrayCache(limit);
this.trades[symbol] = stored;
}
const cache = this.trades[symbol];
const trade = this.parseWsTrade(data, market);
cache.append(trade);
const messageHash = 'trades.' + symbol;
client.resolve(cache, messageHash);
}
parseWsTrade(trade, market = undefined) {
// {
// "amount": 2530.3042,
// "contractMatchPairId": 19868235,
// "contractPairId": 1,
// "direction": false,
// "pair": "ETH-USD",
// "price": 2321.38,
// "quantity": 1.09,
// "time": "08:40:47",
// "timestamp": 1725871247000
// }
const timestamp = this.safeInteger(trade, 'timestamp', Date.now());
const direction = this.safeBool(trade, 'direction');
const id = this.safeInteger(trade, 'contractMatchPairId');
const marketId = this.safeString(trade, 'contractPairId');
if (market === undefined) {
market = this.safeMarket(marketId);
}
const symbol = market['symbol'];
return this.safeTrade({
'info': trade,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'symbol': symbol,
'order': undefined,
'type': undefined,
'side': this.parseWsTradeSide(direction),
'takerOrMaker': undefined,
'price': this.safeString(trade, 'price'),
'amount': this.safeString(trade, 'quantity'),
'cost': this.safeString(trade, 'amount'),
'fee': {
'currency': undefined,
'cost': undefined,
'rate': undefined,
},
}, market);
}
parseWsTradeSide(direction) {
if (direction) {
return 'buy';
}
return 'sell';
}
/**
* @method
* @name astros#watchMyTrades
* @description watches information on multiple trades made by the user
* @param {string} symbol unified market symbol of the market trades were made in
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trade structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] '/spotMarket/tradeOrders' or '/spot/tradeFills' default is '/spotMarket/tradeOrders'
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
async watchMyTrades(symbol = undefined, since = undefined, limit = undefined, params = {}) {
const event = 'api_deal_user';
await this.loadMarkets();
if (symbol) {
const market = this.market(symbol);
params['pair'] = market['info']['symbol'];
}
const messageHash = 'myTrades.' + symbol;
const trades = await this.subscribe(event, messageHash, messageHash, params);
if (this.newUpdates && symbol) {
limit = trades.getLimit(symbol, limit);
}
return this.filterBySymbolSinceLimit(trades, symbol, since, limit, true);
}
handleMyTrade(client, message) {
// {
// "data": {
// "contractPairId": 1,
// "currentEntrustId": 180641687,
// "dealAmount": "46.698",
// "dealPrice": "2334.9",
// "dealQuantity": "0.02",
// "dealTime": "1725871432612",
// "direction": "LONG",
// "feeAmt": "0.028018",
// "feeCoin": "USD",
// "isClose": false,
// "isTaker": true,
// "matchId": 19868419,
// "matchType": 1,
// "symbol": "ETH-USD",
// "clientOrderId":"1725871431488"
// },
// "event": "api_deal_user",
// "success": true
// }
if (this.myTrades === undefined) {
const limit = this.safeInteger(this.options, 'tradesLimit', 1000);
this.myTrades = new ArrayCacheBySymbolById(limit);
}
const data = this.safeDict(message, 'data', {});
const marketId = this.safeString(data, 'contractPairId');
const market = this.safeMarket(marketId);
const parsed = this.parseWsMyTrade(data, market);
const myTrades = this.myTrades;
myTrades.append(parsed);
const messageHash = 'myTrades';
client.resolve(myTrades, messageHash);
const symbolSpecificMessageHash = messageHash + '.' + market['symbol'];
client.resolve(myTrades, symbolSpecificMessageHash);
}
parseWsMyTrade(trade, market = undefined) {
// {
// "contractPairId": 1,
// "currentEntrustId": 180641687,
// "dealAmount": "46.698",
// "dealPrice": "2334.9",
// "dealQuantity": "0.02",
// "dealTime": "1725871432612",
// "direction": "LONG",
// "feeAmt": "0.028018",
// "feeCoin": "USD",
// "isClose": false,
// "isTaker": true,
// "matchId": 19868419,
// "matchType": 1,
// "symbol": "ETH-USD",
// "clientOrderId":"1725871431488"
// }
const timestamp = this.safeInteger(trade, 'dealTime', Date.now());
const direction = this.safeString(trade, 'direction');
const isTaker = this.safeBool(trade, 'isTaker');
const marketId = this.safeString(trade, 'contractPairId');
if (market === undefined) {
market = this.safeMarket(marketId);
}
const symbol = market['symbol'];
return this.safeTrade({
'info': trade,
'id': timestamp,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'symbol': symbol,
'order': this.safeString(trade, 'currentEntrustId'),
'type': undefined,
'side': this.parseDirectionSide(direction),
'takerOrMaker': this.parseTakerOrMaker(isTaker),
'price': this.safeString(trade, 'dealPrice'),
'amount': this.safeString(trade, 'dealQuantity'),
'cost': this.safeString(trade, 'dealAmount'),
'fee': {
'currency': this.safeString(trade, 'feeCoin'),
'cost': this.safeString(trade, 'feeAmt'),
'rate': undefined,
},
}, market);
}
/**
* @method
* @name astros#watchPositions
* @description watch all open positions
* @param {string[]|undefined} symbols list of unified market symbols
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum number of positions to retrieve
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {string} [params.instType] one of 'USDT-FUTURES', 'USDC-FUTURES', 'COIN-FUTURES', 'SUSDT-FUTURES', 'SUSDC-FUTURES' or 'SCOIN-FUTURES', default is 'USDT-FUTURES'
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure}
*/
async watchPositions(symbols = undefined, since = undefined, limit = undefined, params = {}) {
const event = 'api_position';
await this.loadMarkets();
if (symbols === undefined) {
throw new ArgumentsRequired(this.id + ' watchPositions() requires an array argument for symbols');
}
if (symbols.length < 1) {
throw new ArgumentsRequired(this.id + ' watchPositions() requires an array argument for symbols');
}
params['pairs'] = [];
Object.values(this.markets).forEach((market) => {
params['pairs'].push(market['info']['symbol']);
});
const messageHash = 'positions.' + params['pair'];
const newPositions = await this.subscribe(event, messageHash, messageHash, params);
if (this.newUpdates) {
return newPositions;
}
return this.filterBySymbolsSinceLimit(newPositions, symbols, since, limit, true);
}
handlePositions(client, message) {
// {
// "data": {
// "canClosedQuantity": "0.06",
// "changeType": "NEW",
// "contractPairId": 1,
// "currentQuantity": "0.06",
// "direction": "LONG",
// "marginAmount": "39.890168",
// "marginCallAmount": "7.5",
// "openingPrice": "2300.045",
// "operateQuantity": "0",
// "positionId": 4796701,
// "positionType": 3,
// "symbol": "ETH-USD"
// },
// "event": "api_position",
// "success": true
// }
const data = this.safeValue(message, 'data', {});
const marketId = this.safeString(data, 'contractPairId');
const market = this.safeMarket(marketId);
if (this.positions === undefined) {
this.positions = new ArrayCacheBySymbolBySide();
}
const cache = this.positions;
const newPositions = [];
const position = this.parsePosition(data, market);
newPositions.push(position);
cache.append(position);
const messageHash = 'positions.' + market['symbol'];
client.resolve(newPositions, messageHash);
}
parseWsPosition(position, market = undefined) {
// {
// "canClosedQuantity": "0.06",
// "changeType": "NEW",
// "contractPairId": 1,
// "currentQuantity": "0.06",
// "direction": "LONG",
// "marginAmount": "39.890168",
// "marginCallAmount": "7.5",
// "openingPrice": "2300.045",
// "operateQuantity": "0",
// "positionId": 4796701,
// "positionType": 3,
// "symbol": "ETH-USD"
// }
const marketId = this.safeString(position, 'symbol');
const marginModeId = this.safeInteger(position, 'positionType');
const openingPrice = this.safeNumber(position, 'openingPrice');
const marginMode = this.getSupportedMapping(marginModeId, {
'4': 'cross',
'3': 'isolated',
});
const changeType = this.safeString(position, 'changeType');
let liquidationPrice = undefined;
if (changeType === 'LIQUIDATE') {
liquidationPrice = openingPrice;
}
const timestamp = Date.now();
let contractSize = undefined;
if (market !== undefined) {
contractSize = market['contractSize'];
}
const direction = this.safeString(position, 'direction');
const side = this.parseDirectionSide(direction);
return this.safePosition({
'info': position,
'id': this.safeString(position, 'positionId'),
'symbol': this.safeSymbol(marketId, market),
'notional': undefined,
'marginMode': marginMode,
'liquidationPrice': liquidationPrice,
'entryPrice': openingPrice,
'unrealizedPnl': undefined,
'percentage': undefined,
'contracts': this.safeNumber(position, 'currentQuantity'),
'contractSize': contractSize,
'markPrice': undefined,
'side': side,
'hedged': false,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'maintenanceMargin': undefined,
'maintenanceMarginPercentage': undefined,
'collateral': undefined,
'initialMargin': this.safeNumber(position, 'marginAmount'),
'initialMarginPercentage': undefined,
'leverage': undefined,
'marginRatio': undefined,
});
}
/**
* @method
* @name astros#watchOrders
* @description watches information on an order made by the user
* @param {string} symbol unified symbol of the market the order was made in
* @param {int} [since] timestamp in ms of the earliest order to watch
* @param {int} [limit] the maximum amount of orders to watch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.channel] choose what channel to use. Can open_order or order_history.
* @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
async watchOrders(symbol = undefined, since = undefined, limit = undefined, params = {}) {
const event = 'api_entrust';
await this.loadMarkets();
if (symbol) {
const market = this.market(symbol);
params['pair'] = market['info']['symbol'];
}
const messageHash = event + '.' + symbol;
const orders = await this.subscribe(event, messageHash, messageHash, params);
if (this.newUpdates && symbol) {
limit = orders.getLimit(symbol, limit);
}
return this.filterBySymbolSinceLimit(orders, symbol, since, limit, true);
}
handleOrders(client, message) {
// {
// "data": {
// "changeType": "NEW",
// "clientOrderId": "1725870680532",
// "contractPairId": 1,
// "currentEntrustId": 180632923,
// "dealAmount": "0.00",
// "dealQuantity": "0",
// "direction": "LONG",
// "isClose": false,
// "isMarket": false,
// "lever": 1,
// "matchType": 1,
// "price": "2000",
// "quantity": "0.02",
// "symbol": "ETH-USD"
// },
// "event": "api_entrust",
// "success": true
// }
const data = this.safeDict(message, 'data', {});
const event = 'api_entrust';
const marketId = this.safeString(data, 'contractPairId');
const market = this.safeMarket(marketId);
const messageHash = event + '.' + market['symbol'];
let stored = this.orders;
if (stored === undefined) {
const limit = this.safeInteger(this.options, 'ordersLimit', 1000);
stored = new ArrayCacheBySymbolById(limit);
this.orders = stored;
}
const order = this.parseOrder(data, market);
stored.append(order);
client.resolve(stored, messageHash);
}
parseOrder(order, market = undefined) {
// {
// "changeType": "NEW",
// "clientOrderId": "1725870680532",
// "contractPairId": 1,
// "currentEntrustId": 180632923,
// "dealAmount": "0.00",
// "dealQuantity": "0",
// "direction": "LONG",
// "isClose": false,
// "isMarket": false,
// "lever": 1,
// "matchType": 1,
// "price": "2000",
// "quantity": "0.02",
// "symbol": "ETH-USD"
// }
const id = this.safeString(order, 'currentEntrustId');
const filled = this.safeString(order, 'dealQuantity');
const quantity = this.safeString(order, 'quantity');
const changeType = this.safeString(order, 'changeType');
const status = this.parseOrderStatus(changeType, filled, quantity);
const isMarket = this.safeBool(order, 'isMarket');
const type = this.parseOrderType(isMarket);
const direction = this.safeString(order, 'direction');
const side = this.parseDirectionSide(direction);
const marketId = this.safeString(order, 'contractPairId');
if (market === undefined) {
market = this.safeMarket(marketId);
}
const symbol = market['symbol'];
const timestamp = Date.now();
let price = this.safeString(order, 'price');
let remaining = Precise.stringSub(quantity, filled);
const amount = this.safeString(order, 'quantity', Precise.stringAdd(filled, remaining));
const cost = Precise.stringMul(price, filled);
if (changeType === 'CANCELED') {
remaining = String(0);
}
if (isMarket) {
price = undefined;
}
const clientOrderId = this.safeString(order, 'clientOrderId');
const matchType = this.safeInteger(order, 'matchType');
const timeInForce = this.parseTimeInForce(matchType);
return this.safeOrder({
'id': id,
'info': order,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': this.iso8601(timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'timeInForce': timeInForce,
'side': side,
'status': status,
'price': price,
'triggerPrice': undefined,
'amount': amount,
'filled': filled,
'remaining': remaining,
'average': undefined,
'cost': cost,
'fee': undefined,
'trades': undefined,
}, market);
}
}