Java Code Examples for com.alibaba.fastjson.JSONObject#getBigDecimal()

The following examples show how to use com.alibaba.fastjson.JSONObject#getBigDecimal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FinanceConsumer.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 处理充值消息,key值为币种的名称(注意是全称,如Bitcoin)
 *
 * @param record
 */
@KafkaListener(topics = {"deposit"})
public void handleDeposit(ConsumerRecord<String, String> record) {
    logger.info("topic={},key={},value={}", record.topic(), record.key(), record.value());
    if (StringUtils.isEmpty(record.value())) {
        return;
    }
    JSONObject json = JSON.parseObject(record.value());
    if (json == null) {
        return;
    }
    BigDecimal amount = json.getBigDecimal("amount");
    String txid = json.getString("txid");
    String address = json.getString("address");
    Coin coin = coinService.findOne(record.key());
    logger.info("coin={}", coin);

    if (coin != null && walletService.findDeposit(address, txid) == null) {
        MessageResult mr = walletService.recharge(coin, address, amount, txid);
        logger.info("wallet recharge result:{}", mr);
    }
}
 
Example 2
Source File: BitfinexUtil.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 统一解析Trades
 */
public static Trades parseTrades(JSONArray r) {
    List<Trade> trades = new ArrayList<>(r.size());
    for (int i = 0; i < r.size(); i++) {
        JSONObject t = r.getJSONObject(i);
           /*{
                "timestamp":1548042361,
                "tid":333729405,
                "price":"3584.3",
                "amount":"0.015",
                "exchange":"bitfinex",
                "type":"sell"
            },*/
        Long time = t.getLong("timestamp");
        String id = t.getString("tid");
        Side side = Side.valueOf(t.getString("type").toUpperCase());
        BigDecimal price = t.getBigDecimal("price");
        BigDecimal amount = t.getBigDecimal("amount");
        trades.add(new Trade(r.getString(i), time, id, side, price, amount));
    }
    return new Trades(trades);
}
 
Example 3
Source File: BinanceExchange.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected Balances transformBalances(List<String> results, ExchangeInfo info) {
    String result = results.get(0);
    if (useful(result)) {
        JSONArray r = JSON.parseObject(result).getJSONArray("balances");
        List<Balance> balances = new ArrayList<>(r.size());
        for (int i = 0; i < r.size(); i++) {
            JSONObject t = r.getJSONObject(i);
            String currency = t.getString("asset");
            BigDecimal free = t.getBigDecimal("free");
            BigDecimal used = t.getBigDecimal("locked");
            balances.add(new Balance(r.getString(i), currency, free, used));
        }
        return new Balances(balances);
    }
    return null;
}
 
Example 4
Source File: Okexv3Util.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 解析单个币种余额
 *
 * @param result 原始数据
 * @param r      json
 * @return Balance
 */
public static Balance parseBalance(String result, JSONObject r) {
    /*
     * {
     *     "frozen":"0",
     *     "hold":"0",
     *     "id":"6278097",
     *     "currency":"USDT",
     *     "balance":"127.613453580677953",
     *     "available":"127.613453580677953",
     *     "holds":"0"
     * }
     */
    return new Balance(result, r.getString("currency"),
            r.getBigDecimal("available"), r.getBigDecimal("hold"));
}
 
Example 5
Source File: BitfinexExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
    protected Ticker transformTicker(List<String> results, ExchangeInfo info) {
        String result = results.get(0);
        if (useful(result)) {
            JSONObject d = JSON.parseObject(result);
                /*{
                    "mid":"3953.05",
                    "bid":"3953.0",
                    "ask":"3953.1",
                    "last_price":"3953.1",
                    "low":"3902.0",
                    "high":"4227.0",
                    "volume":"37560.79069276",
                    "timestamp":"1545458269.236464"
                }*/
            BigDecimal timestamp = d.getBigDecimal("timestamp");

            Long time = timestamp.multiply(CommonUtil.THOUSAND).longValue();
//            BigDecimal open = null;
            BigDecimal high = d.getBigDecimal("high");
            BigDecimal low = d.getBigDecimal("low");
            BigDecimal close = d.getBigDecimal("last_price");
            BigDecimal volume = d.getBigDecimal("volume");

            return new Ticker(result, time, null, high, low, close, volume);
        }
        return null;
    }
 
