<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter SYSTEM "gnc-gui-C.dtd">
<!-- (Do not remove this comment block.)
Version: 1.0.0
Last modified: August 08th 2021

Maintainers:
  xxx
Author:
  TANIGUCHI Yasuaki <yasuakit@gmail.com>
  Christian Wehling <christian.wehling@web.de>
Translators:
  (translators put your name and email here)
-->
<chapter id="finance-quote"
         xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Setting Up the Quote Retrieval</title>

  <abstract>
    <para>If you have more than a couple of commodities, you will tire of having to update their quotes
      constantly. &app; has the ability to automatically download the most recent quote for your
      commodities using the Internet. This is accomplished through the &app-perl; module &app-fq;,
      which must be installed in order to activate this feature.
    </para>
  </abstract>

  <itemizedlist>
    <title>Prerequisites for an Online Quote update with &app-fq; are</title>

    <listitem>
      <para>the &app-perl; language interpreter and
      </para>
    </listitem>

    <listitem>
      <para>the &app-perl;-module &app-fq; with any dependencies
      </para>
      <para>the &app-perl;-module JSON::Parse to manage the output of &app-fq;.
      </para>
    </listitem>
  </itemizedlist>

  <note>
    <para>If you get stuck while performing the steps described here, you can reach many helpful users on the
      channels mentioned under <xref linkend="more_help" />.
    </para>
  </note>

  <para>You can also leave out this step and manually update your stock quotes.
  </para>

  <sect1 id="finance-quote-perl-install">
    <title>Installing &app-perl;</title>

    <abstract>
      <para>The installation of &app-perl; is essentially dependent on the operating system used. The effort for
        installation is low and is described in this section.
      </para>
    </abstract>

    <para>To check if &app-perl; is already installed on your system, call the command
      <userinput>perl -v</userinput> in the terminal.
<!-- Fixme: https://bugs.gnucash.org/show_bug.cgi?id=798618 -->
    <informalexample><?dbfo pgwide="1"?>
<screen language="console">$ perl -v
This is perl 5, version 30, subversion 0 (v5.30.0) built for x86_64-linux-gnu-thread-multi
</screen>
    </informalexample>
      If you are shown the version number of the &app-perl; interpreter, skip the next details
      and continue instead with <xref linkend="finance-quote-install" />.
    </para>

    <procedure>
      <title>On &lin;</title>

      <step>
        <para>On most systems &app-perl; is probably already installed. If with the previous command does not show
          a version, then the easiest way is to use your system&rsquo;s package manager for installation.
        </para>
      </step>

      <step>
        <para>When using the &app; &flatpak; package, &app-perl; and &app-fq; are already functionally installed.
        </para>
      </step>
    </procedure>

    <procedure>
      <title>On &mac;</title>

      <step>
        <para>&app-perl; is normally already set up under &mac;.
        </para>
      </step>
    </procedure>

    <procedure>
      <title>On &win;</title>

      <step>
        <para>Under &win; run the program &gmi.winOS.inst-fq; to run. This will
          install <ulink url="&url-wp-en;Strawberry_Perl">Strawberry Perl</ulink>.
          <footnote>
            <para>&app; Version 2.2.6 and before require <ulink url="&url-wp-en;ActivePerl">ActivePerl</ulink>. in
              version 5.8.
            </para>
          </footnote>

          <footnote>
            <para>&app; Version 2.4 and before require <ulink url="&url-wp-en;ActivePerl">ActivePerl</ulink> Version
              5.16.3 and later.
            </para>
          </footnote>
        </para>
      </step>

      <step>
        <para>For execution you need <emphasis>Administrator privilegies</emphasis>, which are requested in the
          dialog. The installation can take more then 15 minutes.
        </para>
      </step>

      <step>
        <para>If during the installation the error message <computeroutput>No such file or directory
          </computeroutput> or <computeroutput>permission denied</computeroutput> are displayed,
          then it may help to disable the antivirus software temporarily.
        </para>
      </step>
    </procedure>

    <tip>
      <para>Afterwards it&rsquo;s a good idea to include the folder where &app; is installed,
        under &win; e.g. <userinput><replaceable>C:\Program Files (x86)\gnucash\bin</replaceable></userinput>,
        to your <envar>PATH</envar> environment variable.
        This way it&rsquo;s easier for you to use some <xref linkend="fq-command-line" /> when needed.
        Please refer to the documentation for your operating system for more information.
      </para>
    </tip>
  </sect1>

  <sect1 id="finance-quote-install">
    <title>Installing &app-fq;</title>

    <para>To determine if the &app-perl; module &app-fq; is already installed on your system, type
      <userinput>perldoc Finance::Quote</userinput> in a terminal window and check to see if there is
      any documentation
