0

私は、私はインタラクティブ・ブローカー自体を尋ねていPythonでとibapi両方の新しい午前のibapiにおける一連の要求を取得する方法を、彼らは私に言った:のpython

をself.doneは、もともと親で定義されています が現在のAPI接続が「完了」であることを示すために使用されるクラスEClient。 自分で構築したループを停止するための指標として使用しないでください。 が必要なすべての履歴データをダウンロードするまで、1つのAPIクライアント接続を有効にしておくことができます。 データを要求するペースを遅くする必要がある場合は、 pythonの他のスレッド制御(sleep()関数など)を使用して、 ループに待機時間を追加して、全員の履歴データ要求を送信しません で契約しています。

だから、私は自己を使用せずに反復のための次に渡す方法の提案を見てほしいエラーが

self.done = True 

から来たこれは私のコード

from ibapi import wrapper 
from ibapi.client import EClient 
from ibapi.wrapper import EWrapper 
from ibapi.contract import Contract as IBcontract 
from threading import Thread 
import queue 
import datetime 
from ibapi.utils import iswrapper #just for decorator 
from ibapi.common import * 
from ibapi.contract import * 
from ibapi.ticktype import * 

class TestApp(wrapper.EWrapper, EClient): 

def __init__(self): 
    wrapper.EWrapper.__init__(self) 
    EClient.__init__(self, wrapper=self) 


@iswrapper 
def historicalData(self, reqId:int, bar: BarData): 
    print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, 
      "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, 
      "Count:", bar.barCount, "WAP:", bar.average) 
    if all_data.iloc[reqId,7] == 0: 
     all_data.iloc[reqId,7] = bar.close 
    self.done = True 

@iswrapper 
def historicalDataEnd(self, reqId: int, start: str, end: str): 
    super().historicalDataEnd(reqId, start, end) 
    print("HistoricalDataEnd ", reqId, "from", start, "to", end) 

@iswrapper 
def historicalDataUpdate(self, reqId: int, bar: BarData): 
    print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open, 
      "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, 
      "Count:", bar.barCount, "WAP:", bar.average) 