Example 6
Source File: CoinController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 测试请求
 *
 * @param url
 * @return
 */
private BigDecimal getWalletBalance(String url) {
    try {
        //http请求
        String resultStr = getSend(url, null);
        log.info(url + ">>>result>>>" + resultStr);
        JSONObject resultJson = JSONObject.parseObject(resultStr);
        BigDecimal bigDecimal = resultJson.getBigDecimal("data");
        return bigDecimal;
    } catch (Exception e) {
        log.error("error={}", e);
        return new BigDecimal("0");
    }
}
 
Example 7
Source File: Util.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static long getJsonLongValue(JSONObject jsonObject, String key, boolean required) {
    BigDecimal bigDecimal = jsonObject.getBigDecimal(key);
    if (required && bigDecimal == null) {
        throw new InvalidParameterException("key [" + key + "] not exist");
    }
    return (bigDecimal == null) ? 0L : bigDecimal.longValueExact();
}
 
Example 8
Source File: Okexv3Util.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 统一解析Trades
 */
public static Trades parseTrades(JSONArray r) {
    List<Trade> trades = new ArrayList<>(r.size());
    for (int i = 0, l = r.size(); i < l; i++) {
        /*
         * [
         *     {
         *         "time":"2019-01-11T14:02:02.536Z",
         *         "timestamp":"2019-01-11T14:02:02.536Z",
         *         "trade_id":"861471459",
         *         "price":"3578.8482",
         *         "size":"0.0394402",
         *         "side":"sell"
         *     },
         */
        JSONObject t = r.getJSONObject(i);
        Long time = t.getDate("timestamp").getTime();
        String id = t.getString("trade_id");
        Side side = Side.valueOf(t.getString("side").toUpperCase());
        BigDecimal price = t.getBigDecimal("price");
        BigDecimal amount = t.getBigDecimal("size");
        Trade trade = new Trade(r.getString(i), time, id, side, price, amount);
        trades.add(trade);
    }
    return new Trades(trades.stream()
            .sorted((t1, t2) -> t2.getTime().compareTo(t1.getTime()))
            .collect(Collectors.toList()));
}
 
Example 9
Source File: JSONUtil.java    From easyweb-shiro with MIT License 5 votes vote down vote up
/**
 * 得到BigDecimal类型的值
 */
