Skip to content

Instantly share code, notes, and snippets.

@drinchev
Last active September 20, 2023 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drinchev/272431338ad7ba306c2db1f892c75d80 to your computer and use it in GitHub Desktop.
Save drinchev/272431338ad7ba306c2db1f892c75d80 to your computer and use it in GitHub Desktop.
Candle Stick In Terminal
const UP_MOVE = 1;
const DOWN_MOVE = -1;
const SYMBOL_STICK = "│";
const SYMBOL_CANDLE = "┃";
const SYMBOL_HALF_TOP = "╽";
const SYMBOL_HALF_BOTTOM = "╿";
const SYMBOL_HALF_CANDLE_TOP = "╻";
const SYMBOL_HALF_CANDLE_BOTTOM = "╹";
const SYMBOL_HALF_STICK_TOP = "╷";
const SYMBOL_HALF_STICK_BOTTOM = "╵";
const SYMBOL_NOTHING = " ";
interface DataPoint {
open : number,
high : number,
low : number,
close : number
}
function draw( height : number, data : DataPoint[] ) {
const [MAX, MIN] = data.reduce( ( [prevMax, prevMin], item ) => [
Math.max( prevMax,
item.open,
item.high,
item.low,
item.close ),
Math.min( prevMin,
item.open,
item.high,
item.low,
item.close )
], [0, 0] );
console.log( data );
console.log( "\n" );
const cells = data.map( point => [
Math.ceil( point.open / MAX * (height - 1) ),
Math.ceil( point.high / MAX * (height - 1) ),
Math.floor( point.low / MAX * (height - 1) ),
Math.floor( point.close / MAX * (height - 1) ),
] );
return new Array( height )
.fill( "" )
.map( ( _, index ) => index )
.reverse()
.map( row => [
...cells.map( ( [open, high, low, close], index ) => {
// console.log( { index, row, open, high, low, close } );
if ( Math.max( open, high ) < row || Math.min( low, close ) > row ) {
return " ";
} else {
const start = Math.max( open, close );
const end = Math.min( open, close );
if ( row > start ) {
if ( high === row ) {
return SYMBOL_HALF_STICK_TOP;
} else {
return SYMBOL_STICK;
}
}
if ( row < end ) {
if ( low === row ) {
return SYMBOL_HALF_STICK_BOTTOM;
} else {
return SYMBOL_STICK;
}
}
if ( row === start ) {
if ( start < high ) {
return SYMBOL_HALF_TOP;
} else {
return SYMBOL_HALF_CANDLE_TOP;
}
}
if ( row === end ) {
if ( end > low ) {
return SYMBOL_HALF_BOTTOM;
} else {
return SYMBOL_HALF_CANDLE_BOTTOM;
}
}
if ( row < start && row > end ) {
return SYMBOL_CANDLE;
}
return "X";
}
} ),
"\n"
] )
.flat( 2 )
.join( "" );
}
console.log( draw( 10, [
{ open : 1, high : 1, low : 0, close : 1 },
{ open : 1, high : 3, low : 0, close : 2 },
{ open : 4, high : 6, low : 2, close : 3 },
{ open : 1, high : 2, low : 1, close : 1 }
] ) );
/*
OUTPUT :
[
{ open: 1, high: 1, low: 0, close: 1 },
{ open: 1, high: 3, low: 0, close: 2 },
{ open: 4, high: 6, low: 2, close: 3 },
{ open: 1, high: 2, low: 1, close: 1 }
]
╷┃
│╿
╽╵╷
╻╿ ╽
╿│ ╹
╵╵
*/
┷ ━
█ █
┯ █
│ █
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment