<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Articles</title><link>http://www.4xlab.net/cs/forums/24/ShowForum.aspx</link><description>A list of articles and tutorials published.</description><dc:language>en-US</dc:language><generator>CommunityServer 1.1 (Build: 1.1.0.51101)</generator><item><title>A comparison between moving averages.</title><link>http://www.4xlab.net/cs/forums/157/ShowPost.aspx</link><pubDate>Fri, 06 Oct 2006 22:54:30 GMT</pubDate><guid isPermaLink="false">3bf9340b-8e96-4367-9a26-b022cb783a8d:157</guid><dc:creator>asimon</dc:creator><slash:comments>0</slash:comments><description>&lt;P&gt;A comparison between moving averages.&lt;/P&gt;
&lt;P&gt;Moving averages are used in Technical Analysis of the Forex or Stock Market to determine the direction of the trend. Less sensitive averages are used for establishing longer term trends. Conversely, shorter term averages indicate the direction of the shorter trend. Popular values for technicians are the 10, 20 and 50 day Simple Moving Averages (SMA).&lt;/P&gt;
&lt;P&gt;This short article will explore the behavior of different moving averages when using a sinusoidal wave as input. Noise will be introduced to study how fast the indicators respond and how long they remember the anomalous values. &lt;/P&gt;
&lt;P&gt;&lt;IMG height=475 src="/images/Average_Studies.JPG" width=490 border=0&gt;&lt;/P&gt;
&lt;P&gt;This graph shows the behavior of different averages when calculated using a sinusoidal wave oscillating from -1 to +1. Noise has been introduced to the sine wave at the first positive&amp;nbsp;peak.&lt;/P&gt;
&lt;P&gt;The averages plotted are: &lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;Modified Average: A front weighted average:&amp;nbsp;( prev avg * 4 + input value ) / 5. 
&lt;LI&gt;Average: A 5 period simple moving average. 
&lt;LI&gt;Short Average: a 3 period simple moving average. 
&lt;LI&gt;FMA: The Fast Moving Average, calculated as follows:&amp;nbsp;(3 period SMA&amp;nbsp;+ (3 period SMA&amp;nbsp;- 5 period SMA)).&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;The front weighted Modified Average&amp;nbsp;indicator has the most lag of them all. It also does not reach the +1 and -1 extremes of the input signal. The 5 period and 3 periods moving averages track closer, but still show some lag. &lt;/P&gt;
&lt;P&gt;The Fast Moving Average&amp;nbsp;tracks closer to the input wave than the other averages and its two components. It reacts faster to the noise introduced in the signal and returns to tracking the sine wave sooner than the other averages. This simple indicator returns values similar to other fast moving averages such as the Hull Moving Average (HMA), or the Jurik Moving Average (JMA). &lt;/P&gt;
&lt;P&gt;The C# .NET source code for the Simple Moving Average, Fast Moving Average and Hull Moving Average are included in the &lt;A href="/cs/forums/17/ShowPost.aspx"&gt;4XLab.NET platform&lt;/A&gt;. The graph for this article has been plotted using Excel. The spreadsheet is available for download as an attachment. The implementation of the Jurik Moving Average is available through Jurik's Research website &lt;A href="http://www.jurikres.com"&gt;http://www.jurikres.com&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description></item><item><title>Creating a Mechanical Trading System Part 3: Get real time quotes using DDE</title><link>http://www.4xlab.net/cs/forums/146/ShowPost.aspx</link><pubDate>Mon, 11 Sep 2006 00:27:27 GMT</pubDate><guid isPermaLink="false">3bf9340b-8e96-4367-9a26-b022cb783a8d:146</guid><dc:creator>asimon</dc:creator><slash:comments>0</slash:comments><description>&lt;UL&gt;
&lt;LI&gt;&lt;A HREF="/images/Realtime_Quotes_src.zip"&gt;Download source - 55 Kb&lt;/A&gt; 
&lt;LI&gt;&lt;A HREF="/images/Realtime_Quotes_demo.zip"&gt;Download demo - 43 Kb&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;&lt;IMG height=298 src="/images/Realtime_Quotes.jpg" width=298&gt;&lt;/P&gt;
&lt;H2&gt;Introduction&lt;/H2&gt;This is the third article in the series: &lt;BR&gt;&lt;A href="http://www.codeproject.com/useritems/Technical_Indicators.asp"&gt;Creating a Mechanical Trading System Part 1: Technical Indicators&lt;/A&gt; &lt;BR&gt;&lt;A href="http://www.codeproject.com/useritems/Trading_System.asp"&gt;Creating a Mechanical Trading System Part 2: Four Percent Trading System&lt;/A&gt; &lt;BR&gt;Creating a Mechanical Trading System Part 3: Get real time quotes using DDE &lt;BR&gt;
&lt;P&gt;The first article in this series introduced a project to code mechanical trading system robots for the .NET platform using the C# language. The second article introduced how to code a trading system that will watch price action and make buying or selling decisions. This article shows how to obtain real time forex quotes for several currency pairs using the DDE protocol and the Metatrader 4 trading terminal.&lt;/P&gt;
&lt;P&gt;It is the aim of this project to write a program that does not depend on any underlying platform to execute, but rather receives price data directly from a broker and places orders via an API. &lt;/P&gt;
&lt;P&gt;The code provided here is part of a larger project to create a backtesting platform and an automated FOREX trading robot. Source code for this project is available at &lt;A HREF="/"&gt;http://www.4xlab.net/&lt;/A&gt; &lt;/P&gt;
&lt;H2&gt;Background&lt;/H2&gt;
&lt;P&gt;DDE (Dynamic Data Exchange) is an interprocess communication system that enables two applications to share the same data. This mechanism is deprecated in favor of other alternatives such as OLE or COM. In financial applications, it is popular and DDE enabled applications are still being built. The interaction between a quote provider and a client is typically limited to receiving real time quotes. DDE is not used to get historical data or enter trades.&lt;/P&gt;
&lt;P&gt;For a DDE dialog to occur, two applications must be running, the server, or provider of data, and the client, or consumer. If the server application is not running, the client connection attempts will fail. In this example, the server will be Metatrader Terminal 4.0, and the clients will be Microsoft Excel and the 4X DDE Client. &lt;/P&gt;
&lt;H2&gt;Connecting to Metatrader 4 using Excel:&lt;/H2&gt;
&lt;P&gt;The default installation of Metatrader does not enable the DDE server. It must be manually enabled once. To do so, click on Tools -&amp;gt; Options on the Server tab (selected by default), ensure the 'Enable DDE server' option is checked, click OK to save your options. &lt;/P&gt;
&lt;P&gt;Once Metatrader is running, connected to a server, and its DDE server has been enabled, launch Excel. To test the connection, type in a cell =MT4|ASK!EURUSD , this command obtains the ASK quote for the EUR USD pair using the MT4 DDE server. The cell content should display the last ask price for the pair and automatically update this value in real time if everything is working properly. If Metatrader is not running, or the DDE server is not enabled, Excel will try to start it using the non existing MT4.exe filename, which will fail and #VALUE! or #REF! will be displayed in cells using live data.&lt;/P&gt;
&lt;P&gt;Excel implements a DDE client with a syntax that is extremely easy to use and helps in debugging. To communicate, the client needs to know the DDE Application name, the DDE Topic, and the DDE Item. To make a request, the syntax is as follows: &lt;FONT face="Courier New"&gt;=DDEAppName|DDETopic!DDEItem&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;To communicate with Metatrader 4, the DDEAppName is MT4, the DDETopic is one of the commands listed below and the DDEItem is the currency pair you are interested in.&lt;/P&gt;
&lt;H2&gt;MT4 DDE Topics&lt;/H2&gt;
&lt;UL&gt;
&lt;LI&gt;BID 
&lt;P&gt;&lt;I&gt;Item:&lt;/I&gt; Currency Pair &amp;nbsp;&amp;nbsp;&lt;I&gt;Example:&lt;/I&gt; =MT4|BID!USDCHF &amp;nbsp;&amp;nbsp;&lt;I&gt;Sample Output:&lt;/I&gt; 1.2472&lt;BR&gt;Returns the BID or selling price for the pair &lt;/P&gt;
&lt;LI&gt;ASK 
&lt;P&gt;&lt;I&gt;Item:&lt;/I&gt; Currency Pair &amp;nbsp;&amp;nbsp;&lt;I&gt;Example:&lt;/I&gt; =MT4|ASK!GBPUSD &amp;nbsp;&amp;nbsp;&lt;I&gt;Sample Output:&lt;/I&gt; 1.8656&lt;BR&gt;Returns the ASK or buying price for the pair &lt;/P&gt;
&lt;LI&gt;HIGH 
&lt;P&gt;&lt;I&gt;Item:&lt;/I&gt; Currency Pair &amp;nbsp;&amp;nbsp;&lt;I&gt;Example:&lt;/I&gt; =MT4|HIGH!EURUSD &amp;nbsp;&amp;nbsp;&lt;I&gt;Sample Output:&lt;/I&gt; 1.2873&lt;BR&gt;Returns the High price for the pair &lt;/P&gt;
&lt;LI&gt;LOW 
&lt;P&gt;&lt;I&gt;Item:&lt;/I&gt; Currency Pair &amp;nbsp;&amp;nbsp;&lt;I&gt;Example:&lt;/I&gt; =MT4|LOW!USDJPY &amp;nbsp;&amp;nbsp;&lt;I&gt;Sample Output:&lt;/I&gt; 115.95&lt;BR&gt;Returns the Low price for the pair &lt;/P&gt;
&lt;LI&gt;QUOTE 
&lt;P&gt;&lt;I&gt;Item:&lt;/I&gt; Currency Pair &amp;nbsp;&amp;nbsp;&lt;I&gt;Example:&lt;/I&gt; =MT4|QUOTE!AUDUSD &amp;nbsp;&amp;nbsp;&lt;I&gt;Sample Output:&lt;/I&gt; 2006/09/08 19:58 0.7540 0.7546&lt;BR&gt;Returns the Time, BID and ASK prices for the pair&lt;/P&gt;
&lt;LI&gt;TIME 
&lt;P&gt;&lt;I&gt;Item:&lt;/I&gt; Does not take an Item &amp;nbsp;&amp;nbsp;&lt;I&gt;Example:&lt;/I&gt; =MT4|TIME &amp;nbsp;&amp;nbsp;&lt;I&gt;Sample Output:&lt;/I&gt; 2006/09/08 19:58&lt;BR&gt;Returns the server time&lt;/P&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;The DDE Topic STATUS and DDE Items ACCOUNT, BALANCE and CONNECT have been deprecated and obsoleted in version 4.0 of the client. The queries =MT|STATUS!ACCOUNT =MT|STATUS!BALANCE and =MT|STATUS!CONNECT only work in previous versions of the trading terminal. &lt;/P&gt;
&lt;H2&gt;Other DDE Enabled Financial Applications&lt;/H2&gt;Other financial applications share some of the previous DDE topics. Some of those applications and their App Names are: eSignal (WINROS): Stock Quotes, Thinkorswim (TOS): Stocks and futures broker. 
&lt;H2&gt;Using the code&lt;/H2&gt;
&lt;P&gt;The code below shows the minimum number of steps required to setup the NDDE library to receive real time quotes from Metatrader 4. Metatrader responds to the initial request for a value using &lt;CODE&gt;client.Request(Item, 60000);&lt;/CODE&gt; with N\A and instead only sends the quotes as updates via the Advise mechanism. &lt;/P&gt;
&lt;P&gt;This code connects to the MT4 DDE server and the QUOTE topic. It then sets up item update notifications using &lt;CODE&gt;StartAdvise&lt;/CODE&gt; for the desired currency pairs. The &lt;CODE&gt;OnAdvise&lt;/CODE&gt; event handler prints the tick received using the Item (pair) and Text (quote) attributes of the &lt;CODE&gt;DdeAdviseEventArgs&lt;/CODE&gt; object it receives as a parameter. &lt;/P&gt;
&lt;P&gt;If an exception is thrown during this process, it means that Metatrader is not started or its DDE server is not enabled. The user is informed to launch Metatrader, or to follow the procedure to enable the DDE server. &lt;/P&gt;File: Form1.cs&lt;BR&gt;&lt;PRE&gt;//
// 4XDDEClient, a part of the www.4xlab.net Forex Lab Project
//