def main(): 
    t = time() 
    max_amount_per_Iter = 70 #max number per iter to save cost 
    max_Iter = ceil(len(all_data)/max_amount_per_Iter) 
    for i in range (0,max_Iter): 
     print('====================round : ',i+1,'===============================') 
     app = TestApp() 
     app.connect("127.0.0.1", 7496, clientId=i) 
     print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime())) 
     for j in range (0,min(max_amount_per_Iter,len(all_data)-i*max_amount_per_Iter)): 
      print(j+i*70) 
     app.i = j+i*max_amount_per_Iter 

     contract = Contract() 
     contract.symbol = all_data.iloc[app.i,0] 
     contract.secType = all_data.iloc[app.i,1] 
     contract.currency = all_data.iloc[app.i,3] 
     contract.exchange = all_data.iloc[app.i,2]    

     app.reqHistoricalData(app.i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 

     app.run() 

    sleep(1) 
    app.disconnect() 
    sleep(0.02) 
    print('=========End round : ',i+1,'with time :',time() - t,'==============') 

if __name__ == "__main__": 
    main() 

だと思います。 TWSを完了または切断します。私がself.doneを含まなければ、プログラムは無限ループで最初にi = 0、j = 0の反復で実行され、誰もそれを止めるように指示しません。

あなたは私のものを解決することができ、直接答えを知らないのであれば、あなたがお勧めすることができます:

  1. は、この場合には使用することができ、他のフロー制御はありますか?

  2. このケースで使用できる場合は、cancelHistoricalDataコマンドを使用しますか?

  3. クラス内でクラスを作成して実行する方法はありますか?self.done = Trueは、クラス内で自分のIDを切断してサブクラスでのみ実行しますか?

PS。私は

アップデートV2 requestMarketData

と同じ問題を抱えているこれは、私はあなたが過去のデータは、 self.doneではなく、フェッチ終了するために、別のフラグを使用する必要が

====================round : 1 =============================== 
step2 
serverVersion:124 connectionTime:b'20170821 22:34:09 ICT' 
0 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:hfarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:jfarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfuture 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:eufarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:cashfarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm.us 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ilhmds 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:euhmds 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:fundfarm 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ushmds 
HistoricalData. 0 Date: 20170815 Open: 67.2 High: 68.24 Low: 66.99 Close: 68.02 Volume: 13268 Count: 9453 WAP: 67.8105 
HistoricalData. 0 Date: 20170816 Open: 68.28 High: 68.91 Low: 67.45 Close: 68.01 Volume: 11950 Count: 9723 WAP: 68.457 
HistoricalData. 0 Date: 20170817 Open: 67.8 High: 68.53 Low: 66.83 Close: 66.89 Volume: 11407 Count: 9432 WAP: 67.504 
HistoricalData. 0 Date: 20170818 Open: 66.91 High: 67.25 Low: 66.57 Close: 66.78 Volume: 12091 Count: 9637 WAP: 66.8445 
HistoricalData. 0 Date: 20170821 Open: 66.9 High: 66.96 Low: 66.14 Close: 66.28 Volume: 3317 Count: 2541 WAP: 66.3425 
HistoricalDataEnd 0 from 20170814 22:34:14 to 20170821 22:34:14 
ERROR:root:ERROR 1 504 Not connected 
ERROR:root:ERROR 2 504 Not connected 
ERROR:root:ERROR 3 504 Not connected 
ERROR:root:ERROR 4 504 Not connected 
ERROR:root:ERROR 5 504 Not connected 
ERROR:root:ERROR 6 504 Not connected 
ERROR:root:ERROR 7 504 Not connected 
ERROR:root:ERROR 8 504 Not connected 
ERROR:root:ERROR 9 504 Not connected 
ERROR:root:ERROR 10 504 Not connected 
ERROR:root:ERROR 11 504 Not connected 
ERROR:root:ERROR 12 504 Not connected 
ERROR:root:ERROR 13 504 Not connected 
ERROR:root:ERROR 14 504 Not connected 
ERROR:root:ERROR 15 504 Not connected 
ERROR:root:ERROR 16 504 Not connected 
ERROR:root:ERROR 17 504 Not connected 
ERROR:root:ERROR 18 504 Not connected 
ERROR:root:ERROR 19 504 Not connected 
ERROR:root:ERROR 20 504 Not connected 
ERROR:root:ERROR 21 504 Not connected 
ERROR:root:ERROR 22 504 Not connected 
ERROR:root:ERROR 23 504 Not connected 
ERROR:root:ERROR 24 504 Not connected 
ERROR:root:ERROR 25 504 Not connected 
ERROR:root:ERROR 26 504 Not connected 
ERROR:root:ERROR 27 504 Not connected 
ERROR:root:ERROR 28 504 Not connected 
ERROR:root:ERROR 29 504 Not connected 
ERROR:root:ERROR 30 504 Not connected 
ERROR:root:ERROR 31 504 Not connected 
ERROR:root:ERROR 32 504 Not connected 
ERROR:root:ERROR 33 504 Not connected 
ERROR:root:ERROR 34 504 Not connected 
ERROR:root:ERROR 35 504 Not connected 
ERROR:root:ERROR 36 504 Not connected 
ERROR:root:ERROR 37 504 Not connected 
ERROR:root:ERROR 38 504 Not connected 
ERROR:root:ERROR 39 504 Not connected 
ERROR:root:ERROR 40 504 Not connected 
ERROR:root:ERROR 41 504 Not connected 
ERROR:root:ERROR 42 504 Not connected 
ERROR:root:ERROR 43 504 Not connected 
ERROR:root:ERROR 44 504 Not connected 
ERROR:root:ERROR 45 504 Not connected 
ERROR:root:ERROR 46 504 Not connected 
ERROR:root:ERROR 47 504 Not connected 
ERROR:root:ERROR 48 504 Not connected 
ERROR:root:ERROR 49 504 Not connected 
ERROR:root:ERROR 50 504 Not connected 
ERROR:root:ERROR 51 504 Not connected 
ERROR:root:ERROR 52 504 Not connected 
ERROR:root:ERROR 53 504 Not connected 
ERROR:root:ERROR 54 504 Not connected 
ERROR:root:ERROR 55 504 Not connected 
ERROR:root:ERROR 56 504 Not connected 
ERROR:root:ERROR 57 504 Not connected 
ERROR:root:ERROR 58 504 Not connected 
ERROR:root:ERROR 59 504 Not connected 
ERROR:root:ERROR 60 504 Not connected 
ERROR:root:ERROR 61 504 Not connected 
ERROR:root:ERROR 62 504 Not connected 
ERROR:root:ERROR 63 504 Not connected 
ERROR:root:ERROR 64 504 Not connected 
ERROR:root:ERROR 65 504 Not connected 
ERROR:root:ERROR 66 504 Not connected 
ERROR:root:ERROR 67 504 Not connected 
ERROR:root:ERROR 68 504 Not connected 
ERROR:root:ERROR 69 504 Not connected 
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 
=========End round : 1 with time : 7.807971477508545 ============== 
====================round : 2 =============================== 
step2 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:hfarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:jfarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfuture 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:eufarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:cashfarm 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm.us 
ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ilhmds 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:euhmds 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:fundfarm 
ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ushmds 
serverVersion:124 connectionTime:b'20170821 22:34:17 ICT' 
70 
HistoricalData. 70 Date: 20170815 Open: 117.23 High: 117.62 Low: 116.58 Close: 117.43 Volume: 7232 Count: 6205 WAP: 117.1295 
HistoricalData. 70 Date: 20170816 Open: 117.49 High: 119.59 Low: 117.03 Close: 119.25 Volume: 16468 Count: 11498 WAP: 118.8035 
HistoricalData. 70 Date: 20170817 Open: 119.19 High: 119.48 Low: 116.46 Close: 116.47 Volume: 12285 Count: 10072 WAP: 117.4645 
HistoricalData. 70 Date: 20170818 Open: 116.0 High: 117.84 Low: 115.46 Close: 116.88 Volume: 14917 Count: 10824 WAP: 116.9795 
HistoricalData. 70 Date: 20170821 Open: 116.85 High: 117.4 Low: 116.15 Close: 116.77 Volume: 3471 Count: 2599 WAP: 116.5535 
HistoricalDataEnd 70 from 20170814 22:34:19 to 20170821 22:34:19 
ERROR:root:ERROR 71 504 Not connected 
ERROR:root:ERROR 72 504 Not connected 
+0

正確に何が問題なのか教えてください。過去のデータをダウンロードしたいのですが、何がうまくいかなかったかは分かりませんでした。データを取得していませんか?またはエラーが発生しましたか? IBに送った質問を共有することもできます。私は答えから分かりません。 – Janos

+0

私は結果を追加しました。提案ありがとう! –

+0

このサンプルコードを正しくインデントしましたか? – Janos

答えて

0

私はここで少し再設計をお勧めしたいです。

この例では、selfを使用してAPIから切断します。完了=あなたが最初のデータを取得した直後。要求されたデータは非常に高速なイベントに到着するため、その前にすべてのデータを取得します。あなたの出力に見られる結果:最初のリクエストのすべてのデータを取得して処理した後、自分自身が切断されています。これは私のために繰り返す...

  1. 'self.done = True'行を削除します。これは何か良いことをする、あなたはそれを望んでいない。

  2. コードを再構成するため、APIに次のリクエストを送信する前にhistoricalDataEndイベントを待機します。 APIは並列要求を処理できますが、サーバーは非常に頻繁な履歴データ要求を許容しません。リクエストが速すぎると、ペース違反エラーが発生します。いくつかの要求間のsleep()も必要かもしれません。

  3. 私はapp.run()が切断を待っていると仮定します。そのため、「done」フラグの操作が必要でした。その行も削除してください。このコールが実際にメッセージをキャッチする必要がある場合(私はあなたのTestAppクラスとそのベースを知らない)、あなたの要求されたデータが到着して処理された後にdisconnect()を呼び出すことを確認してください。 Iこの場合、今のjに対して内app.run()呼び出しの後に不足している次のループ、前に必要な再接続...ここ

は私の提案の修正です:

from ibapi import wrapper 
from ibapi.client import EClient 
from ibapi.wrapper import EWrapper 
from ibapi.contract import Contract as IBcontract 
from threading import Thread 
import queue 
import datetime 
from ibapi.utils import iswrapper #just for decorator 
from ibapi.common import * 
from ibapi.contract import * 
from ibapi.ticktype import * 

class TestApp(wrapper.EWrapper, EClient): 

def __init__(self): 
    wrapper.EWrapper.__init__(self) 
    EClient.__init__(self, wrapper=self) 


@iswrapper 
def historicalData(self, reqId:int, bar: BarData): 
    print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, 
      "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, 
      "Count:", bar.barCount, "WAP:", bar.average) 
    if all_data.iloc[reqId,7] == 0: 
     all_data.iloc[reqId,7] = bar.close 
    # the line below is not necessary 
    #self.done = True 

