Exemplo n.º 1
0
    def ConnectToUpbit(self):
        # 객체생성(Upbit 연결)
        access = "frGzp5hUEaQBNQ1uuO60Dx3QGkSm5ugsEVdfrpnr"
        secret = "L4wHqPfrfc7x8NYWHaL8IoUxbV8MBuhoxZG2ZHJa"
        upbit = pyupbit.Upbit(access, secret)

        return upbit
Exemplo n.º 2
0
def create_instance():
    with open("upbit.txt") as f:
        lines = f.readlines()
        key = lines[0].strip()
        secret = lines[1].strip()

    inst = pyupbit.Upbit(key, secret)
    return inst
Exemplo n.º 3
0
    def updateData(self, data):
        f = open("api.txt")
        lines = f.readlines()   # 모든 라인 읽어오기
        access = lines[0].strip()  # 0번째 줄 가져오기 strip()메소드를 사용해 '\n'을 없애기.
        secret = lines[1].strip()
        f.close()

        self.upbit = pyupbit.Upbit(access, secret)
        balances = self.upbit.get_balances()

        # 업비트가 지원하는 모든 원화마켓 가져오기
        krw_market = pyupbit.get_tickers(fiat="KRW")
        
        for j in range(len(balances)):
            ticker= "KRW-"+balances[j]['currency']
            
            # 지원하는 원화마켓과 다른 티커는 제외(비상장 코인이나 KRW-KRW문제)
            if ticker in krw_market:
                price = pyupbit.get_current_price(ticker)
                for i in range(len(balances)):
                    # 0) 코인명 
                    item_0 = self.tableBalances.item(i, 0)
                    item_0.setText(f"{balances[i]['currency']}")

                    # 1) 보유수량
                    item_1 = self.tableBalances.item(i, 1)
                    amount1 = float(balances[i]['balance']) + float(balances[i]['locked'])
                    item_1.setText(f"{amount1}")
                    
                    if "KRW-"+balances[i]['currency'] not in krw_market : pass
                    else :
                        # 2) 매수평균가
                        item_2 = self.tableBalances.item(i, 2)
                        item_2.setText(f"{balances[i]['avg_buy_price']} 원")

                        # 3) 평가금액
                        amount2 = price * (float(balances[i]['balance'])+float(balances[i]['locked']))  # 현재가 * (주문가능 금액 + 주문 묶여있는 금액)

                        item_3 = self.tableBalances.item(i, 3)
                        item_3.setText(f"{int(amount2)} 원")

                        # 4) 매수금액
                        amount3 = round(float(balances[i]['avg_buy_price']) * (float(balances[i]['balance']) + float(balances[i]['locked']))) # 매수평균가 * (주문가능 금액 + 주문 묶여있는 금액) 반올림
                        item_4 = self.tableBalances.item(i, 4)
                        item_4.setText(f"{str(amount3)} 원")

                        # 5) 평가손익
                        amount4 = round(amount2 - amount3, 2) # 평가금액 - 매수금액 -> 소수 둘째자리까지 반올림
                        item_5 = self.tableBalances.item(i, 5)
                        item_5.setText(f"{amount4}")
                    
                        try :
                            # 수익률
                            amount5 = round(amount4 / amount3 * 100,2) # 평가손익 / 매수금액
                            item_6 = self.tableBalances.item(i, 6)
                            item_6.setText(f"{str(amount5)} %")

                        except: pass
Exemplo n.º 4
0
    def run(self):

        access = "frGzp5hUEaQBNQ1uuO60Dx3QGkSm5ugsEVdfrpnr"
        #secret = lines[1].strip()
        secret = "L4wHqPfrfc7x8NYWHaL8IoUxbV8MBuhoxZG2ZHJa"
        upbit = pyupbit.Upbit(access, secret)

        Ticker = "KRW-DOGE"
        while self.alive:
            orderbook = pyupbit.get_orderbook(Ticker)
            time.sleep(0.1)
            self.dataSent.emit(orderbook)
Exemplo n.º 5
0
    def run(self):
        while self.alive:
            f = open("api.txt")
            lines = f.readlines()   # 모든 라인 읽어오기
            access = lines[0].strip()  # 0번째 줄 가져오기 strip()메소드를 사용해 '\n'을 없애기.
            secret = lines[1].strip()
            f.close()

            self.upbit = pyupbit.Upbit(access, secret)
            data  = self.upbit.get_balances()
            time.sleep(0.5)
            if data[0] != None:
                self.dataSent.emit(data[0])