using NDde.Client;

namespace _4XDDEClient
{

  public partial class Form1 : Form
  {

	...

    private void StartQuotes()
    {
      try
      {
        if (TheContainer.TheDdeClient == null)
        {
          DdeClient client = new DdeClient("MT4", "QUOTE");
          TheContainer.TheDdeClient = client;

          // Subscribe to the Disconnected event.  
          // This event will notify the application when 
          // a conversation has been terminated.
          client.Disconnected += OnDisconnected;

          // Connect to the server.  
          // It must be running or an exception will be thrown.
          client.Connect();

          // Advise Loop
          client.StartAdvise("USDCHF", 1, true, 60000);
          client.StartAdvise("USDJPY", 1, true, 60000);
          client.StartAdvise("EURUSD", 1, true, 60000);
          client.StartAdvise("GBPUSD", 1, true, 60000);
          client.StartAdvise("EURJPY", 1, true, 60000);
          client.StartAdvise("EURCHF", 1, true, 60000);
          client.StartAdvise("EURGBP", 1, true, 60000);
          client.StartAdvise("USDCAD", 1, true, 60000);
          client.StartAdvise("AUDUSD", 1, true, 60000);
          client.StartAdvise("GBPCHF", 1, true, 60000);
          client.StartAdvise("GBPJPY", 1, true, 60000);
          client.StartAdvise("CHFJPY", 1, true, 60000);
          client.StartAdvise("NZDUSD", 1, true, 60000);
          client.StartAdvise("EURCAD", 1, true, 60000);
          client.StartAdvise("AUDJPY", 1, true, 60000);
          client.StartAdvise("EURAUD", 1, true, 60000);
          client.StartAdvise("AUDCAD", 1, true, 60000);
          client.StartAdvise("AUDNZD", 1, true, 60000);
          client.StartAdvise("NZDJPY", 1, true, 60000);

          // subscribe to the Advise event
          // this method will be called when a quote
          // is received.
          client.Advise += OnAdvise;

          Log("DDE Client Started");
        }
        else
        {
          Log("DDE Client Already Started");
        }
      }
      catch (Exception)
      {
        TheContainer.TheDdeClient = null;
        Log("An exception was thrown during DDE connection");
        Log("Ensure Metatrader 4 is running and DDE is enabled");
        Log("To activate the DDE Server go to Tools -&amp;gt; Options");
        Log("On the Server tab, ensure \"Enable DDE server\" is checked");
      }
    }

