본문 바로가기
Back_end/Api (업비트) 자동매매

[Spring Project] 코인 자동매매 프로그램 만들기 - 1. 업비트 API 호출 + 시세 종목 조회

by 8Antony 2022. 10. 20.

 

업비트 open api 사용

 

open api에서 access token을 생성해야 함.

 

Access Token, Secret Key 는 절대로 외부에 노출하지 말고, 적어둬야함.

 

 

내 자산 조회 (전체 계좌 조회)

https://docs.upbit.com/reference/ticker%ED%98%84%EC%9E%AC%EA%B0%80-%EC%A0%95%EB%B3%B4

 

1. VO 작성 (UPBIT open API에 있는 것들로)

 

 

public class MyBankVo {
	private String currency;
	private String balance;
	private String locked;
	private String avg_buy_price;
	private boolean avg_buy_price_modified;
	private String unit_currency;
	private String korean_name;

 

 

2. api 호출 메소드 (accounts)작성 

 

 

public List<MyBankVo> accounts() {
		
	String accessKey = "***";
        String secretKey = "***";
        String serverUrl = "https://api.upbit.com";

        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        String jwtToken = JWT.create()
                .withClaim("access_key", accessKey)
                .withClaim("nonce", UUID.randomUUID().toString())
                .sign(algorithm);

        String authenticationToken = "Bearer " + jwtToken;

        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(serverUrl + "/v1/accounts");
            request.setHeader("Content-Type", "application/json");
            request.addHeader("Authorization", authenticationToken);

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            return new Gson().fromJson(EntityUtils.toString(entity, "UTF-8"), new TypeToken<List<MyBankVo>>() {}.getType());
            
        } catch (IOException e) {
            return null;
        }
}

 

   

accessKey와 SecretKey는 위에서 발급받은 값을 넣어주면 된다. 

 

 

3. Test 파일에 내 계좌 불러오기 (Java application)

 

 

		List<MyBankVo> listMyBankVo = api.accounts();
		System.out.println(new Gson().toJson(listMyBankVo));

 

 

4. 출력 결과

 

 

내가 가진 코인 목록

 


 

시세 종목 조회

 

1. VO 작성 (UPBIT open API에 있는 것들로)

 

public class MarketVo {
	private String market;
	private String korean_name;
	private String english_name;

 

getter, setter 하기 

 

 

2. api 호출 메소드 (markets)작성 

 

 

public List<MarketVo> markets() throws IOException {
		OkHttpClient client = new OkHttpClient();

		Request request = new Request.Builder()
		  .url("https://api.upbit.com/v1/market/all?isDetails=false")
		  .get()
		  .addHeader("accept", "application/json")
		  .build();

		Response response = client.newCall(request).execute();
		return new Gson().fromJson(response.body().string(), new TypeToken<List<MarketVo>>() {}.getType());
	}

 

 

 

3. Test 파일에 내 계좌 불러오기 (Java application)

 

 

		List<MarketVo> listMarketVo = api.markets();
		System.out.println(new Gson().toJson(listMarketVo));

 

 

4. 출력 결과

 

 

업비트 마켓에 있는 목록

 


 

현재가 (Ticker) 조회

 

 

1. VO 작성 (UPBIT open API에 있는 것들로)

 

 

public class TickerVo {
	private String market;
	private String trade_date;
	private String trade_time;
	private String trade_date_kst;
	private String trade_time_kst;
	private long trade_timestamp;
	private double opening_price;
	private double high_price;
	private double low_price;
	private double trade_price;
	private double prev_closing_price;
	private String change;
	private double change_price;
	private double change_rate;
	private double signed_change_price;
	private double signed_change_rate;
	private double trade_volume;
	private double acc_trade_price;
	private double acc_trade_price_24h;
	private double acc_trade_volume;
	private double acc_trade_volume_24h;
	private double highest_52_week_price;
	private String highest_52_week_date;
	private double lowest_52_week_price;
	private String lowest_52_week_date;
	private long timestamp;

 

 

 

2. api 호출 메소드 (ticker)작성 

 

 

public List<TickerVo> ticker(String markets) throws IOException{
		OkHttpClient client = new OkHttpClient();

		Request request = new Request.Builder()
		  .url("https://api.upbit.com/v1/ticker?markets="+markets)
		  .get()
		  .addHeader("accept", "application/json")
		  .build();

		Response response = client.newCall(request).execute();
		return new Gson().fromJson(response.body().string(), new TypeToken<List<TickerVo>>() {}.getType());
	}

 

파라미터가 있는 이유는 특정 종목에 대한 현재가를 출력하기 위해

 

 

3. Test 파일에 내 계좌 불러오기 (Java application)

 

String markets = "";
		List<TickerVo> listTickerVo = api.ticker("KRW-VET");
		for (TickerVo v : listTickerVo) {
			System.out.println("["+v.getMarket()+"]["+v.getTrade_date()+"]["+v.getTrade_price()+"]");
		}

 

 

4. 출력 결과

 

 

KRW_VET에 대한 Ticker가 온다.

 

+ DB에 삽입 

 

 

5. Service 생성

 

public interface UpbitService {

	void test();

	void insert_ticker(TickerVo tickerVo);

}

 

 

6. 인터페이스 생성 

 

 

@Service
public class UpbitServiceImpl implements UpbitService{

	@Autowired private UpbitDao upbitDao;
	
	@Override
	public void test() {
		upbitDao.test();
	}

	@Override
	public void insert_ticker(TickerVo tickerVo) {
		upbitDao.insert_ticker(tickerVo);
	}

}

 

 

7. Dao 생성

 

 

@Repository
public class UpbitDao {

	@Resource(name="sqlSession") private SqlSession session;
	public void test() {
		session.selectOne("Upbit.test");
	}
	public void insert_ticker(TickerVo tickerVo) {
		session.insert("Upbit.insert_ticker", tickerVo);
	}	
}

 

 

8. 출력 결과

 

 

댓글