jaggedsoft / node-binance-api

Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
MIT License
1.58k stars 768 forks source link

getting unhandled Promise Rejection error saying cannot read property candlesticks of undefined. STILL NEED HELP IF POSSIBLE #454

Open ocmich74 opened 4 years ago

ocmich74 commented 4 years ago

I am getting this error down in the getCandles part of the code and have not been able to resolve it. This is first time posting on github so I apologize if my post isn't correct. I tried to format the code like it looks like in my code editor but when I hit post, it came out like this....

const rp = require('request-promise');
const cheerio = require('cheerio')
const electron = require('electron')
const VWAP = require('technicalindicators').VWAP;
const bullish = require('technicalindicators').bullish;
const unhandled = require('electron-unhandled')
const { setupPing } = require('./indicatorForPing')

unhandled({
    showDialog: true
});
const ipcRenderer = electron.ipcRenderer
const monitorBinance = {
    uri: `https://agile-cliffs-23967.herokuapp.com/ok`,
    transform: function(body) {
        return cheerio.load(body);
    }
};
let binance;
const CronJob = require('cron').CronJob;
ipcRenderer.send('pings:loaded', 'Pings Loaded')

let checkPings = new CronJob('00 * * * * *', function() {
        try {
            watchPings()
        } catch (e) {
            console.error(e)
        }
    }, () => {},
    true,
    `America/New_York`
);

const parsePing = (str) => {
    const qoutePattern = /"(.*?)"/g;
    const pingStr = str.match(qoutePattern)
    const pings = [];
    pingStr.forEach(i => {
        if (i != '"resu"' && i != null && !(String(i).includes('<'))) {
            i = i.split('"')[1].split('|')
            let ticker = i[0] + 'BTC'
            checkTimeframes(ticker)
            .then(isBullish => {
                let bullishTimeFrames = '| ';
                if (isBullish.length >= 0) {
                    isBullish.forEach(t => {
                        bullishTimeFrames = bullishTimeFrames + t.timeframe + ' | '
                    })
                    getCoinPrice(i[0] + 'BTC')
                    .then((CoinPrice) => {
            let ping = {
                symbol: i[0],
                market: 'BTC',
                ticker: ticker,
                ticker_slash: i[0] + '/' + 'BTC',
                exchange: 'binance',
                timestamp: i[7],
                ping_info: {
                    pings: Number(i[1]).valueOf(),
                    net_vol_btc: Number(i[2]).valueOf(),
                    net_vol_per: i[3],
                    net_vol_per_num: Number(String(i[3]).split('%')[0]).valueOf(),
                    recent_total_vol_btc: Number(i[4]).valueOf(),
                    recent_volume_percentage: i[5],
                    recent_volume_percentage_num: Number(String(i[6]).split('%')[0]).valueOf(),
                    recent_net_volume: Number(i[6]),
                    bullish_tf: bullishTimeFrames,
                    first_ping_price: firstPingPrice
                        }
                    }
            pings.push(ping)
                    })
        }
    })
}
        })

    return pings
}

watchPings = () => {
    rp(monitorBinance)
        .then(($) => {
            binance = require('./index').binance
            let result = $('pre').prevObject[0].children[0].data
            const bracketPattern = /[^{\}]+(?=})/g;
            let parse = result.match(bracketPattern)
            parse.forEach(str => {
                let pings = parsePing(str)
                pings.forEach(ping => {
                    setupPing(ping)
                        .then((finishedPing) => {
                            console.log(finishedPing)
                            sendToMain(finishedPing)
                        })
                        .catch((e) => {
                            console.log(e)
                        })
                })
            })
        })
        .catch((err) => {
            //console.log(err)
        })
}
sendToMain = (ping) => {
    try {
        //console.log('sending ping')
        ipcRenderer.send('binance:ping', ping)
    } catch (error) {
        console.log(error)
    }
}

isBelowVWAP = (ticker, timeframe) => {

}

