티스토리 뷰
사전 준비
크라켄에 usd 충전
- 업비트에서 eos 구매 후 크라켄으로 전송(zero fee)
- 크라켄 EOS/USD 마켓에서 eos를 전량 매도(지정가 0.16%)
크라켄 api 키 발급
로그인 후 개인메뉴에서 Security - API 선택
Create and modify orders 체크
(허용 가능한 IP 와 토큰의 유효기간을 함께 설정해주면 보안상 더욱 안전하겠죠)
현재가로 지정가 매수 주문 파이썬 코드
TMI) 시장가 매수를 하면 코드가 더 간단하지만, 시장가(0.26%) 매수보다 지정가(0.16%) 매수 수수료가 더 저렴합니다.
import time
import base64
import hashlib
import hmac
import requests
import urllib.parse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--api_key', help='Kraken API key')
parser.add_argument('--api_secret', help='Kraken API secret')
parser.add_argument('--amount', help='dolla amount')
parser.add_argument('--diff', help='diff on current price')
args = parser.parse_args()
print('\n' + time.strftime('%Y.%m.%d %H:%M:%S'))
print('\n==== args ====')
print('key: ' + args.api_key)
print('secret: ' + args.api_secret)
print('amount: ' + args.amount)
print('diff: ' + args.diff)
api_key = args.api_key
api_secret = args.api_secret
amount = float(args.amount)
diff = float(args.diff)
pair = 'XBTUSD'
def get_kraken_signature(urlpath, data, secret):
postdata = urllib.parse.urlencode(data)
encoded = (str(data['nonce']) + postdata).encode()
message = urlpath.encode() + hashlib.sha256(encoded).digest()
mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
sigdigest = base64.b64encode(mac.digest())
return sigdigest.decode()
def kraken_request(endpoint, data, api_key, api_secret):
sig = get_kraken_signature('/0/private/'+endpoint, data, api_secret)
# Step 4: Prepare headers
headers = {
'API-Key': api_key,
'API-Sign': sig
}
# Step 5: Send request
url = 'https://api.kraken.com/0/private/' + endpoint
print("\n=== INPUT ===")
print(url)
print(headers)
print(data)
response = requests.post(url, headers=headers, data=data)
return response.json()
def buy_btc(api_key, api_secret, amount, diff):
# Step 1: Get current price
response = requests.get(
'https://api.kraken.com/0/public/Ticker?pair='+pair)
response_json = response.json()
last_trade_price = float(response_json['result']['XXBTZUSD']['c'][0])
price = last_trade_price + diff
# Step 2: Place buy order
data = {
'nonce': str(int(time.time() * 1000)),
'pair': pair,
'type': 'buy',
'ordertype': 'limit',
'price': round(price, 2),
'volume': round(amount / price, 8),
}
return kraken_request('AddOrder', data, api_key, api_secret)
result = buy_btc(api_key, api_secret, amount, diff)
print('\n==== OUTPUT ====')
print('Bought ${amount}'.format(amount=amount))
print(result)
print('\n\n\n')
프로그램 실행
$ python3 ~/buybtc.py --api_key=your_api_key --api_secret=your_api_secret
위와 같이 실행해도 되지만 키값이 길어서 번거로울 수 있습니다. 간단하게 buybtc.sh 쉘스크립트를 만들어 놓고 사용하면 편리합니다.
(buybtc.sh 파일에 755 권한 필요)
#!/bin/sh
python3 ~/buybtc.py --api_key=your_api_key --api_secret=your_api_secret --amount=10 --diff=-10
/etc/crontab 파일에 buybtc.sh 반복 수행 설정
/etc/crontab 파일 수정시 root 권한 필요
아래 예시는 매일 0시, 12시 마다 buybtc.sh 를 수행
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
# You can also override PATH, but by default, newer versions inherit it from the environment
#PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#
0 */12 * * * min /home/min/buybtc.sh >> /home/min/buybtc.log
728x90
반응형
댓글