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

in #sct5 years ago (edited)

Telegram 봇을 이용한 매매 기능을 완성하였습니다. 어제 매수는 되는데 매도가 안되는 문제는 변수 사용 방법에 오류가 있었음을 확인하고 수정하였습니다. 그 후 정상적으로 동작을 합니다.

그런데 실 매매를 해보니 호가 창을 보면서 매매를 하지 않다 보니 매도가 혹은 매수가를 실수하는 경우가 종종 있습니다. 따라서 호가 창 매수 호가 보다 더 싼 가격에 매도하거나 그 반대인 경우에는 주문을 내지 않는 방식이 필요할 것 같습니다.

일단 현재까지 완성한 매매에 대하여 설명합니다.
우선 동작 화면입니다.

주문하고자 하는 토큰의 호가 정보를 먼저 검색을 한 후, 사자 혹은 팔자 주문을 내면 됩니다. 주문이 잘 들어갔군요.


사용자가 입력한 명령어를 분석하여 'B' 혹은 'S'인지 확인한 후, 명령어에 이어져 있는 토큰명과 매매가격과 수량을 뽑은 후 order() 함수를 호출합니다.

def echo() :

        elif (symbol[0] == 'B' or symbol[0] == 'S') : # buy token price qty
            args = received.split(' ')
            token = args[1]
            price = args[2]
            qty = args[3]
            ans = "buying " 
            if ( symbol[0] == 'S' ) :
                ans = "selling "
            ret = order(symbol[0], token,price, qty)
            if (ret) :
                ans +=  token + " p:" + str(price) + " qty:" + str(qty) + " " + str(ret)
            else :
                ans +=  token + " " + str(price) + " " + str(qty) + " " + "fail"
            bot.sendMessage(chat_id = update.message.chat_id, text=ans)
            return

order() 함수에서는 스팀API와 스팀엔진API를 이용하여 주문을 냅니다. 정상적으로 주문이 들어갔으면 block#가 돌아옵니다. 정상인 경우에는 주문 내역을 답신하고, 주문 오류인 경우에는 오류라고 답신합니다.

def order(type, token,price, qty) :
    global stm
    global m

    if (stm == 0) :
        nodes = NodeList()
        nodes.update_nodes()
        stm = Steem(node=nodes.get_nodes(), keys=mykeys)
        m=Market(steem_instance=stm)
    ref_block = 0
    try : 
        if ( type == 'S') :
            ret = m.sell(my_account, qty, token, price)
            ref_block = ret['ref_block_num']
            done = json.loads(ret['operations'][0][1]['json'])
            print(done['contractPayload']['symbol'], done['contractAction'], done['contractPayload']['price'], done['contractPayload']['quantity'])
        elif ( type == 'B') :
            ret = m.buy(my_account, qty, token, price)
            ref_block = ret['ref_block_num']
            done = json.loads(ret['operations'][0][1]['json'])
            print(done['contractPayload']['symbol'],done['contractAction'], done['contractPayload']['price'], done['contractPayload']['quantity'])
        else:
            print('unknown type', type)
    except Exception as ex :
        print('error trading', ex)
    
    return ref_block

함수 안에서 global 변수를 사용하기 위해서는 global이라는 key word를 이용하여 선언을 해야 합니다. 어제 문제가 된 부분은 m을 global 선언을 하지 않았더군요. 간단한 문제인데도 확인하는데 시간이 많이 걸렸습니다. 이상하게 한 번은 되고 두 번째부터 동작을 안 하더군요.


텔레그램 봇을 이용한 시세 확인, 잔고 확인, 주문까지 마무리하였습니다. 추가로 할 기능은 주문 취소 및 주문 오류를 방지하기 위한 부분입니다. 그리고 사용하면서 추가로 필요한 기능들을 더 개발할 예정입니다.

텔레그램 봇을 이용하여 할 수 있는 일들이 많이 있을 것 같습니다. 필요한 기능들을 좀 더 추가해보겠습니다.

Sort:  

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

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.

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.414 which ranks you at #2398 across all Steem accounts.
Your rank has improved 26 places in the last three days (old rank 2424).

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

Evaluation of your UA score:
  • Some people are already following you, keep going!
  • The readers like your work!
  • Good user engagement!

Feel free to join our @steem-ua Discord server

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.033
BTC 62559.43
ETH 3092.10
USDT 1.00
SBD 3.86