<commit_before>'use strict';

// ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

// ---------------------------------------------------------------------------

module.exports = class bl3p extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bl3p',
            'name': 'BL3P',
            'countries': [ 'NL', 'EU' ], // Netherlands, EU
            'rateLimit': 1000,
            'version': '1',
            'comment': 'An exchange market by BitonicNL',
            'has': {
                'CORS': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/28501752-60c21b82-6feb-11e7-818b-055ee6d0e754.jpg',
                'api': 'https://api.bl3p.eu',
                'www': [
                    'https://bl3p.eu',
                    'https://bitonic.nl',
                ],
                'doc': [
                    'https://github.com/BitonicNL/bl3p-api/tree/master/docs',
                    'https://bl3p.eu/api',
                    'https://bitonic.nl/en/api',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        '{market}/ticker',
                        '{market}/orderbook',
                        '{market}/trades',
                    ],
                },
                'private': {
                    'post': [
                        '{market}/money/depth/full',
                        '{market}/money/order/add',
                        '{market}/money/order/cancel',
                        '{market}/money/order/result',
                        '{market}/money/orders',
                        '{market}/money/orders/history',
                        '{market}/money/trades/fetch',
                        'GENMKT/money/info',
                        'GENMKT/money/deposit_address',
                        'GENMKT/money/new_deposit_address',
                        'GENMKT/money/wallet/history',
                        'GENMKT/money/withdraw',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', 'maker': 0.0025, 'taker': 0.0025 },
                'LTC/EUR': { 'id': 'LTCEUR', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR', 'maker': 0.0025, 'taker': 0.0025 },
            },
        });
    }

    async fetchBalance (params = {}) {
        let response = await this.privatePostGENMKTMoneyInfo ();
        let data = response['data'];
        let balance = data['wallets'];
        let result = { 'info': data };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let account = this.account ();
            if (currency in balance) {
                if ('available' in balance[currency]) {
                    account['free'] = parseFloat (balance[currency]['available']['value']);
                }
            }
            if (currency in balance) {
                if ('balance' in balance[currency]) {
                    account['total'] = parseFloat (balance[currency]['balance']['value']);
                }
            }
            if (account['total']) {
                if (account['free']) {
                    account['used'] = account['total'] - account['free'];
                }
            }
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    parseBidAsk (bidask, priceKey = 0, amountKey = 0) {
        return [
            bidask[priceKey] / 100000.0,
            bidask[amountKey] / 100000000.0,
        ];
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetMarketOrderbook (this.extend ({
            'market': market['id'],
        }, params));
        let orderbook = response['data'];
        return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price_int', 'amount_int');
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetMarketTicker (this.extend ({
            'market': this.marketId (symbol),
        }, params));
        let timestamp = ticker['timestamp'] * 1000;
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['bid']),
            'ask': parseFloat (ticker['ask']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['last']),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': parseFloat (ticker['volume']['24h']),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        return {
            'id': trade['trade_id'].toString (),
            'timestamp': trade['date'],
            'datetime': this.iso8601 (trade['date']),
            'symbol': market['symbol'],
            'type': undefined,
            'side': undefined,
            'price': trade['price_int'] / 100000.0,
            'amount': trade['amount_int'] / 100000000.0,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetMarketTrades (this.extend ({
            'market': market['id'],
        }, params));
        let result = this.parseTrades (response['data']['trades'], market, since, limit);
        return result;
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let market = this.market (symbol);
        let order = {
            'market': market['id'],
            'amount_int': parseInt (amount * 100000000),
            'fee_currency': market['quote'],
            'type': (side === 'buy') ? 'bid' : 'ask',
        };
        if (type === 'limit')
            order['price_int'] = parseInt (price * 100000.0);
        let response = await this.privatePostMarketMoneyOrderAdd (this.extend (order, params));
        return {
            'info': response,
            'id': response['data']['order_id'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostMarketMoneyOrderCancel ({ 'order_id': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = this.implodeParams (path, params);
        let url = this.urls['api'] + '/' + this.version + '/' + request;
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            body = this.urlencode (this.extend ({ 'nonce': nonce }, query));
            let secret = this.base64ToBinary (this.secret);
            // eslint-disable-next-line quotes
            let auth = request + "\0" + body;
            let signature = this.hmac (this.encode (auth), secret, 'sha512', 'base64');
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Rest-Key': this.apiKey,
                'Rest-Sign': this.decode (signature),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>bl3p fetchTicker consistency<commit_after>'use strict';

// ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

// ---------------------------------------------------------------------------

module.exports = class bl3p extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bl3p',
            'name': 'BL3P',
            'countries': [ 'NL', 'EU' ], // Netherlands, EU
            'rateLimit': 1000,
            'version': '1',
            'comment': 'An exchange market by BitonicNL',
            'has': {
                'CORS': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/28501752-60c21b82-6feb-11e7-818b-055ee6d0e754.jpg',
                'api': 'https://api.bl3p.eu',
                'www': [
                    'https://bl3p.eu',
                    'https://bitonic.nl',
                ],
                'doc': [
                    'https://github.com/BitonicNL/bl3p-api/tree/master/docs',
                    'https://bl3p.eu/api',
                    'https://bitonic.nl/en/api',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        '{market}/ticker',
                        '{market}/orderbook',
                        '{market}/trades',
                    ],
                },
                'private': {
                    'post': [
                        '{market}/money/depth/full',
                        '{market}/money/order/add',
                        '{market}/money/order/cancel',
                        '{market}/money/order/result',
                        '{market}/money/orders',
                        '{market}/money/orders/history',
                        '{market}/money/trades/fetch',
                        'GENMKT/money/info',
                        'GENMKT/money/deposit_address',
                        'GENMKT/money/new_deposit_address',
                        'GENMKT/money/wallet/history',
                        'GENMKT/money/withdraw',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', 'maker': 0.0025, 'taker': 0.0025 },
                'LTC/EUR': { 'id': 'LTCEUR', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR', 'maker': 0.0025, 'taker': 0.0025 },
            },
        });
    }

    async fetchBalance (params = {}) {
        let response = await this.privatePostGENMKTMoneyInfo ();
        let data = response['data'];
        let balance = data['wallets'];
        let result = { 'info': data };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let account = this.account ();
            if (currency in balance) {
                if ('available' in balance[currency]) {
                    account['free'] = parseFloat (balance[currency]['available']['value']);
                }
            }
            if (currency in balance) {
                if ('balance' in balance[currency]) {
                    account['total'] = parseFloat (balance[currency]['balance']['value']);
                }
            }
            if (account['total']) {
                if (account['free']) {
                    account['used'] = account['total'] - account['free'];
                }
            }
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    parseBidAsk (bidask, priceKey = 0, amountKey = 0) {
        return [
            bidask[priceKey] / 100000.0,
            bidask[amountKey] / 100000000.0,
        ];
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetMarketOrderbook (this.extend ({
            'market': market['id'],
        }, params));
        let orderbook = response['data'];
        return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price_int', 'amount_int');
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetMarketTicker (this.extend ({
            'market': this.marketId (symbol),
        }, params));
        let timestamp = ticker['timestamp'] * 1000;
        let last = parseFloat (ticker['last']);
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['bid']),
            'bidVolume': undefined,
            'ask': parseFloat (ticker['ask']),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': parseFloat (ticker['volume']['24h']),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        return {
            'id': trade['trade_id'].toString (),
            'timestamp': trade['date'],
            'datetime': this.iso8601 (trade['date']),
            'symbol': market['symbol'],
            'type': undefined,
            'side': undefined,
            'price': trade['price_int'] / 100000.0,
            'amount': trade['amount_int'] / 100000000.0,
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetMarketTrades (this.extend ({
            'market': market['id'],
        }, params));
        let result = this.parseTrades (response['data']['trades'], market, since, limit);
        return result;
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let market = this.market (symbol);
        let order = {
            'market': market['id'],
            'amount_int': parseInt (amount * 100000000),
            'fee_currency': market['quote'],
            'type': (side === 'buy') ? 'bid' : 'ask',
        };
        if (type === 'limit')
            order['price_int'] = parseInt (price * 100000.0);
        let response = await this.privatePostMarketMoneyOrderAdd (this.extend (order, params));
        return {
            'info': response,
            'id': response['data']['order_id'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostMarketMoneyOrderCancel ({ 'order_id': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = this.implodeParams (path, params);
        let url = this.urls['api'] + '/' + this.version + '/' + request;
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            body = this.urlencode (this.extend ({ 'nonce': nonce }, query));
            let secret = this.base64ToBinary (this.secret);
            // eslint-disable-next-line quotes
            let auth = request + "\0" + body;
            let signature = this.hmac (this.encode (auth), secret, 'sha512', 'base64');
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Rest-Key': this.apiKey,
                'Rest-Sign': this.decode (signature),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>


<commit_before>"use strict";

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange')
const { ExchangeError } = require ('./base/errors')

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'hasCORS': false,
            'hasFetchTickers': true,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'tickers': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'tickers': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
        });
    }

    commonCurrencyCode (currency) {
        if (currency == 'IOT')
            return 'IoTcoin';
        if (currency == 'BLC')
            return 'Cryptobullcoin';
        return currency;
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets['result'].length; p++) {
            let market = markets['result'][p];
            let id = market['MarketName'];
            let base = market['MarketCurrency'];
            let quote = market['BaseCurrency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetBalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetOrderbook (this.extend ({
            'market': this.marketId (symbol),
            'type': 'both',
            'depth': 100,
        }, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['buy']),
            'ask': parseFloat (ticker['sell']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['lastprice']),
            'change': undefined,
            'percentage': undefined,
            'average': parseFloat (ticker['avg']),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.tickersGetPrices (params);
        let result = { 'info': tickers };
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let uppercase = id.toUpperCase ();
            let market = undefined;
            let symbol = undefined;
            if (uppercase in this.markets_by_id) {
                market = this.markets_by_id[uppercase];
                symbol = market['symbol'];
            } else {
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.tickersGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'],
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api == 'private') {
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api == 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api == 'tickers')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
}
<commit_msg>minor edits to ccex<commit_after>"use strict";

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange')
const { ExchangeError } = require ('./base/errors')

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'hasCORS': false,
            'hasFetchTickers': true,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'tickers': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'tickers': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
        });
    }

    commonCurrencyCode (currency) {
        if (currency == 'IOT')
            return 'IoTcoin';
        if (currency == 'BLC')
            return 'Cryptobullcoin';
        return currency;
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets['result'].length; p++) {
            let market = markets['result'][p];
            let id = market['MarketName'];
            let base = market['MarketCurrency'];
            let quote = market['BaseCurrency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result.push (this.extend (this.fees['trading'], {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            }));
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetBalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetOrderbook (this.extend ({
            'market': this.marketId (symbol),
            'type': 'both',
            'depth': 100,
        }, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['buy']),
            'ask': parseFloat (ticker['sell']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['lastprice']),
            'change': undefined,
            'percentage': undefined,
            'average': parseFloat (ticker['avg']),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.tickersGetPrices (params);
        let result = { 'info': tickers };
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let uppercase = id.toUpperCase ();
            let market = undefined;
            let symbol = undefined;
            if (uppercase in this.markets_by_id) {
                market = this.markets_by_id[uppercase];
                symbol = market['symbol'];
            } else {
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.tickersGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'],
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api == 'private') {
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api == 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api == 'tickers')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
}
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOrderBooks': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'tickers': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'tickers': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                        'fullorderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
        });
    }

    commonCurrencyCode (currency) {
        if (currency === 'IOT')
            return 'IoTcoin';
        if (currency === 'BLC')
            return 'Cryptobullcoin';
        if (currency === 'XID')
            return 'InternationalDiamond';
        return currency;
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets['result'].length; p++) {
            let market = markets['result'][p];
            let id = market['MarketName'];
            let base = market['MarketCurrency'];
            let quote = market['BaseCurrency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result.push (this.extend (this.fees['trading'], {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            }));
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetBalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'market': this.marketId (symbol),
            'type': 'both',
        };
        if (typeof limit !== 'undefined')
            request['depth'] = limit; // 100
        let response = await this.publicGetOrderbook (this.extend (request, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    async fetchOrderBooks (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        // let orderBooks = [];
        let orderBooksResult = [];
        //     // TODO: rework to satisfy basic rules from the contributing doc, too many errors
        //     try {
        //         let response = await this.publicGetFullorderbook ();
        //         if (response && response.success && response.result) {
        //             let types = Object.keys (response.result);
        //             for (let i = 0; i < types.length; i++) {
        //                 let type = types[i];
        //                 let orderBookItems = response.result[type];
        //                 for (let j = 0; j < orderBookItems.length; j++) {
        //                     let orderBookItem = orderBookItems[j];
        //                     // this line won't transpile, can't use functions like that
        //                     // it is not portable to other languages
        //                     // let index = orderBooks.findIndex (function (f) {
        //                     //     return f['symbol'] === orderBookItem.Market.replace ('-', '/').toUpperCase ();
        //                     // });
        //                     // if (index < 0) {
        //                     //     orderBooks.push ({
        //                     //         symbol: orderBookItem.Market.replace ('-', '/').toUpperCase (),
        //                     //         bids: [],
        //                     //         asks: [],
        //                     //     });
        //                     //     index = orderBooks.length - 1;
        //                     // }
        //                     // if (type === 'buy') {
        //                     //     orderBooks[index]['bids'].push ([orderBookItem['Rate'], orderBookItem['Quantity']]);
        //                     // } else if (type === 'sell') {
        //                     //     orderBooks[index]['asks'].push ([orderBookItem['Rate'], orderBookItem['Quantity']]);
        //                     // }
        //                 }
        //             }
        //             for (let k = 0; k < orderBooks.length; k++) {
        //                 let orderBook = orderBooks[k];
        //                 orderBooksResult.push (orderBook);
        //             }
        //         }
        //     } catch (e) {
        //         throw new ExchangeError ('fetchOrderBooks() returned error:' + e.message + ' for full orderbook.');
        //     }
        return orderBooksResult;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['buy']),
            'ask': parseFloat (ticker['sell']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['lastprice']),
            'change': undefined,
            'percentage': undefined,
            'average': parseFloat (ticker['avg']),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.tickersGetPrices (params);
        let result = { 'info': tickers };
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let uppercase = id.toUpperCase ();
            let market = undefined;
            let symbol = undefined;
            if (uppercase in this.markets_by_id) {
                market = this.markets_by_id[uppercase];
                symbol = market['symbol'];
            } else {
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.tickersGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'],
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api === 'private') {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api === 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'tickers')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<commit_msg>fixing ccex fetchOrderBooks intermediary state #1050<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class ccex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'ccex',
            'name': 'C-CEX',
            'countries': [ 'DE', 'EU' ],
            'rateLimit': 1500,
            'has': {
                'CORS': false,
                'fetchTickers': true,
                'fetchOrderBooks': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
                'api': {
                    'tickers': 'https://c-cex.com/t',
                    'public': 'https://c-cex.com/t/api_pub.html',
                    'private': 'https://c-cex.com/t/api.html',
                },
                'www': 'https://c-cex.com',
                'doc': 'https://c-cex.com/?id=api',
            },
            'api': {
                'tickers': {
                    'get': [
                        'coinnames',
                        '{market}',
                        'pairs',
                        'prices',
                        'volume_{coin}',
                    ],
                },
                'public': {
                    'get': [
                        'balancedistribution',
                        'markethistory',
                        'markets',
                        'marketsummaries',
                        'orderbook',
                        'fullorderbook',
                    ],
                },
                'private': {
                    'get': [
                        'buylimit',
                        'cancel',
                        'getbalance',
                        'getbalances',
                        'getopenorders',
                        'getorder',
                        'getorderhistory',
                        'mytrades',
                        'selllimit',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'taker': 0.2 / 100,
                    'maker': 0.2 / 100,
                },
            },
        });
    }

    commonCurrencyCode (currency) {
        if (currency === 'IOT')
            return 'IoTcoin';
        if (currency === 'BLC')
            return 'Cryptobullcoin';
        if (currency === 'XID')
            return 'InternationalDiamond';
        return currency;
    }

    async fetchMarkets () {
        let markets = await this.publicGetMarkets ();
        let result = [];
        for (let p = 0; p < markets['result'].length; p++) {
            let market = markets['result'][p];
            let id = market['MarketName'];
            let base = market['MarketCurrency'];
            let quote = market['BaseCurrency'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = base + '/' + quote;
            result.push (this.extend (this.fees['trading'], {
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'info': market,
            }));
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privateGetBalances ();
        let balances = response['result'];
        let result = { 'info': balances };
        for (let b = 0; b < balances.length; b++) {
            let balance = balances[b];
            let code = balance['Currency'];
            let currency = this.commonCurrencyCode (code);
            let account = {
                'free': balance['Available'],
                'used': balance['Pending'],
                'total': balance['Balance'],
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'market': this.marketId (symbol),
            'type': 'both',
        };
        if (typeof limit !== 'undefined')
            request['depth'] = limit; // 100
        let response = await this.publicGetOrderbook (this.extend (request, params));
        let orderbook = response['result'];
        return this.parseOrderBook (orderbook, undefined, 'buy', 'sell', 'Rate', 'Quantity');
    }

    async fetchOrderBooks (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let result = {};
        let response = await this.publicGetFullorderbook ();
        let types = Object.keys (response['result']);
        for (let i = 0; i < types.length; i++) {
            let type = types[i];
            let orderBookItems = response['result'][type];
            for (let j = 0; j < orderBookItems.length; j++) {
                let orderBookItem = orderBookItems[j];
                // this line won't transpile, can't use functions like that
                // it is not portable to other languages
                let index = orderBooks.findIndex (function (f) {
                    return f['symbol'] === orderBookItem['Market'].replace ('-', '/').toUpperCase ();
                });
                if (index < 0) {
                    orderBooks.push ({
                        symbol: orderBookItem['Market'].replace ('-', '/').toUpperCase (),
                        bids: [],
                        asks: [],
                    });
                    index = orderBooks.length - 1;
                }
                if (type === 'buy') {
                    orderBooks[index]['bids'].push ([orderBookItem['Rate'], orderBookItem['Quantity']]);
                } else if (type === 'sell') {
                    orderBooks[index]['asks'].push ([orderBookItem['Rate'], orderBookItem['Quantity']]);
                }
            }
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = ticker['updated'] * 1000;
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['buy']),
            'ask': parseFloat (ticker['sell']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['lastprice']),
            'change': undefined,
            'percentage': undefined,
            'average': parseFloat (ticker['avg']),
            'baseVolume': undefined,
            'quoteVolume': this.safeFloat (ticker, 'buysupport'),
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.tickersGetPrices (params);
        let result = { 'info': tickers };
        let ids = Object.keys (tickers);
        for (let i = 0; i < ids.length; i++) {
            let id = ids[i];
            let ticker = tickers[id];
            let uppercase = id.toUpperCase ();
            let market = undefined;
            let symbol = undefined;
            if (uppercase in this.markets_by_id) {
                market = this.markets_by_id[uppercase];
                symbol = market['symbol'];
            } else {
                let [ base, quote ] = uppercase.split ('-');
                base = this.commonCurrencyCode (base);
                quote = this.commonCurrencyCode (quote);
                symbol = base + '/' + quote;
            }
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.tickersGetMarket (this.extend ({
            'market': market['id'].toLowerCase (),
        }, params));
        let ticker = response['ticker'];
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.parse8601 (trade['TimeStamp']);
        return {
            'id': trade['Id'],
            'info': trade,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['OrderType'].toLowerCase (),
            'price': trade['Price'],
            'amount': trade['Quantity'],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetMarkethistory (this.extend ({
            'market': market['id'],
            'type': 'both',
            'depth': 100,
        }, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'privateGet' + this.capitalize (side) + type;
        let response = await this[method] (this.extend ({
            'market': this.marketId (symbol),
            'quantity': amount,
            'rate': price,
        }, params));
        return {
            'info': response,
            'id': response['result']['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        return await this.privateGetCancel ({ 'uuid': id });
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api];
        if (api === 'private') {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ().toString ();
            let query = this.keysort (this.extend ({
                'a': path,
                'apikey': this.apiKey,
                'nonce': nonce,
            }, params));
            url += '?' + this.urlencode (query);
            headers = { 'apisign': this.hmac (this.encode (url), this.encode (this.secret), 'sha512') };
        } else if (api === 'public') {
            url += '?' + this.urlencode (this.extend ({
                'a': 'get' + path,
            }, params));
        } else {
            url += '/' + this.implodeParams (path, params) + '.json';
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (api === 'tickers')
            return response;
        if ('success' in response)
            if (response['success'])
                return response;
        throw new ExchangeError (this.id + ' ' + this.json (response));
    }
};
<|endoftext|>


<commit_before>var print = function (inp) {
}

Array.prototype.avs = function () {

    if (this.length > 0) {
        for (var i = 1; i < this.length; i++) {
            if (this[i] !== this[0])
                return false;
        }
    }
    return true;
}

Date.prototype.gDate = function () {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth() + 1).toString();
    var dd = this.getDate().toString();
    return yyyy + (mm[1] ? mm : "0" + mm[0]) + (dd[1] ? dd : "0" + dd[0])
};

var metTemp = ['
' +
    '
',
    '

' + '

0%

'
];

var wetTemp = '

Weather
 Hourly temps.(°C)

<canvas class = "met weather canvas"></canvas>

';
var wetNotTemp = '

Weather
Data not available.

<canvas class = "met weather canvas"></canvas>

';
var imCT = '

 Pictures
 Pictures.

';
var imNT = '
 Pictures
 Data not available.

';
var imT = [''];

var totalPercents = {};

var addMetric = function (elemClass, metTitle) {
    var div = metTemp[0] + elemClass;
    div += metTemp[1] + metTitle;
    div += metTemp[2] + elemClass;
    div += metTemp[3] + elemClass;
    div += metTemp[4] + elemClass;
    div += metTemp[5] + elemClass;
    div += metTemp[6] + elemClass;
    div += metTemp[7];
    $("#metrics").append(div);
    setTimeout(
        function () {
            $(".metcont").css("opacity", "1");
        }, 100);
};

var setMainProg = function () {
    var res = 0;
    var num = 0;
    print(totalPercents);
    $.each(totalPercents, function (i) {
        res += totalPercents[i];
        num++;
    });
    var amt = res / num;
    $(".overview.progfill").css("background-color", getCol(amt));
    $(".overview.progfill").css("box-shadow", "0px 7px 0px 0px " + getShadCol(amt));
    $(".overview.proglab").text(Math.round(amt).toString() + "%");
    if (amt > 100) {
        amt = 100;
    }
    $(".overview.progfill").css("width", amt.toString() + "%");
};

var getJSON = function (requestURL) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", requestURL, false);
    xmlHttp.send(null);
    return $.parseJSON(xmlHttp.responseText);
};

var setProg = function (elemClass, progAmt, descUp) {
    var bar = $("." + elemClass + ".progfill");
    var base = $("." + elemClass + ".progbase");
    var label = $("." + elemClass + ".proglab");
    var desc = $("." + elemClass + ".progdesc");
    if (progAmt != null) {
        bar.css("background-color", getCol(progAmt));
        bar.css("box-shadow", "0px 7px 0px 0px " + getShadCol(progAmt));
        label.text(Math.round(progAmt).toString() + "%");
        totalPercents[elemClass] = progAmt;
        if (progAmt > 100) {
            progAmt = 100;
        }
        bar.css("width", progAmt.toString() + "%");
    }
    desc.text(descUp);
    setMainProg();
};

var addProg = function (elemClass, progAmt, descUp) {
    addMetric(elemClass, elemClass);
    setProg(elemClass, progAmt, descUp);
};

var getCol = function (progAmt) {
    return (progAmt < 50) ? "#F75E5E" : (progAmt < 80) ? "#F59631" : "#5EE66E";
};

var getShadCol = function (progAmt) {
    return (progAmt < 50) ? "#CF3636" : (progAmt < 80) ? "#DE7C14" : "#22BF35";
};

window.onscroll = function () {
    if ($("body").scrollTop() > 10) {
        $("#divider").css("opacity", "1");
    } else {
        $("#divider").css("opacity", "0");
    }
};

var getMet = function (usern, metric, date) {
    var user = getJSON("http://vps.ritwikd.com:8081/" + usern + "?type=user");
    var data = getJSON("http://vps.ritwikd.com:8081/" + usern + "?type=data&metric=" + metric + "&date=" + date);
    if (data.value == null) {
        return null;
    }
    return [data.value, parseInt(user.metrics[metric][0]), user.metrics[metric][1]];
};

var getUser = function (usern) {
    var user = getJSON("http://vps.ritwikd.com:8081/" + usern + "?type=user");
    return user;
}

function respChart(selector, data) {

    var option = {
        scaleOverlay: false,
        scaleOverride: false,
        scaleSteps: null,
        scaleStepWidth: null,
        scaleStartValue: null,
        scaleLineColor: "rgba(0,0,0,.1)",
        scaleLineWidth: 1,
        scaleShowLabels: true,
        scaleLabel: "<%=value%>",
        scaleFontFamily: "arial",
        scaleFontSize: 10,
        scaleFontStyle: "normal",
        scaleFontColor: "#909090",
        scaleShowGridLines: true,
        scaleGridLineColor: "rgba(0,0,0,.05)",
        scaleGridLineWidth: 1,
        bezierCurve: true,
        pointDot: true,
        pointDotRadius: 3,
        pointDotStrokeWidth: 1,
        datasetStroke: true,
        datasetStrokeWidth: 2,
        datasetFill: true,
        animation: true,
        animationSteps: 60,
        animationEasing: "easeOutQuart",
        onAnimationComplete: null
    }

    var ctx = selector.get(0).getContext("2d");

    var container = $(selector).parent();

    $(window).resize(generateChart);

    function generateChart() {

        var ww = selector.attr('width', $(container).width());

        new Chart(ctx).Line(data, option);
    };

    generateChart();

}

function setDate (date) {
    $.get('http://vps.ritwikd.com:8081/' + username + "?type=write&date=" + date, function(response) {
        console.log(response);
    });
    isvalid = false;
    $("#datebar a").css("color", "#444444");
    $("#datebar a").css("font-weight", "300");
    $("#datebar a").css("font-size", "100%");
    $(location.hash + " a").css("color", "#4093E6");
    $(location.hash + " a").css("font-weight", "500");
    $(location.hash + " a").css("font-size", "125%");
    $(location.hash).className = "active";
    $("#metrics").html('
Metrics
');
    totalPercents = {};
    $.each(mets, function(item) {
        curMet = getMet(username, item, date);
        if (curMet[0] == "null") {
            addProg(item.charAt(0).toUpperCase() + item.substring(1), null, "Data not available.");
        } else {
            isvalid = true;
            addProg(item.charAt(0).toUpperCase() + item.substring(1), 100 * curMet[0] / curMet[1], curMet[0].toString() + " out of " + curMet[1].toString() + " " + curMet[2] + ".");
        }
    });
    if (isvalid == false) {
        $(".overview.progfill").css("background-color", "#F5F5F5");
        $(".overview.progfill").css("box-shadow", "0px 0px 0px 0px rgba(0, 0, 0, 0)");
        $(".overview.proglab").text("0%");
        $(".overview.progfill").css("width", "0%");
    }
    $.each(stats, function(item) {
        var data = getJSON("http://vps.ritwikd.com:8081/" + username + "?type=data&metric=" + item + "&date=" + date);
        if (item == "weather") {
            if (data.value == "null") {
                $("#metrics").append(wetNotTemp);
            } else {
                $("#metrics").append(wetTemp);
                respChart($(".met.canvas"), {
                    "labels": ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
                    datasets: [{
                        label: "Temps",
                        fillColor: " rgba(146, 255, 141, 1)",
                        strokeColor: "rgba(220,220,220,0.8)",
                        highlightFill: "rgba(220,220,220,0.75)",
                        highlightStroke: "rgba(220,220,220,1)",
                        data: data.temps
                    }]
                });
            }

        } else if (item == "photos") {
            if (data.value == "null") {
                $("#metrics").append(imNT);
            } else {
                $("#metrics").append(imCT);
                for (var j = 0; j < data.value.length; j++) {
                    $(".met.photos.progcont").append(imT[0] + data.value[j] + imT[1] + data.value[j] + imT[2]);
                }
            }

        }
    });
}

var dkey;
var date = new Date();
var username = sessionStorage.getItem('username');
var curMet;
var user = getUser(username);
var mets = user.metrics;
var stats = user.stats;
var name = user.fullname;
$(".usertitle").text(name);
var isvalid = false;

if (location.hash.length == 9) {
    setDate(location.hash.substring(1));
} else {
    location.hash = "#" + date.gDate();
}

for (var i = 0; i < 10; i++) {
    dkey = date.toString().substring(4, 10) + ',' + date.toString().substring(10, 15);
    $("#datebar").append('
' + dkey + '
');
    date.setDate(date.getDate() - 1);
}

$("#datebar a").css("color", "#444444");

$(window).on('hashchange', function () {
    setDate(location.hash.substring(1));
});

$(document).ready(function() {
    $(".fancybox").fancybox();
});

<commit_msg>Fixing reload problem.<commit_after>var print = function (inp) {
}

Array.prototype.avs = function () {

    if (this.length > 0) {
        for (var i = 1; i < this.length; i++) {
            if (this[i] !== this[0])
                return false;
        }
    }
    return true;
}

Date.prototype.gDate = function () {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth() + 1).toString();
    var dd = this.getDate().toString();
    return yyyy + (mm[1] ? mm : "0" + mm[0]) + (dd[1] ? dd : "0" + dd[0])
};

var metTemp = ['
' +
    '
',
    '

' + '

0%

'
];

var wetTemp = '

Weather
 Hourly temps.(°C)

<canvas class = "met weather canvas"></canvas>

';
var wetNotTemp = '

Weather
Data not available.

<canvas class = "met weather canvas"></canvas>

';
var imCT = '

 Pictures
 Pictures.

';
var imNT = '
 Pictures
 Data not available.

';
var imT = [''];

var totalPercents = {};

var addMetric = function (elemClass, metTitle) {
    var div = metTemp[0] + elemClass;
    div += metTemp[1] + metTitle;
    div += metTemp[2] + elemClass;
    div += metTemp[3] + elemClass;
    div += metTemp[4] + elemClass;
    div += metTemp[5] + elemClass;
    div += metTemp[6] + elemClass;
    div += metTemp[7];
    $("#metrics").append(div);
    setTimeout(
        function () {
            $(".metcont").css("opacity", "1");
        }, 100);
};

var setMainProg = function () {
    var res = 0;
    var num = 0;
    print(totalPercents);
    $.each(totalPercents, function (i) {
        res += totalPercents[i];
        num++;
    });
    var amt = res / num;
    $(".overview.progfill").css("background-color", getCol(amt));
    $(".overview.progfill").css("box-shadow", "0px 7px 0px 0px " + getShadCol(amt));
    $(".overview.proglab").text(Math.round(amt).toString() + "%");
    if (amt > 100) {
        amt = 100;
    }
    $(".overview.progfill").css("width", amt.toString() + "%");
};

var getJSON = function (requestURL) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", requestURL, false);
    xmlHttp.send(null);
    return $.parseJSON(xmlHttp.responseText);
};

var setProg = function (elemClass, progAmt, descUp) {
    var bar = $("." + elemClass + ".progfill");
    var base = $("." + elemClass + ".progbase");
    var label = $("." + elemClass + ".proglab");
    var desc = $("." + elemClass + ".progdesc");
    if (progAmt != null) {
        bar.css("background-color", getCol(progAmt));
        bar.css("box-shadow", "0px 7px 0px 0px " + getShadCol(progAmt));
        label.text(Math.round(progAmt).toString() + "%");
        totalPercents[elemClass] = progAmt;
        if (progAmt > 100) {
            progAmt = 100;
        }
        bar.css("width", progAmt.toString() + "%");
    }
    desc.text(descUp);
    setMainProg();
};

var addProg = function (elemClass, progAmt, descUp) {
    addMetric(elemClass, elemClass);
    setProg(elemClass, progAmt, descUp);
};

var getCol = function (progAmt) {
    return (progAmt < 50) ? "#F75E5E" : (progAmt < 80) ? "#F59631" : "#5EE66E";
};

var getShadCol = function (progAmt) {
    return (progAmt < 50) ? "#CF3636" : (progAmt < 80) ? "#DE7C14" : "#22BF35";
};

window.onscroll = function () {
    if ($("body").scrollTop() > 10) {
        $("#divider").css("opacity", "1");
    } else {
        $("#divider").css("opacity", "0");
    }
};

var getMet = function (usern, metric, date) {
    var user = getJSON("http://vps.ritwikd.com:8081/" + usern + "?type=user");
    var data = getJSON("http://vps.ritwikd.com:8081/" + usern + "?type=data&metric=" + metric + "&date=" + date);
    if (data.value == null) {
        return null;
    }
    return [data.value, parseInt(user.metrics[metric][0]), user.metrics[metric][1]];
};

var getUser = function (usern) {
    var user = getJSON("http://vps.ritwikd.com:8081/" + usern + "?type=user");
    return user;
}

function respChart(selector, data) {

    var option = {
        scaleOverlay: false,
        scaleOverride: false,
        scaleSteps: null,
        scaleStepWidth: null,
        scaleStartValue: null,
        scaleLineColor: "rgba(0,0,0,.1)",
        scaleLineWidth: 1,
        scaleShowLabels: true,
        scaleLabel: "<%=value%>",
        scaleFontFamily: "arial",
        scaleFontSize: 10,
        scaleFontStyle: "normal",
        scaleFontColor: "#909090",
        scaleShowGridLines: true,
        scaleGridLineColor: "rgba(0,0,0,.05)",
        scaleGridLineWidth: 1,
        bezierCurve: true,
        pointDot: true,
        pointDotRadius: 3,
        pointDotStrokeWidth: 1,
        datasetStroke: true,
        datasetStrokeWidth: 2,
        datasetFill: true,
        animation: true,
        animationSteps: 60,
        animationEasing: "easeOutQuart",
        onAnimationComplete: null
    }

    var ctx = selector.get(0).getContext("2d");

    var container = $(selector).parent();

    $(window).resize(generateChart);

    function generateChart() {

        var ww = selector.attr('width', $(container).width());

        new Chart(ctx).Line(data, option);
    };

    generateChart();

}

function setDate (date) {
    $.get('http://vps.ritwikd.com:8081/' + username + "?type=write&date=" + date, function(response) {
        console.log(response);
    });
    isvalid = false;
    $("#datebar a").css("color", "#444444");
    $("#datebar a").css("font-weight", "300");
    $("#datebar a").css("font-size", "100%");
    $(location.hash + " a").css("color", "#4093E6");
    $(location.hash + " a").css("font-weight", "500");
    $(location.hash + " a").css("font-size", "125%");
    $(location.hash).className = "active";
    $("#metrics").html('
Metrics
');
    totalPercents = {};
    $.each(mets, function(item) {
        curMet = getMet(username, item, date);
        if (curMet[0] == "null") {
            addProg(item.charAt(0).toUpperCase() + item.substring(1), null, "Data not available.");
        } else {
            isvalid = true;
            addProg(item.charAt(0).toUpperCase() + item.substring(1), 100 * curMet[0] / curMet[1], curMet[0].toString() + " out of " + curMet[1].toString() + " " + curMet[2] + ".");
        }
    });
    if (isvalid == false) {
        $(".overview.progfill").css("background-color", "#F5F5F5");
        $(".overview.progfill").css("box-shadow", "0px 0px 0px 0px rgba(0, 0, 0, 0)");
        $(".overview.proglab").text("0%");
        $(".overview.progfill").css("width", "0%");
    }
    $.each(stats, function(item) {
        var data = getJSON("http://vps.ritwikd.com:8081/" + username + "?type=data&metric=" + item + "&date=" + date);
        if (item == "weather") {
            if (data.value == "null") {
                $("#metrics").append(wetNotTemp);
            } else {
                $("#metrics").append(wetTemp);
                respChart($(".met.canvas"), {
                    "labels": ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""],
                    datasets: [{
                        label: "Temps",
                        fillColor: " rgba(146, 255, 141, 1)",
                        strokeColor: "rgba(220,220,220,0.8)",
                        highlightFill: "rgba(220,220,220,0.75)",
                        highlightStroke: "rgba(220,220,220,1)",
                        data: data.temps
                    }]
                });
            }

        } else if (item == "photos") {
            if (data.value == "null") {
                $("#metrics").append(imNT);
            } else {
                $("#metrics").append(imCT);
                for (var j = 0; j < data.value.length; j++) {
                    $(".met.photos.progcont").append(imT[0] + data.value[j] + imT[1] + data.value[j] + imT[2]);
                }
            }

        }
    });
}

var dkey;
var date = new Date();
var username = sessionStorage.getItem('username');
var curMet;
var user = getUser(username);
var mets = user.metrics;
var stats = user.stats;
var name = user.fullname;
$(".usertitle").text(name);
var isvalid = false;

if (location.hash.length == 9) {
    setDate(location.hash.substring(1));
} else {
    location.hash = "#" + date.gDate();
}

for (var i = 0; i < 10; i++) {
    dkey = date.toString().substring(4, 10) + ',' + date.toString().substring(10, 15);
    $("#datebar").append('
' + dkey + '
');
    date.setDate(date.getDate() - 1);
}

$("#datebar a").css("color", "#444444");

$(window).on('hashchange', function () {
    setDate(location.hash.substring(1));
});

$(document).ready(function() {
    $(".fancybox").fancybox();
    $(location.hash + " a").css("color", "#4093E6");
    $(location.hash + " a").css("font-weight", "500");
    $(location.hash + " a").css("font-size", "125%");
});

<|endoftext|>


<commit_before>'use strict';

function add_split(){
    if(core_intervals['timer']['paused']){
        return;
    }

    calculate_time();
    core_elements['splits'].innerHTML +=
      current_time['hours'] + ':'
      + current_time['minutes'] + ':'
      + current_time['seconds'] + '.'
      + current_time['milliseconds'] + '
';
}

function calculate_time(){
    time_ms = date_to_timestamp() - start_time;
    current_time['hours'] = Math.floor(time_ms / 3600000);
    current_time['minutes'] = Math.floor(time_ms / 60000) % 60;
    current_time['seconds'] = Math.floor(time_ms / 1000) % 60;
    current_time['milliseconds'] = time_ms % 1000;

    // Add extra 0s.
    current_time['minutes'] = core_digits_min({
      'number': current_time['minutes'],
    });
    current_time['seconds'] = core_digits_min({
      'number': current_time['seconds'],
    });
    current_time['milliseconds'] = core_digits_min({
      'digits': 3,
      'number': current_time['milliseconds'],
    });
}

function draw(){
    calculate_time();
    const ids = [
      'hours',
      'milliseconds',
      'minutes',
      'seconds',
    ];
    for(const id in ids){
        core_elements[ids[id]].textContent = current_time[ids[id]];
    }
}

function reset_timer(){
    if(core_menu_open
      || !globalThis.confirm('Clear splits and reset timer?')){
        return;
    }

    stop();

    start_time = -1;

    const ids = {
      'hours': '0',
      'milliseconds': '000',
      'minutes': '00',
      'seconds': '00',
      'splits': '',
    };
    for(const id in ids){
        core_elements[id].textContent = ids[id];
    }
}

function start(){
    if(core_menu_open){
        return;
    }

    document.getElementById('reset-key-display').value = 'Reset [T]';
    document.getElementById('start-key-display').value = 'Start [X]';
    start_time = date_to_timestamp() - (start_time === -1 ? 0 : time_ms);
    core_interval_resume_all();
}

function stop(){
    core_interval_pause_all();
}
<commit_msg>removed unnecessary comments<commit_after>'use strict';

function add_split(){
    if(core_intervals['timer']['paused']){
        return;
    }

    calculate_time();
    core_elements['splits'].innerHTML +=
      current_time['hours'] + ':'
      + current_time['minutes'] + ':'
      + current_time['seconds'] + '.'
      + current_time['milliseconds'] + '
';
}

function calculate_time(){
    time_ms = date_to_timestamp() - start_time;
    current_time['hours'] = Math.floor(time_ms / 3600000);
    current_time['minutes'] = Math.floor(time_ms / 60000) % 60;
    current_time['seconds'] = Math.floor(time_ms / 1000) % 60;
    current_time['milliseconds'] = time_ms % 1000;

    current_time['minutes'] = core_digits_min({
      'number': current_time['minutes'],
    });
    current_time['seconds'] = core_digits_min({
      'number': current_time['seconds'],
    });
    current_time['milliseconds'] = core_digits_min({
      'digits': 3,
      'number': current_time['milliseconds'],
    });
}

function draw(){
    calculate_time();
    const ids = [
      'hours',
      'milliseconds',
      'minutes',
      'seconds',
    ];
    for(const id in ids){
        core_elements[ids[id]].textContent = current_time[ids[id]];
    }
}

function reset_timer(){
    if(core_menu_open
      || !globalThis.confirm('Clear splits and reset timer?')){
        return;
    }

    stop();

    start_time = -1;

    const ids = {
      'hours': '0',
      'milliseconds': '000',
      'minutes': '00',
      'seconds': '00',
      'splits': '',
    };
    for(const id in ids){
        core_elements[id].textContent = ids[id];
    }
}

function start(){
    if(core_menu_open){
        return;
    }

    document.getElementById('reset-key-display').value = 'Reset [T]';
    document.getElementById('start-key-display').value = 'Start [X]';
    start_time = date_to_timestamp() - (start_time === -1 ? 0 : time_ms);
    core_interval_resume_all();
}

function stop(){
    core_interval_pause_all();
}
<|endoftext|>


<commit_before>'use strict';

function generate(){
    core_storage_save();

    // Generate passwords.
    var loopcounter = core_storage_data['repeat'] - 1;
    var passwords = '';
    do{
        passwords += core_html_format({
          'string': core_random_string({
            'characters': core_storage_data['characters'],
            'length': core_storage_data['length'] - 1,
          }),
        }) + '
';
    }while(loopcounter--);
    document.getElementById('passwords').innerHTML = passwords;
}
<commit_msg>changed var to let<commit_after>'use strict';

function generate(){
    core_storage_save();

    // Generate passwords.
    let loopcounter = core_storage_data['repeat'] - 1;
    let passwords = '';
    do{
        passwords += core_html_format({
          'string': core_random_string({
            'characters': core_storage_data['characters'],
            'length': core_storage_data['length'] - 1,
          }),
        }) + '
';
    }while(loopcounter--);
    document.getElementById('passwords').innerHTML = passwords;
}
<|endoftext|>