볼린져 밴드로 비트코인 아마존 AWS 자동화하기 (full coding 공개)

볼린져 밴드 곡선으로 비트코인 자동화를 실현하고 싶죠? 아래 코드를 복사하고, 개인의 업비트 ID, Slack ID token을 넣고 돌려 보세요. 즉시 실행이 가능하고, 아마존 AWS 에 올려놓으면 자동으로 돌아갑니다.


upbit-bitcoin-auto-aws


 

볼린져 밴드로 비트코인 자동화 따라하기

볼린져 밴드 곡선에서 1분 단위로 설정을 해 봤어요.

설정 값이 민감하기 때문에 설정하는 방법은 따로 설명할게요.

궁금한 사항이 있으면 댓글로 알려주세요.


추가 글로 알려드릴게요.


업비트 토큰, Slack 토큰만 변경하시고 Run 해보세요

궁금한 사항은 댓글로 알려주세요.


(코드가 조금 지저분해도 이해해주세요. 쓸데없는 것도 많아요. 다음 글에서 차근 차근 단계별로 설명해 줄게요)


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# pip install --upgrade pip
# pip install pandas
# pip install pyupbit
# pip install schedule
# pip install -U pyupbit

##########################################################

import schedule
import time
import pyupbit
import requests  # slack
# import pandas as pd


##########################################################


# #집 IP# 
access = "xxxxxxxzkAf"
secret = "xxxxxxxx7CcIP8t"



# slack ##api.slack.com 에서 확인 / 

myToken = "xxxxxxxxkv2Q"


# Configuration
coin = "KRW-BTC"
# with open("key.txt") as f:
#     access, secret = [line.strip() for line in f.readlines()]

# Upbit Initialization
upbit = pyupbit.Upbit(access, secret)
print("I am 5 billion")


##########################################################

def post_message(token, channel, text):
    """슬랙 메시지 전송"""
    response = requests.post("https://slack.com/api/chat.postMessage",
                             headers={"Authorization": "Bearer "+token},
                             data={"channel": channel, "text": text}
                             )

# ##########################################################

def scheduled_start_alarm():
    post_message(myToken, "#stock", "Good morning, I am making money")

# ##########################################################

def get_balance(ticker):
    """잔고 조회"""
    balances = upbit.get_balances()
    for b in balances:
        if b['currency'] == ticker:
            if b['balance'] is not None:
                return float(b['balance'])
            else:
                return 0
    return 0

def get_current_price(ticker):
    """현재가 조회"""
    return pyupbit.get_orderbook(ticker=ticker)["orderbook_units"][0]["ask_price"]

# def get_avg_price(ticker):
#     """매수 평균가 조회"""
#     avgprice = upbit.get_balances()
#     for b in avgprice:
#         if b['currency'] == ticker:
#             if b['avg_buy_price'] is not None:
#                 return float(b['avg_buy_price'])
#             else:
#                 return 0
#     return 0

##########################################################

# # 시작 메세지 슬랙 전송
post_message(myToken, "#stock", "I am 5 billion rich")
# # post_message(myToken, "#stock", "BTC 잔고 : " + str(get_balance("KRW-BTC")))  # 잔고 #Slack
# # post_message(myToken, "#stock", "KRW 잔고 : " + str(get_balance("KRW")))  # 잔고 #Slack
# # BTC_price = pyupbit.get_current_price("KRW-BTC")  # Slack
# # post_message(myToken, "#stock", "BTC 현재가 : " + str(BTC_price))


##########################################################

def fetch_data(fetch_func, max_retries=20, delay=0.5):
    for i in range(max_retries):
        res = fetch_func() # fetch_func() 함수를 호출하여 데이터
        if res is not None: # 가져온 데이터가 None이 아닌 경우 루프를 종료
            return res
        time.sleep(delay) # 데이터를 가져오지 못한 경우 0.5초 동안 대기
    return None

def get_cur_price(ticker):
    return fetch_data(lambda: pyupbit.get_current_price(ticker))

def get_balance_cash():
    return fetch_data(lambda: upbit.get_balance("KRW"))


def get_balance_coin(ticker):
    return fetch_data(lambda: upbit.get_balance(ticker))

def get_buy_avg(ticker):
    return fetch_data(lambda: upbit.get_avg_buy_price(ticker))

def get_order_info(ticker):
    try:
        orders = fetch_data(lambda: upbit.get_order(ticker))
        if orders and "error" not in orders[0]:
            return orders[-1]
    except Exception as e:
        print(e)
    return None

# percent = 0.9995
# krw = get_balance("KRW") 