Exemplo n.º 6
0
def buy_market_order(coin_name):
    coin = 'KRW-'+coin_name
    price = pyupbit.get_current_price(coin)
    print(price)

    # access_key = ""
    # secret_key = ""

    upbit = pyupbit.Upbit(access_key, secret_key)
    my_balance = upbit.get_balances()[0]['balance']
    print(my_balance)

    ret = upbit.buy_limit_order(coin, price, '{0:.2f}'.format(my_balance/price*1.1))
    print(ret)
Exemplo n.º 7
0
 def slot_clickStart(self):
     f = open("api.txt")
     lines = f.readlines() # 모든 라인 읽어오기
     access = lines[0].strip()
     secret = lines[1].strip()
     f.close()
     
     self.upbit = pyupbit.Upbit(access, secret)
     self.ticker = "KRW-ETH"
     start_now = datetime.datetime.now()
     start_now = start_now.strftime("%Y/%m/%d %H:%M:%S")
     self.textEdit.append(f"{start_now} 자동매매를 시작합니다.")
     self.vw = VolatilityWorker(self.ticker, self.upbit)
     self.vw.tradingSent.connect(self.slot_tradingSignal)
     self.vw.start()
Exemplo n.º 8
0
    def slot_window_change(self):
        access = self.ui.lineEdit.text()
        secret = self.ui.lineEdit_2.text()

        with open('api.txt', 'w') as f:
            f.write(access)
            f.write("\n"+ secret)

        upbit = pyupbit.Upbit(access,secret)
        mybtc = upbit.get_balances("KRW-ETH")
        # print(type(mybtc[0]))

        # 연결 성공시 로그인창 닫고 메인창 열기
        if  type(mybtc[0]) is list:
            QMessageBox.information(self, "연결 확인", "연결 성공!")
            self.ui.close()
            self.ui = uic.loadUi("source/new_main2.ui", self)
            self.ui.show()

        # 연결 실패시 실패 메시지 출력
        elif type(mybtc[0]) is dict :
            QMessageBox.information(self, "연결 확인", "연결 실패!")
Exemplo n.º 9
0
    def initUI(self):
        access = ''
        secret = ''
        upbit = pyupbit.Upbit(access, secret)
        btn1 = QPushButton('시작', self)
        btn1.resize(btn1.sizeHint())
        btn1.move(30,50)
        resp = upbit.buy_market_order("KRW-ETH", 5000)
        pprint.pprint(resp)

        btn2 = QPushButton('종료', self)
        btn2.resize(btn1.sizeHint())
        btn2.move(150,50)


        btn1.clicked.connect(self.buttonClicked)
        btn2.clicked.connect(self.buttonClicked)

        self.statusBar()

        self.setGeometry(300,300,290,150)
        self.setWindowTitle('자동 매매 시작/종료')
        self.show()
Exemplo n.º 10
0
    def __init__(self):
        super().__init__()
        config = self.check_config()
        if not config:
            self.logger.error("coin_config.ini 파일이 유효하지 않아 프로그램을 종료합니다.")
            exit(-1)
        upbit_config = config['UPBIT']
        self.access = upbit_config.get("UPBIT_OPEN_API_ACCESS_KEY")
        self.secret = upbit_config.get("UPBIT_OPEN_API_SECRET_KEY")

        discord_config = config['DISCORD']
        self.webhook_url = discord_config.get("DISCORD_WEBHOOK_URL")
        self.heartbeat_url = discord_config.get("DISCORD_HEARTBEAT_URL")
        self.heartbeat_interval = int(discord_config.get("HEARTBEAT_INTERVAL"))

        self.upbit = pyupbit.Upbit(self.access, self.secret)
        self.cmm_config = dict(config['CMM'])
        self.cmm_config['interval'] = self.cmm_config['interval']
        self.cmm_config['count'] = int(self.cmm_config['count'])
        self.cmm_config['max_dca_buy_cnt'] = int(self.cmm_config['max_dca_buy_cnt'])
        self.cmm_config['dca_buy_rate'] = int(self.cmm_config['dca_buy_rate'])
        self.cmm_config['value_k'] = float(self.cmm_config['value_k'])
        self.cmm_config['delay'] = int(self.cmm_config['delay'])
        self.cmm_config['start_amount'] = int(self.cmm_config['start_amount'])
        self.cmm_config['multiple_amount'] = int(self.cmm_config['multiple_amount'])
        self.cmm_config['profit_rate'] = int(self.cmm_config['profit_rate'])

        self.svb_config = dict(config['SVB'])
        self.svb_config['profit_rate'] = int(self.svb_config['profit_rate'])
        self.svb_config['buy_amount'] = int(self.svb_config['buy_amount'])

        self.discord_conn = DiscordConnector(self.cmm_config,
                                             webhook_url=self.webhook_url,
                                             heartbeat_url=self.heartbeat_url)
        self.hold_krw = float(self.get_balance_info()['balance'])
        self.reporter = Reporter()