@iswrapper 
def historicalDataEnd(self, reqId: int, start: str, end: str): 
    super().historicalDataEnd(reqId, start, end) 
    print("HistoricalDataEnd ", reqId, "from", start, "to", end) 
    print('=========End round : ',app.i+1,'with time :',time() - app.t,'==============') 

    app.i++ 
    if app.i==len(all_data): 
     app.disconnect() # Disconnect here: get out of app.run() when all data processed 
    else: 
     # add some sleep here if necessary 
     reqNext() 


@iswrapper 
def historicalDataUpdate(self, reqId: int, bar: BarData): 
    print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open, 
      "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, 
      "Count:", bar.barCount, "WAP:", bar.average) 


def reqNext(): 
    print('====================round : ',app.i+1,'===============================') 
    contract = Contract() 
    contract.symbol = all_data.iloc[app.i,0] 
    contract.secType = all_data.iloc[app.i,1] 
    contract.currency = all_data.iloc[app.i,3] 
    contract.exchange = all_data.iloc[app.i,2] 
    app.reqHistoricalData(app.i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 


def main(): 
    app = TestApp() 
    app.connect("127.0.0.1", 7496, clientId=1234) 
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime())) 

    app.i = 0 
    app.t = time() 
    reqNext() 
    app.run() 
    # when we arrive here, app is disconnected already 


