All files / Exchanges Bitsaa.ts

6.84% Statements 8/117
0% Branches 0/19
0% Functions 0/23
6.96% Lines 8/115

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 2501x 1x   1x 1x 1x     1x   1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import axios, { AxiosInstance } from 'axios'
import * as crypto from 'crypto';
import CryptoCoin from '../util/CrytoCoin';
import Order from '../util/Order';
import { OrderTypeEnum } from '../enums';
import Account from '../util/Account';
import { Currency } from '../enums/index';
import ExchangeInterface from '../Interfaces/ExchangeInterface';
import Ticker from '../util/Ticker';
 
const BASE_URL = 'https://bitssa.com/api/v2'
 
export default class Bitsaa implements ExchangeInterface {
    privateApi: AxiosInstance
    publicApi: AxiosInstance
    baseUrl: string
    apiKey: string
    secretKey: string
 
    constructor(obj?: Object) {
        if (obj) {
            const objKeys = Object.keys(obj)
            for (const key of objKeys) {
                this[key] = obj[key]
            }
        }
        this.baseUrl = BASE_URL
        this.privateApi = axios.create({
            baseURL: this.baseUrl
        })
        this.publicApi = axios.create({
            baseURL: this.baseUrl
        })
 
        this.privateApi.interceptors.request.use(
            config => this.axiosInterceptor(config),
            error => Promise.reject(error)
        );
    }
 
    static getExtraParams(url: string):object {
        const index  = url.indexOf('?')
        const result = { url }
        if (index !== -1) {
            const newUrl = url.substr(index + 1)
            result.url = result.url.substr(0, index)
            const params     = newUrl.split('&')
        }
        return result
    }
 