def buy_all(coin):
    balance = upbit.get_balance("KRW") * 0.9995
    if balance >= 5000:
        print(upbit.buy_market_order(coin, balance))


def sell_all(coin):
    balance = upbit.get_balance(coin)
    price = pyupbit.get_current_price(coin)
    if price * balance >= 5000:
        print(upbit.sell_market_order(coin, balance))


if __name__ == '__main__':
    try:
        upbit = pyupbit.Upbit(auth.access, auth.secret)

        # set variables
        coin = "KRW-BTC"
        fees = 0.0005
        K = 0.5

        start_balance = upbit.get_balance("KRW")
        df = pyupbit.get_ohlcv(coin, count=2, interval="day")
        targetPrice = get_targetPrice(df, K)
        print(datetime.datetime.now().strftime('%y/%m/%d %H:%M:%S'),
              "\t\tBalance :", start_balance, "KRW \t\tYield :",
              ((start_balance / start_balance) - 1) * 100,
              "% \t\tNew targetPrice :", targetPrice, "KRW")

        while True:
Exemplo n.º 12
0
 def sell_coinself(self,coin,price,access_key=None, secret=None):
     upbit_ = pyupbit.Upbit(access_key, secret)
     coins = pyupbit.Upbit.get_balance(self.target_coin)
     print(pyupbit.Upbit.sell_market_order(self.target_coin, coins))
Exemplo n.º 13
0
 def buy_market_order(self,coin,access_key=None, secret=None):
     upbit_ = pyupbit.Upbit(access_key,secret)
     won = pyupbit.Upbit.get_balance('KRW')
     print('%d 보유 금액',won)
     print(pyupbit.Upbit.buy_market_order(self.target_coin,won))
Exemplo n.º 14
0
            #print(rt)
            
            
            sql = """UPDATE tacker SET avgprice = %s WHERE id = %s AND currency = %s """
            cursor.execute(sql, (b['avg_buy_price'] ,id ,tabkerName))
            time.sleep(1)
        time.sleep(1)



# CREATE TABLE tacker (
# id VARCHAR(100) NOT NULL,
# currency VARCHAR(100) NOT NULL,
# avgprice DECIMAL(9,2),
# selper1 DECIMAL(9,2),
# selper1_1 DECIMAL(9,2),
# selper2 DECIMAL(9,2),
# selper2_1 DECIMAL(9,2),
# selper3 DECIMAL(9,2),
# selper3_1 DECIMAL(9,2),
# PRIMARY KEY(id ,currency)
# ) ENGINE=MYISAM CHARSET=utf8;


myKey = Login()
upbit = pyupbit.Upbit(myKey[0], myKey[1])

while True :
    SetPerOrder()
    time.sleep(1)
Exemplo n.º 15
0
# querystring = {"market":"KRW-ATOM","count":"200"}
# response = requests.request("GET", url, params=querystring)
# data = response.json()
# df = pd.DataFrame(data)
# print(df)


def get_ma(ticker, intervalMinute, icount):
    df = pyupbit.get_ohlcv(ticker,
                           interval="minute" + str(intervalMinute),
                           count=icount)
    ma = df['close'].rolling(icount).mean().iloc[-1]
    return ma


upbit = pyupbit.Upbit("C0Az21yejT3prbheZAUdZMCUGi9Tr1R0OlSNgIp3",
                      "ZRozlBWm55cYlLjSmf9eBzYjhpuxUWeXKPFNzf4Q")

while True:
    ticker = "KRW-MVL"

    inter = 5
    df = pyupbit.get_ohlcv(ticker, interval="minute" + str(inter), count=200)
    ohlc: pd.DataFrame = df
    ohlc["volume"] = ohlc["volume"]
    delta = ohlc["volume"].diff()
    ttaD = ohlc["volume"].copy()
    evg = ttaD.abs().sum() / ttaD.count()

    ttal, gains, declines = df["volume"].copy(), df["volume"].copy(
    ), df["volume"].copy()
    ttal[df['close'] < df['open']] = ttal * -1
import pyupbit
import datetime
import numpy as np
import time

# 주문불가 key : 모든 IP 사용 가능
#con_key = "..."
#sec_key = "..."

# 주문 가능 key : upbit API key 획득 후 customize
# con_key = "..."
# sec_key = "..."

