상세 컨텐츠

본문 제목

[안드로이드]빗썸 api를 사용해서 현재 매도/매수 정보 가져오기

안드로이드

by aries574 2020. 11. 4. 18:18

본문


2020/11/03 - [안드로이드] - [안드로이드]빗썸 api를 사용해서 현재가 정보 가져오기

이전에 빗썸 api를 사용해서 현재가 정보를 가져오는 방법에 대해 썼습니다. 이번 시간에는 

아래 그림과 같은 현재 매도/매수 정보를 직접 가져와서 화면에 보여주는걸 만들어 보려고 합니다.

1. 환경설정

app -> AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kwon.coin">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<uses-library
android:name="org.apache.http.legacy"
android:required="false" />

</application>
</manifest>



2. 라이브러리 추가

Gradle Scripts -> build.gradle(Module:app)

implementation 'com.android.volley:dc-volley:1.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'


3. 클래스 추가(Java -> 마우스 오른쪽 -> New -> Java Class)


DataList.java

public class DataList {

CoinList data;
String status;
}


OrderBookInfo.java

public class OrderBookInfo {

private String price; //가격
private String quantity; //갯수

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

public String getQuantity() {
return quantity;
}

public void setQuantity(String quantity) {
this.quantity = quantity;
}
}


CoinList.java

import java.util.ArrayList;

public class CoinList {

ArrayList<OrderBookInfo> bids = new ArrayList<OrderBookInfo>();
ArrayList<OrderBookInfo> asks = new ArrayList<OrderBookInfo>();
}


OrderBookAdapter.java (화면과 데이터 연결)

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class OrderBookAdapter extends RecyclerView.Adapter<OrderBookAdapter.Viewholder>{

ArrayList<OrderBookInfo> items = new ArrayList<OrderBookInfo>();

@NonNull
@Override
public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View itemView = inflater.inflate(R.layout.orderbook_item, viewGroup, false);

return new Viewholder(itemView);
}

@Override
public void onBindViewHolder(@NonNull Viewholder viewHolder, int position) {

OrderBookInfo item = items.get(position);
viewHolder.setItem(item);
}


@Override
public int getItemViewType(int position) {

return super.getItemViewType(position);
}

//아이템 건수
@Override
public int getItemCount() {

return items.size();
}

//아이템 등록
public void addItem(OrderBookInfo coin){

items.add(coin);
}


public void removeItem(int count){

for(int i=0; i< count-1; i++){
items.remove(i);
}

}

/**
* 아이템 전체삭제
*/
public void removeAllItem(){
items.clear();
}


//아이템 저장
public void setItems(ArrayList<OrderBookInfo> items){

this.items = items;
}

//아이템 조회
public OrderBookInfo getItem(int position){

return items.get(position);
}


static class Viewholder extends RecyclerView.ViewHolder{

CardView cardView;
TextView textPrice;
TextView textQuantity;

public Viewholder(@NonNull View itemView) {
super(itemView);
textPrice = itemView.findViewById(R.id.price);
textQuantity = itemView.findViewById(R.id.quantity);
cardView = itemView.findViewById(R.id.cardView);
}

public void setItem(OrderBookInfo orderBook){

int position = getAdapterPosition();

if(position >= 30){ //매수 빨강

textPrice.setTextColor(Color.rgb(0,0,0)); //검정
textQuantity.setTextColor(Color.rgb(0,0,0));

if( position % 2 == 0){
cardView.setBackgroundColor(Color.rgb(255,162,162)); //옅은 빨강 아래랑
}else{
cardView.setBackgroundColor(Color.rgb(255,198,198)); //완전 옅은 빨강
}

textPrice.setText(" " +orderBook.getPrice()+"");
textQuantity.setText(orderBook.getQuantity()+"");

}else{ //매도

textPrice.setTextColor(Color.rgb(0,0,0));
textQuantity.setTextColor(Color.rgb(0,0,0));

if(position % 2 == 0){
cardView.setBackgroundColor(Color.rgb(198,255,255)); //완전 옅은 파랑
}else{
cardView.setBackgroundColor(Color.rgb(144,246,255)); // 옅은 파랑
}

textPrice.setText(" " + orderBook.getPrice()+"");
textQuantity.setText(orderBook.getQuantity()+"");
}
}
}
}


4. 화면추가 ( res -> layout -> 마우스오른쪽 -> New -> Layout Resource File)


