[암호화폐] 프로젝트#1 : 업비트 지정가 자동 매수/매도하기[5]

avatar

업비트 지정가 자동 매수/매도 프로그램을 개발 중입니다. 오늘은 다섯 번째 이야기입니다.

어제 설명한 자료 구조를 바탕으로 작업을 마무리해서 test 중입니다. 아직은 정상적으로 동작을 하지 않아서 좀 더 살펴보아야 할 것 같습니다.

오늘은 자동 매매를 위하여 추가로 필요한 모듈에 대하여 기술합니다.

첫 번째는 로그입니다. 프로그램이 잘 동작하다가 죽는 경우에 어디에서 문제가 생겼는지 혹은 어디까지 실행이 되었는지 확인이 필요한 경우가 많습니다. 이럴 때 많이 사용하는 것이 로그입니다. 로그는 너무 많이 출력해도 정보로써의 가치가 떨어지고, 너무 적으면 문제점을 파악하기가 어렵습니다. 따라서 적당한 양을 적당한 곳에서 출력하는 노하우가 필요합니다.

파이썬에서는 로그를 위한 패키지로 logging이 있습니다.

사용법은 간단합니다.
로깅용 레벨을 설정하고, handler를 logger에 등록하면 됩니다. 화면에 출력하는 로그 뿐 아니라 파일에 저장할 수도 있습니다. 한참 동작한 후 문제의 원인을 찾으려면 파일 로깅도 함께 하는 것이 좋습니다.

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler("mymodule.log")
stream_handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)

로그 설정에 관련된 위 절차를 쭉~~ 실행한 후 필요한 곳에서 logger를 부르기만 하면 됩니다.

logger.info("start")

파일에도 저장하도록 설정을 해 놓았기 때문에 "mymodule.log"에도 같은 내용이 저장됩니다.


두 번째는 텔레그램 봇입니다.

원격에서 계속 돌고 있을 자동 매매 프로그램의 상태도 확인하고, 필요한 경우에 중지 시켰다가 다시 가동시킬 수 있으면 관리가 편할 것입니다.

텔레그램 봇을 사용하는 방법은 @goodhello님이 소개해 주셨습니다[1]. 이렇게 간단하게 텔레그램 봇을 사용할 수 있다니 깜짝 놀랬습니다. 그래서 이번 프로젝트에 텔레그램 봇도 추가하기로 했습니다.

제가 하고 싶은 것은 사용자의 명령어에 반응하는 봇입니다. 그 방법은 [2] 글을 참고하였습니다.

텔레그램 봇은 callback 방식으로 동작합니다. 원하는 명령어에 해당하는 함수를 등록하면 됩니다.

def pause(bot, update) :
    print('pause', update.message.chat.username)
    bot.sendMessage(chat_id = update.message.chat_id, text='pause')

def resume(bot, update) :
    print('resume', update.message.chat.username)
    bot.sendMessage(chat_id = update.message.chat_id, text='resume')


updater = Updater(token=my_token)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))
dp.add_handler(MessageHandler(Filters.text, echo))
dp.add_handler(CommandHandler('pause', pause))
dp.add_handler(CommandHandler('resume', resume))
dp.add_handler(CallbackQueryHandler(callback_get))

logger.info("start")
updater.start_polling(timeout=3)
updater.idle()

그리고 하는 김에 토큰의 최근 시세와 매도 호가를 알려주는 봇을 만들어 보았습니다.

사용자가 /로 시작하는 명령어가 아닌 일반 텍스트를 입력하면 아래 함수로 call이 불려지도록 설정했습니다.

dp.add_handler(MessageHandler(Filters.text, echo))

echo라는 함수에서 사용자가 입력한 토큰의 최근 거래 가격과 매도 3 호가를 돌려줍니다.



def echo(bot, update) :
    print('echo', update.message.chat.username)
    response = update.message.text + " : "
    symbol = update.message.text.upper()
    found = 0

    response = last_price(response, symbol) 
    bot.sendMessage(chat_id = update.message.chat_id, text=response)

    rets = api.find("market", "sellBook", {'symbol':symbol})
    cnt = 1
    for ret in rets :
        ans = format(float(ret['price']), "2.5f") + "  " +  format(float(ret['quantity']), "0.4f")
        bot.sendMessage(chat_id = update.message.chat_id, text=ans)
        if (cnt >= 3) :
            break
        cnt += 1

이렇게 완성된 코드를 기반으로 텔레그램에서 동작하는 화면입니다.

이제 필요한 주변 기능은 거의 개발이 된 것 같습니다. 매매 알고리즘만 문제없이 쌩쌩 돌아가면 될 것 같습니다. 그런데 뭐가 문제인지 몇 번 매매하다가 딴 세상에서 놀고 있네요. 좀더 디버깅을 한 후 안정화가 되면 정리해서 글 올리겠습니다.


[1] https://www.steemcoinpan.com/sct/@goodhello/8-and-and
[2] https://blog.naver.com/stelch/221445190054



0
0
0.000
6 comments
avatar

To listen to the audio version of this article click on the play image.

Brought to you by @tts. If you find it useful please consider upvoting this reply.

0
0
0.000
avatar

jcar토큰 7월 구독 보팅입니다. 삼복 무더위, 건강하게 이겨나가세요. ^^

0
0
0.000
avatar

Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 700K SP virus707 account.

0
0
0.000
avatar

Congratulations @tradingideas! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published a post every day of the week

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Vote for @Steemitboard as a witness to get one more award and increased upvotes!
0
0
0.000
avatar

Hi @tradingideas!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 4.419 which ranks you at #2372 across all Steem accounts.
Your rank has improved 187 places in the last three days (old rank 2559).

In our last Algorithmic Curation Round, consisting of 366 contributions, your post is ranked at #233.

Evaluation of your UA score:
  • Some people are already following you, keep going!
  • The readers like your work!
  • Try to work on user engagement: the more people that interact with you via the comments, the higher your UA score!

Feel free to join our @steem-ua Discord server

0
0
0.000