kimpro82 / MyInvestmentModules

Someday these will be an integrated trading system, but not now. So I am sad.
1 stars 1 forks source link

Upbit / Python : Init. #34

Closed kimpro82 closed 1 year ago

kimpro82 commented 1 year ago
kimpro82 commented 1 year ago

from ChatGPT

Q. Give me codes to get list of top 20 volume cryptocurrencies by Upbit API in Python.

A. You can use the requests library in Python to retrieve a list of the top 20 volume cryptocurrencies from the Upbit API. Here's an example of how you can do it:

import requests

# Upbit API endpoint to retrieve the top 20 volume cryptocurrencies
url = "https://api.upbit.com/v1/market/all"

# Send a GET request to the API endpoint
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    # Get the data from the response as a JSON object
    data = response.json()
    # Filter the data to include only the market information for cryptocurrencies
    markets = [market for market in data if market['market'].startswith('KRW-')]
    # Sort the markets by descending order of trading volume
    sorted_markets = sorted(markets, key=lambda market: market['acc_trade_price_24h'], reverse=True)
    # Get the top 20 volume cryptocurrencies
    top_20_markets = sorted_markets[:20]
    # Print the market names and trading volumes of the top 20 volume cryptocurrencies
    for market in top_20_markets:
        print(market['market'], market['acc_trade_price_24h'])
else:
    print("Request failed with status code:", response.status_code)

This code sends a GET request to the Upbit API and retrieves information on all available markets. The market information is then filtered to include only the markets for cryptocurrencies traded in Korean Won (KRW). The filtered markets are then sorted in descending order of trading volume over the past 24 hours (acc_trade_price_24h field), and the top 20 volume markets are selected. Finally, the code prints the market names and trading volumes of the top 20 volume cryptocurrencies.

kimpro82 commented 1 year ago

from ChatGPT

Q. Give me codes to login by Upbit API in python

A. To use the authenticated endpoints of the Upbit API, you need to obtain an access key and secret key from the Upbit website. Once you have obtained these keys, you can use the requests library in Python to login and obtain an authentication token from the Upbit API. Here's an example of how you can do it:

import jwt
import uuid
import hashlib
import requests
import os

access_key = os.environ['UPBIT_ACCESS_KEY']
secret_key = os.environ['UPBIT_SECRET_KEY']
server_url = "https://api.upbit.com"

# Generate a JWT token for authentication
payload = {
    "access_key": access_key,
    "nonce": str(uuid.uuid4()),
}
jwt_token = jwt.encode(payload, secret_key)

# Create a signature hash using the JWT token and secret key
signature = hashlib.sha512(jwt_token).hexdigest()

# Send a POST request to the Upbit API to obtain an access token
headers = {"Authorization": f"Bearer {jwt_token}", "Content-Type": "application/json"}
response = requests.post(f"{server_url}/v1/signin", headers=headers)
if response.status_code == 200:
    access_token = response.json()['token']
    print("Access token:", access_token)
else:
    print("Request failed with status code:", response.status_code)

In this code, we first obtain the access key and secret key from environment variables using the os module. We then generate a JWT token with a random nonce and encode it using the secret key. Next, we create a signature hash using the encoded JWT token and the secret key. We use the JWT token and signature hash to send a POST request to the Upbit API to obtain an access token. If the request is successful, the access token is printed to the console. Note that the access token is valid for 30 minutes, after which you will need to obtain a new one using the same process.

kimpro82 commented 1 year ago

from ChatGPT

Q. Give me codes to get the signal to determine if UBMI index is on or under the 90-days moving average by Upbit API in Python

A. Unfortunately, the Upbit API does not provide a direct method for obtaining the signal to determine if the UBMI index is on or under the 90-day moving average. However, you can use the following approach to compute this signal:

  1. Retrieve the daily UBMI index prices for the past 90 days using the /v1/candles/days API endpoint.
  2. Compute the 90-day moving average of the UBMI index prices.
  3. Get the latest UBMI index price using the /v1/candles/minutes/1 API endpoint.
  4. Compare the latest UBMI index price with the 90-day moving average. If the latest price is below the moving average, the signal is "under the moving average". Otherwise, the signal is "on the moving average".

