こんにちは!スナフキンです.先日チャネルブレイクアウト戦略を使ったbotを作成したのですが,そのコードを公開します.コードを全て解説する時間はさすがにないので,概要を述べたあとに重要な変数と重要な関数のみを解説します.本botはヒストリカルデータを用いてバックテストを行う機能も搭載しており,botの勉強を始める方にとってはそのあたりの実装についての勉強教材になるかもしれません.実運用・バックテストともに可能です.また,自分の設定したローソク足の時間軸でのトレードが可能です.
ちなみに2018/2/21-2018/3/10の5分足でのバックテスト結果は以下です.
ぼく個人の感情から,なるべく早く公開したいので,さしあたってチャネルブレイクアウト戦略そのものの説明などはGoogle先生にお任せします.(気が向いたら更新して細かい解説もします.)
2018/9/9追記
こちらの方がnoteで詳しい解説をしてくださっているようです.34記事の超大作シリーズとなっているので,これを読むとコードの理解が進むと思います.
https://note.mu/wanna_be_free/n/ndb77d394a54e
概要と変数の説明
本botはチャネルブレイクアウト戦略を少し改良したものになります.具体的には以下のような点を改良(拡張)しています.
- チャネルブレイクアウト戦略は期間安値・期間高値の更新でエントリーおよびクローズ,ドテン売買するが,何期間高値・安値でエントリーし何期間高値・安値でクローズするかを設定可能.→ex. エントリー5期間でクローズ3期間ならドテン売買は行わなくなる.(もちろん,エントリーとクローズの期間を同じにすれば通常のチャネルブレイクアウト戦略のようにドテン売買する)
- レンジ相場でのエントリーを減らすために,レンジ判定ロジックを導入している.(レンジ判定は,一定期間の値幅または価格の標準偏差の変動で行います.)
- 大きな値幅をとったあとのnトレードではロットを1/10に減らす処理を入れている.(大きいトレンドのあとの大きなリバや戻りで損をしやすいため)
- 成行注文のスリッページによる執行コストを考慮したバックテストが可能(ただし定額固定)
さて,重要な変数の解説ですが今書いていて眠くなってきたのでまた明日以降に気が向いたときに書きます.コードは載せておくので販売・商用目的以外はご自由にご利用ください.
また,質問は自分であらゆる手段(本記事のコメント欄,Google検索,TwitterのBot使用者の過去Tweet検索,くーるぜろさんのbotDiscord(くーるぜろさんにTwitterで申請すれば入れます.))を使って調べた後に,Discordのマナブくんチャンネルにお願いします.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 |
#_*_ coding: utf-8 _*_ import pybitflyer import json import requests import csv import math import pandas as pd import time import requests import datetime from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_tornado import PubNubTornado from pubnub.pnconfiguration import PNReconnectionPolicy from tornado import gen import threading from collections import deque class ChannelBreakOut: def __init__(self): #pubnubから取得した約定履歴を保存するリスト(基本的に不要.) self._executions = deque(maxlen=300) self._lot = 0.01 self._product_code = "FX_BTC_JPY" #各パラメタ. self._entryTerm = 10 self._closeTerm = 5 self._rangeTerm = 15 self._rangeTh = 5000 self._waitTerm = 5 self._waitTh = 20000 self._candleTerm = "1T" #現在のポジション.1ならロング.-1ならショート.0ならポジションなし. self._pos = 0 #注文執行コスト.遅延などでこの値幅を最初から取られていると仮定する self._cost = 3000 self.order = Order() self.api = pybitflyer.API("your key", "your secret") #ラインに稼働状況を通知 self.line_notify_token = 'your token' self.line_notify_api = 'https://notify-api.line.me/api/notify' @property def cost(self): return self._cost @cost.setter def cost(self, value): self._cost = value @property def candleTerm(self): return self._candleTerm @candleTerm.setter def candleTerm(self, val): """ valは"5T","1H"などのString """ self._candleTerm = val @property def waitTh(self): return self._waitTh @waitTh.setter def waitTh(self, val): self._waitTh = val @property def waitTerm(self): return self._waitTerm @waitTerm.setter def waitTerm(self, val): self._waitTerm = val @property def rangeTh(self): return self._rangeTh @rangeTh.setter def rangeTh(self,val): self._rangeTh = val @property def rangeTerm(self): return self._rangeTerm @rangeTerm.setter def rangeTerm(self,val): self._rangeTerm = val @property def executions(self): return self._executions @executions.setter def executions(self, val): self._executions = val @property def pos(self): return self._pos @pos.setter def pos(self, val): self._pos = int(val) @property def lot(self): return self._lot @lot.setter def lot(self, val): self._lot = round(val,3) @property def product_code(self): return self._product_code @product_code.setter def product_code(self, val): self._product_code = val @property def entryTerm(self): return self._entryTerm @entryTerm.setter def entryTerm(self, val): self._entryTerm = int(val) @property def closeTerm(self): return self._closeTerm @closeTerm.setter def closeTerm(self, val): self._closeTerm = int(val) def calculateLot(self, margin): """ 証拠金からロットを計算する関数. """ lot = math.floor(margin*10**(-4))*10**(-2) return round(lot,2) def calculateLines(self, df_candleStick, term): """ 期間高値・安値を計算する. candleStickはcryptowatchのローソク足.termは安値,高値を計算する期間.(5ならローソク足5本文の安値,高値.) """ lowLine = [] highLine = [] for i in range(len(df_candleStick.index)): if i < term: lowLine.append(df_candleStick["high"][i]) highLine.append(df_candleStick["low"][i]) else: low = min([price for price in df_candleStick["low"][i-term:i]]) high = max([price for price in df_candleStick["high"][i-term:i]]) lowLine.append(low) highLine.append(high) return (lowLine, highLine) def calculatePriceRange(self, df_candleStick, term): """ termの期間の値幅を計算. """ low = [min([df_candleStick["close"][i-term+1:i].min(),df_candleStick["open"][i-term+1:i].min()]) for i in range(len(df_candleStick.index))] high = [max([df_candleStick["close"][i-term+1:i].max(), df_candleStick["open"][i-term+1:i].max()]) for i in range(len(df_candleStick.index))] low = pd.Series(low) high = pd.Series(high) priceRange = [high.iloc[i]-low.iloc[i] for i in range(len(df_candleStick.index))] return priceRange def isRange(self,df_candleStick ,term, th): """ レンジ相場かどうかをTrue,Falseの配列で返す.termは期間高値・安値の計算期間.thはレンジ判定閾値. """ #値幅での判定. if th != None: priceRange = self.calculatePriceRange(df_candleStick, term) isRange = [th > i for i in priceRange] #終値の標準偏差の差分が正か負かでの判定. elif th == None and term != None: df_candleStick["std"] = [df_candleStick["close"][i-term+1:i].std() for i in range(len(df_candleStick.index))] df_candleStick["std_slope"] = [df_candleStick["std"][i]-df_candleStick["std"][i-1] for i in range(len(df_candleStick.index))] isRange = [i > 0 for i in df_candleStick["std_slope"]] else: isRange = [False for i in df_candleStick.index] return isRange def judge(self, df_candleStick, entryHighLine, entryLowLine, closeHighLine, closeLowLine, entryTerm): """ 売り買い判断.ローソク足の高値が期間高値を上抜けたら買いエントリー.(2)ローソク足の安値が期間安値を下抜けたら売りエントリー.judgementリストは[買いエントリー,売りエントリー,買いクローズ(売り),売りクローズ(買い)]のリストになっている.(二次元リスト)リスト内リストはの要素は,0(シグナルなし),価格(シグナル点灯)を取る. """ judgement = [[0,0,0,0] for i in range(len(df_candleStick.index))] for i in range(len(df_candleStick.index)): #上抜けでエントリー if df_candleStick["high"][i] > entryHighLine[i] and i >= entryTerm: judgement[i][0] = entryHighLine[i] #下抜けでエントリー if df_candleStick["low"][i] < entryLowLine[i] and i >= entryTerm: judgement[i][1] = entryLowLine[i] #下抜けでクローズ if df_candleStick["low"][i] < closeLowLine[i] and i >= entryTerm: judgement[i][2] = closeLowLine[i] #上抜けでクローズ if df_candleStick["high"][i] > closeHighLine[i] and i >= entryTerm: judgement[i][3] = closeHighLine[i] # else: pass return judgement def judgeForLoop(self, high, low, entryHighLine, entryLowLine, closeHighLine, closeLowLine): """ 売り買い判断.入力した価格が期間高値より高ければ買いエントリー,期間安値を下抜けたら売りエントリー.judgementリストは[買いエントリー,売りエントリー,買いクローズ(売り),売りクローズ(買い)]のリストになっている.(値は0or1) ローソク足は1分ごとに取得するのでインデックスが-1のもの(現在より1本前)をつかう. """ judgement = [0,0,0,0] #上抜けでエントリー if high > entryHighLine[-1]: judgement[0] = 1 #下抜けでエントリー if low < entryLowLine[-1]: judgement[1] = 1 #下抜けでクローズ if low < closeLowLine[-1]: judgement[2] = 1 #上抜けでクローズ if high > closeHighLine[-1]: judgement[3] = 1 return judgement #エントリーラインおよびクローズラインで約定すると仮定する. def backtest(self, judgement, df_candleStick, lot, rangeTh, rangeTerm, originalWaitTerm=10, waitTh=10000, cost = 0): #エントリーポイント,クローズポイントを入れるリスト buyEntrySignals = [] sellEntrySignals = [] buyCloseSignals = [] sellCloseSignals = [] nOfTrade = 0 pos = 0 pl = [] pl.append(0) #トレードごとの損益 plPerTrade = [] #取引時の価格を入れる配列.この価格でバックテストのplを計算する.(ので,どの価格で約定するかはテストのパフォーマンスに大きく影響を与える.) buy_entry = [] buy_close = [] sell_entry = [] sell_close = [] #各ローソク足について,レンジ相場かどうかの判定が入っている配列 isRange = self.isRange(df_candleStick, rangeTerm, rangeTh) #基本ロット.勝ちトレードの直後はロットを落とす. originalLot = lot #勝ちトレード後,何回のトレードでロットを落とすか. waitTerm = 0 for i in range(len(judgement)): if i > 0: lastPL = pl[-1] pl.append(lastPL) #エントリーロジック if pos == 0 and not isRange[i]: #ロングエントリー if judgement[i][0] != 0: pos += 1 buy_entry.append(judgement[i][0]) buyEntrySignals.append(df_candleStick.index[i]) #ショートエントリー elif judgement[i][1] != 0: pos -= 1 sell_entry.append(judgement[i][1]) sellEntrySignals.append(df_candleStick.index[i]) #ロングクローズロジック elif pos == 1: #ロングクローズ if judgement[i][2] != 0: nOfTrade += 1 pos -= 1 buy_close.append(judgement[i][2]) #値幅 plRange = buy_close[-1] - buy_entry[-1] pl[-1] = pl[-2] + (plRange-self.cost) * lot buyCloseSignals.append(df_candleStick.index[i]) plPerTrade.append((plRange-self.cost)*lot) #waitTh円以上の値幅を取った場合,次の10トレードはロットを1/10に落とす. if plRange > waitTh: waitTerm = originalWaitTerm lot = originalLot/10 elif waitTerm > 0: waitTerm -= 1 lot = originalLot/10 if waitTerm == 0: lot = originalLot #ショートクローズロジック elif pos == -1: #ショートクローズ if judgement[i][3] != 0: nOfTrade += 1 pos += 1 sell_close.append(judgement[i][3]) plRange = sell_entry[-1] - sell_close[-1] pl[-1] = pl[-2] + (plRange-self.cost) * lot sellCloseSignals.append(df_candleStick.index[i]) plPerTrade.append((plRange-self.cost)*lot) #waitTh円以上の値幅を取った場合,次の10トレードはロットを1/10に落とす. if plRange > waitTh: waitTerm = originalWaitTerm lot = originalLot/10 elif waitTerm > 0: waitTerm -= 1 lot = originalLot/10 if waitTerm == 0: lot = originalLot #さらに,クローズしたと同時にエントリーシグナルが出ていた場合のロジック. if pos == 0 and not isRange[i]: #ロングエントリー if judgement[i][0] != 0: pos += 1 buy_entry.append(judgement[i][0]) buyEntrySignals.append(df_candleStick.index[i]) #ショートエントリー elif judgement[i][1] != 0: pos -= 1 sell_entry.append(judgement[i][1]) sellEntrySignals.append(df_candleStick.index[i]) #最後にポジションを持っていたら,期間最後のローソク足の終値で反対売買. if pos == 1: buy_close.append(df_candleStick["close"][-1]) plRange = buy_close[-1] - buy_entry[-1] pl[-1] = pl[-2] + plRange * lot pos -= 1 buyCloseSignals.append(df_candleStick.index[-1]) nOfTrade += 1 plPerTrade.append(plRange*lot) elif pos ==-1: sell_close.append(df_candleStick["close"][-1]) plRange = sell_entry[-1] - sell_close[-1] pl[-1] = pl[-2] + plRange * lot pos +=1 sellCloseSignals.append(df_candleStick.index[-1]) nOfTrade += 1 plPerTrade.append(plRange*lot) return (pl, buyEntrySignals, sellEntrySignals, buyCloseSignals, sellCloseSignals, nOfTrade, plPerTrade) def describeResult(self, entryTerm, closeTerm, fileName=None, candleTerm=None, rangeTh=5000, rangeTerm=15, originalWaitTerm=10, waitTh=10000, showFigure=True, cost=0): """ signalsは買い,売り,中立が入った配列 """ import matplotlib.pyplot as plt if fileName == None: s_hour = 0 s_min = 0 e_hour = 23 e_min = 59 number = int((e_hour - s_hour)*60 + e_min - s_min) start_timestamp = datetime.datetime(2018, 3, 24, s_hour, s_min, 0, 0).timestamp() end_timestamp = datetime.datetime(2018, 3, 24, e_hour, e_min, 0, 0).timestamp() candleStick = self.getSpecifiedCandlestick(number, "60", start_timestamp, end_timestamp) else: candleStick = self.readDataFromFile(fileName) if candleTerm != None: df_candleStick = self.processCandleStick(candleStick, candleTerm) else: df_candleStick = self.fromListToDF(candleStick) entryLowLine, entryHighLine = self.calculateLines(df_candleStick, entryTerm) closeLowLine, closeHighLine = self.calculateLines(df_candleStick, closeTerm) judgement = self.judge(df_candleStick, entryHighLine, entryLowLine, closeHighLine, closeLowLine, entryTerm) pl, buyEntrySignals, sellEntrySignals, buyCloseSignals, sellCloseSignals, nOfTrade, plPerTrade = self.backtest(judgement, df_candleStick, 1, rangeTh, rangeTerm, originalWaitTerm=originalWaitTerm, waitTh=waitTh, cost=cost) plt.figure() plt.subplot(211) plt.plot(df_candleStick.index, df_candleStick["high"]) plt.plot(df_candleStick.index, df_candleStick["low"]) plt.ylabel("Price(JPY)") ymin = min(df_candleStick["low"]) - 200 ymax = max(df_candleStick["high"]) + 200 plt.vlines(buyEntrySignals, ymin , ymax, "blue", linestyles='dashed', linewidth=1) plt.vlines(sellEntrySignals, ymin , ymax, "red", linestyles='dashed', linewidth=1) plt.vlines(buyCloseSignals, ymin , ymax, "black", linestyles='dashed', linewidth=1) plt.vlines(sellCloseSignals, ymin , ymax, "green", linestyles='dashed', linewidth=1) plt.subplot(212) plt.plot(df_candleStick.index, pl) plt.hlines(y=0, xmin=df_candleStick.index[0], xmax=df_candleStick.index[-1], colors='k', linestyles='dashed') plt.ylabel("PL(JPY)") #各統計量の計算および表示. winTrade = sum([1 for i in plPerTrade if i > 0]) loseTrade = sum([1 for i in plPerTrade if i < 0]) winPer = round(winTrade/(winTrade+loseTrade) * 100,2) winTotal = sum([i for i in plPerTrade if i > 0]) loseTotal = sum([i for i in plPerTrade if i < 0]) profitFactor = round(winTotal/-loseTotal, 3) maxProfit = max(plPerTrade) maxLoss = min(plPerTrade) print("Total pl: {}JPY".format(int(pl[-1]))) print("The number of Trades: {}".format(nOfTrade)) print("The Winning percentage: {}%".format(winPer)) print("The profitFactor: {}".format(profitFactor)) print("The maximum Profit and Loss: {}JPY, {}JPY".format(maxProfit, maxLoss)) if showFigure: plt.show() else: plt.clf() return pl[-1], profitFactor def getCandlestick(self, number, period): """ number:ローソク足の数.period:ローソク足の期間(文字列で秒数を指定,Ex:1分足なら"60").cryptowatchはときどきおかしなデータ(price=0)が含まれるのでそれを除く. """ #ローソク足の時間を指定 periods = [period] #クエリパラメータを指定 query = {"periods":','.join(periods)} #ローソク足取得 res = \ json.loads(requests.get("https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc", params=query).text)[ "result"] # ローソク足のデータを入れる配列. data = [] for i in periods: row = res[i] length = len(row) for column in row[:length - (number + 1):-1]: # dataへローソク足データを追加. if column[4] != 0: column = column[0:6] data.append(column) return data[::-1] def fromListToDF(self, candleStick): """ Listのローソク足をpandasデータフレームへ. """ date = [price[0] for price in candleStick] priceOpen = [int(price[1]) for price in candleStick] priceHigh = [int(price[2]) for price in candleStick] priceLow = [int(price[3]) for price in candleStick] priceClose = [int(price[4]) for price in candleStick] date_datetime = map(datetime.datetime.fromtimestamp, date) dti = pd.DatetimeIndex(date_datetime) df_candleStick = pd.DataFrame({"open" : priceOpen, "high" : priceHigh, "low": priceLow, "close" : priceClose}, index=dti) return df_candleStick def processCandleStick(self, candleStick, timeScale): """ 1分足データから各時間軸のデータを作成.timeScaleには5T(5分),H(1時間)などの文字列を入れる """ df_candleStick = self.fromListToDF(candleStick) processed_candleStick = df_candleStick.resample(timeScale).agg({'open': 'first','high':'max','low': 'min','close': 'last'}) processed_candleStick = processed_candleStick.dropna() return processed_candleStick #csvファイル(ヘッダなし)からohlcデータを作成. def readDataFromFile(self,filename): for i in range(1, 10, 1): with open(filename, 'r', encoding="utf-8") as f: reader = csv.reader(f) header = next(reader) for row in reader: candleStick = [row for row in reader if row[4] != "0"] dtDate = [datetime.datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') for data in candleStick] dtTimeStamp = [dt.timestamp() for dt in dtDate] for i in range(len(candleStick)): candleStick[i][0] = dtTimeStamp[i] candleStick = [[float(i) for i in data] for data in candleStick] return candleStick def lineNotify(self, message, fileName=None): payload = {'message': message} headers = {'Authorization': 'Bearer ' + self.line_notify_token} if fileName == None: try: requests.post(self.line_notify_api, data=payload, headers=headers) except: pass else: try: files = {"imageFile": open(fileName, "rb")} requests.post(self.line_notify_api, data=payload, headers=headers, files = files) except: pass def describePLForNotification(self, pl, df_candleStick): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt close = df_candleStick["close"] index = range(len(pl)) # figure fig = plt.figure(figsize=(20,12)) #for price ax = fig.add_subplot(2, 1, 1) ax.plot(df_candleStick.index, close) ax.set_xlabel('Time') # y axis ax.set_ylabel('The price[JPY]') #for PLcurve ax = fig.add_subplot(2, 1, 2) # plot ax.plot(index, pl, color='b', label='The PL curve') ax.plot(index, [0]*len(pl), color='b',) # x axis ax.set_xlabel('The number of Trade') # y axis ax.set_ylabel('The estimated Profit/Loss(JPY)') # legend and title ax.legend(loc='best') ax.set_title('The PL curve(Time span:{})'.format(self.candleTerm)) # save as png today = datetime.datetime.now().strftime('%Y%m%d') number = "_" + str(len(pl)) fileName = today + number + ".png" plt.savefig(fileName) plt.close() return fileName def loop(self,entryTerm, closeTerm, rangeTh, rangeTerm,originalWaitTerm, waitTh,candleTerm=None): """ 注文の実行ループを回す関数 """ self.executionsProcess() #pubnubが回り始めるまで待つ. time.sleep(20) pos = 0 pl = [] pl.append(0) lastPositionPrice = 0 lot = self.lot originalLot = self.lot waitTerm = 0 try: candleStick = self.getCandlestick(50, "60") except: print("Unknown error happend when you requested candleStick") if candleTerm == None: df_candleStick = self.fromListToDF(candleStick) else: df_candleStick = self.processCandleStick(candleStick, candleTerm) entryLowLine, entryHighLine = self.calculateLines(df_candleStick, entryTerm) closeLowLine, closeHighLine = self.calculateLines(df_candleStick, closeTerm) #直近約定件数30件の高値と安値 high = max([self.executions[-1-i]["price"] for i in range(30)]) low = min([self.executions[-1-i]["price"] for i in range(30)]) while True: #1分ごとに基準ラインを更新 if datetime.datetime.now().second < 2 : print("Renewing candleSticks") try: candleStick = self.getCandlestick(50, "60") except: print("Unknown error happend when you requested candleStick") if candleTerm == None: df_candleStick = self.fromListToDF(candleStick) else: df_candleStick = self.processCandleStick(candleStick, candleTerm) entryLowLine, entryHighLine = self.calculateLines(df_candleStick, entryTerm) closeLowLine, closeHighLine = self.calculateLines(df_candleStick, closeTerm) #直近約定件数30件の高値と安値 high = max([self.executions[-1-i]["price"] for i in range(30)]) low = min([self.executions[-1-i]["price"] for i in range(30)]) judgement = self.judgeForLoop(high, low, entryHighLine, entryLowLine, closeHighLine, closeLowLine) #現在レンジ相場かどうか. isRange = self.isRange(df_candleStick, rangeTerm, rangeTh) try : ticker = self.api.ticker(product_code=self.product_code) except: print("Unknown error happend when you requested ticker.") finally: pass best_ask = ticker["best_ask"] best_bid = ticker["best_bid"] #ここからエントリー,クローズ処理 if pos == 0 and not isRange[-1]: #ロングエントリー if judgement[0]: print(datetime.datetime.now()) self.order.market(size=lot, side="BUY") pos += 1 message = "Long entry. Lot:{}, Price:{}".format(lot, best_ask) self.lineNotify(message) lastPositionPrice = best_ask #ショートエントリー elif judgement[1]: print(datetime.datetime.now()) self.order.market(size=lot,side="SELL") pos -= 1 message = "Short entry. Lot:{}, Price:{}, ".format(lot, best_bid) self.lineNotify(message) lastPositionPrice = best_bid elif pos == 1: #ロングクローズ if judgement[2]: print(datetime.datetime.now()) self.order.market(size=lot,side="SELL") pos -= 1 plRange = best_bid - lastPositionPrice pl.append(pl[-1] + plRange * lot) message = "Long close. Lot:{}, Price:{}, pl:{}".format(lot, best_bid, pl[-1]) fileName = self.describePLForNotification(pl, df_candleStick) self.lineNotify(message,fileName) #一定以上の値幅を取った場合,次の10トレードはロットを1/10に落とす. if plRange > waitTh: waitTerm = originalWaitTerm lot = round(originalLot/10,3) elif waitTerm > 0: waitTerm -= 1 lot = round(originalLot/10,3) if waitTerm == 0: lot = originalLot elif pos == -1: #ショートクローズ if judgement[3]: print(datetime.datetime.now()) self.order.market(size=lot, side="BUY") pos += 1 plRange = lastPositionPrice - best_ask pl.append(pl[-1] + plRange * lot) message = "Short close. Lot:{}, Price:{}, pl:{}".format(lot, best_ask, pl[-1]) fileName = self.describePLForNotification(pl, df_candleStick) self.lineNotify(message,fileName) #一定以上の値幅を取った場合,次の10トレードはロットを1/10に落とす. if plRange > waitTh: waitTerm = originalWaitTerm lot = round(originalLot/10,3) elif waitTerm > 0: waitTerm -= 1 lot = round(originalLot/10,3) if waitTerm == 0: lot = originalLot time.sleep(0.5) message = "Waiting for channelbreaking." if datetime.datetime.now().minute % 5 == 0 and datetime.datetime.now().second < 1: print(message) self.lineNotify(message) def executionsProcess(self): """ pubnubで価格を取得する場合の処理(基本的に不要.) """ channels = ["lightning_executions_FX_BTC_JPY"] executions = self.executions class BFSubscriberCallback(SubscribeCallback): def message(self, pubnub, message): execution = message.message for i in execution: executions.append(i) config = PNConfiguration() config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' config.reconnect_policy = PNReconnectionPolicy.LINEAR config.ssl = False config.set_presence_timeout(60) pubnub = PubNubTornado(config) listener = BFSubscriberCallback() pubnub.add_listener(listener) pubnub.subscribe().channels(channels).execute() pubnubThread = threading.Thread(target=pubnub.start) pubnubThread.start() def getSpecifiedCandlestick(self,number, period, start_timestamp, end_timestamp): """ number:ローソク足の数.period:ローソク足の期間(文字列で秒数を指定,Ex:1分足なら"60").cryptowatchはときどきおかしなデータ(price=0)が含まれるのでそれを除く """ # ローソク足の時間を指定 periods = [period] # クエリパラメータを指定 query = {"periods": ','.join(periods), "after": str(int(start_timestamp)), "before": str(int(end_timestamp))} # ローソク足取得 try: res = json.loads(requests.get("https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc", params=query).text) res = res["result"] except: print(res) # ローソク足のデータを入れる配列. data = [] for i in periods: row = res[i] length = len(row) for column in row[:length - (number + 1):-1]: # dataへローソク足データを追加. if column[4] != 0: column = column[0:6] data.append(column) return data[::-1] #注文処理をまとめている class Order: def __init__(self): self.product_code = "FX_BTC_JPY" self.key = "your key" self.secret = "your secret" self.api = pybitflyer.API(self.key, self.secret) def limit(self, side, price, size, minute_to_expire=None): print("Order: Limit. Side : {}".format(side)) response = {"status":"internalError in order.py"} try: response = self.api.sendchildorder(product_code=self.product_code, child_order_type="LIMIT", side=side, price=price, size=size, minute_to_expire = minute_to_expire) except: pass while "status" in response: try: response = self.api.sendchildorder(product_code=self.product_code, child_order_type="LIMIT", side=side, price=price, size=size, minute_to_expire = minute_to_expire) except: pass time.sleep(3) return response def market(self, side, size, minute_to_expire= None): print("Order: Market. Side : {}".format(side)) response = {"status": "internalError in order.py"} try: response = self.api.sendchildorder(product_code=self.product_code, child_order_type="MARKET", side=side, size=size, minute_to_expire = minute_to_expire) except: pass while "status" in response: try: response = self.api.sendchildorder(product_code=self.product_code, child_order_type="MARKET", side=side, size=size, minute_to_expire = minute_to_expire) except: pass time.sleep(3) return response def stop(self, side, size, trigger_price, minute_to_expire=None): print("Order: Stop. Side : {}".format(side)) response = {"status": "internalError in order.py"} try: response = self.api.sendparentorder(order_method="SIMPLE", parameters=[{"product_code": self.product_code, "condition_type": "STOP", "side": side, "size": size,"trigger_price": trigger_price, "minute_to_expire": minute_to_expire}]) except: pass while "status" in response: try: response = self.api.sendparentorder(order_method="SIMPLE", parameters=[{"product_code": self.product_code, "condition_type": "STOP", "side": side, "size": size,"trigger_price": trigger_price, "minute_to_expire": minute_to_expire}]) except: pass time.sleep(3) return response def stop_limit(self, side, size, trigger_price, price, minute_to_expire=None): print("Side : {}".format(side)) response = {"status": "internalError in order.py"} try: response = self.api.sendparentorder(order_method="SIMPLE", parameters=[{"product_code": self.product_code, "condition_type": "STOP_LIMIT", "side": side, "size": size,"trigger_price": trigger_price, "price": price, "minute_to_expire": minute_to_expire}]) except: pass while "status" in response: try: response = self.api.sendparentorder(order_method="SIMPLE", parameters=[{"product_code": self.product_code, "condition_type": "STOP_LIMIT", "side": side, "size": size,"trigger_price": trigger_price, "price": price, "minute_to_expire": minute_to_expire}]) except: pass return response def trailing(self, side, size, offset, minute_to_expire=None): print("Side : {}".format(side)) response = {"status": "internalError in order.py"} try: response = self.api.sendparentorder(order_method="SIMPLE", parameters=[{"product_code": self.product_code, "condition_type": "TRAIL", "side": side, "size": size, "offset": offset, "minute_to_expire": minute_to_expire}]) except: pass while "status" in response: try: response = self.api.sendparentorder(order_method="SIMPLE", parameters=[{"product_code": self.product_code, "condition_type": "TRAIL", "side": side, "size": size, "offset": offset, "minute_to_expire": minute_to_expire}]) except: pass return response def optimization(): entryAndCloseTerm = [(5,3),(5,5),(10,10),(20,10)] rangeThAndrangeTerm = [(5000,5),(5000,15),(10000,15),(None,15),(None,20),(None,15)] waitTermAndwaitTh = [(10,10000),(10,20000),(5,10000)] paramList = [] for i in entryAndCloseTerm: for j in rangeThAndrangeTerm: for k in waitTermAndwaitTh: channelBreakOut = ChannelBreakOut() channelBreakOut.entryTerm = i[0] channelBreakOut.closeTerm = i[1] channelBreakOut.rangeTh = j[0] channelBreakOut.rangeTerm = j[1] channelBreakOut.waitTerm = k[0] channelBreakOut.waitTh = k[1] channelBreakOut.candleTerm = "1T" #テスト pl, profitFactor = channelBreakOut.describeResult(entryTerm=channelBreakOut.entryTerm, closeTerm=channelBreakOut.closeTerm, rangeTh=channelBreakOut.rangeTh, rangeTerm=channelBreakOut.rangeTerm, originalWaitTerm=channelBreakOut.waitTerm, waitTh=channelBreakOut.waitTh, candleTerm=channelBreakOut.candleTerm,fileName="20180221_0310.csv", showFigure=False) paramList.append([pl,profitFactor, i,j,k]) pF = [i[1] for i in paramList] pL = [i[0] for i in paramList] print("ProfitFactor max:") print(paramList[pF.index(max(pF))]) print("PL max:") print(paramList[pL.index(max(pL))]) if __name__ == '__main__': #とりあえず5分足,5期間安値・高値でエントリー,クローズする設定 channelBreakOut = ChannelBreakOut() channelBreakOut.entryTerm = 5 channelBreakOut.closeTerm = 5 channelBreakOut.rangeTh = None channelBreakOut.rangeTerm = None channelBreakOut.waitTerm = 0 channelBreakOut.waitTh = 10000 channelBreakOut.candleTerm = "5T" channelBreakOut.cost = 0 #実働 #channelBreakOut.loop(channelBreakOut.entryTerm, channelBreakOut.closeTerm, channelBreakOut.rangeTh, channelBreakOut.rangeTerm, channelBreakOut.waitTerm, channelBreakOut.waitTh) #バックテスト channelBreakOut.describeResult(entryTerm=channelBreakOut.entryTerm, closeTerm=channelBreakOut.closeTerm, rangeTh=channelBreakOut.rangeTh, rangeTerm=channelBreakOut.rangeTerm, originalWaitTerm=channelBreakOut.waitTerm, waitTh=channelBreakOut.waitTh, candleTerm=channelBreakOut.candleTerm,showFigure=True, cost=channelBreakOut.cost) #最適化 #optimization() |
コメント
はじめまして、botやプログラミングの勉強をしようと思いスナフキン様のページを教えてもらい勉強させていただいております。ありがとうございます。
すごく初歩的なことかもしれませんが教えていただけましたら幸甚です。
上記コードを実行して現在下記が表示されている状況です。
======================= RESTART: C:\python\bitcoin.py =======================
Total pl: JPY
The number of Trades:
The Winning percentage: %
The profitFactor:
The maximum Profit and Loss: JPY, JPY
損益等のグラフも出ています。これだけで感動いたしました。
ただ、KEY等はいれましたがそれ以外いじっていません。
この状態で自動でトレードは行われるのですか?設定しなければいけない数値があるのでしょうか?
本当に初歩的な質問で申し訳ございません。
よろしくお願い申し上げます。
はじめまして.お読みいただきありがとうございます.注文はloop関数で回すので,ifmainでコメントアウトしているloop()を有効して実行すればOKです.ただし,パラメタの設定が重要で,その辺りは今後ブログ記事で解説を行う予定なのでそちらでご確認ください
[…] チャネルブレイクアウト戦略を使ったBTCFX自動取引Bot(pythonコード) […]
こんな貴重なものの公開、ありがとうございます!
ちなみにこれはMEXでも使えるように成るのでしょうか?
そのためにはどのあたりを調節すればよいのでしょうか?
MEXの場合,Taker’s feeとの戦いになると思います.MEXでの運用自体はAPIをMEXのものに変えれば良いだけですが,儲けたいのなら(当然そうですが)MEXの場合はTaker’s feeで取られる以上の期待値が必要になります.
そのため,エントリーを絞るロジック,あるいはなんとかMakerになる方法を考える必要がありますね
ご回答本当にありがとうございます!
せっかくお答えいただいたのに知識が足りず理解がしっかりとできませんで本当に申し訳ありません。
ブログ楽しみにしています!それまでに知識を詰め込んでおきます!
はじめまして、最近bot製作に興味が出てきまして、大変勉強させていただいております。
上記のコードをAPIキーなどを変更し実行してみたのですが
557行目コード:high = max([self.executions[-1-i][“price”] for i in range(30)])
にて
IndexError: deque index out of range
が出ております。
#pubnubが回り始めるまで待つ.
の時間を変えてみましたが結果は同じでした。上記のエラーを解消するにはどのような修正を行えばよいのでしょうか。すみませんがコメントいただければ幸いです。
よろしくおねがいいたします。
マエダさん
同じエラーが他の方も出たということで,今原因を確かめています.(自分の環境では特にエラーが出ないので,まだ分かっていません.)とりあえず,high = …の近くでprint(self.executions)して, dequeの中身を確認してみてください.
裁量トレードで感情に任せてしまう瞬間があり、改善できないものだろうかと答えを探していたら、スナフキンさんのブログに偶然辿り着きました。こんな素晴らしい内容を教えてくれるブログはそうありません。これからもどうぞよろしくお願いします。
noteアップされたようですので、これから購入させていただきます⭐️
お読みいただきありがとうございます.自分も同じ理由でシストレを始めました笑
noteまで購入いただきありがとうございます.なにか分からないことがあればご質問ください.
コードがすごき綺麗ですしバックテスト、最適化まで付けて無料公開なんてすごいです。ファンになりました。
python始めたのが12月頃で,それまでは主にJavaしか使ったことがなかったので,実は命名規則とか変なところがあるんですよね笑
でもそう言っていただけると嬉しいです.ありがとうございます.
[…] チャネルブレイクアウト戦略を使ったBTCFX自動取引Bot(pythonコード) – マクロ… […]
はじめまして。
このようなコードを無料で公開なんて頭があがりません、ありがとうございます。
一つ質問なのですが、このコードではcalculateLot関数は定義しているものの未使用なのでしょうか?
calculateLot関数が使用されていないように見えて気になったので伺ってみました。
# 私はpython初心者なので、そもそもコードが理解出来ていない可能性もあります。笑
はじめまして.はいおっしゃる通りで,calculateLot関数は未使用です.必要なら実働させるときに使ってみてください.
こんにちは、昨日から動かしてみたのですが一度も売買してくれなくてLOOP関数のコメントアウトをはずすというのができてないと思うのですが、実働のコメントアウトをはずしてバックテストにコメントアウトをいれ一番下のoptimization()のコメントアウトをはずすという処理ではダメなんでしょうか?ほかどこのコメントアウトをはずせばよいのでしょう?
ノート購入させていただいてそっちもLOOPのコメントアウトをはずすってあったのですがLOOP関数のコメントアウトしてるとこが、何度もみたつもりなんですが全くみたらなく何処だか教えていただけたら助かります。 ほんとに初歩的な質問で申し訳ない
こんにちは.まず,optimizationは実働とは関係ない処理です.コードを読めばそれが分かるはずです.初歩的な質問をしていただくのは全くかまいませんし,申し訳なく思う必要もありません.しかしぼくのこの記事も,noteにしてもコードの見本を題材にコードを理解できるように,そして書けるようになろうというのが目的であって,ここをこうすれば動かせるよと丁寧に手取り足取り教えて,既存のbotを動かせるようになることは目的ではありません.遠回りに思えるかもしれませんがまず分からないときにすぐに人に聞くのではなく,自分で調べてコードを理解しようとするところから始めてください.結果的にそれがbotトレードで稼ぐ一番の近道になるはずです.もしそうしていれば,質問も「このコードのこの場所でこういった処理を書いていて,自分はこれを実行すると〇〇のようになると思うが,実際にはこうなっている.どうしてか.」というようなものになるはずです.何度も言いますが,そういった種類の「初歩的な」質問は全く構いませんし,申し訳ないなどと思う必要も言う必要もありません.では頑張ってください.
申し訳ない、買い 売りは、はいってたけど
pubnub:Exception in subscribe loop: HTTP Server Error (599): HTTP 599: Timeout while connecting
エラーで買えなかったようです、やはりどこかコメントアウトをはずすのが抜けてるってことなのでしょうか?
何度も申し訳ない、自己解決しました。結局、オーダーのほうに、APIの鍵がはいてなかったという、間抜けな状況でした。たぶんノートのほうもまだみてないけどそうかも。
質問は「Discordのマナブくんチャンネル」のほうでしたね。失礼しました。
#Discordがよくわからなかったのでこちらに書かせてもらいます
公開されたコードを参考にさせてもらっています。非常に有用であり感謝しています。
折角なので私が気になったところを記載します。公開から時間が経っているので既に把握している部分や意図的な箇所もあるかもしれませんがご参考になればと。
155-156
calculateLinesで判定する足の数が1本少なく見える
356
numberの計算に日跨ぎが考慮されていないためローソク足が一日分しか取得できない(そもそもnumberは不要?)
572-575
0.5秒単位にjudgementしてるが、直近の高値安値は1分おきにしか見ていない
625,647
ifをelifにしないとplRange>waithTh時にwaitTermが初期化されない
x98000様
コメントありがとうございます!3番目は意図的なもので,2番目,4番目はミス(というか訂正忘れ)です.
まず3番目については,pubnubのリアルタイムAPIを使って高値・安値ブレイク判定を行っているので0.5秒単位でループを回しています.高値・安値ラインは1本前のローソク足で決まるのでこちらについては1分ごとの更新で問題ないはずです.(逆に0.5秒ごとなどとしてしまうと,CryptowatchのAPI制限にひっかかかる.)
1,2,4番目ですが,これはブログに載せたものがぼくが動かしているものより少し古いもの(バグを発見および訂正する前のもの)であるためです.1番目の指摘についてはロジックがやや変わってしまう(期間が1減ってしまう)ので訂正しておきました.また4番目もすぐに訂正できるのでしておきました.2番目はそれほど影響はないので必要ならば各自変えてくださいということでお願いします.
早速の回答有り難うございます。
3番目について、高値・安値ラインは1分毎でいいですが、pubnubは裏で回っていてもhigh,lowが1分毎にしか更新されないように見えるので、結局1分毎にしか判定できないように思えます。勘違いかな?
今確認しました!そうですね.インデントを1つ下げないとダメですね.結構大事な部分でミスしてました.失礼しました.ありがとうございます!
こちらのプログラムを見て、pythonはこんなことができるのだと知って勉強を始めました。今まで大きなプログラムを作ったことが無かったのであちらこちらに散ったクラスから必要な処理を持ってきて…という工程にとにかく苦戦させられています。
ロジックの変更はpythonを自在にこなせるようになってから。まずはbitmexで使えるように変更することから始める。と目標を立ててやってみているのですが、gitに上がっている別ファイルの方も変更しないとmex対応にできませんよね?
JavaやCに多少触れていたとは言え、1か月程度の学習レベルでは到達不可能な分不相応な事をしようとしてしまっているのでしょうか。
はじめまして!たしかMEX対応版をDiscordのどなたかが作ってDiscordに貼っていた気がします.JavaやCをやっていたのなら全然そんなことはないと思います.ぼくもpythonを触り始めたのは12月末ぐらいなので...
お返事いただけるなんて嬉しいです!
MEX対応版の情報ありがとうございます。短期的に見ればさくっとコピーできちゃえばいいなという欲もありますが、やはり自分で理解して自分で作れるという強みは今後臨機応変に対応していく中でも必要になりますよね。
機械的になれずに裁量で2桁万円飛ばしちゃって反省してシストレを検討し始めました。似たような感じでシストレに移行したという事で、私もこういった物を理解できるレベルに到達できるように(贅沢言えば早めに)頑張ります。
再びコメント失礼します。165,166なのですが、i<termの場合に配列を逆走してしまいませんか?
155,156が修正されているかもしれないと思い、githubの方を見に行ったところ上に上がっているプログラムが一切見つかりませんでした。
最新版は微修正レベルの改善ではなく別物レベルに仕上がっていて、既に上のは無くなってしまっているのでしょうか?
はじめまして。
中年エンジニアでBot運用しています。
チャネルブレイクアウトをモディファイして運用していたのですが、レンジ相場と大きいトレンドの後で損失が大きいのに気付き、ちょうど対策しようとしていました。
そんな時に、この記事にめぐり逢い、とても参考になり、感謝しています。
ところで、ソースコードがとても綺麗ですね。自分も綺麗に書こうと努力しているんですが、とても感心しました。
ありがとうございます.長年エンジニアをされている方にそう言っていただけて嬉しいです.
[…] チャネルブレイクアウト戦略を使ったBTCFX自動取引Bot(pythonコード) […]