public static BigDecimal getBigDecimal(String json, String key) {
    BigDecimal result = null;
    try {
        JSONObject jsonObject = JSON.parseObject(json);
        result = jsonObject.getBigDecimal(key);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 10
Source File: HuobiProExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 解析订单
 * @param result 订单结果
 * @param data json
 * @param tip 错误提示
 * @return 解析订单
 */
protected Order parseOrder(String result, JSONObject data, String tip) {
    Long time = data.getLong("created-at");
    String id = data.getString("id");
    String[] types = data.getString("type").split("-");
    Side side = Side.valueOf(types[0].toUpperCase());
    Type type = null;
    switch (types[1]) {
        case "limit": type = Type.LIMIT; break;
        case "market": type = Type.MARKET; break;
        case "ioc": type = Type.IMMEDIATE_OR_CANCEL; break;
        default:
    }
    State state;
    switch (data.getString("state")) {
        case SUBMITTING:
        case SUBMITTED: state = State.SUBMIT; break;
        case PARTIAL_FILLED: state = State.PARTIAL; break;
        case CANCELLING: state = State.SUBMIT; break;
        case FILLED: state = State.FILLED; break;
        case CANCELED: state = State.CANCEL; break;
        case PARTIAL_CANCELED: state = State.UNDONE; break;
        default: log.error("{} {} parseOrder state --> {}", name, tip, data); return null;
    }
    BigDecimal price = data.getBigDecimal("price");
    BigDecimal amount = data.getBigDecimal("amount");

    BigDecimal deal = null != data.getBigDecimal("field-amount") ?
            data.getBigDecimal("field-amount") : data.getBigDecimal("filled-amount");
    BigDecimal fieldCashAmount = null != data.getBigDecimal("field-cash-amount") ?
            data.getBigDecimal("field-cash-amount") : data.getBigDecimal("filled-cash-amount");
    BigDecimal average = exist(deal) && greater(deal, ZERO) ?
            div(fieldCashAmount, deal, 16) : null;
    if (state == State.SUBMIT && null != deal && greater(deal, ZERO)) {
        state = State.PARTIAL;
    }
    return new Order(result, time, id, side, type, state, price, amount, deal, average);
}
 
Example 11
Source File: BinanceExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
private BigDecimal getBigDecimal(JSONObject t, String name) {
    if (null == t) {
        return null;
    }
    BigDecimal number = t.getBigDecimal(name);
    if (greater(number, ZERO)) {
        return number;
    }
    return null;
}
 
Example 12
Source File: BinanceExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
private OrderDetails parseOrderDetails(JSONObject t) {
    /*
     * "symbol": "LTCBTC",
     * "orderId": 1,
     * "clientOrderId": "myOrder1",
     * "price": "0.1",
     * "origQty": "1.0",
     * "executedQty": "0.0",
     * "cummulativeQuoteQty": "0.0",
     * "status": "NEW",
     * "timeInForce": "GTC",
     * "type": "LIMIT",
     * "side": "BUY",
     * "stopPrice": "0.0",
     * "icebergQty": "0.0",
     * "time": 1499827319559,
     * "updateTime": 1499827319559,
     * "isWorking": true
     */
    Long time = t.getLong("updateTime");
    String id = t.getString("orderId");
    Side side = Side.valueOf(t.getString("side"));

    List<OrderDetail> details = new LinkedList<>();

    if (t.containsKey(FILLS)) {
        JSONArray fills = t.getJSONArray(FILLS);
        for (int i = 0; i < fills.size(); i++) {
            JSONObject tt = fills.getJSONObject(i);
            BigDecimal price = tt.getBigDecimal("price");
            BigDecimal amount = tt.getBigDecimal("qty");
            BigDecimal fee = tt.getBigDecimal("commission");
            String feeCurrency = tt.getString("commissionAsset");
            details.add(new OrderDetail(fills.getString(i), time, id, null, price, amount, fee, feeCurrency, side));
        }
    }
    return new OrderDetails(details);
}
 
Example 13
Source File: BinanceExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected Trades transformTrades(List<String> results, ExchangeInfo info) {
    String result = results.get(0);
    if (useful(result)) {
        try {
            JSONArray r = JSON.parseArray(result);
            List<Trade> trades = new ArrayList<>(r.size());
            for (int i = r.size() - 1; 0 <= i; i--) {
                JSONObject t = r.getJSONObject(i);
                /*
                 * "a": 26129,         // Aggregate tradeId
                 * "p": "0.01633102",  // Price
                 * "q": "4.70443515",  // Quantity
                 * "f": 27781,         // First tradeId
                 * "l": 27781,         // Last tradeId
                 * "T": 1498793709153, // Timestamp
                 * "m": true,          // Was the buyer the maker?
                 * "M": true           // Was the trade the best price match?
                 */
                Long time = t.getLong("T");
                String id = t.getString("f") + "_" + t.getString("l");
                Side side = t.getBoolean("m") ? Side.SELL : Side.BUY;
                BigDecimal price = t.getBigDecimal("p");
                BigDecimal amount = t.getBigDecimal("q");
                Trade trade = new Trade(r.getString(i), time, id, side, price, amount);
                trades.add(trade);
            }

            return new Trades(trades);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 14
Source File: FastJsonUtils.java    From Java-API-Test-Examples with Apache License 2.0 5 votes vote down vote up
/***
 * 解析为长位十进制数
 *
 * @param jsonString json字符串
 * @param key 关键字
 * @return  返回值
 */
public static BigDecimal formBigDecimal(String jsonString, String key) {
    try {
        if (jsonString != null && jsonString.length() > 0) {
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            return jsonObject.getBigDecimal(key);
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 15
Source File: BitfinexUtil.java    From GOAi with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
     * 解析币对精度信息
     * @param result 原始数据
     * @return 精度列表
     */
    public static List<Precision> parsePrecisions(String result) {
        JSONArray r = JSON.parseArray(result);
        List<Precision> precisions = new ArrayList<>(r.size());
        for (int i = 0; i < r.size(); i++) {
            /*
             * {
             *  "pair":"vsyusd",
             *  "price_precision":5,
             *  "initial_margin":"30.0",
             *  "minimum_margin":"15.0",
             *  "maximum_order_size":"50000.0",
             *  "minimum_order_size":"0.001",
             *  "expiration":"NA",
             *  "margin":false
             * }
             *  "pair":"btcusd",
                "price_precision":5,
                "initial_margin":"30.0",
                "minimum_margin":"15.0",
                "maximum_order_size":"2000.0",
                "minimum_order_size":"0.004",
                "expiration":"NA",
                "margin":true
             */
            JSONObject t = r.getJSONObject(i);
            String data = r.getString(i);
            String symbol = new StringBuilder(t.getString("pair").toUpperCase())
                    .insert(3, "_").toString();
//            Integer base = null;
            Integer count = t.getInteger("price_precision");
//            BigDecimal baseStep = null;
//            BigDecimal countStep = null;
            BigDecimal minBase = t.getBigDecimal("minimum_order_size");
//            BigDecimal minCount = null;
            BigDecimal maxBase = t.getBigDecimal("maximum_order_size");
//            BigDecimal maxCount = null;
            precisions.add(new Precision(data, symbol, null, count,
                    null, null, minBase, null, maxBase, null));
        }
        return precisions;
    }
 
Example 16
Source File: MemberPromotionController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
private Map getMemberPromotions(PageModel pageModel, MemberPromotionScreen screen){
    List<BooleanExpression> booleanExpressions = new ArrayList<>() ;
    if(!StringUtils.isEmpty(screen.getAccount())) {
        booleanExpressions.add(QMember.member.username.like("%"+screen.getAccount()+"%")
                .or(QMember.member.realName.like("%"+screen.getAccount()+"%"))
                .or(QMember.member.mobilePhone.like(screen.getAccount()+"%"))
                .or(QMember.member.email.like(screen.getAccount()+"%")));
    }
    if(screen.getMinPromotionNum()!=-1) {
        booleanExpressions.add(QMember.member.firstLevel.add(QMember.member.secondLevel).goe(screen.getMinPromotionNum()));
    }

    if(screen.getMaxPromotionNum()!=-1) {
        booleanExpressions.add(QMember.member.firstLevel.add(QMember.member.secondLevel).loe(screen.getMaxPromotionNum()));
    }

    RewardPromotionSetting setting = rewardPromotionSettingService.findByType(PromotionRewardType.REGISTER);

    Assert.notNull(setting,"注册奖励配置 null");

    String info = setting.getInfo() ;

    JSONObject jsonObject = JSONObject.parseObject(info);

    BigDecimal one = jsonObject.getBigDecimal("one");

    BigDecimal two = jsonObject.getBigDecimal("two");

    Map<String,String> map = new HashMap<>();

    Page<Member> page = memberService.findAll(PredicateUtils.getPredicate(booleanExpressions),pageModel.getPageable());

    List<PromotionMemberVO> list = page.getContent().stream().map(x -> PromotionMemberVO.builder().id(x.getId())
            .username(x.getUsername())
            .email(x.getEmail())
            .mobilePhone(x.getMobilePhone())
            .realName(x.getRealName())
            .promotionCode(x.getPromotionCode())
            .promotionNum(x.getFirstLevel()+x.getSecondLevel())
            .reward(map.put(setting.getCoin().getName(),
                    BigDecimalUtils.mul(one,new BigDecimal(x.getFirstLevel()+"").add(
                            BigDecimalUtils.mul(two,new BigDecimal(x.getSecondLevel()+""))
                    )).toString())!=null?map:null)
            .build())
            .collect(Collectors.toList());
    Map<String,Object> map1 = new HashMap();
    map1.put("total",page.getTotalElements());
    map1.put("list",list);
    return map1 ;
}
 
Example 17
Source File: BinanceExchange.java    From GOAi with GNU Affero General Public License v3.0 4 votes vote down vote up
private Order parseOrder(String result, JSONObject t) {
    /*
     * "symbol": "LTCBTC",
     * "orderId": 1,
     * "clientOrderId": "myOrder1",
     * "price": "0.1",
     * "origQty": "1.0",
     * "executedQty": "0.0",
     * "cummulativeQuoteQty": "0.0",
     * "status": "NEW",
     * "timeInForce": "GTC",
     * "type": "LIMIT",
     * "side": "BUY",
     * "stopPrice": "0.0",
     * "icebergQty": "0.0",
     * "time": 1499827319559,
     * "updateTime": 1499827319559,
     * "isWorking": true
     */
    Long time = t.getLong("updateTime");
    String id = t.getString("orderId");
    State state = null;
    switch (t.getString("status")) {
        case "NEW": state = State.SUBMIT; break;
        case "PARTIALLY_FILLED": state = State.PARTIAL; break;
        case "FILLED": state = State.FILLED; break;
        case "CANCELED": state = State.CANCEL; break;
        case "PENDING_CANCEL": state = State.CANCEL; break;
        case "REJECTED": state = State.CANCEL; break;
        case "EXPIRED": state = State.CANCEL; break;
        default:
    }
    Side side = Side.valueOf(t.getString("side"));
    Type type = null;
    //STOP_LOSS
    //STOP_LOSS_LIMIT
    //TAKE_PROFIT
    //TAKE_PROFIT_LIMIT
    //LIMIT_MAKER
    switch (t.getString("type")) {
        case "LIMIT" : type = Type.LIMIT; break;
        case "MARKET" : type = Type.MARKET; break;
        default:
    }

    BigDecimal price = t.getBigDecimal("price");
    BigDecimal amount = t.getBigDecimal("origQty");
    BigDecimal deal = t.getBigDecimal("executedQty");
    BigDecimal average = greater(deal, ZERO) ?
            div(t.getBigDecimal("cummulativeQuoteQty"), deal) : ZERO;
    return new Order(result, time, id, side, type,
            greater(deal, ZERO) && state == State.CANCEL ? State.UNDONE : state,
            price, amount, deal, average);
}
 
Example 18
Source File: HoubiProUtil.java    From GOAi with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 解析 币对余额
 * 单独写 不用解析所有的币了
 * @param result 原始数据
 * @param symbol 币对
 * @return Account
 */
public static Account parseAccount(String result, String symbol) {
    JSONObject r = JSON.parseObject(result);

    if (OK.equals(r.getString(STATUS))) {
        JSONArray list = r.getJSONObject("data").getJSONArray("list");

        JSONObject freeBase = null;
        JSONObject frozenBase = null;
        JSONObject freeCount = null;
        JSONObject frozenCount = null;

        String[] symbols = symbol.split("_");

        String base = symbols[0].toLowerCase();
        String count = symbols[1].toLowerCase();

        for (int i = 0; i < list.size(); i++) {
            JSONObject t = list.getJSONObject(i);

            String coin = t.getString("currency");
            String type = t.getString("type");

            if (base.equals(coin)) {
                if ("trade".equals(type)) {
                    freeBase = t;
                } else if ("frozen".equals(type)) {
                    frozenBase = t;
                }
            } else if (count.equals(coin)) {
                if ("trade".equals(type)) {
                    freeCount = t;
                } else if ("frozen".equals(type)) {
                    frozenCount = t;
                }
            }
        }
        if (null != freeBase && null != frozenBase && null != freeCount && null != frozenCount) {
            return new Account(System.currentTimeMillis(),
                    new Balance("[" + freeBase.toJSONString() + "," + frozenBase.toJSONString() + "]",
                            base.toUpperCase(), freeBase.getBigDecimal("balance"), frozenBase.getBigDecimal("balance")),
                    new Balance("[" + freeCount.toJSONString() + "," + frozenCount.toJSONString() + "]",
                            count.toUpperCase(), freeCount.getBigDecimal("balance"), frozenCount.getBigDecimal("balance")));
        }
    }
    return null;
}
 
Example 19
Source File: CommonUtil.java    From GOAi with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * 读取指定属性
 *
 * @param r    json
 * @param name 名称
 * @return BigDecimal
 */
private static BigDecimal getBigDecimal(JSONObject r, String name) {
    return null != name && r.containsKey(name) ? r.getBigDecimal(name) : null;
}
 
Example 20
Source File: CommonUtil.java    From GOAi with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * 解析档位
 *
 * @param result 元素数据
 * @param row    数组
 * @return 档位
 */
public static Row parseRowByKey(String result, JSONObject row) {
    return new Row(result, row.getBigDecimal("price"), row.getBigDecimal("amount"));
}