import * as _ from 'lodash' ; import * as crypto from 'crypto' ; import * as fs from 'fs' ; import * as querystring from 'querystring' ; import { Execution , Order , Broker , QuoteSide , Quote } from './types' ; interface ToStringable { toString ( ) : string ; } export function padStart ( s , n ) { return _ . padStart ( s . toString ( ) , n ) ; } export function padEnd ( s , n ) { return _ . padEnd ( s . toString ( ) , n ) ; } export function hr ( width ) { return _ . join ( _ . times ( width , _ . constant ( '-' ) ) , '' ) ; } export function eRound ( n ) { return _ . round ( n , 10 ) ; } export function almostEqual ( a , b , tolerancePercent ) { return Math . sign ( a ) === Math . sign ( b ) && Math . abs ( a - b ) <= Math . abs ( b ) * ( tolerancePercent / 100 ) ; } export function delay ( time ) { return new Promise ( resolve => setTimeout ( resolve , time ) ) ; } export function hmac ( secret , text , algo = 'sha256' ) { return crypto . createHmac ( algo , secret ) . update ( text ) . digest ( 'hex' ) ; } export const nonce = ( function ( ) { let prev = 0 ; return function ( ) { const n = Date . now ( ) ; if ( n <= prev ) { prev += 1 ; return prev . toString ( ) ; } prev = n ; return prev . toString ( ) ; } ; } ) ( ) ; export function timestampToDate ( n ) { return new Date ( n * 1000 ) ; } export function safeQueryStringStringify ( o ) { const noUndefinedFields = _ . pickBy ( o , _ . negate ( _ . isUndefined ) ) ; return querystring . stringify ( noUndefinedFields ) ; } export function revive < T , K > ( T , o ) { const newObject = Object . create ( T . prototype ) ; return Object . assign ( newObject , o ) as T ; } function removeBom ( s ) { return s . charCodeAt ( 0 ) === 0xfeff ? s . slice ( 1 ) : s ; } export function readJsonFileSync ( filepath ) { const content = fs . readFileSync ( filepath , 'utf-8' ) ; return JSON . parse ( removeBom ( content ) ) ; } export function toExecution ( order ) { return { broker : order . broker , brokerOrderId : order . brokerOrderId , cashMarginType : order . cashMarginType , side : order . side , symbol : order . symbol } ; } export function toQuote ( broker , side , price , volume ) { return { broker , side , price , volume } ; } export function cwd ( ) { return process . env . NODE_ENV === 'test' ? `${ process . cwd ( ) }/src/__tests__/sandbox` : process . cwd ( ) ; } export function splitSymbol ( symbol ) { const [ baseCcy , quoteCcy ] = symbol . split ( '/' ) ; return { baseCcy , quoteCcy } ; } export function formatQuote ( quote ) { return ( `${ padEnd ( quote . broker , 10 ) } ${ quote . side } ` + `${ padStart ( quote . price . toLocaleString ( ) , 7 ) } ${ _ . round ( quote . volume , 3 ) }` ) ; }