English Русский 中文 Español Deutsch Português
メタトレーダー5のカスタムニュースフィードを作成する

メタトレーダー5のカスタムニュースフィードを作成する

MetaTrader 5 | 3 4月 2018, 10:58
1 343 0
Francis Dube
Francis Dube

イントロダクション

MetaTrader5 は、トレーダーが必要とする多くの便利な関数があります。そのトレードスタイルに関係なく、ライブニュースフィードへのアクセスが可能です。 相場に何らかの影響を与える可能性がある貴重なコンテキストをトレーダーに提供します。 唯一の制限は、提供されるニュースの範囲です。 トレーダーは、ニュースの種類だけでなく、その発信元を選択することができ、柔軟なニュースフィードへのアクセスから恩恵を受けることができます。


組み込みのニュースフィード

ブローカーとトレードに依存して、ライブニュースフィードが非常に有用であっても完全には役に立たないことができます。 ブローカーによってターミナルに実装されている方法に依存してしまいます。 一部のブローカーは、評判のニュースコンセントから関連ニュースフィードへのアクセスを提供します。 また一部のブローカーはそのようなことをしません。 リクエストを満たすアプリケーションを構築する可能性を探ります。

ニュース API

すべてのニュースは、自由にインターネット上で利用可能であるため、必要とするニュースに直接アクセスする便利な方法です。 これを実現する1つの方法は、RSS ツールを使用することです。 以前、メタトレーダー5の RSS リーダーをコーディングする方法についての記事を書きました。 このルートの最大の欠点は、手動で各 URL を入力することです。ターミナル内の web リクエストを有効にするために必要で、冗長になることができます.

最善の解決策は、webAPIを使用することだと考えています。 広範な検索の後、複数のニュースコンセントへのアクセスを提供する API を使用します。 NewsAPI と呼ばれ、json メタデータを返す HTTP Get リクエストを介してアクセスされます。 1つは、選択したニュースコンセントによって 公開 されているニュースの見出しを取得することができます。 そこから選択するさまざまなニュースコンセントがあり、今後より多くの追加されるでしょう。 ユーザーはまた新しい情報元を提案するように促されます。 このサービスは、言語の多様性を欠いているように見え、米国とヨーロッパベースのニュースコンセントによって支配されています。 でも、それでも通用すると思います。 もう1つの利点は、すべての単一の web アドレスからアクセス可能であるという事実です。

NewsAPI アクセス

NewsAPI を使用するには、フルサービスへのアクセスを許可する必要があります。 これを行うには、公式サイトにアクセスし、[API キーの取得] をクリックします。 メールアドレスを登録すると、すべてのメソッドにアクセスするために必要な API キーが表示されます。

NewsAPI ウェブサイト


API の使用

API 全体には、2つのメインURLを使用してリクエストを行うことによってアクセスします。

  1. https://newsapi.org/v1/sources? -として作られたリクエストは、API で利用可能なすべてのニュースソースのリストを返します。
    この一覧には、最新のニュースヘッドラインをリクエストするときに指定する必要がある各ソースの識別子情報も含まれます。ソースの URL は、返されるソースのリストの種類を指定する省略可能なパラメータによって修飾できます。
  2. https://newsapi.org/v1/articles? -この記事の URL は、特定のソースからニュースの見出しやスニペットを返します。 URL には2つの必須パラメータが含まれている必要があります。 一つ目は、必要なソースを一意に識別する識別子です。 2つ目は、承認の API キーです。

パラメータ(Parameters)
詳細(Description)
パラメータのとれる値(Possible parameter values)
ソース/記事(Sources/Articles)
 サンプル(Example)
カテゴリ (オプション)
ソースを取得したいカテゴリ ビジネス、エンターテイメント、ゲーム、一般、音楽、政治、科学と自然、スポーツ、技術 ソース
https://newsapi.org/v1/sources?category=business


言語 (オプション)
ニュースソースの言語
en, de, fr ソース
https://newsapi.org/v1/sources?language=en
国 (オプション)
ソースがベースになっている国
au, de, gb, in, it, us ソース
https://newsapi.org/v1/sources?country=us
ソース (必須)
ニュースソースの識別子
ソース URL を使用してリクエストによって返されたリストからいずれかを選択します。
記事
https://newsapi.org/v1/articles?source=cnbc&apiKey=API_KEY
api キー (必須)
ユーザー認証トークン

記事
上記の例を参照
 ソート ニュースの見出しを並べ替えるメソッド、すなわち人気度は、ウェブサイト上に表示される順序です。
 トップ,最新,人気があります  記事  https://newsapi.org/v1/articles?source=cnbc&sortBy=top&apiKey=API_KEY

上の表は、API の2つの URL と共に使用できる主なパラメータを示しています。 完全なリストについては、ウェブサイトで利用できるドキュメントを参照してください。

API を テスト するためのスクリプト

API の使用方法についての一般的な考え方を適用しましょう。 作成するスクリプトは、API リクエストを行うことによって与えられ、習熟させる目的を果たします。 これを実現するために、スクリプトで web リクエストを作成し、テキストファイルに保存する必要があります。 このスクリプトを使用して、任意の API リクエストをテストし、レスポンスを観察できるようにする必要があります。

ここでは、スクリプト NewsAPI_test のコードです。

//+------------------------------------------------------------------+
//|                                                NewsAPI_test mq5 |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property script_show_inputs


#define BASE_URL "https://newsapi.org/v1/"
#define SRCE "sources?"
#define ATCLE "articles?source="
#define API_KEY "&apiKey=484c84eb9765418fb58ea936908a47ac"
//+------------------------------------------------------------------+
R//|                                                                 |
//+------------------------------------------------------------------+
enum mode 
  {
   sources,
   記事
  };

input string sFilename="sorce.txt";
input mode Mode=sources;
input string parameters="";
int timeout=5000;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   TestWebRequest();
  }
//+------------------------------------------------------------------+
//|TestWebRequest |
//+------------------------------------------------------------------+
void TestWebRequest(void)
  {
   string cookie=NULL,headers;
   char post[],result[];
   int res;
   string _url;
//---
   switch(Mode)
     {
      case sources:
         _url=BASE_URL+SRCE+parameters;
         break;
      case articles:
         _url=BASE_URL+ATCLE+parameters+API_KEY;
         break;
     }
//---
   ResetLastError();
   res=WebRequest("GET",_url,cookie,NULL,timeout,post,0,result,headers);

   if(res==-1)
     {
      Alert("Could not download file");
      return;
     }
   else Print("Download success");

   string pStream=CharArrayToString(result,0,-1,CP_UTF8);

   int hFile=FileOpen(sFilename,FILE_BIN|FILE_WRITE);

   if(hFile==INVALID_HANDLE)
     {
      Print("Invalid file handle");
      return;
     }

   FileWriteString(hFile,pStream);
   FileClose(hFile);

   return;
  }

まず、API リクエストを構成する URL のさまざまなコンポーネントを表す定義ディレクティブがあります。 最初のユーザーエントリーとして、1つが API レスポンスをキャッシュするために使用されるファイル名を入力する sFilename があります。 Mode パラメータは、API の2つのメインURL間の切り替えを可能にする列挙体です。

パラメータという名前のユーザーインプットパラメータは、API リクエストに含める追加の省略可能な URL パラメータのエントリです。 このスクリプトは、選択したパラメータの設定に応じて URL API の呼び出しを構築します。 webrequest 関数が成功した場合、メタデータはファイルに保存されます。