    private void OnAdvise(object sender, DdeAdviseEventArgs args)
    {
      Log(args.Item+": " + args.Text);
    }

  }

  public class TheContainer
  {
    public static Form1 TheForm;
    public static DdeClient TheDdeClient;
  }

&lt;/PRE&gt;
&lt;H2&gt;Credits&lt;/H2&gt;This article uses the capable NDDE library which implements a DDE client, server and monitor in C# 2.0 &lt;BR&gt;This library is available at: &lt;A href="http://workspaces.gotdotnet.com/ndde"&gt;http://workspaces.gotdotnet.com/ndde&lt;/A&gt; &lt;BR&gt;&lt;BR&gt;This project and the NDDE library require the .NET Framework 2.0 installed with Visual Studio 2005, or available at &lt;BR&gt;&lt;A href="http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5"&gt;http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&lt;/A&gt; &lt;BR&gt;
&lt;H2&gt;Read More About It&lt;/H2&gt;
&lt;P&gt;Alpari user's guide for Metatrader&lt;BR&gt;&lt;A href="http://www.alpari-idc.com/en/userguide/metatrader/4.php"&gt;http://www.alpari-idc.com/en/userguide/metatrader/4.php&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;AmiBroker DDE guide&lt;BR&gt;&lt;A href="http://www.amibroker.com/dde.html"&gt;http://www.amibroker.com/dde.html &lt;/A&gt;&lt;/P&gt;
&lt;P&gt;The DDE client page in the 4XLab.NET site&lt;BR&gt;&lt;A HREF="/cs/forums/136/ShowPost.aspx"&gt;http://www.4xlab.net/cs/forums/136/ShowPost.aspx&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;&lt;BR&gt;&amp;nbsp;&lt;/P&gt;This article is published on &lt;A href="http://www.codeproject.com/useritems/Realtime_Quotes.asp"&gt;http://www.codeproject.com/useritems/Realtime_Quotes.asp&lt;/A&gt;&lt;A&gt;&lt;/A&gt;</description></item><item><title>Creating a Mechanical Trading System Part 2: Four Percent Trading System</title><link>http://www.4xlab.net/cs/forums/145/ShowPost.aspx</link><pubDate>Mon, 11 Sep 2006 00:23:42 GMT</pubDate><guid isPermaLink="false">3bf9340b-8e96-4367-9a26-b022cb783a8d:145</guid><dc:creator>asimon</dc:creator><slash:comments>0</slash:comments><description>&lt;UL&gt;
&lt;LI&gt;&lt;A href="/images/Trading_System_src.zip"&gt;Download source files - 35 Kb&lt;/A&gt; &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;&lt;IMG height=300 src="/images/Trading_System.jpg" width=300&gt;&lt;/P&gt;
&lt;H2&gt;Introduction&lt;/H2&gt;
&lt;P&gt;The first article in this series introduced a project to code mechanical trading system robots for the .NET platform using the C# language. This article introduces how to code a trading system that will watch price action and make buying or selling decisions. It is the aim of this project to write a program that does not depend on any underlying platform to execute, but rather receives price data directly from a broker and places orders via an API. &lt;/P&gt;
&lt;P&gt;The code provided here is part of a larger project to create a backtesting platform and an automated FOREX trading robot. Source code for this project is available at &lt;A href="/"&gt;http://www.4xlab.net&lt;/A&gt; &lt;/P&gt;
&lt;H2&gt;Background&lt;/H2&gt;
&lt;P&gt;This article implements the 4 percent model, developed by Ned Davis and popularized by Martin Zweig in his book Winning on Wall Street. This is a very simple trend following model that will put you on the right side of a sustained trend. This is not to say that this system does not have weaknesses. If too small of a percentage is chosen, the system can whipsaw, or execute many small losing trades. &lt;/P&gt;
&lt;P&gt;This system makes an initial buying or selling decision depending on whether the prices rise or fall more than a certain percentage from the first price seen. Once the initial direction is set, the system reverses its position when the prices retrace a certain percentage from a local maximum or minimum value. For example, if the system is buying, and the price rises to a maximum of 104, then retraces back to 100, the system will then close the long position and sell to establish a short position. &lt;/P&gt;
&lt;P&gt;This is a reversal system and it is continuously in the market. To fully utilize its potential, it must be implemented on a market that allows traders to go long or short with equal ease. The futures, options, and Forex markets all possess this property. &lt;/P&gt;
&lt;P&gt;This project implements the random walk algorithm to generate simulated price data. The algorithm is shown in the boxes below. A virtual coin is flipped each time the function is called. If heads, the price increases by 1c, if tails, the price decreases by 1c. This random data is then sent to the account manager and to the trading system. The trading system makes a decision and notifies the account manager if it wants to buy or sell. The account manager then outputs the trade log to the screen. &lt;/P&gt;
&lt;H2&gt;Simulated Trading Example&lt;/H2&gt;
&lt;P&gt;The screenshot at the beginning of this article shows a run of the algorithm through random walk data. The price starts at 100 and starts randomly moving up and down by 1c. Since 100 is going to be the fist price, the first decision will be to buy if prices rise by 4% to 104, or sell if prices fall by 4% to 96. In this example, the 96 price target was hit first and the system places a sell order. The system is now looking for new lows, if prices retrace from this new low by 4%, then the system closes the sell order and places a buy order. In this example, the system reverses position at 98.01 as shown, since the prices must have come down to 94.08 (4% below 98.01). In the hypothetical example shown, after adding the transactions shown in the screen, the system shows a profit of 4.92. This very simple system that will put you on the right side of a sustained trend, but is susceptible to whipsaws if the percentage is not appropriate for the width of the oscillations between maximums and minimums. Perhaps use of the ATR or the ADX indicators could reduce the whipsaws.&lt;/P&gt;
&lt;H2&gt;Using the code&lt;/H2&gt;
&lt;P&gt;This project has been arranged so that an unmodified trading system taken from the 4xlab.net project executes successfully. The supporting class framework has been implemented in a minimalistic way to allow this system to output trading decisions. Features such as parameter optimization and end of trading reports containing gains, loses and drawdown figures are not available in this project. &lt;/P&gt;
&lt;P&gt;The FourPercentModel.cs file contains a complete implementation for a trading system. The &lt;CODE&gt;fPercentageChange&lt;/CODE&gt; class inherits from the &lt;CODE&gt;ForexObject&lt;/CODE&gt;. This allows the framework to receive and execute trading systems by treating them as their base class (ForexObject). &lt;/P&gt;
&lt;P&gt;The Base class &lt;CODE&gt;ForexObject&lt;/CODE&gt; defines the following methods &lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;CODE&gt;&lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; Init(string pParameters)&lt;/CODE&gt; 
&lt;P&gt;This method initializes the object. This was chosen instead of the constructor to allow an existing object to be re-initialized and allow the object to remember multiple runs with different parameters for optimization purposes.&lt;/P&gt;
&lt;P&gt;The system is initialized by sending it a parameter string in which parameter:value pairs are separated by semicolons. If no parameters are sent, the object is responsible for selecting default values.&lt;/P&gt;
&lt;LI&gt;&lt;CODE&gt;&lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; ReceiveTick(sTick pTick)&lt;/CODE&gt; 
&lt;P&gt;The following two methods are used by the object to receive real time quote data. If the object wants to receive tick data, it will register itself with the framework as a tick listener. The private method &lt;CODE&gt;DecisionFunction&lt;/CODE&gt; must be called either here, or in the &lt;CODE&gt;ReceiveCandle&lt;/CODE&gt; method.&lt;/P&gt;
&lt;P&gt;The &lt;CODE&gt;DecisionFunction&lt;/CODE&gt; method is responsible for analyzing quote data and making buying or selling decisions executed through the &lt;CODE&gt;Account&lt;/CODE&gt; object. In this example it can be seen that the decision function involves looking for new minimums or new maximums depending on the current trading direction. Once prices retrace by a specified percentage, the system reverses direction. Trades are entered by calling &lt;CODE&gt;Framework.Account.EnterTrade(&lt;SPAN class=cpp-keyword&gt;int&lt;/SPAN&gt; pDirection)&lt;/CODE&gt;. For buy orders, use +1 for direction, use -1 for sell orders. The Account object returns its trading status via the &lt;CODE&gt;Framework.Account.InTrade()&lt;/CODE&gt; method. A positive value means a buy order is open; a negative value means a sell order is open. Zero is returned if the there are no trades open.&lt;/P&gt;
&lt;LI&gt;&lt;CODE&gt;&lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; ReceiveCandle(sCandle pCandle, &lt;SPAN class=cpp-keyword&gt;int&lt;/SPAN&gt; pPeriod, string pCBTitle) &lt;/CODE&gt;
&lt;P&gt;This method is used by the object to receive candle data. To accomplish this, the object must register itself with the framework as a candle listener.&lt;/P&gt;
&lt;LI&gt;&lt;CODE&gt;&lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;bool&lt;/SPAN&gt; Finished()&lt;/CODE&gt; 
&lt;P&gt;This method allows the object to be called several times by the framework. The object can choose to change quote data after the end of each run and compare runs internally. If so, the first time the object is finished receiving quote data and this method is called, the object switches quote data and returns false. The second time around, this method will return true.&lt;/P&gt;
&lt;LI&gt;&lt;CODE&gt;&lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override string Title()&lt;/CODE&gt; 
&lt;P&gt;This method allows individual objects in a collection to be identified by a friendly name.&lt;/P&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;File: FourPercentModel.cs&lt;/P&gt;&lt;PRE&gt;&lt;SPAN class=cpp-comment&gt;//&lt;/SPAN&gt;
&lt;SPAN class=cpp-comment&gt;// 4X Lab.NET © Copyright 2005-2006 ASCSE LLC&lt;/SPAN&gt;
&lt;SPAN class=cpp-comment&gt;// http://www.4xlab.net&lt;/SPAN&gt;
&lt;SPAN class=cpp-comment&gt;// email: 4xlab@4xlab.net&lt;/SPAN&gt;
&lt;SPAN class=cpp-comment&gt;//&lt;/SPAN&gt;

using System;

&lt;SPAN class=cpp-keyword&gt;namespace&lt;/SPAN&gt; FourPercentShell
{
    &lt;SPAN class=cpp-comment&gt;// UNMODIFIED CLASS, SAME AS IN 4XLAB.NET&lt;/SPAN&gt;
    
    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; &lt;SPAN class=cpp-keyword&gt;class&lt;/SPAN&gt; fPercentageChange : ForexObject
    {
    &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; iPercentage;
    &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; iMin;
    &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; iMax;

    &lt;SPAN class=cpp-keyword&gt;bool&lt;/SPAN&gt;   FirstTick;
    sTick  Tick;
    &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; Spread;

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; fPercentageChange()
    {
    }

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; Init(string pParameters)
    {
        &lt;SPAN class=cpp-keyword&gt;this&lt;/SPAN&gt;.InitializeParameters(pParameters,&lt;SPAN class=cpp-string&gt;"PERCENT:0.001;"&lt;/SPAN&gt;);

        iPercentage = PParser.GetDouble(&lt;SPAN class=cpp-string&gt;"PERCENT"&lt;/SPAN&gt;,&lt;SPAN class=cpp-literal&gt;0&lt;/SPAN&gt;);

        Framework.TickServer.RegisterTickListener(&lt;SPAN class=cpp-string&gt;"System"&lt;/SPAN&gt;,&lt;SPAN class=cpp-string&gt;"*"&lt;/SPAN&gt;,&lt;SPAN class=cpp-keyword&gt;this&lt;/SPAN&gt;);

        Framework.WriteGraphLine(&lt;SPAN class=cpp-string&gt;"InTrade,Margin,Tick,Min,MinTh,Max,MaxTh"&lt;/SPAN&gt;);

        FirstTick = &lt;SPAN class=cpp-keyword&gt;true&lt;/SPAN&gt;;
    }

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; ReceiveTick(sTick pTick)
    {
        Spread    = pTick.Ask - pTick.Bid;
        Tick    = pTick;

        DecisionFunction();
    }

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; ReceiveCandle(sCandle pCandle, &lt;SPAN class=cpp-keyword&gt;int&lt;/SPAN&gt; pPeriod, string pCBTitle)
    {
    }

    
    &lt;SPAN class=cpp-keyword&gt;private&lt;/SPAN&gt; &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; DecisionFunction()
    {

        &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (FirstTick)
        {
        FirstTick = &lt;SPAN class=cpp-keyword&gt;false&lt;/SPAN&gt;;
        iMin = Tick.Bid;
        iMax = Tick.Bid;
        }
        &lt;SPAN class=cpp-keyword&gt;else&lt;/SPAN&gt;
        {
        &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (Framework.Account.InTrade()==&lt;SPAN class=cpp-literal&gt;1&lt;/SPAN&gt;)
        {
            &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (Tick.Bid &amp;gt; iMax)
            {
            iMax = Tick.Bid;
            }
            
            &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; ((iMax-Tick.Bid) &amp;gt; iPercentage*iMax)
            {
            Framework.Account.ExitTrade();
            Framework.Account.EnterTrade(-&lt;SPAN class=cpp-literal&gt;1&lt;/SPAN&gt;);
            iMin = Tick.Bid;
            iMax = &lt;SPAN class=cpp-literal&gt;0&lt;/SPAN&gt;;
            }
        }

        &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (Framework.Account.InTrade()==-&lt;SPAN class=cpp-literal&gt;1&lt;/SPAN&gt;)
        {
            &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (Tick.Bid &amp;lt; iMin)
            {
            iMin = Tick.Bid;
            }
            
            if ((Tick.Bid-iMin) &amp;gt; iPercentage*iMin)
            {
            Framework.Account.ExitTrade();
            Framework.Account.EnterTrade(&lt;SPAN class=cpp-literal&gt;1&lt;/SPAN&gt;);
            iMax = Tick.Bid;
            iMin = &lt;SPAN class=cpp-literal&gt;0&lt;/SPAN&gt;;
            }
        }

        &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (Framework.Account.InTrade()==&lt;SPAN class=cpp-literal&gt;0&lt;/SPAN&gt;)
        {

            &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; ((Tick.Bid-iMin) &amp;gt; iPercentage*iMin)
            {
            Framework.Account.EnterTrade(&lt;SPAN class=cpp-literal&gt;1&lt;/SPAN&gt;);
            iMax = Tick.Bid;
            iMin = &lt;SPAN class=cpp-literal&gt;0&lt;/SPAN&gt;;
            }

            &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; ((iMax-Tick.Bid) &amp;gt; iPercentage*iMax)
            {
            Framework.Account.EnterTrade(-&lt;SPAN class=cpp-literal&gt;1&lt;/SPAN&gt;);
            iMin = Tick.Bid;
            iMax = &lt;SPAN class=cpp-literal&gt;0&lt;/SPAN&gt;;
            }

        }

        }

        &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; logInTrade = Framework.Account.InTrade();
        &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; logMargin  = Framework.Account.GetAccount().C;

        &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; MinTh = iMin + iMin*iPercentage;
        &lt;SPAN class=cpp-keyword&gt;double&lt;/SPAN&gt; MaxTh = iMax - iMax*iPercentage;

        Framework.WriteGraphLine(logInTrade+&lt;SPAN class=cpp-string&gt;","&lt;/SPAN&gt;+logMargin+&lt;SPAN class=cpp-string&gt;","&lt;/SPAN&gt;+Tick.Bid+&lt;SPAN class=cpp-string&gt;","&lt;/SPAN&gt;+
                     iMin+&lt;SPAN class=cpp-string&gt;","&lt;/SPAN&gt;+MinTh+&lt;SPAN class=cpp-string&gt;","&lt;/SPAN&gt;+iMax+&lt;SPAN class=cpp-string&gt;","&lt;/SPAN&gt;+MaxTh);
    }

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override &lt;SPAN class=cpp-keyword&gt;bool&lt;/SPAN&gt; Finished()
    {
        &lt;SPAN class=cpp-keyword&gt;bool&lt;/SPAN&gt; returnv = &lt;SPAN class=cpp-keyword&gt;true&lt;/SPAN&gt;;

        &lt;SPAN class=cpp-keyword&gt;return&lt;/SPAN&gt; returnv;
    }

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; override string Title()
    {
        &lt;SPAN class=cpp-keyword&gt;return&lt;/SPAN&gt; &lt;SPAN class=cpp-string&gt;"% Trend Change"&lt;/SPAN&gt;;
    }
    }

}

&lt;/PRE&gt;
&lt;P&gt;The following file shows how the Tick Server generates simulated price data based on the random walk model. First, the price is incremented or decremented depending on a random number. Then a Tick object is created with Bid and Ask prices. Afterwards, the tick is sent first to the account simulator and to the registered tick listener later. The code implemented here only allows for one registered tick listener in addition to the account simulator. &lt;/P&gt;File: Framework.cs &lt;PRE&gt;    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; &lt;SPAN class=cpp-keyword&gt;class&lt;/SPAN&gt; oTickServer
    {
    
    ...

    &lt;SPAN class=cpp-keyword&gt;public&lt;/SPAN&gt; &lt;SPAN class=cpp-keyword&gt;void&lt;/SPAN&gt; GenerateTick()
    {
        &lt;SPAN class=cpp-keyword&gt;int&lt;/SPAN&gt; randomint = (&lt;SPAN class=cpp-keyword&gt;int&lt;/SPAN&gt;)(RNG.NextDouble()*&lt;SPAN class=cpp-literal&gt;1000&lt;/SPAN&gt;);

        &lt;SPAN class=cpp-keyword&gt;if&lt;/SPAN&gt; (randomint&amp;gt;&lt;SPAN class=cpp-literal&gt;500&lt;/SPAN&gt;)
        {
        price++;
        }
        &lt;SPAN class=cpp-keyword&gt;else&lt;/SPAN&gt;
        {
        price--;
        }

        Tick = &lt;SPAN class=cpp-keyword&gt;new&lt;/SPAN&gt; sTick();

        Tick.Bid = price;
        Tick.Ask = Tick.Bid + &lt;SPAN class=cpp-literal&gt;0.01&lt;/SPAN&gt;;

        Framework.Account.ReceiveTick(Tick);
        tl.ReceiveTick(Tick);
    }

    ...

    }
&lt;/PRE&gt;
&lt;H2&gt;Read More About It&lt;/H2&gt;
&lt;P&gt;Google search for "four percent model"&lt;BR&gt;&lt;A href="http://www.google.com/search?q=four+percent+model"&gt;http://www.google.com/search?q=four+percent+model&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;Post on four percent model, contains a link to an optimization tutorial, download more trading systems and a trading simulator&lt;BR&gt;&lt;A HREF="/cs/forums/100/ShowPost.aspx"&gt;http://www.4xlab.net/cs/forums/100/ShowPost.aspx&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;This article is published on &lt;A href="http://www.codeproject.com/useritems/Trading_System.asp"&gt;http://www.codeproject.com/useritems/Trading_System.asp&lt;/A&gt;&lt;/P&gt;</description></item><item><title>Creating a Mechanical Trading System Part 1: Technical Indicators</title><link>http://www.4xlab.net/cs/forums/144/ShowPost.aspx</link><pubDate>Mon, 11 Sep 2006 00:10:14 GMT</pubDate><guid isPermaLink="false">3bf9340b-8e96-4367-9a26-b022cb783a8d:144</guid><dc:creator>asimon</dc:creator><slash:comments>0</slash:comments><description>&lt;UL&gt;
&lt;LI&gt;&lt;A HREF="/images/Technical_Indicators_src.zip"&gt;Download source files - 1 Kb&lt;/A&gt; &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;&lt;IMG height=251 src="/images/Technical_Indicators.jpg" width=595&gt;&lt;/P&gt;
&lt;H2&gt;Introduction&lt;/H2&gt;
&lt;P&gt;This article explains how to code technical analysis indicators on the .NET platform using the C# language. This is the first step towards creating a fully automated trading robot that does not depend on any underlying platform to perform its tasks. The final product will receive quotes directly from a broker via an API, perform price analysis, and decide whether or not to place orders to buy or sell.&lt;/P&gt;
&lt;P&gt;The code provided here is part of a larger project to create a backtesting platform and an automated FOREX trading robot. Source code for this project is available at &lt;A HREF="/"&gt;http://www.4xlab.net/&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;This will cover the implementation details of the Exponential Moving Average, and the Moving Average Convergence Divergence (MACD) indicators. These two indicators have been chosen to exemplify how modular design and object oriented programming can help create complex indicators out of simple ones.&lt;/P&gt;
&lt;P&gt;The MACD indicator has been chosen for this article since it produces a rather distinct entry signal based on its two lines crossing. This article does not advocate taking the crossovers both as entry and exit signals since this indicator is lagging and produces signals once the trend has changed. The entries provided by this indicator should be complemented with exit techniques based on other indicators. Of particular interest are exits described by Charles Le Beau using the Average True Range indicator such as the Chandelier and Yoyo Exits.&lt;/P&gt;
&lt;H2&gt;Background&lt;/H2&gt;
&lt;P&gt;The nature of the final product, a trading robot, demands that the indicators are coded with real time signals in mind. Each indicator has four important methods:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;I&gt;&lt;CODE&gt;&lt;I&gt;Constructor&lt;/I&gt;&lt;/CODE&gt;&lt;/I&gt;: Initializes the object and instantiates any other indicators needed. 
&lt;LI&gt;&lt;I&gt;&lt;CODE&gt;&lt;I&gt;ReceiveTick&lt;/I&gt;&lt;/CODE&gt;&lt;/I&gt;: Informs the indicator that a new value has been received. The indicator can now store it in an internal buffer, or perform computations with the new value 
&lt;LI&gt;&lt;I&gt;&lt;CODE&gt;&lt;I&gt;Value&lt;/I&gt;&lt;/CODE&gt;&lt;/I&gt;: Returns the value of the indicator. This method uses the internal buffer filled by ReceiveTick to compute its data. 
&lt;LI&gt;&lt;I&gt;&lt;CODE&gt;&lt;I&gt;IsPrimed&lt;/I&gt;&lt;/CODE&gt;&lt;/I&gt;: Returns true when the indicator has received enough values to start producing a meaningful output. For example, a 14 period simple moving average will not return output values until 14 input values are received. &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;The MACD indicator is constructed with three EMAs. A slow (longer period) EMA and a fast (shorter period) EMA both receive the current price. The difference from the fast and slow EMAs is called the MACD, and is sent to a third EMA called the Signal. The values plotted in the chart are the MACD and the Signal. By instantiating three EMA objects and defining the relationships between them, a more complex indicator such as the MACD can be easily created.&lt;/P&gt;
&lt;P&gt;Indicators have to be instantiated first with the proper parameters. Then the &lt;CODE&gt;ReceiveTick&lt;/CODE&gt; method needs to be called with a value. To obtain the result from the indicator, the &lt;CODE&gt;Value&lt;/CODE&gt; method needs to be called. This method returns a value of 0 if not enough values have been received. The &lt;CODE&gt;IsPrimed&lt;/CODE&gt; method can be called to determine if the indicator has received enough values to compute a value.&lt;/P&gt;
&lt;P&gt;Note that the &lt;CODE&gt;ReceiveTick&lt;/CODE&gt; method can either receive price data, or data from another indicator. This flexibility is what enables the MACD indicator to be built from three Exponential Moving Average objects&lt;/P&gt;
&lt;H2&gt;Source Code&lt;/H2&gt;&lt;PRE&gt;&lt;SPAN class=cs-comment&gt;//&lt;/SPAN&gt;
&lt;SPAN class=cs-comment&gt;// 4X Lab.NET © Copyright 2005-2006 ASCSE LLC&lt;/SPAN&gt;
&lt;SPAN class=cs-comment&gt;// http://www.4xlab.net&lt;/SPAN&gt;
&lt;SPAN class=cs-comment&gt;// email: 4xlab@4xlab.net&lt;/SPAN&gt;
&lt;SPAN class=cs-comment&gt;//&lt;/SPAN&gt;

using System;

namespace _4XLab.NET
{
    public class iEMA
    {
        private int tickcount;
        private int periods;
        private double dampen;
        private double emav;