<!-- Fixme: https://bugs.gnucash.org/show_bug.cgi?id=798618 -->
    <informalexample><?dbfo pgwide="1"?>
<screen language="console">
$ perldoc Finance::Quote
NAME
    Finance::Quote - Get stock and mutual fund quotes from various exchanges

SYNOPSIS
       [...]
</screen>
    </informalexample>
      available. If you are now shown documentation, then &app-fq; is already installed and you can
      configure periodical quotes update as described in <xref linkend="fq-auto-quote" />.
      If no documentation is displayed, you will have to continue with this chapter.
    </para>

    <para>The process of installing &app-fq; depends on the system. For the different supported systems, you
      can follow the instructions below:
    </para>

    <procedure>
      <title>On &lin;</title>

      <step>
        <simpara>Close &app;.
        </simpara>
      </step>

      <step>
        <simpara>Run the <userinput>gnucash-cli --quotes info</userinput> command to verify that the program is already in a directory
          that is entered in the <envar>PATH</envar> environment variable.
          <footnote>
            <simpara>If you&rsquo;ve installed &app; packages provided by your distribution,
              <filename>gnucash-cli</filename> must be on your <envar>PATH</envar>. The currentness of your
              distribution can be checked under
              <ulink url="&url-repo;perl:finance-quote/versions"><citetitle>&app-fq;-
              versions</citetitle></ulink>.
            </simpara>
          </footnote>
        </simpara>
      </step>

      <step>
        <simpara>Next, update &app-fq; with <userinput>sudo gnc-fq-update</userinput>.
        </simpara>
      </step>

      <step>
        <simpara>Run <userinput>gnucash-cli --quotes info</userinput> to check &app-fq; works properly. This command returns the
          version number of &app-fq; module currently installed as well as a list of sources
          available via the &app-fq; module. It will also inform you if there is a problem with your
          installation or if it is missing, and may suggest a fix.
        </simpara>
      </step>
    </procedure>

    <procedure>
      <title>On &mac;</title>
      <note><para>You must be logged in with a user id that can administer the mac to use this procedure.</para></note>
      <step>
        <simpara>Close &app;.
        </simpara>
      </step>

      <step>
        <simpara>Install &app-xcode;
          <footnote>
            <para>You can install &app-xcode; from the App Store or install the
              much smaller Xcode command line tools by running <userinput>
              sudo xcode-select --install</userinput> from a Terminal.app prompt.
            </para>
          </footnote>
         if it is not installed. It contains devel tools, which are required
         by CPAN to build and test the needed &app-fq; modules.
        </simpara>
      </step>

      <step>
        <simpara>Open a Finder window, select <guimenu>Applications</guimenu> from the sidebar, double-click <guimenu>Utilities</guimenu> in the file area, then double-click on <guimenu>Terminal</guimenu> to open <application>Terminal</application></simpara>
      </step>
      <step>
        <simpara>In the Terminal window enter <userinput>sudo /Applications/Gnucash.app/Contents/Resources/bin/gnc-fq-update</userinput>. That script asks lots of questions. Accept the default for each.
        </simpara>
      </step>
      <step>
        <simpara>Type <userinput>exit</userinput> or <keycombo action='simul'><keycap>Control</keycap><keycap>D</keycap></keycombo> to terminate the shell followed by <keycombo action='simul'><keycap>Command</keycap><keycap>Q</keycap></keycombo> to quit <application>Terminal</application>.
        </simpara>
      </step>
    </procedure>

    <procedure>
      <title>On &win;</title>

      <step>
        <simpara>Close &app;.
        </simpara>
      </step>

      <step>
        <simpara>Run &gmi.winOS.inst-fq;. This is a small utility that installs &app-fq; for you.
        </simpara>
      </step>
    </procedure>
  </sect1>

  <sect1 id="fq-command-line">
    <title>Using &app-cli; for Testing and Automation.</title>

    <abstract>
      <para>&app; provides a commandline facility &app-cli; that one can use in a terminal session to check the version and supported source modules, to display the quotes or exchange rates for selected securities or currencies, or to update all of the prices in a book without launching the GUI.
      </para>
    </abstract>
    <sect2 id="fq-check-version">
      <title>Displaying the Finance::Quote Version and Supported Sources</title>
      <para><command>gnucash-cli --quotes info</command> produces the following output:</para>
      <!-- Fixme: https://bugs.gnucash.org/show_bug.cgi?id=798618 -->
      <informalexample><?dbfo pgwide="1"?>
      <screen language="console">
  $ gnucash-cli --quotes info
  Found Finance::Quote version 1.52.
  Finance::Quote sources:
  aex          alphavantage              amfiindia    asegr        asx
  aufunds      australia    bamosz       bet          bloomberg    bourso
  bse          bseindia     canada       canadamutual              comdirect
  cse          deka         dutch        dwsfunds     europe
  fetch_live_currencies     fidelity     fidelity_direct
  finanzpartner             fondsweb     fool         ftfunds      fundata
  fundlibrary  goldmoney    greece       hu           hufund       hungary
  hustock      iexcloud     india        indiamutual  known_currencies
  morningstarau             morningstarch             morningstarjp
  mstaruk      nasdaq       nseindia     nyse         nzx          onvista
  oslobors     romania      seb_funds    six          tesouro_direto
  tiaacref     tmx          tradeville   troweprice   troweprice_direct
  tsp          ukfunds      unionfunds   usa          usfedbonds   yahoo_json
  za
      </screen></informalexample>
      <para>If there's a problem with your installation it will tell you about it. For example in this case we're missing the Perl modules Finance::Quote and JSON::Parse:</para>
      <informalexample><?dbfo pgwide="1"?>
      <screen language="console">
  $ gnucash-cli --quotes info
  Failed to initialize Finance::Quote: missing_modules Finance::Quote JSON::Parse
      </screen></informalexample>
    </sect2>

    <sect2 id="fq-print-quotes">
      <title>Displaying Quotes in a Terminal Window</title>
      <para>To display a quote for one or more stocks or the exchange rate for one or more currencies you can use <userinput>gnucash-cli --quotes dump</userinput> as follows. It offers two output forms for non-currency securities and one for currency exchange rates.
      <itemizedlist>
        <listitem><para>Currencies use the source <userinput>currency</userinput> and require at least two ISO-4217 currency codes; the exchange rates are denominated in the first code. For example:
      <informalexample><?dbfo pgwide="1"?>
      <screen language="console">
        $ gnucash-cli --quotes dump currency USD GBP EUR
        1 GBP = 1.11917349089527 USD

        1 EUR = 0.9717 USD
      </screen></informalexample></para></listitem>
      <listitem><para>Stocks</para><itemizedlist>
      <listitem><para>A short form displaying only the fields that GnuCash uses along with comments indicating whether the fields are optional or required; you can use this to determine if GnuCash will be able to use the quote to update your book's price database.
      <informalexample><?dbfo pgwide="1"?>
      <screen language="console">
        $ gnucash-cli --quotes dump yahoo_json AAPL
        Finance::Quote fields GnuCash uses:
            symbol: AAPL            &lt;=== required
              date: 10/14/2022      &lt;=== recommended
          currency: USD             &lt;=== required
              last: 138.38          &lt;=\
               nav:                 &lt;=== one of these
             price:                 &lt;=/
      </screen></informalexample></para></listitem>
      <listitem><para>With the <userinput>-v</userinput> option a possibly longer output showing all of the fields &app-fq; returned. This can be useful to troubleshoot problems with a &app-fq; source module.
      <informalexample><?dbfo pgwide="1"?>
      <screen language="console">
        $ ALPHAVANTAGE_API_KEY=123456789 bin/gnucash-cli -V --quotes dump alphavantage INTC
        INTC:
                     method =&gt; alphavantage
                   p_change =&gt; -1.9304
                       high =&gt; 26.6300
                       date =&gt; 10/14/2022
         currency_set_by_fq =&gt; 1
                      close =&gt; 26.4200
                   currency =&gt; USD
                    isodate =&gt; 2022-10-14
                        low =&gt; 25.7600
                    success =&gt; 1
                        net =&gt; -0.5100
                       open =&gt; 26.4600
                     symbol =&gt; INTC
                     volume =&gt; 48118005
                       last =&gt; 25.9100
      </screen></informalexample>
      Notice that in this case we used alphavantage and provided the <userinput>ALPHAVANTAGE_API_KEY</userinput> on the command line. That's not necessary if the key is already stored in the shell environment or in GnuCash preferences.</para>
      </listitem></itemizedlist></listitem>
      </itemizedlist>
      </para></sect2>
    <sect2 id="fq-auto-quote">
      <title>Updating Prices Automatically with &app-cli;</title>
    <para>You have to register the &app-cli; with a scheduler in order to get Online
      Quotes automatically and periodically. The method depends on your OS.
    </para>

    <example>
      <title>Automated quote retrieval every Friday at 4:00 p.m.</title>

      <procedure>
        <title>On &lin; and &mac;</title>

        <para>Register <command>gnucash-cli</command> with <application>cron</application>.
        </para>

        <step>
          <simpara>Run <command>crontab -e</command>.
          </simpara>
        </step>

        <step>
          <para>Add the following line to your crontab:
            <informalexample>