if __name__ == "__main__": 
    main() 
+0

私は 'self.done = True'でこれを試していますが、それは動作しますが、その無駄な時間がかかります。このコードは10分以上かかるので、モデルの時間枠では実用的ではありません。 –

+0

確かに、私はあなたのプログラムを再構成することを提案しました。あなたのmain()メソッドでreqHistoricalData()** once **を呼び出し、あなたのhistoricalDataEnd()メソッドでもう一度呼び出すと、TestAppの** one **インスタンスを持つのが最善ですあなたが必要とするすべてのデータを取得するまで、必要な回数だけメソッドを呼び出します。 – Janos

+0

私はそれに応じて私の答えを更新しました – Janos

0

のために印刷しようと、いくつかの結果があるとして、 IBは「予約済み」であることを示す。

あなたxTestAppのインスタンスであるprint x.__dict__場合、あなたはすでに基底クラスで使用されているものを見るだろう、とあなたはここに示されている方法のために行っているものを除き上書きするべきではありません。

また、印刷するのではなく、結果を保存する場合は、私はここにそうであるように、それは、キューを使用することをお勧めします:

https://gist.github.com/robcarver17/f50aeebc2ecd084f818706d9f05c1eb4

+0

はい、フラグが必要な場合は別のフラグにする必要があります。しかし、なぜ彼はその旗が必要なのかを説明することができます: "私はself.doneを含まない場合、プログラムは無限ループで実行されます"。私はexanpleコードが適切にインデントされているのだろうかと思います... – Janos

+0

Janos、私はそれを単に止めないので、私はインターネット上の他の例のようにself.doneを置かなければなりません。 –

0

ビッグヤノスが本当に助けてくれてありがとう、私は少しこれを変更して、それは仕事です!私はあなたのコードので、この

を向上させるだろうという考えのため

おかげで私はそれがrunable作られたいくつかのバグを持っています。

from ibapi import wrapper 
from ibapi.client import EClient 
from ibapi.wrapper import EWrapper 
from ibapi.contract import Contract as IBcontract 
from threading import Thread 
import queue 
import datetime 
from ibapi.utils import iswrapper #just for decorator 
from ibapi.common import * 
from ibapi.contract import * 
from ibapi.ticktype import * 

class TestApp(wrapper.EWrapper, EClient): 

    def __init__(self): 
     wrapper.EWrapper.__init__(self) 
     EClient.__init__(self, wrapper=self) 


    @iswrapper 
    def historicalData(self, reqId:int, bar: BarData): 
     print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, 
       "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, 
      "Count:", bar.barCount, "WAP:", bar.average) 
     if all_data.iloc[reqId,7] == 0: 
      all_data.iloc[reqId,7] = bar.close 
    # the line below is not necessary 
    #self.done = True 

    @iswrapper 
    def historicalDataEnd(self, reqId: int, start: str, end: str): 
     super().historicalDataEnd(reqId, start, end) 
     print("HistoricalDataEnd ", reqId, "from", start, "to", end) 
     print('=========End round : ',self.i+1,'with time :',time() - self.t,'==============') 

     self.i = self.i+1 
     if self.i==len(all_data): 
      self.disconnect() # Disconnect here: get out of app.run() when all data processed 
     else: 
     # add some sleep here if necessary 
      reqNext(self.i,self) 


    @iswrapper 
    def historicalDataUpdate(self, reqId: int, bar: BarData): 
     print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open, 
       "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, 
       "Count:", bar.barCount, "WAP:", bar.average) 


def reqNext(i,app): 
     print('====================round : ',i+1,'===============================') 
     contract = Contract() 
     contract.symbol = all_data.iloc[i,0] 
     contract.secType = all_data.iloc[i,1] 
     contract.currency = all_data.iloc[i,3] 
     contract.exchange = all_data.iloc[i,2] 
     app.reqHistoricalData(i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 


def main(): 
    app = TestApp() 
    app.connect("127.0.0.1", 7496, clientId=1234) 
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime())) 
    app.i = 0 
    app.t = time() 
    reqNext(app.i,app) 
    app.run() 
    # when we arrive here, app is disconnected already 


if __name__ == "__main__": 
    main() 
+1

申し訳ありませんが、私はPythonを使用していません。私はちょうど私の概念を実証した – Janos

+0

申し訳ありませんが、あなたは私をたくさん助けている。私はこの分野で新しく、あなたの方法は私の世界を広げ、私はさらに検索を始める方法がわからないdef/classに関する私のビジョンを広げています。私はこの1ヶ月で闘争しているので、IOUは大きな時間です。 –