Here's an example of how you can implement this approach in Python:

import requests
import numpy as np

# Upbit API endpoints for UBMI index prices
url_daily = "https://api.upbit.com/v1/candles/days"
url_latest = "https://api.upbit.com/v1/candles/minutes/1"

# Parameters for retrieving daily UBMI index prices
market = "KRW-UBMI"
count = 90

# Send a GET request to the API endpoint to retrieve daily UBMI index prices
params = {"market": market, "count": count}
response = requests.get(url_daily, params=params)

# Check if the request was successful
if response.status_code == 200:
    # Get the data from the response as a JSON object
    data = response.json()
    # Extract the closing prices from the data
    prices = np.array([float(candle['trade_price']) for candle in data])
    # Compute the 90-day moving average of the prices
    ma = np.mean(prices)
    # Print the moving average
    print("90-day moving average:", ma)

    # Send a GET request to the API endpoint to retrieve the latest UBMI index price
    params = {"market": market, "count": 1}
    response = requests.get(url_latest, params=params)
    # Check if the request was successful
    if response.status_code == 200:
        # Get the data from the response as a JSON object
        data = response.json()
        # Extract the latest price from the data
        latest_price = float(data[0]['trade_price'])
        # Print the latest price
        print("Latest UBMI index price:", latest_price)

        # Compare the latest price with the moving average to determine the signal
        if latest_price < ma:
            print("Signal: Under the moving average")
        else:
            print("Signal: On the moving average")
    else:
        print("Request failed with status code:", response.status_code)
else:
    print("Request failed with status code:", response.status_code)

Note that this code assumes that the UBMI index is traded in Korean Won (KRW) on the Upbit exchange, and that the moving average is computed using the closing prices of the UBMI index. You may need to adjust the code accordingly if these assumptions do not hold.

kimpro82 commented 1 year ago

from ChatGPT

Q. Give me codes to get all the cryptocurrencies' real-time informations from Upbit API and save them into SQLite3 database in Python

A. Here's an example Python code that uses the Upbit API to retrieve real-time information for all cryptocurrencies and save the data into a SQLite3 database:

import sqlite3
import requests
import time

# Define Upbit API endpoint
url = "https://api.upbit.com/v1/ticker"

# Define SQLite3 database connection and cursor
conn = sqlite3.connect('crypto_data.db')
c = conn.cursor()

# Create a table to store the data
c.execute('''CREATE TABLE IF NOT EXISTS crypto_data
             (market text, trade_date_utc text, trade_time_utc text,
              trade_price real, trade_volume real)''')
conn.commit()

# Retrieve real-time information for all cryptocurrencies
markets = requests.get(url).json()

# Loop through the markets and insert the data into the database
for market in markets:
    # Extract the data for the current market
    market_name = market['market']
    trade_date_utc = market['trade_date_utc']
    trade_time_utc = market['trade_time_utc']
    trade_price = market['trade_price']
    trade_volume = market['acc_trade_volume']

    # Insert the data into the database
    c.execute("INSERT INTO crypto_data VALUES (?, ?, ?, ?, ?)",
              (market_name, trade_date_utc, trade_time_utc, trade_price, trade_volume))
    conn.commit()

    # Wait for a short time before sending the next request
    time.sleep(0.1)

# Close the database connection
conn.close()

This code retrieves the real-time information for all cryptocurrencies using the Upbit API and stores the data into a SQLite3 database. The code uses a loop to iterate over the list of markets and inserts the data into the database using an SQL INSERT statement. Note that the code pauses for a short time between requests to avoid hitting the rate limit of the API.

kimpro82 commented 1 year ago

from ChatGPT

Q. Can you recommend the most proper DBMS for dealing crypto-currency price data? It'll be better if it is an open source and easy to extend to a web application for remote monitoring.