upbit = pyupbit.Upbit(con_key, sec_key)
'''
for ticker in pyupbit.get_tickers():
    if ticker.split('-')[0]=="KRW":
        balance = upbit.get_balance('-'+ticker.split('-')[1])
        if balance > 0:
            print(ticker, ": ", balance)
            time.sleep(0.1)

'''
'''
order = upbit.buy_limit_order(COI,50,10000)
print(order)

time.sleep(3)
cancel = upbit.cancel_order(order['uuid'])
print(cancel)
'''
Exemplo n.º 17
0
#dfAll.to_excel("btc.xlsx") #전체가격 엑셀

# def cal_target(ticker): #적정가 구하기(안쓸꺼임 참고만)
#     yesterday = dfDay.iloc[-2]
#     today = dfDay.iloc[-1]
#     yesterdayRange = yesterday['high']-yesterday['low']
#     target = today['open']+ yesterdayRange * 0.5
#     return target

f = open("upbit.txt")
lines = f.readlines()
access = lines[0].strip() #access key #strip '\n' 제거
secret = lines[1].strip() #secret key #strip '\n' 제거
f.close

upbit = pyupbit.Upbit(access, secret) #업비트 객체 생성후 계좌 접근
myMoney = upbit.get_balance("KRW") #잔고 구하기

runCoin = "KRW-EOS"
runTf = True
buying = "180000"
selling = "0.9"
num = 0
myBuyPrice = 189400.0 #매수가 임의 입력

def tradingCoin():
    global runTf
    global num
    while runTf:
        amount = upbit.get_balance(runCoin) #코인 보유 수량 구하기    
        nowTime = datetime.datetime.now()
Exemplo n.º 18
0
from time import sleep
import logging.handlers
import logging
import traceback

log_handlers = [
    logging.handlers.RotatingFileHandler(filename='/home/coinbot/ysl_log.txt',
                                         maxBytes=1024),
    logging.StreamHandler()
]
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s [%(levelname)s] : %(message)s',
                    handlers=log_handlers)
logger = logging.getLogger('auto_trade_logger')

upbit = pyupbit.Upbit(os.environ['ysl_accesskey'], os.environ['ysl_secretkey'])
max_buy_limit = 10000
max_sell_limit_rate = 1.04
max_auto_trade_sceond = 60 * 60 * 3
loop_auto_trade_second = 0
wait_second = 10
my_money = 100000
user_id = 'ysl'
conn = psycopg2.connect(host='localhost',
                        dbname='botdb',
                        user='******',
                        password=os.environ['db_password'],
                        port='5432')
conn.autocommit = True
cur = conn.cursor()
Exemplo n.º 19
0
conn = psycopg2.connect(host=os.environ['db_url'], dbname='botdb', user='******', password=os.environ['db_password'], port='5432')
conn.autocommit = True
cur = conn.cursor()
cur.execute("select get_code('system_parameter','control_bot_token','hoonkim') accesskey, get_code('system_parameter','control_bot_signing_secret','hoonkim') secretkey")
slack_key = cur.fetchall()
print(slack_key)
# Initializes your app with your bot token and signing secret
app = App(
    token=slack_key[0][0],
    signing_secret=slack_key[0][1]
)
cur.execute("select get_code('system_parameter','accesskey','hoonkim') accesskey, get_code('system_parameter','secretkey','hoonkim') secretkey")
upbit_key = cur.fetchall()
print(upbit_key)
upbit = pyupbit.Upbit(upbit_key[0][0], upbit_key[0][1])
@app.message("hello")
def message_hello(message, say):
    # say() sends a message to the channel where the event was triggered
    logger.info(message)
    say(
        blocks=[
            {
                "type": "section",
                "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"},
                "accessory": {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "Click Me"},
                    "action_id": "button_click"
                }
            }
import multiprocessing
from os import system
import sys
import pyupbit as pu
import time
import numpy as np

##########################################################################################################
#markets 정보가 바뀐 경우 새로 실행(market이 새로 추가된 경우, 상장 폐지된 경우)
#buy_markets에 있는 코인이 상장 폐지된 경우 직접 디지털 출금 주소 생성 후 출금
#업비트 거래소 점검 시 프로그램 직접 종료 후 점검 완료 후 다시 실행
##########################################################################################################
access = ''     # access key
secret = ''     # secret key
upbit = pu.Upbit(access,secret)
##########################################################################################################

def get_buy_markets():  

    buy_markets = []
    ordered_markets = []

    for coin in upbit.get_balances():
        if coin['currency']=='KRW' or coin['currency']=='USDT':
            continue

        if float(coin['balance']) == 0.0:
            ordered_markets.append('KRW-'+coin['currency'])
            continue