<screen>0 16 * * 5 gnucash-cli --quotes get &user-datafile; &gt; /dev/null 2&gt;&amp;1</screen>
            </informalexample>

            <important>
              <para>On &lin; if there is no graphic session that has already started the dbus, running on your computer at the
                time of the quote request, you must do the entry as follows instead:
                <informalexample>
<screen>0 16 * * 5 env `dbus-launch` sh -c 'trap "kill $DBUS_SESSION_BUS_PID" EXIT;
gnucash-cli --quotes get &user-datafile; &gt; /dev/null 2&gt;&amp;1</screen>
                </informalexample>
                (Do not copy the line breaks into the crontab, they were inserted here only for the
                purpose of readability).
              </para>
            </important>
          </para>
        </step>
      </procedure>

      <procedure>
        <title>On &win;</title>

        <para>Register <command>gnucash-cli</command> with Task Scheduler.
        </para>

        <step>
          <simpara>Select
            <menuchoice>
              <guimenu>Start</guimenu><guisubmenu>Windows Administrative
              Tools</guisubmenu><guimenuitem>Task Scheduler</guimenuitem>
            </menuchoice>
            .
          </simpara>
        </step>

        <step>
          <simpara>Select <guimenuitem>Create Task</guimenuitem>.
          </simpara>
        </step>

        <step>
          <simpara>Enter the appropirate items on <guilabel>Create Task</guilabel> Window.
          </simpara>
        </step>
      </procedure>

      <para>Adjust the time to the close of the stock exchange and consider <emphasis>fund quotes</emphasis>,
        that the net asset value (NAV) is determined well after the markets closed. The types have
        their description in <xref linkend="tool-price" />.
<!-- FIXME: adjust the link to a proper ID -->
      </para>
    </example>

    <para>Some users have made additions to the wiki and shared their experiences on the
      <ulink url="&url-wiki-OQ;#Updating_enabled_Quotes_from_outside_GnuCash">Online Quotes Page on
      GnuCash Wiki</ulink>.
    </para>
    </sect2>
  </sect1>
</chapter>