getCoinPrice = (ticker) => {
    return new Promise((resolve, reject) => {
        binance.prices('BTCUSDT', (err, btc) => {
            if (err)
                reject(err)
            binance.prices(ticker, (error, coin) => {
                if (error)
                    reject(error)
                resolve({
                    btc_p: coin[ticker],
                    usdt_p: (Number(btc.BTCUSDT) * Number(coin[ticker]))
                })
            })
        })
    })
}

checkTimeframes = (t) => {
    return new Promise((resolve, reject) => {
        let isBullish = []
        let lowTF = [isTFB(t, '1m'), isTFB(t, '3m'), isTFB(t, '5m'), isTFB(t, '30m')]
        let medTF = [isTFB(t, '1h'), isTFB(t, '4h'), isTFB(t, '6h'), isTFB(t, '12h')]
        let highTF = [isTFB(t, '1d'), isTFB(t, '3d'), isTFB(t, '1w'), isTFB(t, '1M')]
        Promise.all(lowTF)
            .then(lowerTFStatus => {
                lowerTFStatus.forEach(s => {
                    if (s.bullish)
                        isBullish.push(s)
                })
                Promise.all(medTF)
                    .then(medTFStatus => {
                        medTFStatus.forEach(s => {
                            if (s.bullish)
                                isBullish.push(s)
                        })
                        Promise.all(highTF)
                            .then(highTFStatus => {
                                highTFStatus.forEach(s => {
                                    if (s.bullish)
                                        isBullish.push(s)
                                })
                                resolve(isBullish)
                            })
                            .catch((err) => {
                                reject(err)
                            })
                    })
                    .catch(err => {
                        reject(err)
                    })
            })
            .catch(err => {
                reject(err)
            })
    })
}
isTFB = (ticker, timeframe) => {
    return new Promise((resolve, reject) => {
        getCandles(ticker, timeframe, 5)
            .then((candles) => {
                let status = getCandleStatus(candles)
                resolve({
                    bullish: status,
                    timeframe: timeframe,
                })
            })
            .catch((err) => {
                reject(err)
            })
    })
}

getCandles = (ticker, time, amount) => {
    return new Promise((resolve, reject) => {
        let candles = [];
        try {
            binance.candlesticks(ticker, time, (error, ticks, symbol) => {
                if (error) {
                    reject(error)
                }
                if (ticks.length != null || ticks.length != 0) {
                    ticks.forEach(tick => {
                        candles.push({
                            open: tick[1],
                            high: tick[2],
                            close: tick[4],
                            low: tick[3],
                            volume: tick[5],
                            time: tick[0]
                        })
                    })
                    resolve(candles);
                } else {
                    reject(null)
                }
            }, { limit: amount });
        } catch (e) {
            reject(e)
        }
    })
}

getCandleStatus = (candles) => {
    let open = [];
    let high = [];
    let close = [];
    let low = [];
    candles.forEach(candle => {
        open.push(candle.open)
        high.push(candle.high)
        low.push(candle.low)
        close.push(candle.close)
    })
    let input = {
        open: open,
        high: high,
        close: close,
        low: low
    }
    let status = bullish(input)
    return status;
}`
jaggedsoft commented 4 years ago

to format javascript code you use 3 backticks like this: ```js some code here .. then 3 more backticks ```

  1. checktime calls isTFB
  2. isTFB needs a delay, if you call it too often you'll get temporarily blacklisted by binance
  3. you're only allowed 1200 weight per minute, you can call await binance.usedWeight() to tell you how much of that you've used up
  4. recommend adding a delay, if your code uses async/await you can do something like this:
    
    const sleep = ms => new Promise( res => setTimeout( res, ms ) );

await sleep(500); // half second delay

ocmich74 commented 4 years ago

Thank you for responding back so quickly. I fixed my code so its formatted correctly. The await sleep didn't work because it doesn't look like my code is async. When i remove the wait code, i still got the candlestick error. Any other suggestions?