Exemplo n.º 21
0
    def run(self):
        price_curr = None
        buy_flag = False
        sell_flag = False
        wait_flag = False

        upbit = pyupbit.Upbit(access, secret)
        cash = upbit.get_balance()
        print("autotrade start")
        print("보유현금", cash)
        post_message(myToken, "#codetest", "Auto Trade start")
        post_message(myToken, "#codetest",
                     "Now Balance : " + str(round(cash, 0)))

        while True:
            try:
                if not self.q.empty():
                    if price_curr != None:
                        self.ma5.append(price_curr)
                        self.ma10.append(price_curr)
                        self.ma15.append(price_curr)
                        self.ma20.append(price_curr)
                        self.ma50.append(price_curr)
                        self.ma120.append(price_curr)
                        self.high1.append(price_curr)
                        self.low1.append(price_curr)
                        self.close1.append(price_curr)

                    curr_ma5 = sum(self.ma5) / len(self.ma5)
                    curr_ma10 = sum(self.ma10) / len(self.ma10)
                    curr_ma15 = sum(self.ma15) / len(self.ma15)
                    curr_ma20 = sum(self.ma20) / len(self.ma20)
                    curr_ma50 = sum(self.ma50) / len(self.ma50)
                    curr_ma120 = sum(self.ma120) / len(self.ma120)
                    target_price = (sum(self.close1) / len(self.close1)) + (
                        (sum(self.high1) / len(self.high1)) -
                        (sum(self.low1) / len(self.low1))) * 0.4

                    price_open = self.q.get()
                    if buy_flag == False:
                        price_buy = price_open * 1.001

                    wait_flag = False
                    print(buy_flag, sell_flag, wait_flag)

                price_curr = pyupbit.get_current_price(self.ticker)
                print("[", datetime.datetime.now(), "]", "[BUY_IMPOSSIBLE!]",
                      "    커런트 프라이스 :", price_curr, "// 타겟 프라이스 :",
                      round(target_price, 2), " //        ",
                      round(curr_ma5, 2), round(curr_ma10, 2), "[",
                      round(curr_ma50 * 1.03, 2), "]", round(curr_ma15, 2),
                      round(curr_ma20, 2), round(curr_ma50, 2),
                      round(curr_ma120, 2))
                if price_curr == None:
                    continue


                if buy_flag == False and sell_flag == False and wait_flag == False and \
                   price_buy != None and price_curr >= curr_ma10 and curr_ma15 >= curr_ma50 and \
                   curr_ma15 <= curr_ma50 * 1.03 and curr_ma120 <= curr_ma50 and curr_ma20 >= curr_ma50 and \
                   curr_ma5 >= curr_ma10 and curr_ma10 >= curr_ma15 and curr_ma15 >= curr_ma20 and price_curr >= target_price:
                    ret = upbit.buy_market_order(self.ticker, cash * 0.9995)
                    print("매수주문", ret)
                    time.sleep(0.2)
                    if ret == None or "error" in ret:
                        print("매수 주문 이상")
                        continue
                    time.sleep(0.2)

                    while True:
                        volume = upbit.get_balance(self.ticker)
                        avg_price = upbit.get_avg_buy_price(self.ticker)
                        print("매수 평균가 :", avg_price, "수량 :", volume)
                        if volume == None and avg_price == None:
                            print("매수 주문 이상")
                            continue
                        time.sleep(0.5)
                        buy_flag = True
                        print(buy_flag, sell_flag, wait_flag)
                        break

                    while True:
                        if buy_flag == True and sell_flag == False and wait_flag == False:
                            price_curr = pyupbit.get_current_price(self.ticker)
                            avg_price = upbit.get_avg_buy_price(self.ticker)
                            print("[", datetime.datetime.now(), "]", "[현재가 :",
                                  price_curr, "]", "손절가 :", avg_price * 0.985,
                                  " // ", "익절가 :", avg_price * 1.011, " // ",
                                  "매수 평균가 :", avg_price)
                            time.sleep(0.2)
                            if price_curr <= avg_price * 0.985 or price_curr >= avg_price * 1.011:
                                ret = upbit.sell_market_order(
                                    self.ticker, volume)
                                if ret == None or 'error' in ret:
                                    continue
                                else:
                                    print("매도주문", ret)
                                    sell_flag = True
                                    break
                                    print(buy_flag, sell_flag, wait_flag)
                                    time.sleep(0.5)

                if buy_flag == True and sell_flag == True and wait_flag == False:
                    uncomp = upbit.get_order(self.ticker)
                    if uncomp != None and len(uncomp) == 0:
                        cash = upbit.get_balance()
                        if cash == None:
                            continue

                        print("매도완료", cash)
                        buy_flag = False
                        sell_flag = False
                        wait_flag = True
                        print(buy_flag, sell_flag, wait_flag)
                        post_message(myToken, "#codetest",
                                     "Now Balance : " + str(round(cash, 0)))

            except:
                print("error")

            time.sleep(0.2)