    axiosInterceptor(config: any) {
        const nounce = new Date().getTime()
 
        let params          = ''
        let queryParamsList = [`access_key=${this.apiKey}`, `tonce=${nounce}`]
 
        let { url } = config
 
        const index = url.indexOf('?')
 
        // Get query parameters from url and add it into array
        if (index !== -1) {
            params = url.substr(index + 1)
            url = url.substr(0, index)
            queryParamsList = queryParamsList.concat(params.split('&'))
        }
        // sorting all query params in alphabateical order
        // since bitsaa require params in alphabatical order
        queryParamsList.sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0))
        const queryParams = queryParamsList.join('&')
 
        const text      = `${config.method.toUpperCase()}|/api/v2${url}|${queryParams}`
        const hash      = crypto.createHmac('sha256', this.secretKey).update(text).digest('hex');
        const newConfig = config
 
        newConfig.url = `${url}?${queryParams}&signature=${hash}`
        // console.log(config);
        // if(nounce !== 2) throw new Error("")
        return newConfig
    }
 
    async getBalance(cryptocoin?:CryptoCoin): Promise<Account> {
        const url = '/members/me.json'
        const res = await this.privateApi.get(url)
        const account = new Account({
            exchangeName: this.getExchangeName()
        })
        for (const accObj of res.data.accounts) {
            account.setBalance(accObj.currency, Number(accObj.balance))
        }
        return account
    }
 
    async getMyOrders(cryptocoin?: CryptoCoin): Promise<any> {
        const url = '/orders.json?market=dkdbtc'
        const res = await this.privateApi.get(url)
        return res.data
    }
 
    async cancelMyAllOrders(cryptocoin?: CryptoCoin): Promise<any> {
        if (!cryptocoin) {
            const url = '/orders/clear.json'
            const res = await this.privateApi.post(url)
            return null;
        }
 
        const ordersList = await this.getMyOrders(cryptocoin)
        return Promise.all(ordersList.map(order => this.cancelMyOrder(order.id, cryptocoin)))
    }
 
    async cancelMyOrder(id: any, cryptocoin: CryptoCoin): Promise<any> {
        const url = `/order/delete.json?id=${id}`
        const res = await this.privateApi.post(url)
        return res.data
    }
 
    static getMarket(cryptocoin: CryptoCoin):string {
        switch (cryptocoin.priCoin) {
            case 'dkd':
                return 'dkdbtc'
            default:
        }
        throw new Error('invalid cryptocoin')
    }
 
    async putOrder(order: Order):Promise<Order> {
        let url  = '/orders.json?'
        url += `market=${Bitsaa.getMarket(order.cryptocoin)}`
        url += `&price=${order.price}`
        url += `&side=${Bitsaa.getOrderType(order.type)}`
        url += `&volume=${order.volume}`
        try {
            const res = await this.privateApi.post(url)
            if (res.data) {
                const newOrder = order
                newOrder.id = res.data.id
                return newOrder
            }
            throw new Error('unable to put order ')
        } catch (error) {
            throw new Error(error)
        }
    }
 
    static getOrderType(type: OrderTypeEnum):string {
        switch (type) {
            case OrderTypeEnum.BUY: return 'buy'
            case OrderTypeEnum.SELL: return 'sell'
            default:
        }
        throw new Error('Invalid Type')
    }
 
    async getBuyOrders(cryptocoin: CryptoCoin): Promise<Order[]> {
        const url = `order_book.json?market=${Bitsaa.getMarket(cryptocoin)}&asks_limit=1`
        const ordersList: Order[] = []
        const res = await this.publicApi.get(url)
        for (const orderObj of res.data.bids) {
            ordersList.push(new Order({
                type  : OrderTypeEnum.BUY,
                volume: orderObj.volume,
                price : orderObj.price,
                cryptocoin
            }))
        }
        return ordersList
    }
    async getSellOrders(cryptocoin: CryptoCoin): Promise<Order[]> {
        const url = `order_book.json?market=${Bitsaa.getMarket(cryptocoin)}&bids_limit=1`
        const ordersList: Order[] = []
        const res = await this.publicApi.get(url)
        for (const orderObj of res.data.asks) {
            ordersList.push(new Order({
                type  : OrderTypeEnum.SELL,
                volume: orderObj.volume,
                price : orderObj.price,
                cryptocoin
            }))
        }
        return ordersList
    }
 
    async getOrders(cryptocoin: CryptoCoin, limit:number = 10):
        Promise<{ buyOrderList: Order[], sellOrderList: Order[] }> {
        const url                    = `order_book.json?market=${Bitsaa.getMarket(cryptocoin)}&asks_limit=${limit}&bids_limit=${limit}`
        const res                    = await this.publicApi.get(url)
        const buyOrderList: Order[]  = []
        const sellOrderList: Order[] = []
        for (const orderObj of res.data.asks) {
            sellOrderList.push(new Order({
                type  : OrderTypeEnum.SELL,
                volume: Number(orderObj.volume),
                price : Number(orderObj.price),
                cryptocoin
            }))
        }
        // console.log(JSON.stringify(sellOrderList));
        for (const orderObj of res.data.bids) {
            buyOrderList.push(new Order({
                type  : OrderTypeEnum.BUY,
                volume: Number(orderObj.volume),
                price : Number(orderObj.price),
                cryptocoin
            }))
        }
        return { buyOrderList, sellOrderList }
    }
 
    getTicker(cryptocoin?: CryptoCoin, withVolume: boolean = false): Promise<Ticker> {
        if (!withVolume) {
            return this.publicApi
                .get(`/tickers/${Bitsaa.getMarket(cryptocoin)}.json`)
                .then((response) => {
                    const result = response.data.ticker
                    const ticker = new Ticker({
                        ask: Number(result.sell),
                        bid: Number(result.buy),
                        cryptocoin
                    })
                    return ticker
                }).catch((err) => {
                    console.log(err);
                    return new Ticker({})
                })
        }
        return this.getOrders(cryptocoin, 1).then((data) => {
            const { buyOrderList, sellOrderList } = data
            const buyOrder = buyOrderList[0]
            const sellOrder = sellOrderList[0]
            const ticker = new Ticker({
                ask      : sellOrder.price,
                bid      : buyOrder.price,
                askVolume: sellOrder.volume,
                bidVolume: buyOrder.volume,
                cryptocoin
            })
            return ticker
        })
    }
 
    toString() {
        return 'Exchange Name: Bitsaa'
    }
 
    getExchangeName(): string {
        return 'bitsaa'
    }
}