# 시장가 매수
def order_buy_market():             
    percent = 0.9995
    krw = get_balance("KRW")    
    
    if krw*percent < 5000:  
        print("amount is better than 5000")
        return 0  

    res = fetch_data(lambda: upbit.buy_market_order("KRW-BTC", krw*percent))

    if 'error' in res:
        print(res)
        res = 0

    return res


btc = get_balance("BTC")

################################################
# # 시장가 매도
# def order_sell_market():
#     res = fetch_data(lambda: upbit.sell_market_order("KRW-BTC", btc))

#     if 'error' in res:
#         print(res)
#         res = 0
#     return res

# 시장가 매도
def order_sell_market():
    try:
        # 업비트의 규칙에 맞게 수량 조정
        adjusted_btc = round(btc, 8)  # BTC의 경우 소수점 8자리로 반올림
        
        # 실제 주문 요청
        res = fetch_data(lambda: upbit.sell_market_order("KRW-BTC", adjusted_btc))

        # 오류 처리
        if 'error' in res:
            print(f"주문 오류 발생: {res}")
            return 0
        return res

    except Exception as e:
        print(f"예외 발생: {e}")
        return 0


################################################

# # 시장가 매도2 & 23:59 시간 매매
# def order_sell_market_2():
#     res = fetch_data(lambda: upbit.sell_market_order("KRW-BTC", btc))
#     print("SELL Order")
#     if 'error' in res:
#         print(res)
#         res = 0
#     return res


################################################

# 볼린져 밴드와 시그널 생성 함수
def get_bollinger_bands(prices, window=2, multiplier=1):

    ### 20일 기간 동안 이동 평균선 계산 (Middle Band)
    sma = prices.rolling(window).mean()

    ### 20일 동안의 표준 편차 계산
    rolling_std = prices.rolling(window).std()

    ### 중간 밴드 + (표준편차 * 2)
    upper_band = sma + (rolling_std * multiplier )
    
    ### 중간 밴드 - (표준편차 * 2)
    lower_band = sma - (rolling_std * multiplier)

    return upper_band, lower_band

cur_price = get_cur_price(coin)