        public iEMA(int pPeriods)
        {
            periods = pPeriods;
            dampen  = 2/((double)1.0+periods);
        }

        public void ReceiveTick(double Val)
        {
            if (tickcount &amp;lt; periods)
                emav += Val;
            if (tickcount ==periods)
                emav /= periods;
            if (tickcount &amp;gt; periods)
                emav = (dampen*(Val-emav))+emav;

            if (tickcount &amp;lt;= (periods+1) )
            {            
                &lt;SPAN class=cs-comment&gt;// avoid overflow by stopping use of tickcount&lt;/SPAN&gt;
                &lt;SPAN class=cs-comment&gt;// when indicator is fully primed&lt;/SPAN&gt;
                tickcount++;
            }
        }

        public double Value()
        {
            double v;

            if (isPrimed())
                v = emav;
            else
                v = 0;

            return v;
        }

        public bool isPrimed()
        {    
            bool v = false;
            if (tickcount &amp;gt; periods)
            {
                v = true;
            }
            return v;
        }
    }

    public class iMACD
    {
        int pSlowEMA, pFastEMA, pSignalEMA;
        iEMA slowEMA, fastEMA, signalEMA;

        &lt;SPAN class=cs-comment&gt;// restriction: pPFastEMA &amp;lt; pPSlowEMA&lt;/SPAN&gt;
        public iMACD(int pPFastEMA, int pPSlowEMA, int pPSignalEMA)
        {
            pFastEMA = pPFastEMA;
            pSlowEMA = pPSlowEMA;
            pSignalEMA = pPSignalEMA;

            slowEMA = new iEMA(pSlowEMA);
            fastEMA = new iEMA(pFastEMA);
            signalEMA = new iEMA(pSignalEMA);
        }