Exemplo n.º 22
0
    def run(self):    
        price_curr = None
        hold_flag = False
        wait_flag = False

        access_key='9nQLNICO2fkCLPA51gUCb05QxdpHtY9mlzkbnt6h'
        secret_key='LTNcZ5vPTVBfL4hKUyjQ0o31llqZGNnLpSYjAgCP'
        upbit = pyupbit.Upbit(access_key, secret_key)
        
        cash  = upbit.get_balance()
        print("보유현금", cash)

        i = 0

        while True:   
            try:  

                if not self.q.empty():
                    if price_curr != None:
                        self.ma15.append(price_curr)
                        self.ma50.append(price_curr)
                        self.ma120.append(price_curr)

                    curr_ma15 = sum(self.ma15) / len(self.ma15)
                    curr_ma50 = sum(self.ma50) / len(self.ma50)
                    curr_ma120 = sum(self.ma120) / len(self.ma120)

                    price_open = self.q.get()
                    if hold_flag == False:
                        price_buy  = price_open * 1.01
                        price_sell = price_open * 1.02
                    wait_flag  = False

                price_curr = pyupbit.get_current_price(self.ticker)

                if hold_flag == False and wait_flag == False and \
                    price_curr >= price_buy and curr_ma15 >= curr_ma50 and \
                    curr_ma15 <= curr_ma50 * 1.03 and curr_ma120 <= curr_ma50 :
                    # 0.05%
                    ret = upbit.buy_market_order(self.ticker, cash * 0.9995)
                    print("매수주문", ret)
                    time.sleep(1)
                    volume = upbit.get_balance(self.ticker)
                    ret = upbit.sell_limit_order(self.ticker, price_sell, volume)
                    print("매도주문", ret)
                    hold_flag = True
                # print(price_curr, curr_ma15, curr_ma50, curr_ma120)

                if hold_flag == True:
                    uncomp = upbit.get_order(self.ticker)
                    if len(uncomp) == 0:
                        cash = upbit.get_balance()
                        print("매도완료", cash)
                        hold_flag = False
                        wait_flag = True

                # 3 minutes
                if i == (5 * 60 * 3):
                    print(f"[{datetime.datetime.now()}] 현재가 {price_curr}, 목표가 {price_buy}, ma {curr_ma15:.2f}/{curr_ma50:.2f}/{curr_ma120:.2f}, hold_flag {hold_flag}, wait_flag {wait_flag}")
                    i = 0
                i += 1
            except:
                print("error")
                
            time.sleep(0.2)
Exemplo n.º 23
0
    """20봉 전 금액 조회"""
    df = pyupbit.get_ohlcv(ticker,
                           interval="minute" + str(intervalMinute),
                           count=icount + 1)
    global a20
    global a21

    a20 = df['close'][1]
    a21 = df['close'][0]


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


upbit = pyupbit.Upbit("LM6x7zWpGDRsx3xyQuLhAeEf4aVI22KLxtCogCfM",
                      "Pm9xi0Jl14auFBJgBq5SwICpvyTLFVRQ95IVOdzv")

while (True):
    print("START---------------")
    for ticker in pyupbit.get_tickers("KRW"):
        m20 = get_ma20(ticker, 20)
        get_After2(ticker, 20)
        np = get_current_price(ticker)
        if m20 < np and a20 < np and np < a21:
            print(ticker + " -> a20 : " + str(a20) + "  . np : " + str(np))
        time.sleep(1)
    print("---------------END")
#balances = upbit.get_balances()
Exemplo n.º 24
0
def get_current_price(ticker):
    """현재가 조회"""
    return pyupbit.get_orderbook(
        tickers=ticker)[0]["orderbook_units"][0]["ask_price"]


coinName = "COIN"
tradingCoin = "KRW-COIN"
k = 0.1

slackChannel = "변동성-전략"

inBuy = True  # 한 번만 매수하기 위함

# 로그인
upbit = pyupbit.Upbit(key0, key1)

# 우리나라 화폐, 암호화폐 생성
krw = upbit.get_balance("KRW")
coins = upbit.get_balance(coinName)

# 얼마나 파는 지, 얼마나 사는 지 설정
buyValue = krw * 0.9995  # 0.9995 인 이유는 수수료 0.005% 때문이다.
sellValue = coins * 0.9995