def trading_signal(prices):

    ### get_bollinger_bands() 함수를 통해 상단/하단 밴드 요청
    upper_band, lower_band = get_bollinger_bands(prices)

    # 강제팔기 : sell margin 을 1 로 변경
    # sell_margin = + 10
    
    sell_margin = + 0.000 
    buy_margin = + 0.0001
    

    #         gap_0 < 0.0018
    gap_0_upper = 0.0018
    high_0 = 0
    low_0 = 0
     
    # lower < gap_1 < upper
    gap_1_lower = gap_0_upper
    gap_1_upper = 0.0025
    
    high_1 = 0.999568676 - sell_margin
    low_1 = 0.999152596 + buy_margin

    # lower < gap_2 < upper
    gap_2_lower = gap_1_upper
    gap_2_upper = 0.003
    
    high_2 = 1.000415193 - sell_margin
    low_2 = 1.002197608 + buy_margin

    # lower < gap_3 < upper
    gap_3_lower = gap_2_upper
    gap_3_upper = 0.0057
    
    high_3 = 1.000393152 - sell_margin
    low_3 = 1.002298272 + buy_margin

    # lower < gap_4 < upper
    gap_4_lower = gap_3_upper
    gap_4_upper = 0.0065
    
    high_4 = 0.995812172 - sell_margin
    low_4 = 1.00008401 + buy_margin

    # lower < gap_5 < upper
    gap_5_lower = gap_4_upper
    gap_5_upper = 0.007
    
    high_5 = 0.995531249 - sell_margin
    low_5 = 1.0004840843 + buy_margin

    # lower < gap_6 < upper
    gap_6_lower = gap_5_upper
    gap_6_upper = 0.009
    
    high_6 = 0.995331249 - sell_margin
    low_6 = 1.000744213 + buy_margin

    # lower < gap_7 < upper
    gap_7_lower = gap_6_upper
    gap_7_upper = 0.0105
    
    high_7 = 0.992278918 - sell_margin
    low_7 = 1.001271166 + buy_margin
    
    # lower < gap_8 < upper
    gap_8_lower = gap_7_upper
    gap_8_upper = 0.013
    
    high_8 = 0.992288094 - sell_margin
    low_8 = 1.001595658 + buy_margin
    
    # lower < gap_9 < upper
    gap_9_lower = gap_8_upper
    gap_9_upper = 0.02
    
    high_9 = 0.992278918
    low_9 = 1.001271166 + buy_margin

    cur_price = get_cur_price(coin)

    band_high_set = upper_band.iloc[-1] * 1
    band_low_set = lower_band.iloc[-1] * 1
    
    band_percent = (band_high_set / band_low_set) - 1

    # # 기본값으로 초기화
    # band_high = None
    # band_low = None

    # gap_0 
    if band_percent < gap_0_upper :     
        band_high = upper_band.iloc[-1] * high_0
        band_low = lower_band.iloc[-1] * low_0
        print("low gap_0 ")
 
    # gap_1   
    elif gap_1_lower < band_percent < gap_1_upper :
        band_high = upper_band.iloc[-1] * high_1
        band_low = lower_band.iloc[-1] * low_1
        print("high gap_1 ")

    # gap_2   
    elif gap_2_lower < band_percent < gap_2_upper :
        band_high = upper_band.iloc[-1] * high_2
        band_low = lower_band.iloc[-1] * low_2
        print("high gap_2 ")
        
    # gap_3   
    elif gap_3_lower < band_percent < gap_3_upper :
        band_high = upper_band.iloc[-1] * high_3
        band_low = lower_band.iloc[-1] * low_3
        print("high gap_3 ")
        
    # gap_4   
    elif gap_4_lower < band_percent < gap_4_upper :
        band_high = upper_band.iloc[-1] * high_4
        band_low = lower_band.iloc[-1] * low_4
        print("high gap_4 ")     
 
    # gap_5   
    elif gap_5_lower < band_percent < gap_5_upper :
        band_high = upper_band.iloc[-1] * high_5
        band_low = lower_band.iloc[-1] * low_5
        print("high gap_5 ")     
    
    # gap_6   
    elif gap_6_lower < band_percent < gap_6_upper :
        band_high = upper_band.iloc[-1] * high_6
        band_low = lower_band.iloc[-1] * low_6
        print("high gap_6 ")     

    # gap_7   
    elif gap_7_lower < band_percent < gap_7_upper :
        band_high = upper_band.iloc[-1] * high_7
        band_low = lower_band.iloc[-1] * low_7
        print("high gap_7 ")     

    # gap_8   
    elif gap_8_lower < band_percent < gap_8_upper :
        band_high = upper_band.iloc[-1] * high_8
        band_low = lower_band.iloc[-1] * low_8
        print("high gap_8 ") 

    # gap_9   
    elif gap_9_lower < band_percent < gap_9_upper :
        band_high = upper_band.iloc[-1] * high_9
        band_low = lower_band.iloc[-1] * low_9
        print("high gap_9 ") 
        # print(f"Band gap_9 : {high_9}")
        # print(f"Band gap_9 : {low_9}") 
    
    elif band_percent > gap_9_upper :
        print("Pass signal 1 Too high ")
        # print(f"Current Price : {cur_price}")
        # print(f"Band High Set : {band_high_set}")
        # print(f"Band Low Set : {band_low_set}")
        # print(f"Band Percent : {band_percent}")
        print() #필수
        return None

    if band_high is None or band_low is None:
        # print("Pass signal 0 Too low ")  #필수
        return None

    # band_mid = (band_high + band_low) / 2


    # cur_price = get_cur_price(coin)

    ### 상단/하단/현재가 출력
    # print(f"HIGH : {band_high} / MID : {band_mid} / LOW : {band_low} / {coin} PRICE : {cur_price} / SET-% : {band_percent} / SET-HIGH : {band_high_set} / SET-LOW : {band_low_set} ")

    ### 현재 가격이 상단 밴드보다 큰 경우는 'BUY' 신호를, 
    ### 하단 밴드보다 낮은 경우는 'SELL' 신호를,
    ### 밴드안에 있는 경우는 'HOLD' 신호를 return
 
    if band_high == 0 :
        # print("Pass signal 0 ")
        # print(f"Current Price : {cur_price}")
        # print(f"Band High Set : {band_high_set}")
        # print(f"Band Low Set : {band_low_set}")
        # print(f"Band Percent : {band_percent}")
        # print(f"Band High : {band_high}")
        # print(f"Band Low : {band_low}") 
        # print()
        return 'PASS'

    elif cur_price > band_high:
        # print("Sell signal 2 ")
        # print(f"Current Price : {cur_price}")
        # print(f"Band High Set : {band_high_set}")
        # print(f"Band Low Set : {band_low_set}")
        # print(f"Band Percent : {band_percent}")
        # print(f"Band High : {band_high}")
        # print(f"Band Low : {band_low}")
        # print()
        # post_message(myToken, "#stock", "Band High : " + str(band_high)) # Slack
        # post_message(myToken, "#stock", "Cur_Price : " + str(cur_price)) # Slack
        # post_message(myToken, "#stock", "Band Low : " + str(band_low)) # Slack
        return 'SELL'
    
    elif cur_price < band_high and cur_price > band_low:
        # print("Hold signal 2 ")
        # print(f"Current Price : {cur_price}")
        # print(f"Band High Set : {band_high_set}")
        # print(f"Band Low Set : {band_low_set}")
        # print(f"Band Percent : {band_percent}")
        # print(f"Band High : {band_high}")
        # print(f"Band Low : {band_low}")
        # print()        
        return 'HOLD'
    
    elif cur_price < band_low:
        # print("Buy signal 2 ")
        # print(f"Current Price : {cur_price}")
        # print(f"Band High Set : {band_high_set}")
        # print(f"Band Low Set : {band_low_set}")
        # print(f"Band Percent : {band_percent}")
        # print(f"Band High : {band_high}")
        # print(f"Band Low : {band_low}")
        # print()
        # post_message(myToken, "#stock", "Band High : " + str(band_high)) # Slack
        # post_message(myToken, "#stock", "Cur_Price : " + str(cur_price)) # Slack
        # post_message(myToken, "#stock", "Band Low : " + str(band_low)) # Slack
        return 'BUY'
    
    else:
        # print("Pass signal 2 ")
        # print(f"Current Price : {cur_price}")
        # print(f"Band High : {band_high}")
        # print(f"Band Low : {band_low}")
        print() #필수
        return 'PASS'
 


