Search code examples
dc.jscrossfilter

Need to make custom reducer to deduct two values


"Date(UTC)","Market","Type","Price","Amount","Total","Fee","Fee Coin"
12:18:07","ETCBTC","BUY","0.002064","1.05","0.00216720","0.00105","ETC"
"2018-05-26 06:01:12","ETCBTC","SELL","0.00207","5.86","0.01213020","0.00001213","BTC"
"2018-05-25 22:47:14","ETCBTC","BUY","0.002","1.32","0.00264000","0.00132","ETC"

This is part of my dataset. The problem is that in my data set "Total" that I need to use is just numbers - to make them work I have to connect them with "Type" (BUY/SELL).

BUY should work like "-" and SELL like "+"; the difference between them is that what I need to display.

I am just learning. So I didn't try a lot.

function show_profit(ndx) {
var typeDim = ndx.dimension(dc.pluck("Type"));
var profit = typeDim.group().reduce(
    function (p, v) {
        p.count++;
        p.total += v.Total;
        return p;
    },
    function (p, v) {
        p.count--;
        p.total -= v.Total;
        return p;
    },
    function () {
        return { count:0, total: 0};
    }
);

dc.barChart("#profit")
    .width(500)
    .height(300)
    .dimension(typeDim)
    .group(profit)
    .valueAccessor(function (d) {
        if (d.value.count == 0) {
            return 0;
        } else {
            return d.value.total;
        }
    })
    .transitionDuration(500)
    .x(d3.scale.ordinal())
    .xUnits(dc.units.ordinal)
    .elasticY(true)
    .xAxisLabel("Type")
    .yAxisLabel("Amount")
    .yAxis().ticks(20);
}

I just made graph with volume per BUY and SELL. My target is to find the difference between BUY and SELL and display it in a line graph.


Solution

  • I'm not sure if I understand your question completely, but if you simply want to apply SELL as positive and BUY as negative, you should be able to multiply the values by 1 or -1 in your reduction functions:

    function mult(type) {
        switch(type) {
        case 'SELL': return 1;
        case 'BUY': return -1;
        default: throw new Error('unknown Type ' + type);
    } 
    var profit = typeDim.group().reduce(
        function (p, v) {
            p.count++;
            p.total += mult(v.Type) * v.Total;
            return p;
        },
        function (p, v) {
            p.count--;
            p.total -= mult(v.Type) * v.Total;
            return p;
        },
        function () {
            return { count:0, total: 0};
        }
    );