# 시작 메세지 슬랙 전송
print("Autotrade start")
post_message(
    myToken, slackChannel, "변동성 돌파 전략으로 자동매매 시작\n매수, 매도 코인 : " +
    str(coinName) + " " + "k값 : " + str(k))
Exemplo n.º 25
0
import pyupbit
import time
import datetime


with open("upbit.txt") as f:
    lines = f.readlines()
    key = lines[0].strip()
    secret = lines[1].strip()
    upbit = pyupbit.Upbit(key, secret)

'''
내 잔고 조회
'''
upbit = pyupbit.Upbit(key, secret)
print(upbit.get_balances())

'''
변동성 돌파 목표가 계산을 위한 함수
'''
def get_target_price(ticker):#재사용을 위해 함수 선언
    df = pyupbit.get_ohlcv(ticker)
    yesterday = df.iloc[-2]#끝에서 2번째인 전일 데이터를 가지고 온다.
    today_open = yesterday['close']#당일 시가를 얻어온다.
    yesterday_high = yesterday['high']#전일 고가를 얻어온다.
    yesterday_low = yesterday['low']#전일 저가를 얻어온다.
    target = today_open + (yesterday_high - yesterday_low)#변동성 돌파 목표가 계산
    return target


'''
Exemplo n.º 26
0
import datetime
import math
import requests

############# 업비트 api auth ############
#with open("Upbit_API_KEY.txt", 'r', encoding='utf-8') as f:
#lines = f.readlines()
#access_key = lines[0].strip()
#secret_key = lines[1].strip()
#upbit = pyupbit.Upbit(access_key, secret_key)
#print(upbit.get_balances())

ACCESS_KEY = ""
SECRET_KEY = ""

upbit = pyupbit.Upbit(ACCESS_KEY, SECRET_KEY)
print(upbit.get_balances())
#########################

##########상수 정의#############
GAP_RATE = 0.1
TICKER = ""


######### 함수 정의 ###########
def log(pLog):
    start = "\n==============" + str(
        datetime.datetime.now()) + "=============\n"
    end = "\n===================================================\n"
    #본인이 로그 기록하고 싶은 경로
    fname = "C:\\Users\\max14\\OneDrive\\바탕 화면\\융합 프로젝트\\trading source\\log_" + str(
Exemplo n.º 27
0
import pyupbit

access_key = "t88RbbxB8NHNyqBUegeVqowGQOGEefeee3W2dGNU"
secret_key = "VCLoAhrxbvyrukYChbxfxD6O1ESegeckIgbqeiQf"

upbit = pyupbit.Upbit(access_key, secret_key)
ret = upbit.buy_limit_order("KRW-XRP", 100, 20)
print(ret)
Exemplo n.º 28
0
    def run(self):
        price_curr = None
        hold_flag = False
        wait_flag = False

        # 로그인
        upbit = pyupbit.Upbit(access, secret)
        cash = upbit.get_balance()
        print("autotrade start")
        print("보유현금", cash)
        post_message(myToken, "#test", "autotrade start")
        post_message(myToken, "#test", "Now Balance : " + str(cash))

        i = 0

        while True:
            try:
                if not self.q.empty():
                    if price_curr != None:
                        self.ma15.append(price_curr)
                        self.ma50.append(price_curr)
                        self.ma120.append(price_curr)

                    curr_ma15 = sum(self.ma15) / len(self.ma15)
                    curr_ma50 = sum(self.ma50) / len(self.ma50)
                    curr_ma120 = sum(self.ma120) / len(self.ma120)

                    price_open = self.q.get()
                    if hold_flag == False:
                        price_buy = int(price_open * 1.01)
                        price_sell = int(price_open * 1.02)
                    wait_flag = False

                price_curr = pyupbit.get_current_price(self.ticker)

                if hold_flag == False and wait_flag == False and \
                        price_curr >= price_buy and curr_ma15 >= curr_ma50 and \
                        curr_ma15 <= curr_ma50 * 1.03 and curr_ma120 <= curr_ma50:
                    # 0.05%
                    ret = upbit.buy_market_order(self.ticker, cash * 0.9995)
                    print("매수주문", ret)
                    time.sleep(1)
                    volume = upbit.get_balance(self.ticker)
                    ret = upbit.sell_limit_order(self.ticker, price_sell,
                                                 volume)
                    print("매도주문", ret)
                    hold_flag = True
                # print(price_curr, curr_ma15, curr_ma50, curr_ma120)

                if hold_flag == True:
                    uncomp = upbit.get_order(self.ticker)
                    if len(uncomp) == 0:
                        cash = upbit.get_balance()
                        print("매도완료", cash)
                        hold_flag = False
                        wait_flag = True

                # 3 minutes
                if i == (5 * 60 * 3):
                    print(
                        f"[{datetime.datetime.now()}] 현재가 {price_curr}, 목표가 {price_buy}, ma {curr_ma15:.2f}/{curr_ma50:.2f}/{curr_ma120:.2f}, hold_flag {hold_flag}, wait_flag {wait_flag}"
                    )
                    i = 0
                i += 1
            except:
                print("error")

            time.sleep(0.2)
Exemplo n.º 29
0
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
import joblib
import datetime
import pyupbit
import csv
from pyupbit.request_api import _call_public_api
from joblib import load

# from pyupbit.errors import UpbitError, TooManyRequests, raise_error
#access =
#secret =     # 본인 값으로 변경
upbit = pyupbit.Upbit(access, secret)


#CHANGE: EVEN, RISE, FALL
def get_change(ticker="KRW-BTC"):
    """
    최종 체결 가격 조회 (현재가)
    :param ticker:
    :return:
    """
    try:
        url = "https://api.upbit.com/v1/ticker"
        contents = _call_public_api(url, markets=ticker)[0]
        if not contents:
            return None
Exemplo n.º 30
0
    def run(self):
        price_curr = None
        hold_flag = False
        wait_flag = False

        # 로그인
        upbit = pyupbit.Upbit(access, secret)
        cash = upbit.get_balance()
        print("autotrade start")
        print("보유현금", cash)
        post_message(myToken, "#test", "autotrade start")
        post_message(myToken, "#test", "Now Balance : " + str(cash))

        i = 0

        while True:
            try:
                if not self.q.empty():
                    if price_curr != None:
                        self.ma15.append(price_curr)
                        self.ma50.append(price_curr)
                        self.ma120.append(price_curr)

                    curr_ma15 = sum(self.ma15) / len(self.ma15)
                    curr_ma50 = sum(self.ma50) / len(self.ma50)
                    curr_ma120 = sum(self.ma120) / len(self.ma120)

                    price_open = self.q.get()
                    if hold_flag == False:
                        price_buy = price_open * 1.01
                        price_sell = price_open * 1.02
                    wait_flag = False

                price_curr = pyupbit.get_current_price(self.ticker)
                if price_curr == None:
                    continue

                if hold_flag == False and wait_flag == False and \
                    price_curr >= price_buy and curr_ma15 >= curr_ma50 and \
                    curr_ma15 <= curr_ma50 * 1.03 and curr_ma120 <= curr_ma50 :
                    # 0.05%
                    ret = upbit.buy_market_order(self.ticker, cash * 0.9995)
                    print("매수 주문", ret)
                    if ret == None or "error" in ret:
                        print("매수 주문 이상")
                        continue

                    while True:
                        order = upbit.get_order(ret['uuid'])
                        if order != None and len(order['trades']) > 0:
                            print("매수 주문 처리 완료", order)
                            post_message(myToken, "#test", "ADA 매수 완료")
                            break
                        else:
                            print("매수 주문 대기 중")
                            time.sleep(0.5)

                    while True:
                        volume = upbit.get_balance(self.ticker)
                        if volume != None:
                            break
                        time.sleep(0.5)

                    while True:
                        price_sell = pyupbit.get_tick_size(price_sell)
                        ret = upbit.sell_limit_order(self.ticker, price_sell,
                                                     volume)
                        if ret == None or 'error' in ret:
                            print("매도 주문 에러")
                            time.sleep(0.5)
                        else:
                            print("매도주문", ret)
                            hold_flag = True
                            break

                # print(price_curr, curr_ma15, curr_ma50, curr_ma120)

                if hold_flag == True:
                    uncomp = upbit.get_order(self.ticker)
                    if uncomp != None and len(uncomp) == 0:
                        cash = upbit.get_balance()
                        if cash == None:
                            continue

                        print("매도완료", cash)
                        post_message(myToken, "#test", "ADA 매도 완료")
                        hold_flag = False
                        wait_flag = True

                # 3 minutes
                if i == (5 * 60 * 3):
                    print(
                        f"[{datetime.datetime.now()}] 현재가 {price_curr}, 목표가 {price_buy}, ma {curr_ma15:.2f}/{curr_ma50:.2f}/{curr_ma120:.2f}, hold_flag {hold_flag}, wait_flag {wait_flag}"
                    )
                    i = 0
                i += 1
            except:
                print("error")

            time.sleep(0.2)