A. There are several open source DBMS options that are commonly used for storing and analyzing cryptocurrency price data. Some popular choices include:

  1. PostgreSQL: PostgreSQL is a powerful open source relational database system that supports SQL and offers advanced features such as indexing, replication, and concurrency control. It has a reputation for being reliable and scalable, and is commonly used in enterprise environments.

  2. MySQL: MySQL is another open source relational database system that is widely used for web applications. It offers many of the same features as PostgreSQL, but is known for being simpler to use and configure.

  3. InfluxDB: InfluxDB is a time-series database system that is designed specifically for handling large volumes of time-stamped data, such as cryptocurrency prices. It has a simple HTTP API and is optimized for high write and query performance.

  4. TimescaleDB: TimescaleDB is a time-series database system that is built on top of PostgreSQL. It offers advanced time-series analysis features such as automatic data partitioning and time-based indexing.

All of these DBMS options have their strengths and weaknesses, and the best choice will depend on your specific use case and requirements. However, if you are looking for a DBMS that is open source and easy to extend to a web application for remote monitoring, then PostgreSQL or MySQL may be good options to consider. Both systems are well-suited for web applications, have a large user community, and offer a wide range of tools and integrations to support application development.

kimpro82 commented 1 year ago

from ChatGPT

Q. Tell me more about MySQL's license in detail

A. MySQL is an open source relational database management system that is distributed under a dual licensing model. This means that MySQL can be used under either an open source license or a commercial license, depending on how it is used.

The open source license for MySQL is the GNU General Public License (GPL), which is a copyleft license that grants users the freedom to run, copy, distribute, and modify the software. The GPL requires that any modifications made to the software be released under the same license, so that the entire community can benefit from improvements and enhancements.

However, there are some restrictions on the use of the open source version of MySQL. For example, if you use MySQL as part of a commercial application, and distribute that application to others, then you may be required to release the source code for your application under the GPL as well. This is known as the "viral" or "infectious" nature of the GPL, and is a fundamental aspect of copyleft licenses.

To avoid these restrictions, MySQL can also be licensed commercially, under a proprietary license that does not require the release of source code. This commercial license is typically used by businesses that want to use MySQL in a proprietary application, without having to release the source code for that application.

In summary, MySQL is distributed under a dual licensing model, with an open source license (GPL) and a commercial license. The open source license grants users the freedom to use and modify the software, but may impose certain restrictions on its use in commercial applications. The commercial license allows businesses to use MySQL in proprietary applications without having to release the source code.

kimpro82 commented 1 year ago

업비트 API를 사용하여 파이썬 코드로 업비트에 로그인하여 잔고를 조회하는 방법은 다음과 같습니다.

import jwt
import uuid
import hashlib
from urllib.parse import urlencode
import requests
import json

# access key와 secret key를 넣어줍니다.
access_key = 'Access key를 입력하세요'
secret_key = 'Secret key를 입력하세요'
# endpoint URL은 변경될 수 있으니 업비트 API 문서를 참고해주세요.
endpoint = 'https://api.upbit.com'

# JWT 토큰 생성 함수
def generate_jwt():
    payload = {
        'access_key': access_key,
        'nonce': str(uuid.uuid4())
    }
    token = jwt.encode(payload, secret_key)
    return token.decode('utf-8')

# 서명 생성 함수
def generate_signature(query):
    m = hashlib.sha512()
    m.update(query.encode('utf-8'))
    return m.hexdigest()

# 잔고 조회 함수
def get_balances():
    url = endpoint + '/v1/accounts'
    payload = {
        'access_key': access_key,
        'nonce': str(uuid.uuid4())
    }
    jwt_token = generate_jwt()
    authorize_token = 'Bearer {}'.format(jwt_token)
    headers = {"Authorization": authorize_token}
    res = requests.get(url, headers=headers)
    return json.loads(res.text)

# 잔고 조회 함수 호출
balances = get_balances()
print(balances)

위 코드에서 access_keysecret_key에 자신의 업비트 API access key와 secret key를 넣어주고, endpoint는 업비트 API 문서에 따라 변경될 수 있으므로 주의해주세요.

위 코드에서는 get_balances() 함수를 사용하여 잔고를 조회하였습니다. 해당 함수를 호출하면 현재 로그인된 계정의 잔고 정보를 JSON 형태로 반환합니다. 이를 통해 파이썬 코드로 업비트에 로그인하여 잔고를 조회할 수 있습니다.