<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Hacking &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/hacking/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Wed, 31 Jan 2024 10:07:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://financial-hacker.com/wp-content/uploads/2017/07/cropped-mask-32x32.jpg</url>
	<title>Hacking &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Trading with REST</title>
		<link>https://financial-hacker.com/crypto-trading-with-rest-part-1/</link>
					<comments>https://financial-hacker.com/crypto-trading-with-rest-part-1/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 17 Oct 2022 11:16:41 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Bittrex]]></category>
		<category><![CDATA[Broker]]></category>
		<category><![CDATA[Hacking]]></category>
		<guid isPermaLink="false">https://financial-hacker.com/?p=4517</guid>

					<description><![CDATA[Many brokers and exchanges can nowadays be accessed online with a REST API that communicates with plain-text HTTP requests. The days of awkward proprietary broker APIs are coming to an end. This article is a step by step instruction of implementating a REST API interface in C for connecting a trading system to the Bittrex &#8230; <a href="https://financial-hacker.com/crypto-trading-with-rest-part-1/" class="more-link">Continue reading<span class="screen-reader-text"> "Trading with REST"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>Many brokers and exchanges can nowadays be accessed online with a REST API that communicates with plain-text HTTP requests. The days of <a href="https://financial-hacker.com/dear-brokers/" target="_blank" rel="noopener">awkward proprietary broker APIs</a> are coming to an end. This article is a step by step instruction of implementating a REST API interface in C for connecting a trading system to the <a href="https://global.bittrex.com/" target="_blank" rel="noopener">Bittrex cryptocurrency exchange.</a> It&#8217;s for the <a href="https://zorro-project.com" target="_blank" rel="noopener">Zorro platform</a>, but the principles are also valid for other exchanges and platforms. The C code for a basic REST API implementation is relatively short and straightforward. <span id="more-4517"></span></p>
<p> For connecting the Zorro platform to a particular broker API, a DLL must be dropped in its Plugin folder. The DLL is then automatically recognized and appears in Zorro&#8217;s Broker selection box. For trading with the broker, the DLL exports functions for getting prices and sending orders. These functions are standardized and described in the <a href="https://zorro-project.com/manual/en/brokerplugin.htm" target="_blank" rel="noopener">Zorro manual</a>. They are the same for all brokers. The following 4 functions are the most important:</p>
<p><strong>BrokerOpen</strong> &#8211; identify the DLL.<br /><strong>BrokerLogin</strong> &#8211; initialize and store login credentials.<br /><strong>BrokerAsset</strong> &#8211; retrieve price and other parameters of an asset.<br /><strong>BrokerBuy2</strong> &#8211; send a buy or sell order.</p>
<p>These four are sufficient for running most trading strategies. The DLL can export additional functions that are useful, but not mandatory, since Zorro works around them when they are not implemented:</p>
<p><strong>BrokerAccount</strong> -get the account state.<br /><strong>BrokerTrade</strong> &#8211; get the trade or order state.<br /><strong>BrokerHistory2</strong> -get price history.<br /><strong>BrokerCommand</strong> &#8211; set special modes, get order book, etc.</p>
<p>Zorro users have written DLLs for several broker APIs, but the code is often redundant and invents the wheel many times again. I&#8217;ll give here an example of a relatively lean broker DLL that can be used as template for individual REST API implementations. Bittrex is a US based digital currency exchange that supports several hundred crypto currencies and provides free API access. We&#8217;re first going to implement the 4 mandatory functions, following the API description on the Bittrex website:</p>
<p><a href="https://bittrex.github.io/api/v3" target="_blank" rel="noopener">https://bittrex.github.io/api/v3</a></p>
<p>We will use the free Visual C++ Community Edition from Microsoft. Aside from the exported functions, we need some internal functions to print messages, send HTTP requests, parse a JSON response, and generate a digital signature. For all this there&#8217;s ready code available on the Internet, but there are also ready functions in Zorro&#8217;s library. To make life easier, we simply import the <a href="https://zorro-project.com/manual/en/funclist.htm" target="_blank" rel="noopener">Zorro function library</a> to the DLL. The VC++ setup for generating such a DLL is described here:</p>
<p><a href="https://zorro-project.com/manual/en/dlls.htm#project" target="_blank" rel="noopener">https://zorro-project.com/manual/en/dlls.htm</a></p>
<p>The setup is for a C++ trading strategy, but works as well for a broker API DLL. First we&#8217;re going to implement the adminstrative stuff, the <strong>BrokerOpen</strong> and <strong>BrokerLogin</strong> functions:</p>
<pre class="prettyprint">#define PLUGIN_TYPE 2<br />#define PLUGIN_NAME "Bittrex V3"<br />#define DLLFUNC extern "C" __declspec(dllexport)<br /><br />int (__cdecl *BrokerMessage)(const char *Text);<br />int (__cdecl *BrokerProgress)(const int Progress);<br />...<br /><br />DLLFUNC int BrokerOpen(char* Name,FARPROC fpMessage,FARPROC fpProgress)<br />{<br />  strcpy_s(Name,32,PLUGIN_NAME);<br />  (FARPROC&amp;)BrokerMessage = fpMessage;<br />  (FARPROC&amp;)BrokerProgress = fpProgress;<br />  return PLUGIN_TYPE;<br />}</pre>
<p>The <strong>BrokerOpen</strong> function is Zorro specific. It sets up two function pointers for printing message and sending heartbeats to Zorro. It&#8217;s needed for recognizing the DLL in the <strong>Plugin</strong> folder and letting the plugin name, &#8220;Bittrex V3&#8221;, appear in the broker scrollbox. </p>
<p>Next we need the login function that&#8217;s called at the begin and the end of any algo trading session</p>
<pre class="prettyprint">struct GLOBAL {<br />  int PriceType,VolType,OrderType;<br />  double Unit; // smallest trade unit<br />  char Path[256]; // send path buffer<br />  char Key[256],Secret[256]; // credentials<br />  char Symbol[64],Uuid[256]; // last trade symbol and UUID<br />  char AccountId[16]; // account currency<br />} G; // parameter singleton<br />...<br /><br />DLLFUNC int BrokerLogin(char* User,char* Pwd,char* Type,char* Accounts)<br />{<br />  if(User) { // login<br />    memset(&amp;G,0,sizeof(G));<br />    strcpy_s(G.Key,User);<br />    strcpy_s(G.Secret,Pwd);<br />    return 1;<br />  } else  // logout<br />    return 0;<br />}</pre>
<p>This function only sets up the <strong>G</strong> struct, a singleton that holds all global variables of the DLL. The <strong>User</strong> and <strong>Pwd</strong> arguments contain the Bittrex key and secret. They are taken from the Zorro login fields or from the account list. <strong>Type</strong> is the account type, ignored here because Bittrex has no demo accounts.  <strong>Account</strong> is the account identifier and also ignored since we&#8217;re not using sub-accounts.</p>
<p>Next comes the function to retrieve prices and other parameters of a particular cryptocurrency. It&#8217;s a bit more complex and requires a HTTP request to the API. Some requests require authentication, some not. For all this we first implement a <strong>send()</strong> function in the DLL that uses Zorro&#8217;s functions for sending <a href="https://zorro-project.com/manual/en/http.htm" target="_blank" rel="noopener">http requests</a> and generating a <a href="https://zorro-project.com/manual/en/hmac.htm" target="_blank" rel="noopener">HMAC signature</a>. The authentication method by the Bittrex REST API V3 is a bit complex:</p>
<p><em>To properly sign an authenticated request for the Bittrex v3 API, the following headers must be included: Api-Key, Api-Timestamp, Api-Content-Hash, Api-Signature. <span style="font-size: revert;">Api-Timestamp is </span>the current time as a UNIX timestamp in epoch-millisecond format. <span style="font-size: revert;">Api-Content-Hash </span>is a SHA512 hash of the request body, Hex-encoded (with no request body, a SHA512 hash of an empty string). For creating the Api-Signature, first generate a string by concatenating the following items: Contents of the Api-Timestamp header; the full URI used to make the request, including query string; the HTTP method of the request, in all caps (GET, POST, DELETE, etc.); Contents of the Api-Content-Hash header. Sign this string via HmacSHA512, using the API secret as the signing secret. Hex-encode the result and populate the Api-Signature header with it.</em></p>
<p>This is the implementation:</p>
<pre class="prettyprint">#define RHEADER "https://api.bittrex.com/v3/"<br />...<br /><br />int sleep(int ms)<br />{<br />  Sleep(ms); <br />  return BrokerProgress(0);<br />}<br /><br />char* send(const char* Url,<br />  int Mode = 0,<br />  const char* Method = NULL,<br />  const char* Body = NULL)
{
  static char Url[1024], Header[2048], Signature[1024],
    Buffer1[1024*1024], Buffer2[2048];
  *Signature = *Header = 0;
  sprintf_s(Url,"%s%s",RHEADER,Url);
  if (Mode &amp; 1) { // Authentication required
    strcpy_s(Header, "Content-Type:application/json");
    strcat_s(Header, "\nAccept:application/json");
    strcat_s(Header, "\nApi-Key: ");
    strcat_s(Header,G.Key);
    strcat_s(Header, "\nApi-Timestamp: ");
    __time64_t Time; _time64(&amp;Time);
    static __time64_t Offset = 0;
    char* TimeStamp = i64toa(Time*1000 + Offset++); 
    strcat_s(Header, TimeStamp);
    strcat_s(Header, "\nApi-Content-Hash: ");
    char* Hash = hmac(Body, 0, 0, 512);
    strcat_s(Header,Hash);
    strcpy_s(Signature, TimeStamp);
    strcat_s(Signature, Url);
    if(Method &amp;&amp; *Method)
      strcat_s(Signature, Method);
    else if(!Body)
      strcat_s(Signature,"GET");
    else
      strcat_s(Signature,"POST");
    strcat_s(Signature, Hash);
    strcat_s(Header, "\nApi-Signature: ");
    strcat_s(Header, hmac(Signature, 0, G.Secret, 512));
  }

  char* Response = Mode &amp; 2? Buffer2 : Buffer1;<br />  int MaxSize = Mode &amp; 2? sizeof(Buffer2) : sizeof(Buffer1);<br />  int Id = http_request(Url,Body,Header,Method);
  if(!Id) goto send_error;
// wait 30 seconds for the server to reply
  int Size = 0, Wait = 3000;  
  while (!(Size = http_status(Id)) &amp;&amp; --Wait &gt; 0)
    if(!sleep(10)) goto send_error;
  if (!Size) goto send_error;
  if(!http_result(Id,Response,MaxSize)) goto send_error;
  Response[MaxSize-1] = 0; // prevent buffer overrun
  http_free(Id);
  return Response;
<br />// transfer unsuccessful?
send_error:
  if(Id) http_free(Id);
  return NULL;
}
</pre>
<p>The above code adds an authentication header with signature when <strong>Mode</strong> == 1. <strong>Mode == 2</strong> selects a second, smaller response buffer and thus allows to evaluate two API responses at the same time. The <strong>sleep</strong> function generates a delay with a heartbeat to keep the Zorro window responsive during long requests. If it returns <strong>0</strong>, someone has hit Zorro&#8217;s [Stop] key and all operations should be aborted. The Windows <strong>_time64</strong> function has only 1-second resolution, so we add an incremented <strong>Offset</strong> for generating unique timestamps.</p>
<p>We&#8217;re now prepared to implement the <strong>BrokerAsset</strong> function:</p>
<pre class="prettyprint">double fixAmount(double Value)<br />{<br />  int Exp = log10(Value);<br />  if (Exp &gt;= 0) Exp++;<br />  return pow(10,Exp);<br />}<br /><br />DLLFUNC int BrokerAsset(char* Symbol,double* pPrice,double* pSpread,<br />double *pVolume, double *pPip, double *pPipCost, double *pMinAmount,<br />double *pMargin, double *pRollLong, double *pRollShort, double *pCommission)<br />{<br />  sprintf_s(G.Url,"markets/%s/ticker",fixSymbol(Symbol));<br />  char* Response = send(G.Url,2);<br />  if(!Response) return 0;<br />  double Bid = strvar(Response, "bidRate", 0.),<br />    Ask = strvar(Response,"askRate",0.);<br />  if (Ask &gt; 0. Bid &gt; 0. &amp;&amp; pSpread) <br />    *pSpread = Ask - Bid;<br />  double Last = strvar(Response, "lastTradeRate", 0.);<br />  if(Ask == 0. || G.PriceType == 2) <br />    Ask = Last;<br />  if (Ask == 0.) return 0; // symbol does not exist<br />  if(pPrice) *pPrice = Ask;<br />  if(pVolume) {<br />    sprintf_s(G.Url,"markets/%s/summary",fixSymbol(Symbol));<br />    Response = send(G.Url,2);<br />    if (Response) {<br />      if (G.VolType == 4)<br />        *pVolume = strvar(Response, "volume", 0);<br />    else<br />        *pVolume = strvar(Response, "quoteVolume", 0);<br />    }<br />  }<br />  if (pMinAmount) { // get lot amount<br />    sprintf_s(G.Url,"markets/%s",fixSymbol(Symbol));<br />    Response = send(G.Url,2);<br />    if (Response) {<br />      *pMinAmount = fixAmount(strvar(Response,"minTradeSize",0.000001));<br />      if (pPip) {<br />        int Exp = strvar(Response,"precision",8);<br />        *pPip = pow(10,-Exp); <br />        while (*pPip * *pMinAmount &lt; 0.000000001)<br />         *pPip *= 10; // avoid too small pip cost<br />        if (pPipCost)<br />          *pPipCost = *pPip * *pMinAmount;<br />      }<br />    }<br />  }<br />  if (pMargin) <br />    *pMargin = -100; // no leverage<br />  return 1;<br />} </pre>
<p>This function is supposed to return current price, current ask-bid spread, and current volume. It can also optionally request other asset specific parameters when available from the API. Otherwise Zorro will replace them with parameter values from the asset list. Broker APIs rarely provide all requested parameters. Make sure to only calculate and fill a parameter when its pointer passed to the function is nonzero. Most of the pointers are NULL most of the time.</p>
<p>The <strong>send</strong> function uses the second buffer because we&#8217;ll need price requests internally for calculating the account state. For getting lot amount, pip size, and pip cost, two more API requests are needed. The values from the response string are parsed with Zorro&#8217;s <strong>strvar</strong> function. The <strong>fixAmount</strong> function converts a value to its next-higher power of 10 &#8211; for instance, 7 is converted to 10 and 0.07 to 0.1. We&#8217;re doing this because we don&#8217;t want a strange number for the lot amount. The pip size is calculated from the precision, but we prevent it from going too small. Bittrex has no leverage, so the margin cost is always 100%.    </p>
<p>The next and final function sends an order to the API:</p>
<pre class="prettyprint">DLLFUNC int BrokerBuy2(char* Symbol,int Volume,double StopDist,double Limit,double *pPrice,int *pFill)<br />{<br />  if(!isConnected() || !Volume) return 0;<br /><br />// compose the body<br />  char Body[256] = "{\n";<br />  strcat_s(Body,"\"marketsymbol\": \"");<br />  strcat_s(Body,fixSymbol(Symbol));<br />  strcat_s(Body,"\",\n\"direction\": \"");<br />  strcat_s(Body,Volume &gt; 0? "BUY" : "SELL");<br />  strcat_s(Body,"\",\n\"type\": \"");<br />  strcat_s(Body,Limit &gt; 0. ? "LIMIT" : "MARKET");<br />  strcat_s(Body,"\",\n\"quantity\": \"");<br />  double Size = labs(Volume);<br />  if(G.Amount &lt; 1.) Size *= G.Amount;<br />  strcat_s(Body,ftoa(Size));<br />  if (Limit &gt; 0.) {<br />    strcat_s(Body,"\",\n\"limit\": \"");<br />    strcat_s(Body,ftoa(Limit));<br />  }<br />  strcat_s(Body,"\",\n\"timeInForce\": \"");<br />  if ((G.OrderType&amp;2) &amp;&amp; Limit &gt; 0.) <br />    strcat_s(Body,"GOOD_TIL_CANCELLED"); // limit orders only<br />  else if (G.OrderType&amp;1) <br />    strcat_s(Body,"FILL_OR_KILL"); // fill all or nothing<br />  else <br />    strcat_s(Body,"IMMEDIATE_OR_CANCEL");<br />  strcat_s(Body,"\"\n}");<br /><br />  char* Response = send("orders",1,0,Body);<br />  if(!Response) return 0;<br /><br />  char* Uuid = strtext(Response,"id","");<br />  if(!*Uuid) return 0; // failed<br />  strcpy(G.Uuid,Uuid);<br />  double Filled = strvar(Response,"fillQuantity",0);<br />  if(Filled == 0. &amp;&amp; !(G.OrderType&amp;2))<br />    return 0; // unfilled FOK/IOC order<br />  double Price = strvar(Response,"proceeds",0);<br />  if (Filled &gt; 0. &amp;&amp; Price &gt; 0. &amp;&amp; pPrice)<br />    *pPrice = Price/Filled;<br />  if (*pFill) *pFill = Filled/min(1.,G.Unit);<br />  return -1; <br />}</pre>
<p>The function first composes a message body in this JSON format (example):</p>
<pre>{<br /><span class="hljs-attr">  "marketSymbol"</span>: <span class="hljs-string">"ETH/BTC"</span>,<br /><span class="hljs-attr">  "direction"</span>: <span class="hljs-string">"BUY"</span>,<br /><span class="hljs-attr">  "type"</span>: <span class="hljs-string">"LIMIT"</span>,<br /><span class="hljs-attr">  "quantity"</span>: <span class="hljs-string">"0.1"</span>,<br /><span class="hljs-attr">  "limit"</span>: "0.008<span class="hljs-string">"</span>,<br /><span class="hljs-attr">  "timeInForce"</span>: "IMMEDIATE_OR_CANCEL<span class="hljs-string">"</span><br />}</pre>
<p>If the order is accepted, the response has this JSON format:</p>
<pre>{<br />  "id": "12345-6789-007-4711",<br />  "marketSymbol": "ETH/BTC",<br />  "direction": "BUY",<br />  "type": "LIMIT",<br />  "quantity": "0.1",<br />  "limit": "0.008",<br />  "timeInForce": "IMMEDIATE_OR_CANCEL",<br />  "fillQuantity": "0.05",<br />  "commission": "0.000002",<br />  "proceeds": "0.00001",<br />  "status": "<span class="json-property-enum" title="Possible values"><span class="json-property-enum-item">CLOSED</span></span>"<br />}</pre>
<p>The relevant fields, especially the id, the fill amount, and the fill price, are parsed from the response and returned. The return value <strong>-1</strong> indicates to Zorro that the order generated no identifer number, but an UUID. It was stored and can be retrieved with a subsequent command. <strong>G.Unit </strong>is the lot amount that was generated with the previous <strong>BrokerAsset</strong> call. </p>
<p>The remaining functions not described here &#8211; <strong>BrokerTrade</strong>, <strong>BrokerAccount</strong>, <strong>BrokerHistory2</strong>, and <strong>BrokerCommand</strong> &#8211;  are implemented in a similar way. You can find them in the full source code in the <strong>Source</strong> folder of the latest Zorro version. </p>
<p><strong>Update, November 2023:</strong> Bittrex recently announced that they will terminate their operation. So the Bittrex API plugin described herein lost its purpose, but you can still use the code as a template for connecting Zorro to any other broker or crypto exchange APIs &#8211; at least as long as they remain operational.  </p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/crypto-trading-with-rest-part-1/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Dear Brokers&#8230;</title>
		<link>https://financial-hacker.com/dear-brokers/</link>
					<comments>https://financial-hacker.com/dear-brokers/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 04 Jan 2016 14:02:11 +0000</pubDate>
				<category><![CDATA[No Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Broker]]></category>
		<category><![CDATA[Hacking]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=1169</guid>

					<description><![CDATA[Whatever software we&#8217;re using for automated trading: We all need some broker connection for the algorithm to receive price quotes and place trades. Seemingly a simple task. And almost any broker supports it through a protocol such as FIX, through an automated platform such as MT4™, or through a specific broker API. But if you &#8230; <a href="https://financial-hacker.com/dear-brokers/" class="more-link">Continue reading<span class="screen-reader-text"> "Dear Brokers&#8230;"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Whatever software we&#8217;re using for automated trading: We all need <strong>some broker connection</strong> for the algorithm to receive price quotes and place trades. Seemingly a simple task. And almost any broker supports it through a protocol such as FIX, through an automated platform such as MT4<img src="https://s.w.org/images/core/emoji/15.0.3/72x72/2122.png" alt="™" class="wp-smiley" style="height: 1em; max-height: 1em;" />, or through a specific broker API. But if you think you can quickly hook up your trading software to a broker API, you&#8217;re up for a bad surprise. Dear brokers &#8211; please read this post and try to make hacker&#8217;s and coder&#8217;s lifes a little easier!<span id="more-1169"></span></p>
<p>A broker API allows software to trade, receive price quotes, and download price history. Those three functions are essential for an automated system. Good-to-have additional features are retrieving trade status, account status, and asset parameters. That&#8217;s six functions, or seven when you count login/logout. A broker API has often more than 100 functions. So you should assume that at least the 6 essential are more than covered. But sadly, it is not so. The debacle begins already with installing and starting up the API. </p>
<h3>API startup</h3>
<p>Installing and starting a broker API can be so simple. The ideal case is a broker that provides no software at all, but just a protocol and a URL for a TCP/IP or UDP connection. You can then use well-established libraries such as curl or enet for connecting to the broker. In the second-best case you get an API DLL that you can redistribute to your clients. Your software then just calls the login function of that DLL, submits the authentification data and the connection is established. But for some unknown reason, many brokers feel obliged to provide connections to their APIs in much more complex and creative ways.</p>
<p><strong>Broker A</strong> required any user to run an API installation package. After an installation dialogue with several Windows incompatibility warnings, the installer produced a bunch of DLLs. Then you can go through a lengthy procedure with many steps of building up all the internal tables and data structures that you need for connecting to your account. In a previous version, the installer also modified the Registry, so you could not step around it and distribute the DLLs directly to your clients together with your software. They had to go through the installation procedure themselves. This is fortunately not required anymore with the current version.</p>
<p><strong>Broker B</strong> offers no direct connection at all. You have the choice of connecting either to their bloated Java trade platform, or to a small &#8220;Gateway&#8221; program. When you connect to the Java platform, your software must once per day log out, restart the platform, and log in again since the platform automatically shuts down every 24 hours. When you connect through the &#8220;Gateway&#8221;, you can not open their platform at the same time (not even from a different PC). So you can&#8217;t even check your positions. If you do, the Gateway connection breaks down and must be manually re-established. This is not a bug as you might think. It is intentionally implemented this way (according to the broker) as a service to their users.</p>
<p>Both broker A and broker B are major, world-wide operating Forex and stock brokers.  </p>
<h3>Getting price quotes</h3>
<p><strong>Broker A</strong> keeps its asset prices in a &#8220;Quote Table&#8221; on his server. For getting a price quote you must first subscribe to that asset. For this you do not just call a function, you build up a &#8220;Request Factory&#8221; and generate a &#8220;Subscription Request&#8221;. Now you can enter the procedure of receiving a response on your request, which involves the creation of a &#8220;Response Listener&#8221;. Subscribing to an asset this way takes about 30 primary lines of C++ code &#8211; and this does not include the secondary code for sending the requests, generating listeners, and all the supplementary stuff. My clients can consider themselves fortunate that I don&#8217;t charge by code line. Getting the price itself then only requires looking up the asset in the server&#8217;s quote table.</p>
<p><strong>Broker B</strong> makes it easy: You can not subscribe market quotes by API at all. You must do that manually on their website, and it is not free (except for Forex). For getting the price, a simple API call is sufficient. Or would be, if you knew the primary exchange, secondary exchange, asset type and sub-type, and other asset parameters. If any of them is not right, you get no price. And don&#8217;t think that these exchange and other parameters are documented somewhere. You&#8217;re supposed to find them out by trial and error, or to ask fellow programmers on the Internet.</p>
<h3>Getting price history</h3>
<p>Although any algorithm trades in real time, it still needs price history on startup for calculating initial values of its indicators and price-analyzing functions. With no access to price history, you had to wait a couple days before the first trade can be placed. Since this is not really practical, price history is an essential API function.</p>
<p><strong>Broker A</strong> provides price history with no major problem. I can almost not believe it. Ok, you must again fire up the &#8220;Request Factory&#8221;, generate requests and listeners, but about 50 code lines enable you to download historical prices. The broker charges no fee for those prices (you can even download them with a demo account), and at least the recent data, from 2010 and above, is in acceptable quality. Eight out of ten points for the price history from broker A.</p>
<p><strong>Broker B</strong> again got creative and enterprising. Their price history from demo accounts is worthless &#8211; you must indeed open a real account and deposit $10,000 when you want historical data. This sum, of course, is also required from a poor coder who only wants to implement a function for getting price history. Not that you get it then easily. Technically it&#8217;s simple &#8211; a few lines of code are enough &#8211; but you only have 60 requests. After that, the price history server is shut down for 10 minutes. 60 requests are enough for a single-asset system, but not for starting a portfolio system, and certainly not for backtests. Why this bizarre limit? Maybe broker B can&#8217;t afford a fast Internet connection for their price history server. Maybe they are using the CEO&#8217;s old PC, located in his living room, and the bandwidth goes down anytime when his kids play Tetris on it. Whatever the reason, that&#8217;s only one out of ten points for the price history from broker B.</p>
<p>Is there a broker with even zero points for the price history? Yes, there is: Broker C has no API function for retrieving historical prices at all. Apparently they had not expected that someone would really use their API. I had no choice but to advise my client to choose another broker for his algorithmic system.</p>
<h3>Handling trades</h3>
<p>We programmers tend to think binary. When we send a fill-or-kill order to the broker API, we assume that the position will be either opened (&#8220;yes&#8221;), or it will not (&#8220;no&#8221;). But from time to time, broker APIs produce a third result, like &#8220;maybe&#8221; or &#8220;I won&#8217;t tell&#8221;. A position that is maybe opened or maybe not can result in an <strong>orphaned trade</strong>. This is a trade opened by the broker, but not reported back to the trading software, and consequently not under automated control. This trade won&#8217;t be closed by a reversal or stop and can thus accumulate a large loss. It can blow the account. Orphaned trades are not a good thing.</p>
<p>Theoretically, they would be so easy to prevent. The API just needs to provide a simple order function with an identifier and a validity limit, like this:</p>
<p><strong>openAtMarket(string Asset, int Amount, int ID, int SecondsValid);</strong></p>
<p><strong>ID =</strong> dear broker, please store this identifier together with the trade and use it for retrieving the trade status in case of doubt.<br />
 <strong>SecondsValid =</strong> dear broker, please disregard the order when after the given number of seconds your API still doesn&#8217;t know if it can fill it or not, or is unable to confirm it for whatever reason. </p>
<p>That&#8217;s the ideal, but how&#8217;s the reality?</p>
<p><strong>Broker A</strong> accepts a ton of parameters in his order functions, but no user-supplied trade <strong>ID</strong> and no <strong>SecondsValid</strong> limit. After sending an order and going through the usual &#8220;Request Factory&#8221; and &#8220;Response Listener&#8221; rigmarole, you&#8217;ll receive a confirmation and can retrieve the trade identifier for managing or closing it later. Or you&#8217;ll get notified that the order failed. Or neither of both. It happens that the API does not react at all on your order, maybe due to a server hickup, an Internet outage, or because it became confused by too many Factories and Listeners. Then you can only guess if your order made it to the server or not. If it did, you have an orphaned trade. But at least you can relatively easily identify and close it manually.</p>
<p><strong>Broker B</strong> provides a simple order function, even with a user-supplied <strong>ID</strong>. And you get confirmation by a simple callback function that the order was filled or not. Usually not, since broker B needs again lots of information about the asset and the order routing, and won&#8217;t execute the order if something is missing or not fitting together. But at least you know the ID. This makes you think that you can later check the trade status. Think again: Broker B won&#8217;t reveal any information about your trades. At least not to you. In fact they do not store your trades at all. They only store net positions. So there is no way to identify orphans. Not even manually, since you can&#8217;t open the trade platform as long as an automated system is running.</p>
<h3>Account parameters and trading costs </h3>
<p><strong>Broker A</strong> provides a function where you can request leverage, pip size, pip cost, rollover, and any other parameters of the selected asset. Enough information to calculate margin and trading costs in advance, what is a good thing for an automated system &#8211; if there weren&#8217;t an important parameter missing. The API does not allow to retrieve the commission. You must enter it manually and store it per asset. Why this important parameter is not provided by the API remains broker A&#8217;s secret.</p>
<p><strong>Broker B</strong> does not have this problem, as its API provides no asset and trading cost information at all &#8211; not even the leverage. For compensation, it supports a sort of &#8220;virtual order&#8221; that can be used to calculate profit, similar to Zorro&#8217;s &#8220;phantom trades&#8221;. Theoretically you could use that to calculate some of the asset parameters in a complex way from a series of virtual orders with different lot sizes. My clients didn&#8217;t pay me for that. For simulating a broker B account in a backtest, you must therefore enter all required asset parameters and trading costs manually in a spreadsheet &#8211; which is no easy task due to the complicated fee and margin structure of that broker.</p>
<hr />
<p>There are APIs for almost all imaginable software tasks. And most are well structured nowadays and relatively easy to use. Why is it not so with most broker APIs? Dear brokers: If you think about providing API access to your customers, please look first into other broker&#8217;s solutions for learning how NOT to do it. And if really necessary, please add detailed documentation about which of the market or order parameters are really required and in which combination.</p>
<p>And if you then still are not sure how to implement your new API, just hire me. I had the dubious pleasure to implement dozens of APIs so far, and can show you how an API for algo trading should look like. And even though you&#8217;ll then have to hand over some shekels to my employer, you&#8217;ll make up for this by winning an excellent reputation. At least among the poor coders and hackers who have to implement your API.</p>
<hr />
<p><strong>Addendum (January 2017):</strong> For the sake of fairness it should be mentioned that broker B has meanwhile removed the bizarre 60 requests limit for historical data. One year of data is now available. Maybe they have read this blog. Or their CEO got a new PC for Christmas. Whatever the reason, it&#8217;s still not sufficient for backtests, but at least for live trading even large portfolio strategies.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/dear-brokers/feed/</wfw:commentRss>
			<slash:comments>19</slash:comments>
		
		
			</item>
		<item>
		<title>I Hired a Contract Coder</title>
		<link>https://financial-hacker.com/i-hired-a-contract-coder/</link>
					<comments>https://financial-hacker.com/i-hired-a-contract-coder/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Thu, 15 Oct 2015 09:57:08 +0000</pubDate>
				<category><![CDATA[No Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Hiring]]></category>
		<category><![CDATA[Money]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=363</guid>

					<description><![CDATA[You&#8217;re a trader with serious ambitions to use algorithmic methods. You already have an idea to be converted to an algorithm. The problem: You do not know to read or write code. So you hire a contract coder. A guy who&#8217;s paid for delivering a script that you can drop in your MT4, Ninja, TradeStation, &#8230; <a href="https://financial-hacker.com/i-hired-a-contract-coder/" class="more-link">Continue reading<span class="screen-reader-text"> "I Hired a Contract Coder"</span></a>]]></description>
										<content:encoded><![CDATA[<p>You&#8217;re a trader with serious ambitions to use algorithmic methods. You already have an idea to be converted to an algorithm. The problem: You do not know to <strong>read or write code</strong>. So you hire a contract coder. A guy who&#8217;s paid for delivering a script that you can drop in your MT4, Ninja, TradeStation, or Zorro platform. Congratulations, now you&#8217;re an algorithmic trader. Just start the script and wait for the money to roll in. &#8211; Does this really work? Answer: it depends.<span id="more-363"></span></p>
<p>Coding contracts can <strong>work out well</strong> or<strong> fail miserably</strong>. It depends on you and on the coder. But mostly on you. As a contract coder* who often hires other contract coders, I got meanwhile some experiences with both sides of the medal. So here are some coder hiring suggestions for increasing the chance to&nbsp;get something useful back for your money.</p>
<h3>Find the coder</h3>
<p>There are three Internet places where you can look for strategy coders: trader forums, freelancer websites, and&nbsp;tool vendors. The latter is my preferred way to acquire coding manpower. I check out&nbsp;advertised indicators, trading systems, or software tools that have some relation to the project at hand. If I like what I see, I contact the developer and ask if she or he does contract work. Most do. This way I know that the new coder has knowledge about the subject, can bring in her experience, and can do commercial quality work.</p>
<p>When contracting on trader forums or freelancer&nbsp;websites, be aware that coding abilities are not equally distributed among&nbsp;the population. Speed and code quality by&nbsp;freelancers differ by <strong>factors up to 10</strong>. So you need some means to judge the coding beforehand. Check out example projects (obviously, don&#8217;t hire someone who has nothing to show). If you can&#8217;t decide among five coders, hire all five. Give them all a small task, a little script, something that can be done in about 3&nbsp;hours. Pay all five for the small task, then select the one with the best work for the real project. The invested money is well spent. A connection to a good coder is a very valuable asset.</p>
<h3>Grill the coder</h3>
<p>Before hiring, interrogate&nbsp;the freelancer about his skills and his approach to&nbsp;the project. And&nbsp;put attention on&nbsp;clear and prompt&nbsp;answers. Many issues arise from misunderstanding. Freelance coders must&nbsp;be able to&nbsp;express themselves not only in script, but also in plain English. As&nbsp;you&#8217;ll most likely communicate by email, test the <strong>promptness</strong>. If&nbsp;it takes your aspiring coder three days to respond on an email even in the negotiating phase, he&#8217;ll likely need three weeks to react on an issue after delivery and payment &#8211; if at all.</p>
<p>One important thing to ask is how the coder tests his&nbsp;scripts. In software development, proper <strong>test procedures</strong> are more important than writing code. A good coder has some test framework for putting his code under stress. This is twice important when the coder, as I sometimes do, sub-contracts parts of the task to other coders. Understanding and testing other people&#8217;s scripts is an additional effort that pays back in better code quality.</p>
<p>Naturally you should also make sure that&nbsp;the coder has basic understanding of trading, and knowledge in math and statistics &#8211; or can at least quickly come to grips with a new field of knowledge. A&nbsp;degree in math, physics, engineering, or computer science is of advantage, even if it pushes up the coder&#8217;s fees. But&nbsp;<strong>understanding the algorithm on a deep level</strong>&nbsp;can be essential&nbsp;for coding a serious trade system. My favorite way to grill a coder was giving her a sheet of paper and asking her for a quick proof of Pythagoras&#8217; theorem. Unfortunately, this only works in a face to face interview, not by email.</p>
<h3>Feed the&nbsp;coder</h3>
<p>An essential part of cooperation with coders is your <strong>project description</strong>. Know your goals precisely, but not too precisely. Some clients are able to describe clearly what they want. Others send long and utterly confused project specifications that leave you completely in the dark of what you have to code. From some clients I got laconic flow diagrams like this: &#8220;Analyze price curve with neural network &#8211; open position when profitable &#8211; close position at price maximum &#8211; repeat&#8221;. Others have 22-page concepts with a complex strategy described up to the finest detail of the user interface button colors. And as they felt that all this could somehow limit the flexibility, they usually require any detail to be adjustable with many different parameters and modes.</p>
<p>A trading strategy is no iPhone app. No one knows beforehand if your idea&nbsp;will work or not. If not, any implemented additional details are wasted money. So split your project&nbsp;into <strong>milestones</strong>. Or let the coder do it. The first milestone is always the proof of concept: a script of just your trade idea, with no stops, extra filters, money management, user interface, or other gimmicks. This should be coded at first, and carefully tested in all possible variants. If this script turns out to be profitable, go on with the next step. Otherwise you won&#8217;t need all the rest.</p>
<p>If your trade idea or algorithm is very secret, the coder should offer you a <strong>non-disclosure agreement</strong>. This way he accepts the responsibility to keep your trade method for himself. Which he should do anyway, of course.</p>
<h3>Don&#8217;t listen to the coder</h3>
<p>At least not to me. I used to advise clients about the success chances of their concept &#8211; even before coding and testing it. For instance I declared a certain strategy doomed to fail since it seemed just a complex hodgepodge of conventional indicators. The client was unimpressed. He told me to code it nevertheless. Now, 18 months later, he&#8217;s still living from the returns of that system. Since then I refrain from unsolicited advising.</p>
<p>But you should very well listen to the coder when he suggests different methods of implementing your system, or modifications for simplifying the algorithm or making it more effective. The coder possibly knows your algorithm better than you.</p>
<h3>Pay the coder</h3>
<p>I will be frank: For&nbsp;almost all coders (I&#8217;m no exception), coding is one of the greatest things on earth. For some, it&#8217;s better than sex. We all would <strong>code for free</strong> if there were no alternative. However, professional ethics and our bank account require that we demand payment.</p>
<p>Since&nbsp;coding speed can be very different, it&#8217;s normally not advised to pay a coder by hour, unless you&#8217;ve worked with her a long time and know her well. Normally the coder will quote the project at a fixed price. The price should include not only the coding, but also a support and warranty period after delivery. It usually does not include training the script or adjusting the parameters. This is your task, as it&#8217;s very time consuming and thus would be expensive, but requires no code knowledge.</p>
<p>Just as coding speed and quality, <strong>coding prices</strong> vary strongly among freelancers. Obviously the cheap price is not always the best. On the other hand, if the project is really interesting and the coder would really like to get the job, you can often negotiate a discount. Some ballpark figures: My own contracts start at EUR 170 per strategy, which is my employer&#8217;s required minimum for a simple script. Contracts for complex projects with options trading or machine learning algorithms are in the EUR 1000-2000 range; individual user interfaces, and special analysis or input / output methods can raise the contract to EUR 10,000 or more. My largest contract so far was 1.5 million EUR. Sadly, the small contracts are much more frequent than the large ones&#8230;</p>
<p>Coders usually demand <strong>advance payment</strong>. How much depends on your prominence&nbsp;in relation to the coder. If you are Warren Buffett and the coder is an unknown guy from India, you&#8217;ll be able to negotiate payment after delivery. If you&#8217;re a nondescript retail trader and the coder is employed&nbsp;by a large company, he&#8217;ll likely ask you for 100% advance payment. In most cases the terms will be 50% in advance and 50% after delivery.</p>
<p>If the script works, pay the rest immediately. This won&#8217;t cost you much, but makes a good impression on the coder. I only ever had one single case where the contract price was not paid at all. This is always a bad idea: We coders talk to each other. Not paying a contract might get you in trouble&nbsp;to ever find a coder again. Or worse: You might find one who implements a little surprise in your trading script&#8230;</p>
<h3>Be independent of the coder</h3>
<p>Even when you hire a coder, it makes sense when you acquire a basic understanding of coding &#8211; for instance through the <a href="http://manual.zorro-project.com/tutorial_var.htm">Zorro tutorial</a>. It will take a day or two. But it will allow you not only to better judge the code quality, but also to modify the script beyond just setting parameters. Then you don&#8217;t need to always wait for a new quote by the coder. And you save money. Remember, I have to charge EUR 170 (at least) no matter if I re-write the script completely or only modify a single line.</p>
<h3>Conclusion</h3>
<p>Be very, very meticulous&nbsp;in selecting a coder and working with her or him, and try to understand as much of the&nbsp;code and its structure as possible. This can be the deciding factor for&nbsp;the success of your project. &#8211; In case you&#8217;re curious about my above&nbsp;mentioned one point five million contract, or about the single case when a&nbsp;contract was not paid, or about my most bizarre experience as a hired coder so far: You can read that story <a href="http://www.republic-of-utopia.com/mystery.htm" target="_blank" rel="noopener noreferrer">here</a>. But it is not suited for minors. So if you&#8217;re below 18, please do not click on that link. Thank you.</p>
<hr>
<p><span style="font-size: 10pt;">* Some&nbsp;coders prefer to be referred to as &#8216;programmers&#8217;. The rationale is that a coder just converts an algorithm in code, while a programmer develops the algorithm. This distinction is not really useful: You can not code a trading strategy when you&#8217;re illiterate in algorithms. Thus,&nbsp;I don&#8217;t care if I&#8217;m a coder or a programmer as long as I&#8217;m paid. </span></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/i-hired-a-contract-coder/feed/</wfw:commentRss>
			<slash:comments>23</slash:comments>
		
		
			</item>
		<item>
		<title>Hacker&#8217;s Tools</title>
		<link>https://financial-hacker.com/hackers-tools-zorro-and-r/</link>
					<comments>https://financial-hacker.com/hackers-tools-zorro-and-r/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Sat, 03 Oct 2015 08:01:30 +0000</pubDate>
				<category><![CDATA[3 Most Useful]]></category>
		<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Aronson]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[TSSB]]></category>
		<category><![CDATA[Vector-based test]]></category>
		<category><![CDATA[Zorro]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=89</guid>

					<description><![CDATA[For our financial hacking experiments (and for harvesting their financial fruits) we need some software machinery for research, testing, training, and live trading financial algorithms. There are many tools for algo trading, but no existing software platform today is really up to all those tasks. You have to put together your system from different software &#8230; <a href="https://financial-hacker.com/hackers-tools-zorro-and-r/" class="more-link">Continue reading<span class="screen-reader-text"> "Hacker&#8217;s Tools"</span></a>]]></description>
										<content:encoded><![CDATA[<p>For our financial hacking experiments (and for harvesting their financial fruits) we need some software machinery for research, testing, training, and live trading financial algorithms. There are many <a href="https://zorro-project.com/algotradingtools.php" target="_blank" rel="noopener">tools for algo trading</a>, but no existing software platform today is really up to all those tasks. You have to put together your system from different software packages. Fortunately, two are normally sufficient. I&#8217;ll use <strong>Zorro</strong> and <strong>R</strong> for most articles on this blog, but will also occasionally look into other tools.<span id="more-89"></span></p>
<h3>Choice of languages</h3>
<p>Algo trading systems are normally based on a script in some programming language. You can avoid writing scripts entirely by using a visual &#8216;strategy builder&#8217;, &#8216;code wizard&#8217; or spreadsheet program for defining your strategy. But this is also some sort of programming, just in a different language that you have to master. And visual builders can only create rather simple &#8216;indicator soup&#8217; systems that are unlikely to produce consistent trading profit. For serious algo trading sytems, real development, and real research, there&#8217;s no stepping around &#8216;real programming&#8217;.</p>
<p>You&#8217;re also not free to select the programming language with the nicest or easiest syntax. One of the best compromises of simplicity and object orientation is probably <strong>Python</strong>. It also offers libraries with useful statistics and indicator functions. Consequently, many strategy developers start with programming their systems in Python&#8230; and soon run into serious limitations. There&#8217;s another criterion that is more relevant for system development than syntax: <strong>execution speed</strong>.</p>
<p>Speed mostly depends on whether a computer language is <strong>compiled </strong>or <strong>interpreted</strong>. <strong>C</strong>,<strong> Pascal</strong>, and <strong>Java </strong>are compiled languages, meaning that the code runs directly on the processor (C, C++, Pascal) or on a &#8216;virtual machine&#8217; (Java). <strong>Python</strong>, <strong>R</strong>, and <strong>Matlab </strong>is interpreted: The code won&#8217;t run by itself, but is executed by an interpreter software. Interpreted languages are much slower and need more CPU and memory resources than compiled languages. It won&#8217;t help much for trading strategies that they have fast C-programmed libraries. All backtests or optimization processes must still run through the bottleneck of interpreted trading logic. Theoretically the slowness can be worked around with &#8216;vectorized coding&#8217; &#8211; see below &#8211; but that has little practical use.</p>
<p>R and Python have other advantages. They are <strong>interactive</strong>: you can enter commands directly at a console. This allows quick code or function testing. Some languages, such as <strong>C#</strong>, are inbetween: They are compiled to a machine-independent interim code that is then, dependent on implementation, either interpreted or converted to machine code. C# is about 4 times slower than C, but still 30 times faster than Python.</p>
<p>Here&#8217;s a benchmark table of the same two test programs written in several languages: a sudoku solver and a loop with a 1000 x 1000 matrix multiplication (in seconds):</p>
<table>
<tbody>
<tr>
<td>Language</td>
<td>Sudoku</td>
<td>Matrix</td>
</tr>
<tr>
<td>C, C++</td>
<td>1.0</td>
<td>1.8</td>
</tr>
<tr>
<td>Java</td>
<td>1.7</td>
<td>2.6</td>
</tr>
<tr>
<td>Pascal</td>
<td>&#8212;</td>
<td>4</td>
</tr>
<tr>
<td>C#</td>
<td>3.8</td>
<td>9</td>
</tr>
<tr>
<td>JavaScript</td>
<td>18.1</td>
<td>16</td>
</tr>
<tr>
<td>Basic (VBA)</td>
<td>&#8212;</td>
<td>25</td>
</tr>
<tr>
<td>Erlang</td>
<td>18</td>
<td>31</td>
</tr>
<tr>
<td>Python</td>
<td>119</td>
<td>121</td>
</tr>
<tr>
<td>Ruby</td>
<td>98</td>
<td>628</td>
</tr>
<tr>
<td>Matlab</td>
<td>&#8212;</td>
<td>621</td>
</tr>
<tr>
<td>R</td>
<td>&#8212;</td>
<td>1738</td>
</tr>
</tbody>
</table>
<p>Speed becomes important as soon as you want to develop a short-term trading system. In the development process you&#8217;re all the time testing system variants. A 10-years backtest with M1 historical data executes the strategy about 3 million times. If a C-written strategy needs 1 minute for this, the same strategy in EasyLanguage would need about 30 minutes, in Python 2 hours, and in R more than 10 hours! And that&#8217;s only a backtest, no optimization or WFO run. If I had coded the <a href="http://www.financial-hacker.com/trend-and-exploiting-it/">trend experimen</a>t in Python or R, I would today still wait for the results. You can see why trade platforms normally use a C variant or a proprietary compiled language for their strategies. <a href="http://www.financial-hacker.com/hacking-hft-systems/">HFT systems</a> are anyway written in C or directly in machine language.</p>
<p>Even compiled languages can have large speed differences due to different implementation of trading and analysis functions. When we compare not Sudoku or a matrix multiplication, but a real trading system &#8211; the small RSI strategy from <a href="http://manual.zorro-project.com/conversion.htm">this page</a> &#8211; we find very different speeds on different trading platforms (10 years backtest, ticks resolution):</p>
<ul style="list-style-type: square;">
<li>Zorro: ~ 0.5 seconds (compiled C)</li>
<li>MT4:  ~ 110 seconds (MQL4, a C variant)</li>
<li>MultiCharts: ~ 155 seconds (EasyLanguage, a C/Pascal mix)</li>
</ul>
<p>However, the differences are not as bad as suggested by the benchmark table. In most cases the slow language speed is partically compensated by fast vector function libraries. A script that does not go step by step through historical data, but only calls library functions that process all data simultaneously, would run with comparable speed in all languages. Indeed some trading systems can be coded in this <strong>vectorized</strong> method, but <b>u</b>nfortunately this works only with simple systems and requires entirely different scripts for backtests and live trading.</p>
<h3>Choice of tools</h3>
<p><strong>Zorro</strong> is a software for financial analysis and algo-trading &#8211; a sort of Swiss Knife tool since you can use it not only for live trading, but also for all sorts of quick tests. It&#8217;s my software of choice for financial hacking because:</p>
<ul style="list-style-type: square;">
<li>It&#8217;s free (unless you&#8217;re rich).</li>
<li>Scripts are in C, event driven and very fast. You can code a system or an idea in 5 minutes.</li>
<li>Open architecture &#8211; you can add anything with DLL plugins.</li>
<li>Minimalistic &#8211; just a frontend to a programming language.</li>
<li>Can be automatized for experiments.</li>
<li>Very stable &#8211; I rarely found bugs and they were fixed fast.</li>
<li>Very accurate, realistic trading simulation, including HFT.</li>
<li>Supports also options and futures, and portfolios of multiple assets.</li>
<li>Has a library with 100s of indicators, statistics and machine learning functions, most with source code.</li>
<li>Is continuously developed and supported (new versions usually come out every 2..3 months).</li>
<li>Last but not least: I know it quite well, as I&#8217;ve written its tutorial&#8230;</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/Zorro.png"><img fetchpriority="high" decoding="async" class="aligncenter wp-image-117 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470.png" alt="Zorro" width="294" height="582" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470.png 294w, https://financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470-152x300.png 152w" sizes="(max-width: 294px) 85vw, 294px" /></a></p>
<p>A strategy example coded in C, the classic SMA crossover:</p>
<pre class="prettyprint">void run()
{
  double* Close = series(priceClose());
  double* MA30 = series(SMA(Close,30));	
  double* MA100 = series(SMA(Close,100));
	
  Stop = 4*ATR(100);
  if(crossOver(MA30,MA100))
    enterLong();
  if(crossUnder(MA30,MA100))
    enterShort();
}</pre>
<p>More code can be found among the <a href="https://zorro-project.com/code.php" target="_blank" rel="noopener">script examples</a> on the Zorro website. You can see that Zorro offers a relatively easy trading implementation. But here comes the drawback of the C language: You can not as easy drop in external libraries as in Python or R. Using a C/C++ based data analysis or machine learning package involves sometimes a lengthy implementation. Fortunately, Zorro can also call R and Python functions for those purposes.</p>
<p><strong>R</strong> is a script interpreter for data analysis and charting. It is not a real language with consistent syntax, but more a conglomerate of operators and data structures that has grown over 20 years. It&#8217;s harder to learn than a normal computer language, but offers some unique advantages. I&#8217;ll use it in this blog when it comes to complex analysis or machine learning tasks. It&#8217;s my tool of choice for financial hacking because:</p>
<ul style="list-style-type: square;">
<li>It&#8217;s free. (&#8220;Software is like sex: it&#8217;s better when it&#8217;s free.&#8221;)</li>
<li>R scripts can be very short and effective (once you got used to the syntax).</li>
<li>It&#8217;s the global standard for data analysis and machine learning.</li>
<li>Open architecture &#8211; you can add modules for almost anything.</li>
<li>Minimalistic &#8211; just a console with a language interpreter.</li>
<li>Very stable &#8211; I found a few bugs in external libraries, but so far never in the main program.</li>
<li>Has tons of &#8220;packages&#8221; for all imaginable mathematical and statistical tasks, and especially for machine learning.</li>
<li>Is continuously developed and supported by the global scientific community (about 15 new packages usually come out every day).</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/r.jpg"><img decoding="async" class="alignnone wp-image-115 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531.jpg" alt="r" width="693" height="576" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531.jpg 693w, https://financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531-300x249.jpg 300w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a></p>
<p>This is the SMA crossover in R for a &#8216;vectorized&#8217; backtest:</p>
<pre class="prettyprint">require(quantmod)
require(PerformanceAnalytics)

Data &lt;- xts(read.zoo("EURUSD.csv", tz="UTC", format="%Y-%m-%d %H:%M", sep=",", header=TRUE))
Close &lt;- Cl(Data)
MA30 &lt;- SMA(Close,30)
MA100 &lt;- SMA(Close,100)
 
Dir &lt;- ifelse(MA30 &gt; MA100,1,-1) # calculate trade direction
Dir.1 &lt;- c(NA,Dir[-length(Dir)]) # shift by 1 for avoiding peeking bias
Return &lt;- ROC(Close)*Dir.1 
charts.PerformanceSummary(na.omit(Return))</pre>
<p>You can see that the vectorized code just consists of function calls. It runs almost as fast as the C equivalent. But it is difficult to read, it can not be used for live trading, and many parts of a trading logic &#8211; even a simple stop loss &#8211; cannot be coded for a vectorized test. Thus, so good R is for interactive data analysis, so hopeless is it for writing trade strategies &#8211; although some R packages (for instance, <strong>quantstrat</strong>) even offer rudimentary optimization and test functions. They all require an awkward coding style and do not simulate trading very realistically, but are still too slow for serious backtests.</p>
<p>Although R can not replace a serious backtest and trading platform, Zorro and R complement each other perfectly: <a href="http://www.financial-hacker.com/build-better-strategies-part-5-developing-a-machine-learning-system/" target="_blank" rel="noopener noreferrer">Here</a> is an example of a machine learning system build together with a deep learning package from R and the training and trading framework from Zorro.</p>
<h3>More hacker&#8217;s tools</h3>
<p>Aside from languages and platforms, you&#8217;ll often need auxiliary tools that may be small, simple, cheap, but all the more important since you&#8217;re using them all the time. For editing not only scripts, but even short CSV lists I use <a href="https://notepad-plus-plus.org/" target="_blank" rel="noopener noreferrer"><strong>Notepad++</strong></a>. For interactive working with R I recommend <a href="https://www.rstudio.com" target="_blank" rel="noopener noreferrer"><strong>RStudio</strong></a>. Very helpful for strategy development is a <strong>file comparison</strong> tool: You often have to compare trade logs of different system variants and check which variant opened which trade a little earlier or later, and which consequences that had. For this I use <a href="http://www.scootersoftware.com/" target="_blank" rel="noopener noreferrer"><strong>Beyond Compare</strong></a>.</p>
<p>Aside from Zorro and R, there&#8217;s also a relatively new system development software that I plan to examine closer at some time in the future, <strong><a href="http://www.tssbsoftware.com/" target="_blank" rel="noopener noreferrer">TSSB</a></strong> for generating and testing bias-free trading systems with advanced machine learning algorithms. David Aronson and Timothy Masters were involved in its development, so it certainly won&#8217;t be as useless as most other &#8220;trade system generating&#8221; software. However, there&#8217;s again a limitation: TSSB can not trade or export, so you can not really use the ingenious systems that you developed with it. Maybe I&#8217;ll find a solution to combine TSSB with Zorro.</p>
<h3>References</h3>
<p><a href="https://www.tiobe.com/tiobe-index/">TIOBE index</a> of top programming languages</p>
<p><a href="http://attractivechaos.github.io/plb/">Speed comparison</a> of programming languages</p>
<hr />
<p><strong>Update (November 2017).</strong> The release of new deep learning packages has made TSSB sort of obsolete. For instance, the H2O package natively supports several ways of features filtering and dimensionality reduction, as well as ensembles, both so far the strength of TSSB. H2O is supported with Zorro&#8217;s <strong>advise</strong> function. Still, the TSSB book by Davin Aronson is a valuable source of methods, approaches, and tips about machine learning for financial prediction.</p>
<p>Download links to the latest versions of Zorro and R are placed on the side bar. A brief tutorial to both Zorro an R is contained in the Zorro manual; a more comprehensive introduction into working with Zorro can be found in the <a href="https://www.createspace.com/7147886" target="_blank" rel="noopener noreferrer">Black Book</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/hackers-tools-zorro-and-r/feed/</wfw:commentRss>
			<slash:comments>19</slash:comments>
		
		
			</item>
		<item>
		<title>Money and How to Get It</title>
		<link>https://financial-hacker.com/money-and-how-to-get-it/</link>
					<comments>https://financial-hacker.com/money-and-how-to-get-it/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Wed, 02 Sep 2015 10:45:51 +0000</pubDate>
				<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[Economy]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Money]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=62</guid>

					<description><![CDATA[Contrary to popular belief, money is no material good. It is created out of nothing by banks lending it. Therefore, for each newly created lot of money there&#8217;s the same amount of debt. You&#8217;re destroying the money by repaying your credits. Since this requires a higher sum due to interest and compound interest, and since &#8230; <a href="https://financial-hacker.com/money-and-how-to-get-it/" class="more-link">Continue reading<span class="screen-reader-text"> "Money and How to Get It"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Contrary to popular belief, <strong>money</strong> is no material good. It is created out of nothing by banks lending it. Therefore, for each newly created lot of money there&#8217;s the same amount of <strong>debt</strong>. You&#8217;re destroying the money by repaying your credits. Since this requires a higher sum due to interest and compound interest, and since money is also permanently withdrawn from circulation by hoarding, the entire money supply must constantly grow. It must never shrink. If it still does, as in the 1930 economic crisis, loan defaults, bank crashes and bankruptcies are the result. The monetary system is therefore a classic <strong>Ponzi scheme</strong>.<span id="more-62"></span></p>
<p>Because the money amount always corresponds to the same amount of private and public debt, this debt amount also must inevitably grow, in spite of all the political lamentoes. Reducing public debt would either destroy money or increase private debt proportionately. This happened in fact in the United States around the turn of the millennium, when then-President <strong>Bill Clinton</strong> managed to get by without borrowing, and even achieved a budget surplus. Which caused interests to drop and banks to look elsewhere for distributing their money. The indirect result of Clinton&#8217;s good deed was a massive increase in private debt that eventually led to the mortgage crash of 2007.</p>
<h3>How to acquire it in large amounts</h3>
<p>Money is considered a good thing in almost all cultures. After all, it allows you to do the things you want, and &#8211; even more important &#8211; not to do things you don&#8217;t want to do. It thus represents freedom. You can get to it with different methods. The most obvious is taking away other people&#8217;s money. Here&#8217;s the Top Ten fortunes by known villains, according to Forbes (in US $):</p>
<ol>
<li>Hugo Drax &#8211; <strong>7.6 billion</strong></li>
<li>Auric Goldfinger &#8211; <strong>6.5 billion</strong></li>
<li>Max Zorin &#8211; <strong>5.3 billion</strong></li>
<li>Lex Luthor &#8211; <strong>4.7 billion</strong></li>
<li>Franz Sanchez &#8211; <strong>1 billion</strong></li>
<li>Ernst Stavro Blofeld &#8211; <strong>640 million</strong></li>
<li>Karl Stromberg &#8211; <strong>640 million</strong></li>
<li>Elektra King &#8211; <strong>420 million</strong></li>
<li>Francisco Scaramanga &#8211; <strong>115 million</strong></li>
<li>Dr. Julius No &#8211; <strong>110 million</strong></li>
</ol>
<p>But the most successful in money taking are not, as you might think, drug cartel bosses or leaders of criminal underground organizations, but <strong>presidents and other heads of state</strong>. They can take their share of money with no risk, since they need not fear the law. Here&#8217;s the Top Ten of the acquired fortunes by this way (in US $):</p>
<ol>
<li>Muammar Gaddafi, Libya &#8211; <strong>55 billion</strong></li>
<li>Hosni Mubarak, Egypt &#8211; <strong>50 billion</strong></li>
<li>Mohamed Suharto, Indonesia &#8211; <strong>25 billion</strong></li>
<li>Alexander Lukashenko, Belarus &#8211; <strong>12 billion</strong></li>
<li>Mobutu Sese Seko, Congo &#8211; <strong>7 billion</strong></li>
<li>Ben Ali, Tunisia &#8211; <strong>4 billion</strong></li>
<li>Gnassingbé Eyadéma, Togo &#8211; <strong>4 billion</strong></li>
<li>Obiang Nguema, Equatorial Guinea &#8211; <strong>3 billion</strong></li>
<li>Slobodan Milosevic, Serbia &#8211; <strong>1 billion</strong></li>
<li>&#8216;Baby Doc&#8217; Duvalier, Haiti &#8211; <strong>600 million</strong></li>
</ol>
<p>This list does naturally not include assets of monarchs such as the Sultan of Brunei, who have no need of pilfering because the country belongs to them by law anyway. Or of dictators like Wladimir Putin, whose estimated 125 billion booty (plus a 17,000 sqft palace) officially does not belong to them, but is kept for them by friendly oligarchs. The listed sums must also be considered in relation to the economy of the country. To bag 600 million in grinding poor Haiti is a much more impressive performance than the lousy one billion that Milosevic could siphon off in industrialized Serbia. But as long as you&#8217;re neither a supervillain, nor a head of state, nor both at the same time, you have no choice but to use other means to acquire money. There&#8217;s also the method of buying something cheap and selling it dear. Not as profitable as being a head of state, but it still can produce some handsome gains (annual income in US $):</p>
<ol>
<li>Jim Simons, Renaissance &#8211; <strong>1.7 billion</strong></li>
<li>Ken Griffin, Citadel &#8211; <strong>1.7 billion</strong></li>
<li>Raymond Dalio, Bridgewater &#8211; <strong>1.4 billion</strong></li>
<li>David Tepper, Apaloosa &#8211; <strong>1.4 billion</strong></li>
<li>Izzy Englander, Millenium &#8211; <strong>1.1 billion</strong></li>
<li>David Shaw, Shaw Group &#8211; <strong>750 million</strong></li>
<li>John Overdeck, Two Sigma &#8211; <strong>500 million</strong></li>
<li>David Siegel, Two Sigma &#8211; <strong>500 million</strong></li>
<li>Andreas Halvorsen, Viking &#8211; <strong>370 million</strong></li>
<li>Joseph Edelman, Perceptive &#8211; <strong>300 million</strong></li>
</ol>
<p>All in this list acquired their wealth with <a href="https://zorro-project.com/algotrading.php" target="_blank" rel="noopener">algorithmic trading</a>. Which is the topic of most of the rest of this blog. It does not produce any goods. But on the other hand, it does not steal from anyone. On the contrary, private, small-scale financial trading can boost demand and soften economic inequality. It can redistribute money from the rich to the poor. So it should be rewarded by the government, for instance by a tax exemption. Well, one can dream, at least&#8230;<a id="why"></a></p>
<h3>Why financial hacking?</h3>
<p>Part of my job is developing financial tools and trading systems for clients. So far we coded hundreds of trading strategies with all sorts of algorithms for all sorts of financial instruments. Some worked and fulfilled the client&#8217;s expectations. Some failed miserably. And some worked in the backtest, but not in live trading. Coming from a background of theoretical physics and computer game programming, I wondered why trading seems not to be an exact science at all. What is the difference between a successful and a doomed strategy? And how can you determine that before actually trading it?</p>
<p>On this blog I&#8217;ll attempt a <strong>hacking approach to algorithmic trading</strong>. Hacking is nothing illegal, it&#8217;s just a pragmatic way to solve problems. Hackers prefer experiment over theory. They don&#8217;t give a damn about the wisdom of gurus or authorities. So I&#8217;ll start with considering all praised trade systems worthless and all &#8220;trader&#8217;s wisdom&#8221; irrational and nonsense until proven otherwise. I will try to evaluate <strong>by systematic experimenting </strong>whether, why, when, and how algorithmic trading does work. My goal is to find out how it can be a reliable income source for a private trader. This might require complex statistical or machine learning algorithms &#8211; but that&#8217;s no big deal with today&#8217;s software tools. All scripts and software to the articles will be put up for download, so anyone interested can reproduce all the results and use the strategies. After all, successful private trading is for the common good.</p>
<p>As this blog is about algorithmic trading, I&#8217;m going to post here a lot of algorithms and source code. Naturally not any trader is able to read code. On the other hand, some basic code and math understanding is required for making sense of the articles. To go from zero to a full understanding of the articles on this blog, here&#8217;s a <a href="http://manual.zorro-project.com/links.htm" target="_blank" rel="noopener noreferrer">list of Useful Books</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/money-and-how-to-get-it/feed/</wfw:commentRss>
			<slash:comments>24</slash:comments>
		
		
			</item>
	</channel>
</rss>