def trading(ticker):

    ### pyupbit.get_ohlcv() 함수를 이용해서 업비트 사이트의 20일 데이터 받아오기
    prices_data = pyupbit.get_ohlcv(ticker, interval="day", count=20)
    prices = prices_data['close']

    ### 받아온 가격 데이터의 종가만을 추출하여 trading_signal() 함수에 전달
    signal = trading_signal(prices)
    time.sleep(1)
    balance_cash = get_balance_cash()
    time.sleep(1)
    balance_coin = get_balance_coin(ticker)
    time.sleep(1)

    ### signal 이 "BUY" 이고 현재 보유 현금이 10000원 보다 많은 경우 매수 주문
    ### signal 이 "SELL" 이고 현재 보유 코인이 1개 보다 많은 경우 매도 주문
    
    cur_price = get_cur_price(coin)
    
    if signal == 'BUY' and balance_cash > 5000:
        print("BUY Order")
        # percent = 0.9995
        # krw = get_balance("KRW") 
        # post_message(myToken,"#stock", "BUY Order") #Slack
        # BTC_price = pyupbit.get_current_price("KRW-BTC")  # Slack
        # post_message(myToken, "#stock", "BTC 현재가 : " + str(BTC_price)) # Slack
        # return order_buy_market("KRW-BTC", krw*percent)               
        return order_buy_market()

    elif signal == 'SELL' and balance_coin > 0:
        print("SELL Order")
        # print()
        # btc = get_balance("BTC")
        # post_message(myToken,"#stock", "SELL Order") #Slack
        # post_message(myToken, "#stock", "KRW 잔고 : " + str(get_balance("KRW")))  # 잔고 #Slack
        # BTC_price = pyupbit.get_current_price("KRW-BTC")  # Slack
        # post_message(myToken, "#stock", "BTC 현재가 : " + str(BTC_price)) # Slack
        # return order_sell_market("KRW-BTC", btc)     
        return order_sell_market()
      
    else:
        # post_message(myToken,"#stock", "Hold position TEST") #Slack
        print("Hold position 3")
        print() #필수
    return None

#############################################

def run():
    ret = trading(coin)
    if ret is not None:
        print(ret)
        # time.sleep(0.5)
        # post_message(myToken, "#stock", "에러가 발생했습니다")


# def run(coin, myToken):
#     try:
#         ret = trading(coin)
#         if ret is not None:
#             print(ret)
#         time.sleep(0.5)
#     except Exception as e:
#         print(f"에러 발생: {e}")  # 에러 메시지 출력
#         post_message(myToken, "#stock", "에러가 발생했습니다")




#############################################
# 특정시간 매매1 (KRW-BTC) 비트코인
sell_time_1 = "23:59"
schedule.every().day.at(sell_time_1).do(order_sell_market)



schedule.every(3).hours.do(scheduled_start_alarm)



# 반복문 시작
while True:
    run()
    try:
        schedule.run_pending()
        time.sleep(10)

    except Exception as e:
        print(e)
        post_message(myToken, "#stock", e)  # Slack
        time.sleep(10)




주요 태그 : #업비트 #업비트코인자동화 #코인자동매매 #볼린져밴드매매 #볼린져밴드


글이 도움이 되셨다면, 댓글 남겨주시면, 더 좋은 글로 보답하겠습니다~!

wish wifi - 위시 와아파이에 방문해 주셔서 감사합니다!

댓글 쓰기

다음 이전