Skip to content

Commit 76f8eab

Browse files
업비트 자동매매,AI,변동성돌파,이동평균선
0 parents  commit 76f8eab

6 files changed

+261
-0
lines changed

Diff for: backtest.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pyupbit
2+
import numpy as np
3+
4+
df = pyupbit.get_ohlcv("KRW-BTC", count=100)
5+
df['range'] = (df['high'] - df['low']) * 0.5
6+
df['target'] = df['open'] + df['range'].shift(1)
7+
8+
fee = 0.05
9+
df['ror'] = np.where(df['high'] > df['target'],
10+
df['close'] / df['target'] - fee,
11+
1)
12+
13+
df['hpr'] = df['ror'].cumprod()
14+
df['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100
15+
print("MDD(%): ", df['dd'].max())
16+
df.to_excel("dd.xlsx")

Diff for: bestk.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import pyupbit
2+
import numpy as np
3+
4+
5+
def get_ror(k=0.5):
6+
df = pyupbit.get_ohlcv("KRW-BTC",count=7)
7+
df['range'] = (df['high'] - df['low']) * k
8+
df['target'] = df['open'] + df['range'].shift(1)
9+
10+
fee = 0.0032
11+
df['ror'] = np.where(df['high'] > df['target'],
12+
df['close'] / df['target'] - fee,
13+
1)
14+
15+
ror = df['ror'].cumprod()[-2]
16+
return ror
17+
18+
19+
for k in np.arange(0.1, 1.0, 0.1):
20+
ror = get_ror(k)
21+
print("%.1f %f" % (k, ror))

Diff for: bitcoinAutoTrade.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import time
2+
import pyupbit
3+
import datetime
4+
5+
access = ""
6+
secret = ""
7+
8+
def get_target_price(ticker, k):
9+
"""변동성 돌파 전략으로 매수 목표가 조회"""
10+
df = pyupbit.get_ohlcv(ticker, interval="minute60")
11+
target_price = df.iloc[0]['close'] + (df.iloc[0]['high'] - df.iloc[0]['low']) * k
12+
return target_price
13+
14+
def get_start_time(ticker):
15+
"""시작 시간 조회"""
16+
df = pyupbit.get_ohlcv(ticker, interval="day", count=1)
17+
start_time = df.index[0]
18+
return start_time
19+
20+
def get_balance(ticker):
21+
"""잔고 조회"""
22+
balances = upbit.get_balances()
23+
for b in balances:
24+
if b['currency'] == ticker:
25+
if b['balance'] is not None:
26+
return float(b['balance'])
27+
else:
28+
return 0
29+
return 0
30+
31+
def get_current_price(ticker):
32+
"""현재가 조회"""
33+
return pyupbit.get_orderbook(ticker=ticker)["orderbook_units"][0]["ask_price"]
34+
35+
# 로그인
36+
upbit = pyupbit.Upbit(access, secret)
37+
print("autotrade start")
38+
39+
40+
41+
# 자동매매 시작
42+
while True:
43+
try:
44+
now = datetime.datetime.now()
45+
start_time = get_start_time("KRW-BTC")
46+
end_time = start_time + datetime.timedelta(days=1)
47+
48+
# 9:00 < 현재 < 8:59:50
49+
if start_time < now < end_time - datetime.timedelta(seconds=10):
50+
target_price = get_target_price("KRW-BTC", 0.5)
51+
current_price = get_current_price("KRW-BTC")
52+
if target_price < current_price:
53+
krw = get_balance("KRW")
54+
if krw > 5000:
55+
upbit.buy_market_order("KRW-BTC", krw*0.9995)
56+
else:
57+
btc = get_balance("BTC")
58+
if btc > 0.00008:
59+
upbit.sell_market_order("KRW-BTC", btc*0.9995)
60+
time.sleep(1)
61+
except Exception as e:
62+
print(e)
63+
time.sleep(1)

Diff for: bitcoinAutoTradeWithAi.py

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import time
2+
import pyupbit
3+
import datetime
4+
import schedule
5+
from fbprophet import Prophet
6+
7+
access = ""
8+
secret = ""
9+
10+
def get_target_price(ticker, k):
11+
"""변동성 돌파 전략으로 매수 목표가 조회"""
12+
df = pyupbit.get_ohlcv(ticker, interval="day", count=2)
13+
target_price = df.iloc[0]['close'] + (df.iloc[0]['high'] - df.iloc[0]['low']) * k
14+
return target_price
15+
16+
def get_start_time(ticker):
17+
"""시작 시간 조회"""
18+
df = pyupbit.get_ohlcv(ticker, interval="day", count=1)
19+
start_time = df.index[0]
20+
return start_time
21+
22+
def get_balance(ticker):
23+
"""잔고 조회"""
24+
balances = upbit.get_balances()
25+
for b in balances:
26+
if b['currency'] == ticker:
27+
if b['balance'] is not None:
28+
return float(b['balance'])
29+
else:
30+
return 0
31+
return 0
32+
33+
def get_current_price(ticker):
34+
"""현재가 조회"""
35+
return pyupbit.get_orderbook(ticker=ticker)["orderbook_units"][0]["ask_price"]
36+
37+
predicted_close_price = 0
38+
def predict_price(ticker):
39+
"""Prophet으로 당일 종가 가격 예측"""
40+
global predicted_close_price
41+
df = pyupbit.get_ohlcv(ticker, interval="minute60")
42+
df = df.reset_index()
43+
df['ds'] = df['index']
44+
df['y'] = df['close']
45+
data = df[['ds','y']]
46+
model = Prophet()
47+
model.fit(data)
48+
future = model.make_future_dataframe(periods=24, freq='H')
49+
forecast = model.predict(future)
50+
closeDf = forecast[forecast['ds'] == forecast.iloc[-1]['ds'].replace(hour=9)]
51+
if len(closeDf) == 0:
52+
closeDf = forecast[forecast['ds'] == data.iloc[-1]['ds'].replace(hour=9)]
53+
closeValue = closeDf['yhat'].values[0]
54+
predicted_close_price = closeValue
55+
predict_price("KRW-BTC")
56+
schedule.every().hour.do(lambda: predict_price("KRW-BTC"))
57+
58+
# 로그인
59+
upbit = pyupbit.Upbit(access, secret)
60+
print("autotrade start")
61+
62+
# 자동매매 시작
63+
while True:
64+
try:
65+
now = datetime.datetime.now()
66+
start_time = get_start_time("KRW-BTC")
67+
end_time = start_time + datetime.timedelta(days=1)
68+
schedule.run_pending()
69+
70+
if start_time < now < end_time - datetime.timedelta(seconds=10):
71+
target_price = get_target_price("KRW-BTC", 0.5)
72+
current_price = get_current_price("KRW-BTC")
73+
if target_price < current_price and current_price < predicted_close_price:
74+
krw = get_balance("KRW")
75+
if krw > 5000:
76+
upbit.buy_market_order("KRW-BTC", krw*0.9995)
77+
else:
78+
btc = get_balance("BTC")
79+
if btc > 0.00008:
80+
upbit.sell_market_order("KRW-BTC", btc*0.9995)
81+
time.sleep(1)
82+
except Exception as e:
83+
print(e)
84+
time.sleep(1)

Diff for: bitcoinAutoTradeWithMa.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import time
2+
import pyupbit
3+
import datetime
4+
5+
access = ""
6+
secret = ""
7+
8+
def get_target_price(ticker, k):
9+
"""변동성 돌파 전략으로 매수 목표가 조회"""
10+
df = pyupbit.get_ohlcv(ticker, interval="day", count=2)
11+
target_price = df.iloc[0]['close'] + (df.iloc[0]['high'] - df.iloc[0]['low']) * k
12+
return target_price
13+
14+
def get_start_time(ticker):
15+
"""시작 시간 조회"""
16+
df = pyupbit.get_ohlcv(ticker, interval="day", count=1)
17+
start_time = df.index[0]
18+
return start_time
19+
20+
def get_ma15(ticker):
21+
"""15일 이동 평균선 조회"""
22+
df = pyupbit.get_ohlcv(ticker, interval="day", count=15)
23+
ma15 = df['close'].rolling(15).mean().iloc[-1]
24+
return ma15
25+
26+
def get_balance(ticker):
27+
"""잔고 조회"""
28+
balances = upbit.get_balances()
29+
for b in balances:
30+
if b['currency'] == ticker:
31+
if b['balance'] is not None:
32+
return float(b['balance'])
33+
else:
34+
return 0
35+
return 0
36+
37+
def get_current_price(ticker):
38+
"""현재가 조회"""
39+
return pyupbit.get_orderbook(ticker=ticker)["orderbook_units"][0]["ask_price"]
40+
41+
# 로그인
42+
upbit = pyupbit.Upbit(access, secret)
43+
print("autotrade start")
44+
45+
# 자동매매 시작
46+
while True:
47+
try:
48+
now = datetime.datetime.now()
49+
start_time = get_start_time("KRW-BTC")
50+
end_time = start_time + datetime.timedelta(days=1)
51+
52+
if start_time < now < end_time - datetime.timedelta(seconds=10):
53+
target_price = get_target_price("KRW-BTC", 0.5)
54+
ma15 = get_ma15("KRW-BTC")
55+
current_price = get_current_price("KRW-BTC")
56+
if target_price < current_price and ma15 < current_price:
57+
krw = get_balance("KRW")
58+
if krw > 5000:
59+
print("구매")
60+
else:
61+
btc = get_balance("BTC")
62+
if btc > 0.00008:
63+
print("판매")
64+
time.sleep(1)
65+
except Exception as e:
66+
print(e)
67+
time.sleep(1)

Diff for: test.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import pyupbit
2+
import math
3+
4+
access = "" # 본인 값으로 변경
5+
secret = "" # 본인 값으로 변경
6+
upbit = pyupbit.Upbit(access, secret)
7+
8+
print("현재 보유 현금 : ", math.floor(upbit.get_balance("KRW")), "원") # 보유 현금 조회
9+
print("현재 보유 리플 : ",upbit.get_balance("KRW-XRP")) # KRW-XRP 조회
10+
math

0 commit comments

Comments
 (0)