개발 일지/코인가격알람앱_캐셔레스트

캐셔 가격알람앱 따라만들기 (1)

hackee 2018. 9. 29. 12:37

일단  캐셔레스트 사이트에서 가격을 받아오려면,  2가지 방법이 있다.

캐셔사이트에 들어갔을때 뜨는 코인 가격을 직접 받아오거나,  제공하는 api가 있어서 그걸 이용하거나.


다행히 캐셔는 후자다.  제공하는 API가 있었다.

https://api.cashierest.com/ApiDC/recenttransactions


들어가보면

이런식으로 사용법이 적혀있다.


어떻게 되는건지 바로 알아보고싶다면

현재 보고있는 브라우저 창에다가 이렇게 입력해보자

 https://rest.cashierest.com/public/recenttransactions?coin=$COIN&offset=$OFFSET&count=$COUNT


여기서 $COIN 자리에  MVL이라 치고 입력해보자

https://rest.cashierest.com/public/recenttransactions?coin=MVL&offset=$OFFSET&count=$COUNT


그럼 이런 결과가 나온다

내용을 보면,  맨위에서부터   오후12:20:52 에   Ask(판매)가 발생했고  2.25란 가격에  109340개를 팔았단걸 알 수 있다.

이렇게 받아오는 내용을 갖고  캐셔 가격알람앱을 만들면 된다.


위 내용을 보기좋게 정리해보면  이렇게 표현된다.

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
{
    "ErrCode":0,
    "ErrMessage":"",
    "ReturnData":
    [
        {
            "TransactionDate":"2018-09-29 오후 12:20:52",
            "ResentType":"Ask",
            "UnitTraded":"109340.00000000",
            "Price":"2.25000000",
            "TotalPrice":"246015.0000000000000000"
        },
        {
            "TransactionDate":"2018-09-29 오전 11:45:30","
            ResentType":"Ask",
            "UnitTraded":"446538.00000000",
            "Price":"2.25000000",
            "TotalPrice":"1004710.5000000000000000"
        }
    ]
 
    .
    .
    .(생략)
}
cs


 우린 이런형태의 데이터를 JSON 형태로 되어있다라 표현한다.


이제 이 데이터를 이용해   안드로이드에서  캐셔 가격알람어플을 만들어보겠다.


1. 일단 안드로이드 스튜디오를 이용해  기본 프로젝트를 만든다.

2. json 파싱법에 대해 검색해본다. ( https://developer.android.com/reference/android/util/JsonReader )

3. 코드 작성

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
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
 
            final TextView tvCoinPrice = (TextView)findViewById(R.id.tv_price);
 
 
            final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
 
                tvCoinPrice.setText(msg.obj.toString());
            }
        };
 
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                URL recentPriceUrl = null;
 
                try {
                    recentPriceUrl = new URL("https://rest.cashierest.com/public/recenttransactions?coin=MVL&offset=$OFFSET&count=1");
 
                    HttpsURLConnection connect = null;
 
                    connect = (HttpsURLConnection) recentPriceUrl.openConnection();
 
                    if(connect.getResponseCode() == 200) {
                        //success
                        InputStream responseBody = connect.getInputStream();
 
                        InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
 
                        JsonReader jsonReader = new JsonReader(responseBodyReader);
 
                        jsonReader.beginObject(); // Start processing the JSON object
                        while (jsonReader.hasNext()) { // Loop through all keys
                            String key = jsonReader.nextName(); // Fetch the next key
                            if (key.equals("ReturnData")) { // Check if desired key
                                // Fetch the value as a String
                                String buyOrAsk = null;
 
                                jsonReader.beginArray();
                                while(jsonReader.hasNext()) {
 
                                    jsonReader.beginObject();
                                    while(jsonReader.hasNext()) {
                                        String name = jsonReader.nextName();
 
                                        if(name.equals("ResentType"))
                                        {
                                            buyOrAsk = jsonReader.nextString();
                                        }
                                        else if(name.equals("Price"))
                                        {
                                            double price = jsonReader.nextDouble();
                                            Message msg = Message.obtain();
                                            String data ="엠블 " + buyOrAsk + " : " + price;
                                            msg.obj = data;
                                            handler.sendMessage(msg);
                                           // tvCoinPrice.setText();
                                        }
                                        else
                                            jsonReader.skipValue();
                                    }
                                    jsonReader.endObject();
                                }
                                jsonReader.endArray();
 
                            } else {
                                jsonReader.skipValue(); // Skip values of other keys
                            }
                        }
 
                        jsonReader.close();
                    }
                    else
                    {
                        //fail
                    }
 
                    connect.disconnect();
 
                }
                catch (MalformedURLException e) { //URL Error
                    e.printStackTrace();
                    return ;
                }
                catch (IOException e) {  //openConnect Error
                    e.printStackTrace();
                    return ;
                }
            }
        });
    }
cs


정말 간단하게 아래 사진처럼  어플을 키면  비동기 (Aysnc)로   캐셔가격을 받아와  화면에 가격을 출력해주는 앱을 만들어보았다.


다음편은   얼추 아래같은 모습으로   엠블 가격은 얼만지 / 현재 매수매도창에 걸린 양은 어떤지 / 원하는 가격 도달시 알람이 울리게 만들어보겠다.