        public void ReceiveTick(double Val)
        {
            slowEMA.ReceiveTick(Val);
            fastEMA.ReceiveTick(Val);

            if (slowEMA.isPrimed() &amp;amp;&amp;amp; fastEMA.isPrimed())
            {
                signalEMA.ReceiveTick(fastEMA.Value()-slowEMA.Value());
            }
        }

        public void Value(out double MACD, out double signal, out double hist)
        {
            if (signalEMA.isPrimed())
            {
                MACD = fastEMA.Value() - slowEMA.Value();
                signal = signalEMA.Value();
                hist = MACD - signal;
            }
            else
            {
                MACD = 0;
                signal = 0;
                hist = 0;
            }
        }

        public bool isPrimed()
        {    
            bool v = false;
            if (signalEMA.isPrimed())
            {
                v = true;
            }
            return v;
        }

    }

}
&lt;/PRE&gt;
&lt;H2&gt;Credits&lt;/H2&gt;The image in this article was obtained with a product that includes software developed as part of the NPlot library project available from: &lt;A href="http://www.nplot.com/"&gt;http://www.nplot.com/&lt;/A&gt; 
&lt;H2&gt;Read More About It&lt;/H2&gt;
&lt;P&gt;&lt;A href="http://en.wikipedia.org/wiki/Weighted_moving_average"&gt;http://en.wikipedia.org/wiki/Weighted_moving_average&lt;/A&gt;&lt;BR&gt;&lt;/P&gt;
&lt;P&gt;Moving Average Formulas:&lt;BR&gt;&lt;A href="http://www.stockcharts.com/education/IndicatorAnalysis/indic_movingAvg.html"&gt;http://www.stockcharts.com/education/IndicatorAnalysis/indic_movingAvg.html&lt;/A&gt;&lt;BR&gt;&lt;/P&gt;
&lt;P&gt;Description of several popular indicators:&lt;BR&gt;&lt;A href="http://www.stockcharts.com/education/IndicatorAnalysis/index.html"&gt;http://www.stockcharts.com/education/IndicatorAnalysis/index.html&lt;/A&gt;&lt;BR&gt;&lt;/P&gt;
&lt;P&gt;Read more about the code and techniques in this article:&lt;BR&gt;&lt;A HREF="/"&gt;http://www.4xlab.net/&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;This article is published on &lt;A href="http://www.codeproject.com/useritems/Technical_Indicators.asp"&gt;http://www.codeproject.com/useritems/Technical_Indicators.asp&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description></item></channel></rss>