2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MACDによるbitflyer取引シミュレータ

Last updated at Posted at 2021-02-08

MACDによる取引シュミレータ

参考ページ

前準備

console
pip install pybitflyer
pip install numpy

ソースコードに関する注意事項

次に示すソースコードは動作が不安定になる場合があります。
例えば、マシンスペックが不足し処理に時間が掛かる場合などです。
「raspberry pi」をはじめとするシングルボードコンピュータにおいて、シングルコアようなスペックでは、処理に時間がかかり動作に不具合を起こす可能性があります。
動作を確認した上でバグを取り払い、シミュレートをすると楽しい人生が送れるかもしれません。

ソースコード

test_macd.py
# -*- coding: utf-8 -*-

##3-clause license ("BSD License 2.0", "Revised BSD License", "New BSD License", or "Modified BSD License")
##修正BSDライセンス・三条項BSDライセンス

##Copyright (c) 2021, a_d_j_u_s_t
##All rights reserved.

##Redistribution and use in source and binary forms, with or without
##modification, are permitted provided that the following conditions are met:
##* Redistributions of source code must retain the above copyright notice, 
##  this list of conditions and the following disclaimer.
##* Redistributions in binary form must reproduce the above copyright notice, 
##  this list of conditions and the following disclaimer in the documentation 
##  and/or other materials provided with the distribution.
##* Neither the name of the <organization> nor the names of its contributors 
##  may be used to endorse or promote products derived from this software 
##  without specific prior written permission.

##THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
##ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
##WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
##DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
##DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
##(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
##LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
##ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
##(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
##SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import numpy as np # プロットするデータ配列を作成するため
import pybitflyer
# 時間の管理に使う
import time
from datetime import datetime
import gc

TRADE_FLAG=1 #ask=1,bid=0

if __name__=='__main__':
    api = pybitflyer.API()
    ticker = api.ticker(product_code="FX_BTC_JPY")
    print(ticker)

    # 最終取引価格を格納する配列
    raws = []
    time_line=[]
    # params
    count = 0
    macd_count = 0
    oneDayCount=0

    data_flg = [False,False]
    data_00_se = 0.0
    data_20_se = 0.0
    data_40_se = 0.0
    MACDList = np.zeros(9)
    bidPrice = 0.0
    askPrice = 0.0
    macd=0.0
    MACD9Average=0.0
    firstTime12 = 0
    ema12New=0.0
    ema12Old=0.0
    firstTime26 = 0
    ema26New=0.0
    ema26Old=0.0

    # plotting
    while True : # フレーム回数分グラフを更新
        try:
            # 毎分00秒に稼働
            if datetime.now().strftime('%S') [0:2]== '20' and data_flg[0] == False and data_flg[1] == False:
                # プロット用データの更新
                tick = api.ticker(product_code = "FX_BTC_JPY")
                if tick['state'] != 'RUNNING':
                    print(tick['timestamp'] +" "+ tick['state'])
                    continue
                data_20_se = tick['ltp']
                data_flg[0] = True
                #print(str(data_flg) + " " + str(data_20_se))
                time.sleep(2)

            # 毎分00秒に稼働
            if datetime.now().strftime('%S') [0:2]== '40' and data_flg[0] == True and data_flg[1] == False:
                # プロット用データの更新
                tick = api.ticker(product_code = "FX_BTC_JPY")
                if tick['state'] != 'RUNNING':
                    print(tick['timestamp'] +" "+ tick['state'])
                    continue
                data_40_se = tick['ltp']
                data_flg[1] = True
                #print(str(data_flg) + " " + str(data_40_se))
                time.sleep(2)

            # 毎分00秒に稼働
            if datetime.now().strftime('%S') [0:2]== '00' and data_flg[0] == True and data_flg[1] == True:
                # プロット用データの更新
                tick = api.ticker(product_code = "FX_BTC_JPY")
                if tick['state'] != 'RUNNING':
                    print(tick['timestamp'] +" "+ tick['state'])
                    continue
                data_00_se = tick['ltp']
                raw_data = (data_00_se + data_20_se + data_40_se) / 3
                raws = np.append(raws,raw_data)
                time_line = np.append(time_line, tick['timestamp'])
                print(tick['timestamp'] + " " + str(tick['ltp']) + " " + str(raw_data))

                # delete zero of raws list.
                if (len(raws)-1) > 1440 and (len(time_line)-1) > 1440:
                    raws_list = raws.tolist()
                    times_list = time_line.tolist()
                    list_1=[]
                    list_2=[]
                    for x in range(1,len(raws_list),1):
                        list_1=np.append(list_1,raws_list[x])
                        list_2=np.append(list_2,times_list[x])
                    raws = []
                    time_line = []
                    raws=np.copy(list_1)
                    time_line=np.copy(list_2)

                if count > 11:
                    y12 = np.zeros(12)
                    for x in range(12,0,-1):
                        y12[12-x]=raws[(len(raws)-x)]

                    if firstTime12 == 0:
                        y12Average=0.
                        for x in range(0,12,1):
                            y12Average+=y12[x]
                        y12Average/=12
                        ema12New=y12Average
                        ema12Old=y12Average
                        firstTime12=1
                    else :
                        ema12New=ema12Old+((2/(12+1))*(y12[len(y12)-1]-ema12Old))
                        ema12Old=ema12New
                        print("ema12="+str(ema12New))


                if count > 25:
                    y26 = np.zeros(26)
                    for x in range(26,0,-1):
                        y26[26-x]=raws[(len(raws)-x)]

                    if firstTime26 == 0:
                        y26Average=0.
                        for x in range(0,26,1):
                            y26Average+=y26[x]
                        y26Average/=26
                        ema26New=y26Average
                        ema26Old=y26Average
                        firstTime26=1
                    else :
                        ema26New=ema26Old+((2/(26+1))*(y26[len(y26)-1]-ema26Old))
                        ema26Old=ema26New
                        print("ema26="+str(ema26New))
                        macd=(ema12New - ema26New)
                        MACDList[macd_count]=macd
                        macd_count += 1
                        if macd_count > 8:
                            macd_count = 0

                if count > 35:
                    count=37

                    MACD9Average=0.0
                    for x in range(0,9,1):
                        MACD9Average += MACDList[x]
                    MACD9Average/=9

                    if macd >= MACD9Average and TRADE_FLAG==1:
                        tick = api.ticker(product_code = "FX_BTC_JPY")
                        bidPrice = tick['ltp']
                        askPrice=0.0
                        TRADE_FLAG=0 #bid=0
                        print("bitcoin=" + str(bidPrice) + " buy " + str(tick['timestamp']))

                    if macd <= MACD9Average and TRADE_FLAG==0:
                        tick = api.ticker(product_code = "FX_BTC_JPY")
                        askPrice = tick['ltp']
                        TRADE_FLAG=1 #ask=1
                        print("bitcoin=" + str(askPrice) + " sel " + str(tick['timestamp']))

                    print(str(macd) + " " + str(MACD9Average))

                data_flg[0] = False
                data_flg[1] = False
                time.sleep(1)
                count += 1
                gc.collect()
        except :#Exception as ex:
            print("errors")# + ex)
            data_flg[0] = False
            data_flg[1] = False
            gc.collect()
            api = pybitflyer.API()
            pass


2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?