안녕하세요!
이번 글에서는 C# 언어를 이용한 업비트 Open API 기본 사용법에 대해 알아보겠습니다.
이번 예제에서는 업비트 개발자센터(https://docs.upbit.com/reference/)의 '전체계좌조회' 항목을 다루겠습니다.
필수 NuGet 패키지
- Newtonsoft.Json
- RestSharp
- System.IdentityModel.Tokens.Jwt
프로젝트 생성
[UpbitApiExample] 프로젝트를 생성해 줍니다.
UpbitUrl클래스 생성
RESTful API방식을 사용하여 정보를 요청하기 위해 [UpbitApiExample] 프로젝트에 [UpbitUrl] 클래스를 생성 후 아래와 같이 코드를 작성해 줍니다.
namespace UpbitApiExample;
public static class UpbitUrl
{
/// <summary>
/// 계좌조회 정보 요청 URL
/// </summary>
public static readonly string Accounts = "https://api.upbit.com/v1/accounts";
}
- [UpbitUrl] 클래스는 정적클래스로 정의하였습니다.
- [UpbitUrl] 클래스의 속성들은 고유한 값을 가지며 외부에서 수정할 수 없도록 readonly 키워드를 사용하였습니다.
* 정보를 요청하는데 필요한 URL은 업비트 개발자센터 각 항목에서 확인할 수 있습니다.
[UpbitAccount] 클래스 생성
요청한 정보를 Json형태로 받아 객체로 변환하기 위한 데이터 클래스인 [UpbitAccount] 클래스를 생성 후 아래와 같이 속성들을 정의하여 줍니다.
namespace UpbitApiExample;
public class UpbitAccount
{
/// <summary>
/// 화폐를 의미하는 영문 대문자 코드
/// </summary>
public string Currency { get; set; }
/// <summary>
/// 주문가능 금액/수량
/// </summary>
public string Balance { get; set; }
/// <summary>
/// 주문 중 묶여있는 금액/수량
/// </summary>
public string Locked { get; set; }
/// <summary>
/// 매수평균가
/// </summary>
public string Avg_buy_price { get; set; }
/// <summary>
/// 매수평균가 수정여부
/// </summary>
public bool Avg_buy_price_modified { get; set; }
/// <summary>
/// 평단가 기준 화폐
/// </summary>
public string Unit_currency { get; set; }
}
- 업비트 개발자 센터에서 정의한 필드명과 타입을 사용하여 response값을 저장합니다.
*데이터 클래스의 속성 정보는 업비트 개발자센터 Response 항목에서 확인할 수 있습니다.
[UpbitApi]클래스 생성
API에 정보를 요청하는 [UpbitApi] 클래스를 생성하고 아래와 같이 코딩하여 줍니다.
using RestSharp;
using Newtonsoft.Json;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
namespace UpbitApiExample;
public class UpbitApi
{
public UpbitApi(string accessKey, string secretKey)
{
_accessKey = accessKey;
_secretKey = secretKey;
}
#region Properties
/// <summary>
/// Upbit에서 발급받은 Access Key
/// </summary>
private string _accessKey;
/// <summary>
/// Upbit에서 발급받은 Secret Key
/// </summary>
private string _secretKey;
#endregion
#region Methods
/// <summary>
/// URL을 사용하여 필요한 정보를 담은 객체를 가져온다.
/// </summary>
/// <param name="url"> API 정보요청 URL </param>
/// <returns> <T>타입 리스트 </returns>
public List<T>? GetUpbitObjectList<T>(string url)
{
var payload = new JwtPayload
{
{ "access_key", _accessKey },
{ "nonce", Guid.NewGuid().ToString() },
{ "query_hash_alg", "SHA512" }
};
byte[] keyBytes = Encoding.Default.GetBytes(_secretKey);
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyBytes);
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, "HS256");
var header = new JwtHeader(credentials);
var secToken = new JwtSecurityToken(header, payload);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(secToken);
var authorizationToken = "Bearer " + jwtToken;
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", authorizationToken);
RestResponse? response = null;
try { response = client.Execute(request); }
catch { throw new Exception(); }
if(response != null && response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<List<T>>(response.Content!);
}
return default;
}
#endregion
}
- 클래스 생성 시 Access Key와 Secret Key를 입력받습니다.
- URL과 Key속성들을 사용하여 RestSharp 라이브러리로 정보를 요청하고, 받아온 Json형태의 정보를 <T> 타입의 객체들의 집합인 List형태로 반환합니다.
[Program] 클래스 작성
Main매서드에서 생성한 클래스들을 사용하여 받아온 정보를 콘솔에 나타냅니다.
namespace UpbitApiExample;
public static class Program
{
public static void Main()
{
Console.Write("Access Key : ");
string accKey = Console.ReadLine()!;
Console.Write("Secret Key : ");
string secKey = Console.ReadLine()!;
UpbitApi api = new(accKey, secKey);
List<UpbitAccount>? accounts = null;
try
{
accounts = api.GetUpbitObjectList<UpbitAccount>(UpbitUrl.Accounts)!;
}
catch(Exception e)
{
Console.WriteLine($"Error : {e.Message}");
}
if(accounts != null)
{
foreach (var account in accounts)
{
Console.WriteLine($"화폐 코드 : {account.Currency}");
Console.WriteLine($"주문가능 금액/수량 : {account.Balance}");
Console.WriteLine($"묶여있는 금액/수량 : {account.Locked}");
Console.WriteLine($"매수평균가 : {account.Avg_buy_price}");
Console.WriteLine($"매수 평균가 수정 여부 : {account.Avg_buy_price_modified}");
Console.WriteLine($"평단가 기준 화폐 : {account.Unit_currency}");
}
}
else
{
Console.WriteLine("Error : Account object is null");
}
}
}
- 빌드 후 업비트에서 발급받은 API의 Access Key와 Secret Key를 입력하면 해당 계정의 계좌정보를 나타내 줍니다.
- 제대로 된 키를 입력 하였음에도 불구하고 정보를 불러오는데 실패한다면, API에 등록된 IP가 현재 사용 중인 네트워크의 IP와 일치하는지 다시 한번 확인해 주세요.
이번 글에서는 업비트 Open API를 사용하여 전체계좌정보를 조회하는 예제를 다루어 보았습니다.
비슷한 방법으로 다른 항목들도 조회가 가능하니, UpbitUrl클래스와 각 항목에 맞는 데이터 클래스를 정의하여 다양한 정보들을 요청하고 받아와 여러 분야에서 사용하실 수 있습니다.
'[C#] > Upbit Open API' 카테고리의 다른 글
[C#] Upbit Open API : API 발급 (2) | 2023.12.04 |
---|