orderBook_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="2dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="2dp"
app:cardElevation="5dp"
app:cardBackgroundColor="@android:color/darker_gray">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/quantity"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:text="거래갯수"
android:textStyle="bold"
android:textColor="#0E0505"
android:textSize="13sp" />
<TextView
android:id="@+id/price"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="거래가"
android:gravity="right"
android:textColor="#0E0505"
android:textStyle="bold"
android:textSize="13sp" />

</LinearLayout>

</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>


5. 화면구성(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:id="@+id/coin_nm"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="text"
/>

<Button
android:id="@+id/btn_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="현재 매도/매수 조회" />
</LinearLayout>

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>


6. 기능구현(MainActivity.java)


import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

private RequestQueue requestQueue; //호가
private EditText coinNm;//입력창

private RecyclerView recycleView;
private OrderBookAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//recycleView 객체참조
recycleView = findViewById(R.id.recycleView);

LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);

//recycleView 레이아웃 설정
recycleView.setLayoutManager(layoutManager);

//recycleView 어뎁터 설정
adapter = new OrderBookAdapter();
recycleView.setAdapter(adapter);

coinNm = findViewById(R.id.coin_nm);

Button btnSearch = findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

//입력값 변수에 담기
String nm = coinNm.getText().toString();

//입력값 체크
if(nm.equals("") || nm == null){
Toast.makeText(getApplication(), "코인이름을 입력해주세요", Toast.LENGTH_SHORT).show();
}else{
//코인값 대문자처리
orderbookSelect(nm.toUpperCase());
}
}
});


if (requestQueue == null) { //호가
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
}


/**
* 매수/매도 api호출
* @param coinNm 코인명
*/
private void orderbookSelect(String coinNm)
{
final String coinName = coinNm;

String url = "https://api.bithumb.com/public/orderbook/"+coinNm;
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// println("응답->" + response);
orderBookResponse(response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
println("에러->" + error.getMessage());
customToastView("에러!!!");
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
request.setShouldCache(false);
requestQueue.add(request);
}

/**
* 호가 데이터 정렬
* @param response 호가정보
*/
private void orderBookResponse(String response) {

Gson gson = new Gson();
DataList orderBookList = gson.fromJson(response, DataList.class);

//상태값이 성공일때만 데이터 뿌려주기
if(orderBookList.status.equals("0000"))
{

//조회 전 화면 클리어
adapter.removeAllItem();

OrderBookInfo bisdInfo;
OrderBookInfo asksInfo;

//매도
int askSize = orderBookList.data.asks.size()-1;

for(int i = askSize; i >= 0; i--)
{

asksInfo = orderBookList.data.asks.get(i);

//VO담기
asksInfo.setPrice(toDoubleFormat(Double.parseDouble(asksInfo.getPrice())));
asksInfo.setQuantity(toDoubleFormat(Double.parseDouble(asksInfo.getQuantity())));
adapter.addItem(asksInfo);
}

//매수
for(int i = 0; i < orderBookList.data.bids.size(); i++)
{
bisdInfo = orderBookList.data.bids.get(i);

//VO담기
bisdInfo.setPrice(toDoubleFormat(Double.parseDouble(bisdInfo.getPrice())));
bisdInfo.setQuantity(toDoubleFormat(Double.parseDouble(bisdInfo.getQuantity())));
adapter.addItem(bisdInfo);
}

adapter.notifyDataSetChanged(); //변경사항 적용

}
}

/**
* 로그 표시
* @param data 로그
*/
private void println( String data)
{
Log.d("MainActivity" , data);
}

/**
* 커스터마이징 메시지
* @param text
*/
private void customToastView(String text){
Toast toastView = Toast.makeText(getApplication(),text, Toast.LENGTH_SHORT);
toastView.setGravity(Gravity.CENTER,0,0);
toastView.show();
}

/**
* 1000자리 콤마
* @param num
* @return
*/
public String toDoubleFormat(Double num) {

DecimalFormat df = null;

if(num >= 100 && num <= 999.9){
df = new DecimalFormat("000.0");
}else if(num >= 10 && num <= 99.99){
df = new DecimalFormat("00.00");
}else if(num >= 1 && num <= 9.9999){
df = new DecimalFormat("0.000");
}else if(num < 1){
df = new DecimalFormat("0.0000");
}else{
df = new DecimalFormat("###,###,###");
}

return df.format(num);
}
}

7. 구동화면

코인명을 입력하고 현재가 조회버튼을 누르면 해당코인 현재 매도/매수정보를 가져옵니다


반응형

관련글 더보기

댓글 영역