テストを実施し、レスポンスを調べることができます。初期テストは、デフォルトのパラメータを使用したスクリプトを実行します。 ファイルを開くと、API レスポンスを読み取ることができます。 データから特定の情報を抽出する必要がある場合に役立ちますので、json オブジェクトの構造に注意することが重要です。

{
   "status":"ok","sources":
   [
     {"id":"abc-news-au","name":"ABC News (AU)","description":"Australia's most trusted source of local, national and world news. Comprehensive, independent, in-depth analysis, the latest business, sport, weather and more.","url":"http://www.abc.net.au/news","category":"general","language":"en","country":"au","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"al-jazeera-english","name":"Al Jazeera English","description":"News, analysis from the Middle East and worldwide, multimedia and interactives, opinions, documentaries, podcasts, long reads and broadcast schedule.","url":"http://www.aljazeera.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"ars-technica","name":"Ars Technica","description":"The PC enthusiast's resource. Power users and the tools they love, without computing religion.","url":"http://arstechnica.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"associated-press","name":"Associated Press","description":"The AP delivers in-depth coverage on the international, politics, lifestyle, business, and entertainment news.","url":"https://apnews.com/","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"bbc-news","name":"BBC News","description":"Use BBC News for up-to-the-minute news, breaking news, video, audio and feature stories. BBC News provides trusted World and UK news as well as local and regional perspectives. Also entertainment, business, science, technology and health news.","url":"http://www.bbc.co.uk/news","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"bbc-sport","name":"BBC Sport","description":"The home of BBC Sport online. Includes live sports coverage, breaking news, results, video, audio and analysis on Football, F1, Cricket, Rugby Union, Rugby League, Golf, Tennis and all the main world sports, plus major events such as the Olympic Games.","url":"http://www.bbc.co.uk/sport","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"bild","name":"Bild","description":"Die Seite 1 für aktuelle Nachrichten und Themen, Bilder und Videos aus den Bereichen News, Wirtschaft, Politik, Show, Sport, und Promis.","url":"http://www.bild.de","category":"general","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"bloomberg","name":"Bloomberg","description":"Bloomberg delivers business and markets news, data, analysis, and video to the world, featuring stories from Businessweek and Bloomberg News.","url":"http://www.bloomberg.com","category":"business","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"breitbart-news","name":"Breitbart News","description":"Syndicated news and opinion website providing continuously updated headlines to top news and analysis sources.","url":"http://www.breitbart.com","category":"politics","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"business-insider","name":"Business Insider","description":"Business Insider is a fast-growing business site with deep financial, media, tech, and other industry verticals. Launched in 2007, the site is now the largest business news site on the web.","url":"http://www.businessinsider.com","category":"business","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"business-insider-uk","name":"Business Insider (UK)","description":"Business Insider is a fast-growing business site with deep financial, media, tech, and other industry verticals. Launched in 2007, the site is now the largest business news site on the web.","url":"http://uk.businessinsider.com","category":"business","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"buzzfeed","name":"Buzzfeed","description":"BuzzFeed is a cross-platform, global network for news and entertainment that generates seven billion views each month.","url":"https://www.buzzfeed.com","category":"entertainment","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"cnbc","name":"CNBC","description":"Get latest business news on stock markets, financial & earnings on CNBC. View world markets streaming charts & video; check stock tickers and quotes.","url":"http://www.cnbc.com","category":"business","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"cnn","name":"CNN","description":"View the latest news and breaking news today for U.S., world, weather, entertainment, politics and health at CNN","url":"http://us.cnn.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"daily-mail","name":"Daily Mail","description":"All the latest news, sport, showbiz, science and health stories from around the world from the Daily Mail and Mail on Sunday newspapers.","url":"http://www.dailymail.co.uk/home/index.html","category":"entertainment","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"der-tagesspiegel","name":"Der Tagesspiegel","description":"Nachrichten, News und neueste Meldungen aus dem Inland und dem Ausland - aktuell präsentiert von tagesspiegel.de.","url":"http://www.tagesspiegel.de","category":"general","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["latest"]},
     {"id":"die-zeit","name":"Die Zeit","description":"Aktuelle Nachrichten, Kommentare, Analysen und Hintergrundberichte aus Politik, Wirtschaft, Gesellschaft, Wissen, Kultur und Sport lesen Sie auf ZEIT ONLINE.","url":"http://www.zeit.de/index","category":"business","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["latest"]},
     {"id":"engadget","name":"Engadget","description":"Engadget is a web magazine with obsessive daily coverage of everything new in gadgets and consumer electronics.","url":"https://www.engadget.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"entertainment-weekly","name":"Entertainment Weekly","description":"Online version of the print magazine includes entertainment news, interviews, reviews of music, film, TV and books, and a special area for magazine subscribers.","url":"http://www.ew.com","category":"entertainment","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"espn","name":"ESPN","description":"ESPN has up-to-the-minute sports news coverage, scores, highlights and commentary for NFL, MLB, NBA, College Football, NCAA Basketball and more.","url":"http://espn.go.com","category":"sport","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"espn-cric-info","name":"ESPN Cric Info","description":"ESPN Cricinfo provides the most comprehensive cricket coverage available including live ball-by-ball commentary, news, unparalleled statistics, quality editorial comment and analysis.","url":"http://www.espncricinfo.com/","category":"sport","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"financial-times","name":"Financial Times","description":"The latest UK and international business, finance, economic and political news, comment and analysis from the Financial Times on FT.com.","url":"http://www.ft.com/home/uk","category":"business","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"focus","name":"Focus","description":"Minutenaktuelle Nachrichten und Service-Informationen von Deutschlands modernem Nachrichtenmagazin.","url":"http://www.focus.de","category":"general","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"football-italia","name":"Football Italia","description":"Italian football news, analysis, fixtures and results for the latest from Serie A, Serie B and the Azzurri.","url":"http://www.football-italia.net","category":"sport","language":"en","country":"it","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"fortune","name":"Fortune","description":"Fortune 500 Daily and Breaking Business News","url":"http://fortune.com","category":"business","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"four-four-two","name":"FourFourTwo","description":"The latest football news, in-depth features, tactical and statistical analysis from FourFourTwo, the UK's favourite football monthly.","url":"http://www.fourfourtwo.com/news","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"fox-sports","name":"Fox Sports","description":"Find live scores, player and team news, videos, rumors, stats, standings, schedules and fantasy games on FOX Sports.","url":"http://www.foxsports.com","category":"sport","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"google-news","name":"Google News","description":"Comprehensive, up-to-date news coverage, aggregated from sources all over the world by Google News.","url":"https://news.google.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"gruenderszene","name":"Gruenderszene","description":"Online-Magazin für Startups und die digitale Wirtschaft. News und Hintergründe zu Investment, VC und Gründungen.","url":"http://www.gruenderszene.de","category":"technology","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"hacker-news","name":"Hacker News","description":"Hacker News is a social news website focusing on computer science and entrepreneurship. It is run by Paul Graham's investment fund and startup incubator, Y Combinator. In general, content that can be submitted is defined as \"anything that gratifies one's intellectual curiosity\".","url":"https://news.ycombinator.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"handelsblatt","name":"Handelsblatt","description":"Auf Handelsblatt lesen sie Nachrichten über Unternehmen, Finanzen, Politik und Technik. Verwalten Sie Ihre Finanzanlagen mit Hilfe unserer Börsenkurse.","url":"http://www.handelsblatt.com","category":"business","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["latest"]},
     {"id":"ign","name":"IGN","description":"IGN is your site for Xbox One, PS4, PC, Wii-U, Xbox 360, PS3, Wii, 3DS, PS Vita and iPhone games with expert reviews, news, previews, trailers, cheat codes, wiki guides and walkthroughs.","url":"http://www.ign.com","category":"gaming","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"independent","name":"Independent","description":"National morning quality (tabloid) includes free online access to news and supplements. Insight by Robert Fisk and various other columnists.","url":"http://www.independent.co.uk","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"mashable","name":"Mashable","description":"Mashable is a global, multi-platform media and entertainment company.","url":"http://mashable.com","category":"entertainment","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"metro","name":"Metro","description":"News, Sport, Showbiz, Celebrities from Metro - a free British newspaper.","url":"http://metro.co.uk","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"mirror","name":"Mirror","description":"All the latest news, sport and celebrity gossip at Mirror.co.uk. Get all the big headlines, pictures, analysis, opinion and video on the stories that matter to you.","url":"http://www.mirror.co.uk/","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"mtv-news","name":"MTV News","description":"The ultimate news source for music, celebrity, entertainment, movies, and current events on the web. It's pop culture on steroids.","url":"http://www.mtv.com/news","category":"music","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"mtv-news-uk","name":"MTV News (UK)","description":"All the latest celebrity news, gossip, exclusive interviews and pictures from the world of music and entertainment.","url":"http://www.mtv.co.uk/news","category":"music","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"national-geographic","name":"National Geographic","description":"Reporting our world daily: original nature and science news from National Geographic.","url":"http://news.nationalgeographic.com","category":"science-and-nature","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"new-scientist","name":"New Scientist","description":"Breaking science and technology news from around the world. Exclusive stories and expert analysis on space, technology, health, physics, life and Earth.","url":"https://www.newscientist.com/section/news","category":"science-and-nature","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"newsweek","name":"Newsweek","description":"Newsweek provides in-depth analysis, news and opinion about international issues, technology, business, culture and politics.","url":"http://www.newsweek.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"new-york-magazine","name":"New York Magazine","description":"NYMAG and New York magazine cover the new, the undiscovered, the next in politics, culture, food, fashion, and behavior nationally, through a New York lens.","url":"http://nymag.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"nfl-news","name":"NFL News","description":"The official source for NFL news, schedules, stats, scores and more.","url":"http://www.nfl.com/news","category":"sport","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"polygon","name":"Polygon","description":"Polygon is a gaming website in partnership with Vox Media. Our culture focused site covers games, their creators, the fans, trending stories and entertainment news.","url":"http://www.polygon.com","category":"gaming","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"recode","name":"Recode","description":"Get the latest independent tech news, reviews and analysis from Recode with the most informed and respected journalists in technology and media.","url":"http://www.recode.net","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"reddit-r-all","name":"Reddit /r/all","description":"Reddit is an entertainment, social news networking service, and news website. Reddit's registered community members can submit content, such as text posts or direct links.","url":"https://www.reddit.com/r/all","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"reuters","name":"Reuters","description":"Reuters.com brings you the latest news from around the world, covering breaking news in business, politics, entertainment, technology, video and pictures.","url":"http://www.reuters.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"spiegel-online","name":"Spiegel Online","description":"Deutschlands führende Nachrichtenseite. Alles Wichtige aus Politik, Wirtschaft, Sport, Kultur, Wissenschaft, Technik und mehr.","url":"http://www.spiegel.de","category":"general","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"t3n","name":"T3n","description":"Das Online-Magazin bietet Artikel zu den Themen E-Business, Social Media, Startups und Webdesign.","url":"http://t3n.de","category":"technology","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"talksport","name":"TalkSport","description":"Tune in to the world's biggest sports radio station - Live Premier League football coverage, breaking sports news, transfer rumours & exclusive interviews.","url":"http://talksport.com","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"techcrunch","name":"TechCrunch","description":"TechCrunch is a leading technology media property, dedicated to obsessively profiling startups, reviewing new Internet products, and breaking tech news.","url":"https://techcrunch.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"techradar","name":"TechRadar","description":"The latest technology news and reviews, covering computing, home entertainment systems, gadgets and more.","url":"http://www.techradar.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-economist","name":"The Economist","description":"The Economist offers authoritative insight and opinion on international news, politics, business, finance, science, technology and the connections between them.","url":"http://www.economist.com","category":"business","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-guardian-au","name":"The Guardian (AU)","description":"Latest news, sport, comment, analysis and reviews from Guardian Australia","url":"https://www.theguardian.com/au","category":"general","language":"en","country":"au","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"the-guardian-uk","name":"The Guardian (UK)","description":"Latest news, sport, business, comment, analysis and reviews from the Guardian, the world's leading liberal voice.","url":"https://www.theguardian.com/uk","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-hindu","name":"The Hindu","description":"The Hindu. latest news, analysis, comment, in-depth coverage of politics, business, sport, environment, cinema and arts from India's national newspaper.","url":"http://www.thehindu.com","category":"general","language":"en","country":"in","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-huffington-post","name":"The Huffington Post","description":"The Huffington Post is a politically liberal American online news aggregator and blog that has both localized and international editions founded by Arianna Huffington, Kenneth Lerer, Andrew Breitbart, and Jonah Peretti, featuring columnists.","url":"http://www.huffingtonpost.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"the-lad-bible","name":"The Lad Bible","description":"The LAD Bible is one of the largest community for guys aged 16-30 in the world. Send us your funniest pictures and videos!","url":"http://www.theladbible.com","category":"entertainment","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-new-york-times","name":"The New York Times","description":"The New York Times: Find breaking news, multimedia, reviews & opinion on Washington, business, sports, movies, travel, books, jobs, education, real estate, cars & more at nytimes.com.","url":"http://www.nytimes.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"the-next-web","name":"The Next Web","description":"The Next Web is one of the world’s largest online publications that delivers an international perspective on the latest news about Internet technology, business and culture.","url":"http://thenextweb.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["latest"]},
     {"id":"the-sport-bible","name":"The Sport Bible","description":"TheSPORTbible is one of the largest communities for sports fans across the world. Send us your sporting pictures and videos!","url":"http://www.thesportbible.com","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-telegraph","name":"The Telegraph","description":"Latest news, business, sport, comment, lifestyle and culture from the Daily Telegraph and Sunday Telegraph newspapers and video from Telegraph TV.","url":"http://www.telegraph.co.uk","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-times-of-india","name":"The Times of India","description":"Times of India brings the Latest News and Top Breaking headlines on Politics and Current Affairs in India and around the World, Sports, Business, Bollywood News and Entertainment, Science, Technology, Health and Fitness news, Cricket and opinions from leading columnists.","url":"http://timesofindia.indiatimes.com","category":"general","language":"en","country":"in","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-verge","name":"The Verge","description":"The Verge covers the intersection of technology, science, art, and culture.","url":"http://www.theverge.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"the-wall-street-journal","name":"The Wall Street Journal","description":"WSJ online coverage of breaking news and current headlines from the US and around the world. Top stories, photos, videos, detailed analysis and in-depth reporting.","url":"http://www.wsj.com","category":"business","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"the-washington-post","name":"The Washington Post","description":"Breaking news and analysis on politics, business, world national news, entertainment more. In-depth DC, Virginia, Maryland news coverage including traffic, weather, crime, education, restaurant reviews and more.","url":"https://www.washingtonpost.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top"]},
     {"id":"time","name":"Time","description":"Breaking news and analysis from TIME.com. Politics, world news, photos, video, tech reviews, health, science and entertainment news.","url":"http://time.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"usa-today","name":"USA Today","description":"Get the latest national, international, and political news at USATODAY.com.","url":"http://www.usatoday.com/news","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"wired-de","name":"Wired.de","description":"Wired reports on how emerging technologies affect culture, the economy and politics.","url":"https://www.wired.de","category":"technology","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["top","latest"]},
     {"id":"wirtschafts-woche","name":"Wirtschafts Woche","description":"Das Online-Portal des führenden Wirtschaftsmagazins in Deutschland. Das Entscheidende zu Unternehmen, Finanzen, Erfolg und Technik.","url":"http://www.wiwo.de","category":"business","language":"de","country":"de","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":["latest"]}
   ]
  }

ファイルを開くときに、レスポンスに、ニュースヘッドラインをリクエストできるすべてのニュース・アウトレットを表す json オブジェクトの配列が含まれていることがわかります。

次に、選択したソースからニュースをリクエストする API 呼び出しのテストを行います。 再びファイルを開いてレスポンスを観察します。

{
   "status":"ok","source":"cnbc","sortBy":"top","articles":
   [
     {"author":"Reuters","title":"'Singles Day' China shopping festival smashes record at the halfway mark","description":"Alibaba said its Singles Day sales surged past last year's total just after midday Saturday, hitting a record $18 billion.","url":"https://www.cnbc.com/2017/11/11/singles-day-china-shopping-festival-smashes-record-at-the-halfway-mark.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/11/10/104835461-RTS1JDT7-singles-day.1910x1000.jpg","publishedAt":"2017-11-11T10:50:08Z"},
     {"author":"The Associated Press","title":"Trump: Putin again denies meddling in 2016 election","description":"President Donald Trump said Saturday that Russia's Vladimir Putin again denied interfering in the 2016 U.S. elections.","url":"https://www.cnbc.com/2017/11/11/trump-putin-again-denies-meddling-in-2016-election.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/08/18/104661874-RTS19PQA-vladimir-putin.1910x1000.jpg","publishedAt":"2017-11-11T12:07:32Z"},
     {"author":"Jeff Cox","title":"GE limps into investor day with shareholders demanding answers on dividend and turnaround plan","description":"As General Electric limps into its investor day presentation Monday, it has gone from a paradigm of success to a morass of excess.","url":"https://www.cnbc.com/2017/11/10/ge-faces-investor-day-with-questions-about-its-past-and-future.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/10/20/104786151-JohnFlannery2.1910x1000.jpg","publishedAt":"2017-11-10T16:16:05Z"},
     {"author":"Sarah Whitten","title":"Here's where military service members can get freebies on Veterans Day","description":"Businesses across the country are saying \"thank you\" to Veterans on Friday by offering freebies to active and retired military members.","url":"https://www.cnbc.com/2016/11/10/heres-where-military-service-members-can-get-freebies-on-veterans-day.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2016/11/10/104097817-GettyImages-496717392.1910x1000.jpg","publishedAt":"2016-11-10T18:30:41Z"},
     {"author":"Morgan Brennan","title":"With an eye toward the North Korean threat, a 'missile renaissance' blooms in the US","description":"Raytheon is cranking out about 20 Standard Missile variants per month, as part of the effort to help repel a possible attack from North Korea.","url":"https://www.cnbc.com/2017/11/11/north-korea-threat-leads-to-a-us-missile-renaissance.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/08/03/104631031-RTS1A3SU.1910x1000.jpg","publishedAt":"2017-11-11T14:00:56Z"},
     {"author":"Larry Kudlow","title":"Larry Kudlow: A pro-growth GOP tax cut is on the way — this year","description":"One way or another, Congress will come up with a significant pro-growth bill, writes Larry Kudlow.","url":"https://www.cnbc.com/2017/11/11/larry-kudlow-pro-growth-gop-tax-cut-is-on-the-way--this-year.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/11/02/104816986-GettyImages-869498942.1910x1000.jpg","publishedAt":"2017-11-11T14:22:58Z"},
     {"author":"Reuters","title":"Trans-Pacific trade deal advances without United States","description":"Last-minute resistance from Canada had raised new doubts about its survival.","url":"https://www.cnbc.com/2017/11/11/trans-pacific-trade-deal-advances-without-united-states.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2016/11/22/104123278-GettyImages-624177112.1910x1000.jpg","publishedAt":"2017-11-11T10:23:03Z"},
     {"author":"Jacob Pramuk","title":"McConnell says he 'misspoke' about middle-class tax hikes","description":"Mitch McConnell told The New York Times that \"you can't guarantee that no one sees a tax increase.\"","url":"https://www.cnbc.com/2017/11/10/mitch-mcconnell-says-he-misspoke-about-republican-tax-plan.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/09/22/104726784-RTX3FY40-mcconnell.1910x1000.jpg","publishedAt":"2017-11-10T23:04:47Z"},
     {"author":"Erin Barry","title":"Start-up Dia&Co is catering the 70 percent of US women the fashion industry ignores","description":"There are more than 100 million plus-size women in the U.S., but finding fashionable clothes in their size can be a challenge.","url":"https://www.cnbc.com/2017/11/10/diaco-caters-to-the-70-percent-of-us-women-fashion-ignores.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/02/22/104298276-Lydia-Gilbert--Nadia-Boujarwah-2_credit-DiaCo_r.1910x1000.jpg","publishedAt":"2017-11-11T14:01:01Z"},
     {"author":"Elizabeth Gurdus","title":"Cramer shares a little-known investing concept critical to buying stocks","description":"Jim Cramer explained why the idea of suitability is crucial when it comes to individual investing.","url":"https://www.cnbc.com/2017/11/10/cramer-shares-an-investing-concept-critical-to-buying-stocks.html","urlToImage":"https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2017/11/10/104835669-GettyImages-825493934.1910x1000.jpg","publishedAt":"2017-11-10T23:10:58Z"}
   ]
  }

この例では、API のレスポンスには json オブジェクトの配列が含まれており、ぞれがニュースの見出しになっています。

最後に、不正な API 呼び出しが行われたときにどのようなレスポンスが得られるかを調査してみましょう。 無効な API キーが使用された場合の結果を次に示します。

{
  "status":"error",
  "code":"apiKeyInvalid",
  "message":"Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API
  key."  
}

エラーレスポンスのもう1つの例として、誤ったソース id でリクエストが行われた場合です。

{
 "status":"error",
 "code":"sourceDoesntExist",
 "message":"The news source you've entered doesn't exist. Check your spelling, or see /v1/sources for a list of valid sources."
}

API を使って再生した後、json パーサーを使用することで、このデータにすばやくアクセスするメソッドについて見てみましょう。

JSON メタデータの解析

mql5.com コードベースには、2つの json ライブラリが用意されています。 最初に使うのはjson.mqhです。 このライブラリを使用すれば、テストスクリプトのコンパイルで、エラーとアラートの数を明らかになります。 このエラーは、ライブラリファイル自体にありました。 ライブラリのコードベースの web ページを参照すると、作成者は、github 上でアクティブに管理されていることを規定しています。 作成者はコードベースを通じて利用可能なファイルを更新していません。

コンパイルエラーを修正するのは簡単でしたが、必要とされたのは、json.mqh ファイルに直接ハッシュファイルを含めることだけです。 アラートは、暗黙的な型キャストによって引き起こされました。 修正した json.mqh ファイルを以下に示します。

//$Id: json. mqh 102 2014-02-24 03:39: 28Z ydrol $
#include "hash.mqh"
#ifndef YDROL_JSON_MQH
#define YDROL_JSON_MQH

// (C)2014 Andrew Lord forex@NICKNAME@lordy.org.uk
// Parse a JSON String - Adapted for mql4++ from my gawk implementation
// ( https://code.google.com/p/oversight/source/browse/trunk/bin/catalog/json.awk )

/*
   TODO 定数 true | false | null を固定オブジェクトとして表すことができます。
      これを行うには、_hash と _array の削除は、オブジェクトをスキップする必要があります。

   TODO test null

   TODO Parse Unicode Escape
*/

/*
   例については json_demo を参照してください。

 これには hash.mqh ( http://codebase.mql4.com/9238 , http://lordy.co.nf/hash )が必要です。

 */

enum ENUM_JSON_TYPE { JSON_NULL,JSON_OBJECT,JSON_ARRAY,JSON_NUMBER,JSON_STRING,JSON_BOOL };

class JSONString;
//すべての JSON 型のジェネリッククラス(Number, String, Bool, Array, Object )
class JSONValue : public HashValue 
  {
private:
   ENUM_JSON_TYPE    _type;

public:
                     JSONValue () {}
                    ~ JSONValue () {}
   ENUM_JSON_TYPE getType () { return _type;}
   void setType(ENUM_JSON_TYPE t) { _type=t; }

   //型のメソッド
   bool isString() { return _type==JSON_STRING; }
   bool isNull() { return _type==JSON_NULL; }
   bool isObject() { return _type==JSON_OBJECT; }
   bool isArray() { return _type==JSON_ARRAY; }
   bool isNumber() { return _type==JSON_NUMBER; }
   bool isBool() { return _type==JSON_BOOL; }

   //子クラスのオーバーライド
   virtual string toString() 
     {
      return "";
     }

   //サブタイプにキャストする便利なゲッター。
   string getString()
     {
      return ((JSONString *)GetPointer(this)).getString();
     }
   double getDouble()
     {
      return ((JSONNumber *)GetPointer(this)).getDouble();
     }
   long getLong()
     {
      return ((JSONNumber *)GetPointer(this)).getLong();
     }
   int getInt ()
     {
      return ((JSONNumber *)GetPointer(this)).getInt();
     }
   bool getBool ()
     {
      return ((JSONBool *)GetPointer(this)).getBool();
     }

   //配列とオブジェクトによる静的 getter 呼び出し。 子の結果を返すとき。
   //アプリケーションがプログラムをストップせずに取得される値をチェックすることができます 
   //(時にはプログラムのストップが望まれているケースがあります。-EAがストップし、障害のあるデータを使用してタスクを続行するよりストップさせた方がマシです。)
   static bool getString(JSONValue *val,string &out)
     {
      if(val!=NULL && val.isString()) 
        {
         out = val.getString();
         return true;
        }
      return false;
     }
   static bool getBool(JSONValue *val,bool &out)
     {
      if(val!=NULL && val.isBool()) 
        {
         out = val.getBool();
         return true;
        }
      return false;
     }
   static bool getDouble(JSONValue *val,double &out)
     {
      if(val!=NULL && val.isNumber()) 
        {
         out = val.getDouble();
         return true;
        }
      return false;
     }
   static bool getLong(JSONValue *val,long &out)
     {
      if(val!=NULL && val.isNumber()) 
        {
         out = val.getLong();
         return true;
        }
      return false;
     }
   static bool getInt(JSONValue *val,int &out)
     {
      if(val!=NULL && val.isNumber()) 
        {
         out = val.getInt();
         return true;
        }
      return false;
     }
  };
//-----------------------------------------
....

テストスクリプト newstest_json のコードについては、以下で詳しく説明します。 このスクリプトは、以前のテストで作成された API 呼び出しから保存された json メタデータを含むファイルを読み取ります。 このスクリプトを実行すると、データに含まれるすべての利用可能なニュース・アウトレットがターミナルに出力されます。

//+------------------------------------------------------------------+
//|                                               newstest_json mq5 |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#property version   "1.00"
#include<json.mqh></json.mqh>
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   Test();
  }
//+------------------------------------------------------------------+
//| Test                                                             |
//+------------------------------------------------------------------+
bool Test()
  {

   string pStream;
   string sources_filename="sources.txt";

   int hFile,iStringSize;

//ファイルの内容の読み取り 
   hFile=::FileOpen(sources_filename,FILE_TXT|FILE_READ|FILE_UNICODE);
   if(hFile==INVALID_HANDLE)
     {
      ::Print("error opening file "+sources_filename);
      return(false);
     }

   while(!::FileIsEnding(hFile))
     {
      iStringSize = ::FileReadInteger(hFile, INT_VALUE);
      pStream    += ::FileReadString(hFile, iStringSize);
     }

   ::FileClose(hFile);

   Print("success opening and reading file");

   JSONParser *parser=new JSONParser();

   JSONValue *jv=parser.parse(pStream);

   if(jv==NULL) 
     {
      Print("error:"+(string)parser.getErrorCode()+parser.getErrorMessage());
        } else {

      if(jv.isObject())
        {
         JSONObject *jo = jv;
         JSONArray  *jd =  jo.getArray("sources");

         for(int i=0;i<jd.size();i++)
           {
            Print(jd.getObject(i).getString("id"));
           }
        }
      delete jv;
     }
   delete parser;

   return(true);
  }

修正されたファイルで、ライブラリはよく機能します。

ライブラリのテスト結果


ここでは、2番目の json ライブラリJAson.mqhを見てみましょう。 このライブラリを使用したテストでは、エラーは発生しませんでした。 完全に稼働しました。 このライブラリのテストには、newstest_JAson スクリプトが使用されていました。

//+------------------------------------------------------------------+
//|                                              newstest_JAson mq5 |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#property version   "1.00"
#include<JAson.mqh></JAson.mqh>
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   Test();
  }
//+------------------------------------------------------------------+
//| Test                                                             |
//+------------------------------------------------------------------+
bool Test()
  {

   string pStream;
   string sources_filename="sources.txt";

   int hFile,iStringSize;

//ファイルの内容の読み取り 
   hFile=::FileOpen(sources_filename,FILE_TXT|FILE_READ|FILE_UNICODE);
   if(hFile==INVALID_HANDLE)
     {
      ::Print("error opening file "+sources_filename);
      return(false);
     }

   while(!::FileIsEnding(hFile))
     {
      iStringSize = ::FileReadInteger(hFile, INT_VALUE);
      pStream    += ::FileReadString(hFile, iStringSize);
     }

   ::FileClose(hFile);

   Print("success opening and reading file");

   CJAVal  srce;

   if(!srce.Deserialize(pStream))
     {
      ::Print("Json deserialize error");
      return(false);
     }

   CJAVal *json_array=new CJAVal(srce["sources"]);

   for(int i=0;i<ArraySize(json_array.m_e);i++)
     {
      Print(json_array[i]["id"].ToStr());
     }

   delete json_array;

   return(true);
  }

そして、テストの結果です。

JAson.mqh ライブラリのテスト結果

このライブラリを最初の mqh と比較すると、いずれも json データ型をすべてサポートしています。 主な差は、json.mqh が各 json データ型をクラスとして実装し、複数のクラスを定義することです。 一方、JAson.mqh では、json データ型はパブリックにアクセス可能なクラスプロパティによって定義されるため、ライブラリは1つのクラスを定義します。

上に移動すると、ニュースを表示するMetaTrader5のアプリケーションをプログラムすることができます。 アプリケーションは、JAson.mqh ライブラリを使用します。 このアプリケーションは、ニュースソースのリストを表示するEAとして実装されます。 リスト内の項目が選択されると、隣接するテキストボックスに、アウトレットから入手できる最新のニューススニペットが表示されます。

CNewsFeed クラス

以前の記事では、標準ライブラリを使用してグラフィカルユーザーインターフェイスを作成しました。 この頃、Anatoli Kazharskiのライブラリの使用法を探求したいと思っています。 定期的に更新し、新しい関数を追加され、ライブラリには、広範なライブラリのバージョンの数が存在します。 「グラフィカルインターフェイス XI: ライブラリコードのリファクタリング」で提供されているバージョンを使用することを選択しました。 必要なものもありますが、不必要なものも入っている印象です。

このアプリケーションは、かなり基本的なものになります, メニューバーや任意のタブは必要ありません. このアプリケーションを作成するためのメインクラスを含むインクルードファイルから始めましょう。

//+------------------------------------------------------------------+
//|                                           NewsFeedProgram mqh |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#include<EasyAndFastGUIWndEvents.mqh></EasyAndFastGUIWndEvents.mqh>
#include<EasyAndFastGUITimeCounter.mqh></EasyAndFastGUITimeCounter.mqh>
#include<JAson.mqh></JAson.mqh>

#define BASE_URL "https://newsapi.org/v1/"
#define SRCE "sources?"
#define ATCLE "articles?source="
#define LATEST "&sortBy=latest"
#define API_KEY "&apiKey=484c84eb9765418fb58ea936908a47ac"
//+------------------------------------------------------------------+
//| Class for creating an application                                |
//+------------------------------------------------------------------+
class CNewsFeed : public CWndEvents
  

NewsFeedprogram.mqh には、GUI ライブラリと json ライブラリも含まれます。 スクリプトの場合と同様に、ディレクティブは URL のコンポーネントを格納します。

//+------------------------------------------------------------------+
//|                                           NewsFeedProgram mqh |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#include<EasyAndFastGUIWndEvents.mqh></EasyAndFastGUIWndEvents.mqh>
#include<EasyAndFastGUITimeCounter.mqh></EasyAndFastGUITimeCounter.mqh>
#include<JAson.mqh></JAson.mqh>

#define BASE_URL "https://newsapi.org/v1/"
#define SRCE "sources?"
#define ATCLE "articles?source="
#define LATEST "&sortBy=latest"
#define API_KEY "&apiKey=484c84eb9765418fb58ea936908a47ac"
//+------------------------------------------------------------------+
//| Class for creating an application                                |
//+------------------------------------------------------------------+
class CNewsFeed : public CWndEvents
  {
private:
   //---タイムカウンタ
   CTimeCounter      m_counter; //ステータスバーのアイテムを更新する
   //---メインウィンドウ
   CWindow           m_window;
   //---ステータスバー
   CStatusBar        m_status_bar;
   //---リストビュー
   CListView         m_listview;
   //---編集
   CTextBox          m_text_box;
   //主な Json オブジェクト 
   CJAVal            srce;
   CJAVal            js;
   //ネストになった要素を参照するための Json ポインタ
   CJAVal           *articles;
   CJAVal           *articlesArrayElement;
   CJAVal           *sources;
   CJAVal           *sourcesArrayElement;

メインクラスの CNewsFeed は、CWndEvents の子孫です。 そのプライベートプロパティは、アプリケーションを構成するコントロールコンポーネント (メインウィンドウフォーム) で、リストビュー、textbox、ステータスバーが接続されています。 ステータスバーを更新するためのタイムカウンタがあります。 CJAVal 型のプライベートプロパティの残りの部分では、json パーサー、srce、および特定のニュースコンセントからのニュースソースと特定のニュースの呼び出しから返される json オブジェクトが含まれる js のプロパティを有効にします。 残りのプロパティは、ネストになった json オブジェクトを参照するポインターです。

このクラスの残りの部分を以下に示します。

//+------------------------------------------------------------------+
//|                                           NewsFeedProgram mqh |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#include<EasyAndFastGUIWndEvents.mqh></EasyAndFastGUIWndEvents.mqh>
#include<EasyAndFastGUITimeCounter.mqh></EasyAndFastGUITimeCounter.mqh>
#include<JAson.mqh></JAson.mqh>

#define BASE_URL "https://newsapi.org/v1/"
#define SRCE "sources?"
#define ATCLE "articles?source="
#define LATEST "&sortBy=latest"
#define API_KEY "&apiKey=484c84eb9765418fb58ea936908a47ac"
//+------------------------------------------------------------------+
//| Class for creating an application                                |
//+------------------------------------------------------------------+
class CNewsFeed : public CWndEvents
  {
private:
   //---タイムカウンタ
   CTimeCounter      m_counter; //ステータスバーのアイテムを更新する
   //---メインウィンドウ
   CWindow           m_window;
   //---ステータスバー
   CStatusBar        m_status_bar;
   //---リストビュー
   CListView         m_listview;
   //---編集
   CTextBox          m_text_box;
   //主な Json オブジェクト 
   CJAVal            srce;
   CJAVal            js;
   //ネストになった要素を参照するための Json ポインタ
   CJAVal           *articles;
   CJAVal           *articlesArrayElement;
   CJAVal           *sources;
   CJAVal           *sourcesArrayElement;
public:
                     CNewsFeed(void);
                    ~CNewsFeed(void);
   //--- Initialization/deinitialization
   bool              OnInitEvent(void);
   void              OnDeinitEvent(const int reason);
   //---タイマ
   void              OnTimerEvent(void);
   //---チャートイベントハンドラ
   virtual void      OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);

   //プログラムのグラフィカルインターフェイスを作成
   bool              CreateGUI(void);
private:
   //---メインウィンドウ
   bool              CreateWindow(const string text);
   //---ステータスバー
   bool              CreateStatusBar(const int x_gap,const int y_gap);
   //---リストビュー
   bool              CreateListView(const int x_gap,const int y_gap);
   //---編集
   bool              CreateTextBox(const int x_gap,const int y_gap);
   //---フィルソース Json オブジェクト
   bool              PrepareSources(void);
   //---フィルアーティクル json オブジェクトのソースから選択した要素に基づいて json オブジェクト
   bool              PrepareArticles(int listview_index);
   //データのダウンロード
   string            DownLoad(string url,string file_name);
  };

グラフィカルユーザーインターフェイスに関連するメソッドの詳細な説明は、 Anatoli Kazharskiによって作成された記事に記載されています。

CTextBox クラスの変更

必要な関数を有効にする変更を加えなければならなかったので、考察したいライブラリの部分があります。 これはtextbox コントロールに特に関連します。 テスト中に、textbox の update () メソッドが、textbox が新しいコンテンツで更新されたときに予期したとおりに反応しなかったことに気付きました。 この問題は、以下に示すように、同じクラスから update メソッドにプライベートメソッドを追加することによって解決されました。

テキストボックス内のコンテンツを更新すると、他の問題も発生します。問題は、アプリケーションを最小化最大化するときに発生します。 犯人は、テキストボックスでした。 問題は主に自動化に関連します。

//+------------------------------------------------------------------+
//|コントロールの更新 |
//+------------------------------------------------------------------+
void CTextBox::Update(const bool redraw=false)
  {
//指定されている場合、テーブルを再描画
   if(redraw)
     {
      //---ドロー
      //ChangeTextBoxSize ();
      WordWrap();
      Draw();
      CalculateTextBoxSize();
      ChangeScrollsSize();
      //---適用
      m_canvas.Update();
      m_textbox.Update();
      return;
     }
//---適用
   m_canvas.Update();
   m_textbox.Update();
  }



最初のスクロールバーの問題。 水平および垂直スクロールは部分的に不全のようですが、テキストボックスを更新した後、スクロールコンテンツが突然消えます。 問題は、テキストボックスに書き込まれた新しいコンテンツは、初期化中に表示される最初のテキストに相対的な "サイズ " パラメータ (すなわち、最大の行の幅と行の数) が大きかったときに発生したことに気づきました。 この問題を回避するために、水平スクロールバーが不要になり、多数の空の行を持つテキストボックスが初期化されるように、ワードラップモードを有効にしました。 垂直平面の listview と textbox の自動は無効になりました。

したがって、アプリケーションを実行し、Gui ライブラリをダウンロードした場合は、aricle のトレーリングストップに表示されているテキストボックスに mqh ファイルを置き換えてください。

Json オブジェクトを処理するためのメソッド

//+------------------------------------------------------------------+
//| method for web requests and caching data                         |
//+------------------------------------------------------------------+     
string CNewsFeed::DownLoad(string url,string file_name="")
  {

//ターミナルが接続されていない場合、EA は接続がないと仮定します。  
   if(!(bool)::TerminalInfoInteger(TERMINAL_CONNECTED))return(NULL);

   string cookie=NULL,headers,pStream;
   char post[],result[];
   int res,hFile;

   ::ResetLastError();
   int timeout=5000;
//web リクエスト
   res=::WebRequest("GET",url,cookie,NULL,timeout,post,0,result,headers);

   if(res==-1)
     {
      ::Print("WebRequest failure");
      return(NULL);
     }

//ダウンロードしたデータストリーム 
   pStream=::CharArrayToString(result,0,-1,CP_UTF8);

   if(file_name!="")
     {

      hFile=::FileOpen(file_name,FILE_BIN|FILE_WRITE);

      if(hFile==INVALID_HANDLE)
        {
         return(pStream);
         ::Print("Invalid file handle - "+file_name+" - could not save data to file");
        }
      //ダウンロードしたデータをファイルに書き込む
      ::FileWriteString(hFile,pStream);
      ::FileClose(hFile);
     }
//Print("download success");
   return(pStream);
  }

Download() -webrequest 関数を介して API 呼び出しを行い、レスポンスを文字列値として返すために使用します。 2番目の文字列パラメータを指定すると、文字列のレスポンスがファイルに保存されます。 エラーが発生した場合、NULL 値が返されます。

//+------------------------------------------------------------------+
//| downloads data to fill sources json object                       |
//+------------------------------------------------------------------+    
bool CNewsFeed::PrepareSources(void)
  {
   string sStream;
   int    iStringSize,hFile;

   string sources_filename="sources.txt";
//データのダウンロード
   sStream=DownLoad(BASE_URL+SRCE,sources_filename);

   if(sStream==NULL)
     {
      if(!::FileIsExist(sources_filename))
        {
         ::Print("error : required file does not exit");
         return(false);
        }
      //ファイルの内容の読み取り 
      hFile=::FileOpen(sources_filename,FILE_TXT|FILE_READ|FILE_UNICODE);
      if(hFile==INVALID_HANDLE)
        {
         ::Print("error opening file "+sources_filename);
         return(false);
        }

      while(!::FileIsEnding(hFile))
        {
         iStringSize = ::FileReadInteger(hFile, INT_VALUE);
         sStream    += ::FileReadString(hFile, iStringSize);
        }

      ::FileClose(hFile);
     }
//json データの解析  
   if(!srce.Deserialize(sStream))
     {
      ::Print("Json deserialize error");
      return(false);
     }
//ソースへの json オブジェクトの割り当て 
   if(srce["status"].ToStr()=="ok")
     {
      sources=srce["sources"];
      return(true);
     }
   else
     {
      Print("error json api access denied");
      return(false);
     }
  }

PrepareSources () は EA の初期化中に一度呼び出され、利用可能なニュースソースの API リクエストを行います。 このレスポンスはファイルに保存され、Json パーサーの逆シリアル化メソッドを使用して解析します。 ここから、json オブジェクトのソース配列がソースポインタに割り当てられます。 接続がなく、.txt ファイルがまだ作成されていない場合、EA は正常に初期化されません。

//+------------------------------------------------------------------+
//| downloads data to fill articles json object                      |
//+------------------------------------------------------------------+     
boolCNewsFeed::P reparearticles (int listview_index)
  {
   string sStream,id;
   int iStringSize,hFile;
//ソースを確認する json オブジェクト 
   if(sources==NULL)
     {
      ::Print("Invalid pointer access");
      return(false);
     }

//チェックインデックス 
   if(listview_index>=::ArraySize(sources.m_e))
     {
      Print("invalid array index reference");
      return(false);
     }
//参照元の配列要素への json オブジェクトの割り当て  
   sourcesArrayElement=sources[listview_index];
//ニュースソースの名前を取得する
   id=sourcesArrayElement["id"].ToStr();
//sourcesArrayElement json オブジェクトのリセット
   sourcesArrayElement=NULL;

//特定のニュースソースのデータをダウンロードする
   sStream=DownLoad(BASE_URL+ATCLE+id+API_KEY,id+".txt");
   if(sStream==NULL)
     {
      if(!::FileIsExist(id+".txt"))
        {
         ::Print("error : required file does not exit");
         return(false);
        }

      //json データファイルの読み取り 
      hFile=::FileOpen(id+".txt",FILE_TXT|FILE_READ|FILE_UNICODE);
      if(hFile==INVALID_HANDLE)
        {
         ::Print("error opening file "+id+".txt");
         return(false);
        }

      while(!::FileIsEnding(hFile))
        {
         iStringSize = ::FileReadInteger(hFile, INT_VALUE);
         sStream    += ::FileReadString(hFile, iStringSize);
        }

      ::FileClose(hFile);
     }

//json ファイルの解析
   if(!js.Deserialize(sStream))
     {
      ::Print("Json deserialize error");
      return(false);
     }
//アーティクルへの json オブジェクトの割り当てポインタ
   if(js["status"].ToStr()=="ok")
     {
      articles=js["articles"];
      return(true);
     }
   else
     {
      Print("error json api access denied");
      return(false);
     }
  }


PrepareArticles ()-この関数は、メインチャートイベントハンドラメソッドで使用されます。 テキストボックスに表示する前に、指定したニュースコンセントからニュースの API リクエストを作成します。 この関数に渡される整数値は、選択したリストビューアイテムのインデックスを表します。 このインデックスは、選択したニュースコンセントを識別するために使用されるため、適切な API リクエスト URL を構築できます。 このAPIレスポンスは、PrepareSources メソッドで処理されるのと同じメソッドで処理されます。

また、API リクエストが既存のファイルに対応している場合にのみ、説明したメソッドの両方が接続なしで機能することに注意してください。

テキストボックスの更新

次に、OnchartEvent メソッドについて見ていきましょう。 リストビューアイテムがクリックされると、最初にテキストボックスが自動的に先頭にスクロールされます。 新しいコンテンツが正しく表示されないようにするために必要です。 リストビューオブジェクト SelectedItemText () と SelectedItemIndex () のメソッドは、クリックされたリストビューアイテムの名前とインデックスを取得するために使用されます。この場合、選択したニュースコンセントの名前と、srce json オブジェクトのソース配列内のポジションを定義します。 この情報から、適切な URL を作成して、PrepareArtilces () メソッドを使用してニュースヘッドラインの API リクエストを作成することができます。 成功した場合、テキストボックスは最新のヘッドラインで更新され、それ以外の場合はテキストボックスにエラーメッセージが表示されます。

//+------------------------------------------------------------------+
//| Chart event handler                                              |
//+------------------------------------------------------------------+
void CNewsFeed::OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
//ニュースソースの1つが選択されている場合 (クリック)
   if(id==CHARTEVENT_CUSTOM+ON_CLICK_LIST_ITEM)
     {
      string nameofobject="";        //選択したニュースソースの名前
      int selected,asize,g;          //selected-選択されたリスト項目のインデックス、asize-記事の配列サイズ json オブジェクト配列、g-配列インデックス
      bool ar=false;                 //ar prepareArticles 法の戻り値
                                     //最初にテキストボックスの先頭にスクロール、垂直スクロールが必要な場合にのみ
      if(m_text_box.GetScrollVPointer().IsScroll())
         m_text_box.VerticalScrolling(0);
      //---
      nameofobject=m_listview.SelectedItemText();
      //---
      selected=m_listview.SelectedItemIndex();
      //--- 
      ar=PrepareArticles(selected);
      //---
      asize=(articles!=NULL)? ::ArraySize(articles.m_e):0;
      //テキストボックスの現在の内容を削除
      m_text_box.ClearTextBox();
      //新しいテキストボックスの内容に見出しを追加
      m_text_box.AddText(0,nameofobject+" Top HeadLines:");
      //PrepareArticles メソッドの成功に応じて、テキストボックスの内容が入力されます。
      if(asize>0 && ar)//PrepareArticles が成功した場合
        {
         string descrip,des;
         for(g=0; g<asize;g++)
           {
            //json オブジェクトをアーティクルの配列要素に設定します。
            articlesArrayElement=articles[g];
            //値を取得 
            des=articlesArrayElement["description"].ToStr();
            //空き時間に応じて、追加のテキストを表示するように設定する
            descrip=(des!="null" && des!="")? " -> "+des:".";
            //テキストボックスに新しいテキストを追加する 
            m_text_box.AddLine(string(g+1)+". "+articlesArrayElement["title"].ToStr()+descrip);
           }
        }
      else //PrepareArticles が成功しない場合
        {
         asize=1; //asize を1つに設定する
         for(g=0; g<asize;g++)
           {
            //テキストボックスにエラーメッセージを表示する
            m_text_box.AddLine("Error retrieving data from feed.");
           }
        }
      //--テキストボックスを再描画する      
      m_text_box.Update(true);
      //--アーティクルオブジェクトのリセット値
      articles=NULL;
      //Print("clicked listview item is "+nameofobject);
      return;
     }
  }

CNewsFeed クラスの定義を決済するので、EAに含めることができます。

NewsFeedProgram EA

このコードは、アプリケーションが実行されるときのようにどのように見えるかのスクリーンショットと一緒に下に表示されます。

//+------------------------------------------------------------------+
//|                                              NewsFeedExpert mq5 |
//|                                          Copyright 2017, ufranco |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, ufranco"
#property link      "https://www.mql5.com"
#property version   "1.00"
#include<NewsFeedProgram.mqh></NewsFeedProgram.mqh>
CNewsFeed program;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int()
  {

   if(!program.OnInitEvent())
     {
      ::Alert("Check your internet connection and set up the terminal \n"+
              "for Web requests");
      return(INIT_FAILED);
     }

//トレーディングパネルの設定
   if(!program.CreateGUI())
     {
      ::Print("Failed to create graphical interface!");
      return(INIT_FAILED);
     }
//---初期化の成功
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   program.OnDeinitEvent(reason);

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
   program.OnTimerEvent();
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
   program.ChartEvent(id,lparam,dparam,sparam);
  }

アプリケーションの最初の外観

ニュース表示


結論

この記事では、ニュース web API を使用してカスタムニュースフィードを作成する可能性を検討しました。 デモンストレーションの EA は非常に基本的であり、アプリが最新のニュースを表示できるように、自動更新関数を有効にすることによって利用することができます。 誰かの役に立つことを願っています。

EA が正しく動作するためには、GUI ライブラリをダウンロードしてください。 次に、この記事に添付されているテキストボックスの mqh ファイルを置き換えます。

この記事で使用されるプログラムとファイル

名前 
種別
詳細(Description)
JAson.mqh
ヘッダーファイル
Json のシリアライズと逆シリアル化ネイティブ MQL クラス
json.mqh
ヘッダーファイル
Json パーサークラス
TextBox.mqh
ヘッダーファイル
チャートに書式付きテキストを表示するための変更されたテキストボックスクラス
NewsFeedProgram.mqh
ヘッダーファイル
ニュースフィード EA のメインクラス
NewsFeedExpert.mq5
EAファイル
メインニュースフィードクラスを実装するEA
NewsAPI_test.mq5
スクリプトファイル
API 呼び出しをテストするためのスクリプト
newstest_JAson.mq5
スクリプトファイル
ジェイソンの関数にアクセスするためのスクリプトをテストします。 JAson.mqh ライブラリ
newstest_json.mq5
スクリプトファイル
json の関数にアクセスするためのスクリプトをテストします。 json.mqh ライブラリー

MetaQuotes Ltdにより英語から翻訳されました。
元の記事: https://www.mql5.com/en/articles/4149

添付されたファイル |
NewsFeedExpert.mq5 (2.48 KB)
NewsAPI_test.mq5 (2.52 KB)
NewsFeedProgram.mqh (35.64 KB)
TextBox.mqh (282.87 KB)
newstest_JAson.mq5 (2.03 KB)
newstest_json.mq5 (2.18 KB)
ビンスによる資金管理 MQL5 ウィザードのモジュールとしての実装 ビンスによる資金管理 MQL5 ウィザードのモジュールとしての実装
この記事は、ラルフ·ビンスによる "The Mathematics of Money Management" に基づいています。 トレードロットの最適なサイズを見つけるために使用される経験的およびパラメトリックメソッドの説明をします。 また、それらのメソッドに基づいて MQL5 ウィザードのトレーディングモジュールの実装を行います。
制御された最適化: シミュレーティットアニーリング 制御された最適化: シミュレーティットアニーリング
MetaTrader5トレーディングプラットフォームのストラテジーテスターは、パラメータと遺伝的アルゴリズムの完全な検索、つまり、2 つの最適化オプションのみを提供します。 この記事では、トレーディング戦略を最適化するための新しいメソッドを提案します (シミュレーティットアニーリング)。 このメソッドのアルゴリズム、実装、およびEAへの統合を考察します。 開発したアルゴリズムは移動平均 EA でテストします。
インジケーターの開発を依頼するための要件定義を作成する方法 インジケーターの開発を依頼するための要件定義を作成する方法
最もよくあるトレードシステムの開発の第一歩は、相場行動パターンを識別できるテクニカルインジケーターの作成です。 専門的に開発されたインジケーターを、フリーランスのサービスからオーダーすることができます。 この記事からは、適切な要件定義を作成する方法を学習します。より速く、希望のインジケーターを取得するのに役立ちます.
トレーダーのライフハック: インジケーターで作られたファストフード トレーダーのライフハック: インジケーターで作られたファストフード
MQL5 に新たに切り替えた場合、この記事は役に立つでしょう。 まず、インジケーターデータとシリーズへのアクセスは、通常の MQL4 スタイルで行われます。 次に、このシンプルさを MQL5 に実装します。 すべての関数は、可能な限り明確であり、ステップバイステップのデバッグに最適です。