[암호화폐] 프로젝트#2 : Telegram Bot을 이용한 매매(1)

in #sct5 years ago

프로젝트 #2를 시작합니다. telegram bot을 이용하여 원하는 토큰을 매매하는 것이 목표입니다.

프로젝트 #1을 하면서 telegram bot에 대한 간단한 예제를 설명했습니다[1]. 시세를 알아보는 간단한 예제였는데, 평상시에 잘 사용하고 있었습니다. 여기에 매매까지 지원이 된다면 좋겠다는 생각이 들어서 시작하게 되었습니다.

일단은 시세를 좀 더 자세하게 보여줄 수 있도록 수정하였습니다.

추가한 내용은 아래와 같습니다.

  • 관심 있는 토큰의 현재가를 한 번에 보여주는 기능
  • 특정 토큰의 매수/매도 호가를 보여주는 기능

우선 여러 토큰의 현재가를 보여주기 위하여 명령어를 추가하였습니다. 처음에는 prices라는 명령어를 사용하였는데, 입력할 글자가 많아서 그냥 p로 줄였습니다.

p를 입력하면 현재 4개의 토큰에 대한 시세를 한꺼번에 보여줍니다.
코드는 간단합니다. 관심 있는 토큰 심블을 list에 넣은 후 해당하는 토큰에 대한 현재가 정보를 전달해줍니다.

INT_SYMBOLS = ['SCT', 'SCTM', 'DEC', 'SPT']
def last_prices(bot, chat_id) :
    data = "```\n"
    found = 0
    rets = api.find("market","metrics")  # ok

    for ret in rets :
        if ( ret['symbol'] in INT_SYMBOLS ) :
            data += ((format(ret['symbol'],"7s") + " : " + format(ret['lastPrice'],"8s") + '\n'))
            found = 1
    data += "```"
    if (found == 1) :
        bot.sendMessage(chat_id = chat_id, text=data, parse_mode="Markdown")
    else :
        data = "no such symbols"
        bot.sendMessage(chat_id = chat_id, text=data)

두 번째로는 특정 토큰의 호가 정보입니다. steem-engine의 order book에는 같은 호가이어도 매도/매수 주체가 틀리면 각각 정보가 들어옵니다. 그래서 호가가 같은 경우에는 합산해서 보여주도록 변경하였습니다.

#[price, qty]
def append_order(obooks, price, qty) :
    for ord in obooks :
        if ord[0] == price :
            ord[1] += qty
            return obooks
    obooks.append([price, qty])
    return obooks

def echo(bot, update) :
    sell_obook = []
    buy_obook = []
    if (symbol != 'P') :
        rets = api.find("market", "sellBook", {'symbol':symbol})
        for ret in rets :
            # 같은 order가 있으면 합산
            sell_obook = append_order(sell_obook, float(ret['price']), float(ret['quantity']))

        rets = api.find("market", "buyBook", {'symbol':symbol})
        for ret in rets :
            buy_obook = append_order(buy_obook, float(ret['price']), float(ret['quantity']))

        sell_obook.sort(key = operator.itemgetter(0, 1)) # 오름차순 가격순
        buy_obook.sort(key = operator.itemgetter(0, 1), reverse=True) # 내일차순 가격순

        ans  = "```"   # markdown
        for i in range(0,4) : 
            ss = format(sell_obook[i][1], "6,.2f") + " " + format(sell_obook[i][0], "2.5f") +  ": " + format(buy_obook[i][0], "0.5f") + " " + format(buy_obook[i][1], "6.2f")
            ans += (ss + '\n')
        ans += "```"  # markdown
        bot.sendMessage(chat_id = update.message.chat_id, text=ans, parse_mode="Markdown")

이렇게 출력을 해보니 호가가 삐뚤 삐뚤 출력이 됩니다. 이런저런 방법을 사용해 보아도 해결되지 않아서 구글 검색을 해 봅니다. 저와 똑같은 문제를 풀고자 하는 질문을 발견합니다[2]. 이럴 때 정말 반갑죠.

그냥 참고 넘어갈 수도 있지만 이렇게 align이 맞지 않으면 왠지 불안합니다. 그래서 [2] 글에 나오는 방식대로 수정을 합니다. 해결 방법은 출력 시에 Markdown 방식을 적용하는 것입니다. 이를 위하여 출력할 글 처음과 마지막에 "```"를 추가하면 됩니다.

아래 그림은 현재 telegram bot에서 출력하는 화면 모습니다.

화면 넓이의 제한 때문에 sctm의 경우에 화면이 조금 이상하지만 이건 그냥 참는 것으로 하겠습니다. 깔끔하게 적용할 수도 있겠지만 이렇게 하자면 한이 없어서 적당한 선에서 타협을 합니다.


[1] https://www.steemcoinpan.com/sct/@tradingideas/1-5
[2] https://stackoverflow.com/questions/56030395/how-to-format-bot-send-message-output-so-it-aligns-like-a-table

Sort:  

이야 대단하시네요. 정말 다양한 걸 만들고 계시네요. 텔레그램 정말 봇 연동하기 좋죠

텔레그램봇이 사용하기 정말 좋네요. 카카오톡도 이렇게 개방형으로 접근했으면 좋겠습니다.
스팀엔진이 워낙 기본 기능만 제공하다보니, 불편한 점이 한 두가지가 아니네요. 그러다보니 자꾸 개발을 하게 되네요.

곰돌이가 @tradingideas님의 소중한 댓글에 $0.007을 보팅해서 $0.016을 살려드리고 가요. 곰돌이가 지금까지 총 6083번 $66.736을 보팅해서 $77.856을 구했습니다. @gomdory 곰도뤼~

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.

jcar토큰,
8월 구독 보팅입니다.
행복한 8월 되세요. ^^

정말 대단한 실력입니다/

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

You received more than 50000 upvotes. Your next target is to reach 55000 upvotes.

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

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

트아님도 정말 꾸준히 개발 잘하시네요!! 멋지십니다!! ㅋ

완팀에 비하면 아마추어 수준입니다 ^^

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.

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.424 which ranks you at #2364 across all Steem accounts.
Your rank has dropped 51 places in the last three days (old rank 2313).

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

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

Coin Marketplace

STEEM 0.14
TRX 0.12
JST 0.026
BTC 54657.34
ETH 2331.85
USDT 1.00
SBD 2.14