Latest Threads

Forum Statistics
  • Forum posts:226
  • Forum threads:59
  • Members:13,493
  • Latest member:g6syqjd295


Posted by: Hassam
04-16-2018, 01:27 PM
Forum: Quantitative Trading Strategies
- Replies (1)

Forex Profit Nexus Trading System is being given as a gift for a few days by Russ Horn. If you have been trading forex for a while you must have heard about Russ Horn. He is giving a Forex Profit Nexus 13 page PDF, plus indicators, templates and an installer free for a few days as part of the pre-launch of his Forex Master Method Evolution System. You can Forex Profit Nexus. Below is a screenshot of this system in action.
[Image: forexprofitnexus1.jpg]
Forex Profit Nexus system comprises of 4 indicators:
1.Wave
2.Arrows
3.Oscillator
4.CCIHisto

Go through the 13 page PDF, Russ Horn explains everything in detail. Oscillator is just the difference of two moving averages just like MACD and it is used to determine market bias. Below is another screenshot of this system:
[Image: forexprofitnexus2.jpg]
As the screenshot shows, when the oscillator is blue, you only look for a buy trade and when the oscillator is orange, you look for sell trades. Now any trading system that can be coded into an indicator like this Forex Profit Nexus System is known as a Quantitative Trading System. You can call it system/strategy whatever you want. This is something important for you to understand.

Quantitative trading strategies can be backtested using market data. Forex Profit Nexus system can be backtested and forward tested. These two tests are important for the evaluation of any trading system. You can download this Forex Profit Nexus System and test it on your demo account. In the next few days, Russ Horn is going to open the door to his Forex Master Method Evolution trading system that can also win a copy free by leaving a comment below the Forex Profit Nexus System download page explaining how this system will help you.

Print this item


Posted by: Hassam
04-11-2018, 06:48 AM
Forum: Stochastic Calculus
- Replies (1)

Monte Carlo simulation is very important when it comes to testing a trading strategy. In this thread I will discuss Monte Carlo simulation with financial applications that traders can use in their trading strategies. Before we start discussing Monte Carlo simulation, we need to have some basic understanding of stochastic calculus. Most of the traders don't have any knowledge of stochastic calculus. So I will start from the very basics in this thread and take you by hand step by step. So let's start first with Probability theory.

Probability Spaces

As a trader you should have some basic understanding of probability theory. Probability Spaces is an important concept to understand. Discussion on probability space starts with a sample space. Sample space is the set of all possible outcomes of an experiment. When trading, our sample space will be set of all possible prices of a currency pair or a stock. Sample space is denoted by Ω. Sample point is the most basic element in the sample space. When defining probability spaces, the concept of sigma algebra is used. We will not use this concept here and try to keep the things as much simple as possible.

Any subset of the sample space is called an Event. Events are denoted by A, B, C etc. An empty set is always a subset of the sample space and is usually denoted by ∅. Sample points are also known as elementary events and denoted by {a} where a is any elementary event. Complement of an event A is denoted by A'. Intersection of two events A and B is denoted by AnB or AB. AnB is the set of elements common to A and B both. Union of two events A and B is denoted by AuB. AuB is the set of elements that belong to A or B.

Probability Measure
We have a sample space and events on that sample space. These events are subsets of the sample space. A Probability Measure is a function also called a mapping that maps each event onto the unit interval [0,1] on the real line. Symbolically we show a probability measure as P: Ω-->[0,1]. What this means is that in simple terms P takes every subset of S and assigns it a value between 0 and 1. Now P cannot be any function. P needs to satisfy the following three conditions before we can call it a probability measure on sample space Ω:

1) P(Ω)=1 what this means is that the probability measure assigned to the sample space is 1. Sample space is always a sure event meaning whatever happens happens within the sample space Ω.
2) For any event A: 0 <P(A)<1 meaning that probability of an event is always between 0 and 1.
3) For any set of events {A1, A2, A3, A4,...} that are mutually disjoint meaning AinAj=∅ we have P(UAi)=∑P(Ai). This means that probability measure is additive for mutually disjoint events that have nothing in common with each other.

For any two events A and B that are not disjoint we have P(AuB)=P(A)+P(B)-P(AnB).

Conditional Probability and Independence
Concept of independence and conditional probability is important. Any two events A and B are independent if P(AB)=P(A)P(B). Similarly events A, B, C and D are independent if P(ABCD)=P(A)P(B)P©P(D). Let A and B be two events. Conditional probability of A given B is denoted by P(A|B) and P(A|B)=P(AB)/P(B). If A and B are independent events than P(A|B)=P(A). What this means is that probability of A happening is independent of probability of event B happening or in other words if B happens it does not affect A in any manner whatsoever.

Print this item


Posted by: Hassam
04-10-2018, 03:09 PM
Forum: Algorithmic Trading With Python
- Replies (9)

Tensorflow is an open source library developed by Google. Tensorflow has become very popular in machine learning, deep learning and reinforcement learning. If you want to develop algorithmic trading strategies using Python than you must master Tensorflow in addition to Pandas and Numpy. I will start separate threads for Pandas and Numpy. In this thread we only discuss Tensorflow. Tensorflow has been developed to efficiently do numerically computations involving very big arrays which are mathematically known as tensors. Tensors are just arrays with many indices. Matrix is a rank 1 tensor. Scalars like real numbers are rank zero tensors. Machine learning/deep learning involves heavy matrix operations and tensor operations.

In a different thread in MQL4 forum, I discussed how difficult it is to develop machine learning/deep learning/reinforcement learning libraries. Tensorflow development took many months spanning a few years. Tensorflow was developed by the Google Brain Team. Lot of effort went into its development so you can well imagine how much effort developing good machine learning/deep learning/reinforcement learning libraries can take. These libraries are developed by teams of professionals. Tensorflow is basically written in C++ with a Python wrapper at the front end.

Tensorflow GPU versus CPU

This is how Tensorflow works conceptually. First we define a computation graph using standard tensorflow components. Tensorflow takes that graph and performs the numerical computations using C++ in a highly efficient manner. Tensorflow has two versions CPU as well as GPU. GPU version is suited for doing very heavy numerical computations involving millions of parameters. First you need a GPU computer. If you have a GPU computer, like an NVIDIA GPU computer, you can install tensorflow gpu on it. As a trader, we won't be doing very heavy computations so CPU is good enough for us. You can install GPU version, its speed is almost the same as that for CPU for small datasets. Tensorflow can also be used for distributed computing and is being used in Google large scale systems. Tensorflow can run on Windows, Linux, macOs as well as mobile devices using iOs and Android. What this means is that you should master tensorflow, you can always find it handy. You can install tensorflow with this simple  pip command

pip install tensorflow

Installing tensorflow gpu requires first installing CUDA and other things before you can install it. As I said I have personally tested it for small datasets there is no advantage going through the extra steps involved in installing gpu version as cpu version provides the services in almost the same time as gpu version. I used the following code to check how much time it takes tensorflow to load on my computer:

from time import time    
t=time()
import tensorflow as tf
print(time()-t)
print(time()-t)

7.185936212539673


it took 7 seconds for tensorflow to load on my computer which is pretty fast. Let's start with a simple calculation x^3/y+8. As I have said first we will build a computation graph:

import tensorflow as tf
x=tf.Variable(89, name="x")
y=tf.Variable(27, name="y")
z=x*x*x/y+8

In the above code we have build a computation graph. Now we need to open a tensorflow session that will build this computation graph. We don't have to worry. Tensorflow will decide how many CPUs/GPUs to use. Of course this is a simple code example and not very complicated. But imagine we had over 20 million parameters. It would have been headache to decide how to do the numerical computation efficiently. Tensorflow would have helped us by deciding how to do numerical computations involving more than 20 million parameters by taking account of the computer's capabilities. For now this is how we are going to start the tensorflow session:

sess = tf.Session()
sess.run(x.initializer)
sess.run(y.initializer)
answer=sess.run(z)
print(answer)
print(answer)
26118.0
sess.close()

In the above code we first start the tensorflow session and then use run to build the graph. In the end we close the session which is important.

Print this item


Posted by: Hassam
04-10-2018, 11:31 AM
Forum: MQL4
- No Replies

ZeroMQ is a messaging library that has bindings in over 2 dozen languages. MT4 is a robust but simple platform. It can stream price data and show it on charts. This is all that it can do. There are a number of inbuilt functions that we can use to define indicators and expert advisors. Indicators and expert advisors that we can build using MQL4 language are really very simple. Most of these indicators are based on simple if-else logic functions. In short, MQL4 is a simple language that follows C/C++ syntax. But it lacks the power of modern object oriented languages like Python, Java, C++ and R.

When we use Python, Java, C++ and R, we have numerous packages and libraries that we can use to do machine learning. We can also use deep learning and reinforcement learning. Writing these libraries and packages is a professional job. Professional developers with many years of coding experience have written these advanced algorithms and then optimized the code so that it executes seamlessly. If you thinking about writing machine learning libraries for MQL4 then forget about it.

If you want to develop EAs and indicators that use machine learning/deep learning/reinforcement learning to predict price action, what is the solution? Solution is simple.  We will use ZeroMQ messaging library. We will use MQL-ZMQ bindings to connect MT4 with Python, Java and R. I have started this thread for this purpose. I will show you how to do it. Writing the MQL-ZMQ MT4 bindings is not easy. it is a difficult job. But our job has been made easy by Mr Ding Li. You can download the MQL-ZMQ bindings for MT4 from his Github. There are a number of bindings provided on ZeroMQ official site. MQL4ZMQ bindings listed on the ZeroMQ site has not been updated for the last 2 years. The bindings that I have suggested were last updated by Mr Ding Li 2 months back. I have gone through the bindings and I think this is the best bindings on MQL4-MT4 that are available.

ØMQ is the official low level API that connect two programs with each other for exchanging data and information. If you have learned a little bit of network programming than immediately the thought of sockets should have come to your mind. ØMQ indeed uses sockets but on steroids. Writing a socket library for MQL4 is a challenging task. There are people who have done it using WinSock32. The problem is you have to do everything from scratch in developing the socket library. WinSock32 get frequently updated by Microsoft, so your job is continuously to update your MQL4 socket library.

Don't know what are sockets? Sockets are packages that allow you to communicate with different programs. Python, Java, C++/C all have socket libraries. But the communication is synchronous. Synchronous sockets are also challenging job. ØMQ is asynchronous.

Print this item


Posted by: Hassam
04-07-2018, 06:52 AM
Forum: Java
- No Replies

Java 11 will be released in September of this year. Java 10 is the recent release now. Java Oracle team is working very hard to make Java the most powerful programming language. Java is already the most popular programming language with millions of programmers. Java has a huge demand in the market so if you learn Java for algorithmic trading, you can also use it to land a high paying job in the market. Java is being used in algorithmic trading a lot. I learned Java so that I could use it in algorithmic trading. But before you can use it in developing algorithmic trading strategies, you should master Java exception handling.

Exception occurs when the code you wrote faces a hurdle or a problem in its execution. Writing exception handling helps the application to resolve these exceptions and continue executing the code as if nothing has happened. So in java runtime errors are thrown as exceptions. Exception is an object in java that represents an error that is preventing the program from executing normally. If this exception is not handled, the program execution will be terminated abruptly. So this is important for you to understand. Exceptions are objects in Java and are defined using classes. The root class meaning the most basic class for exceptions is:

java.lang.Throwable

So Throwable is the root exception class meaning all other exception classes derive from this Throwable class using inheritance. We can also define our own exception classes by extending the Exception class or its subclass. Exception classes are of three types: 1)System Errors, 2) Exceptions and 3) Runtime Exceptions. System errors are thrown by JVM when there is some internal system error. System Errors are rare. But when they occur we can't do much about it. Only thing that we can do is terminate the program gracefully. Exceptions are handled by the Exception class as said earlier. Below are a few exceptions that you can encounter while developing a program:

ClassNotFoundException: Obvious when you try to run a class that is not there you will find this exception thrown.

IOException: This exception relates to input/output commands. You get an IOException FileNotFoundException when you try to open a file that is not there. When you try to read past the end of file, you get EOFException.

RuntimeException:  When you commit numeric mistakes in your code like diving by zero you get ArthimeticException. When you try to access an out of bound array index, you get IndexOutOfBoundException.

Error and RuntimeException are known as unchecked exception and you cannot deal with them using a try catch block code. Unchecked exceptions are due to logic errors in your code that you need to rectify. Java exception handling involves three steps comprising: declaring an exception, throwing an exception and catching an exception.

Declaring Exceptions
Java compiler invokes the main method and starts the program execution. Java does not require you to declare unchecked exceptions that are the runtime exception and the error. However every method must explicity state the types of checked exceptions that it can throw. For example if you are reading/writing a file, your method can throw IOException:

public void ReadCSV throws IOException

We are telling the compiler that our ReadCSV method can throw IOException. If our method can throw multiple exceptions, we should mention that explicitly:

public void ReadCSV throws Exceptio1, Exception2, Exception3

Throwing Exceptions
When the compiler detects an error during program execution it creates an instance of appropriate exception class and throws it like

throws new IllegalArgumentException("Wrong Argument")

This happens when the method wants a positive number but it is passed a negative number.

Catching Exceptions
When an exception is thrown, we can catch it.

try {
statements;
}
catch (Exception1 ex) {
handler of Exception1:
}

If no exception is thrown by the try block, catch block is skipped execution.

Print this item


Posted by: Hassam
04-06-2018, 06:12 AM
Forum: Algorithmic Trading With Python
- No Replies

I was coding a reinforcement learning algorithmic trading strategy in Python. I had to create a number of classes for the reinforcement learning trading trading. If you want to use Python for algorithmic trading then you should have a good grasp over its object oriented programming features. Some say Python is weak in object oriented programming department. I don't agree with that. I decided to starts a thread on Python Object Oriented Programming so as to reinforce my knowledge in this department. Design patterns are very important when it comes to coding. The focus should be on writing code that is efficient. Most new coders will learn this skill over time. When you get time, read a good book on Python Design Patterns.

Algorithmic trading is all about simulation, simulating different trading scenarios and choosing the best scenario. Object oriented programming was also born when someone tried to write simulation code. As I said in the first paragraph, writing efficient code is very important when it comes to algorithmic trading. Latency should be reduced to the minimum. Latency means the time taken to execute a set of commands. When we are coding an algorithmic trading strategy for high frequency data like 1 minute, writing efficient code becomes extremely important.  So our aim should be to write code that runs fast and doesn't waste the system resources. Let's write a small program that measure the time it taken for a program to execute:

from time import sleep, time
#define a function we use sleep for now instead of actual execution
def TradeOpen(sleepTime=0.2):
    sleep(sleepTime)
#define a function to measure how much time taken to execute
def TimeTaken(func, *args, **kwargs):
    t=time()
    func(*args, **kwargs)
    print(func.__name__, 'Time Taken For Execution', time()-t)

TimeTaken(TradeOpen, sleepTime=1)

We already know what is the time taken by this program as it is doing nothing just sleeping. However the above program can be modified and used to measure the time taken by any program to execute. This was the output:

def TimeTaken(func, *args, **kwargs):
    t=time()
    func(*args, **kwargs)
    print(func.__name__, 'Time Taken For Execution', time()-t)


TimeTaken(TradeOpen, sleepTime=1)
TradeOpen Time Taken For Execution 1.0007438659667969

Did you notice *args and *kwargs in the above code? What is this? When you don't know before hand how many parameters to pass in a function definition, *args lets you pass a variable number of parameters in the function definition. Most Python coders use *args for this. You can use *vars if you want just keep this in mind * is important rest you can change. In the same manner **kwargs is an unknown dictionary that you don't know beforehand. Everything in Python is an object. You should remember this. This is very important. Let's define a very simple class:

class AlgorithmicTrading():
    pass

print(type(AlgorithmicTrading()))
<class '__main__.AlgorithmicTrading'>

Most of the time we will be using this pass command when defining algorithmic trading strategies. We will use pass in the beginning when we don't have enough idea about our algorithmic trading strategy.

Print this item


Posted by: Hassam
04-03-2018, 11:07 AM
Forum: Algorithmic Trading With Java
- No Replies

Java is a powerful object oriented programming language. Java is widely used in algorithmic trading. Before you develop an algorithmic trading strategy with Java, you need to read the data. We can easily download the data from MT4 using Tools > History Center menu. I have a file DJ301440.csv that has daily open, high, low and close data for Dow Jones Industrial Average. I want to read it into Java. Below is the code that you will use to read the DJ301440.csv file with Java:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;


public class ReadCSV {

    public static void main(String[] args) {
// DJ301440 is the OHLC daily data for Dow Jones Index        
        File Data1 = new File("D:/Shared/MarketData/DJ301440.csv");
        try {//A Scanner in Java is a class that provides access to a resource
            //The resource is file in our case
            Scanner OHLC1= new Scanner(Data1);
            int count=1;
            //Initialize the delimiter
            OHLC1.useDelimiter(",|\r\n");
            while (OHLC1.hasNext()) {
            String column1 = OHLC1.next();
            String column2 = OHLC1.next();
            Double column3 = OHLC1.nextDouble();
            Double column4 = OHLC1.nextDouble();
            Double column5 = OHLC1.nextDouble();
            Double column6 = OHLC1.nextDouble();
            int    column7 = OHLC1.nextInt();
            count++;
            //Date: %s Time: %s Open: %f High: %f Low: %f Close: %f\n
            System.out.printf("%s %s %f %f %f %f %d\n",
                    column1, column2, column3,column4, column5,
                    column6, column7);
            }
            OHLC1.close();
            System.out.println(count);
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
    }
    
}

Java has the Scanner class that we will use to read the file DJ301440.csv. First we create new file OHLC1 and then read all the data from DJ301440.csv into it. We also print each line and use a count of how many rows were read using count variable. Below is the output:

2018.02.05 00:00 25248.000000 25474.000000 23794.000000 24074.000000 79670
2018.02.06 00:00 24074.000000 24157.000000 23049.000000 23690.000000 47768
2049

As you can see there were 2049 rows in the file. We don't need to print the rows. I did it just to make sure the java code was working correctly.

Print this item


Posted by: Hassam
04-02-2018, 03:06 PM
Forum: Python
- No Replies

I was working on ZeroMQ Python MT4 connection. I thought I should start this threat to reinforce my understanding on Python Network Programming. If you don't know anything about ZeroMQ, don't worry I will introduce you to ZeroMQ in a separate thread. Before you start coding with ZeroMQ, you should have a fairly good idea of network programming. So in this thread, I will also introduce you to Python Network Programming. Today we live in an interconnected world. All this has become possible through internet.

If you want to send messages on the internet to other programs running on different machines, then you should learn something about network programming. Of course if you don't know any programming, you can still use internet as everything has been done for you by the developers when they program their apps. You can seamlessly send emails, download videos, images, PDFs, chat with your friends and do a lot of other things. But all these activities that you do require a lot of things to happen behind the scene between different programs that you don't have to know anything about. Unless you are a programmer trying to program your own app. So if you want to program for the internet you should learn network programming.

What Is A Network?

So let's start with what is a network. A network is a collection of computers, devices that can send data to one another. Sounds familiar! Internet is a huge network that connects millions and millions of computers and other devices with each others. Each machine that gets connected on the network is called a node. This node can be a computer, your smart phone, printers, routers and many other things. So whatever connects with the network is called a node. In simple terms any device that connects with the network is a node. A general purpose computer is called a host. Local host is your own computer.

Print this item


Posted by: Hassam
03-28-2018, 01:06 PM
Forum: R
- Replies (5)

I had started an R Introduction thread in the Algorithmic Trading with R forum. Later on I decided to start an additional forum on R as a programming language. R is a statistical analysis language that was started by two professors in New Zealand in 1993 to teach statistics courses. Over the years it has developed tremendously. Today there are more than 10K R libraries. If you want to do statistical analysis you will find the R library that will do the work for you. In this thread I want to discuss R Object Oriented Programming (OOP) that makes R a general purpose language. 

R uses objects a lot. If you are familiar with OOP that objects are just instances of classes that have been defined. Everything that we use in R is an object based on some S3 class. When R got developed it had a class structure that is known as S3. Most R buildin classes are S3 classes. S3 classes are basically lists. I will define S3 class in a moment. R provides you with polymorphism, encapsulation and inheritance just like any other modern Object Oriented Programming language. In addition to S3 classes we also have now S4 classes which were added after a number of years to add safety to its structure.

Polymorphism means you can use the same function on different classes without much problem. The inbuilt class methods take care of how the function is applied. Inheritance means that we can use a class and derive a new class based on that class that inherits its methods. Inheritance allows you to extend a class to a more specialized class that has the methods of the parent class as well as its own methods.

For example I give you an example FRBS is an R library that does fuzzy logic. But it does only fuzzy type 1 logic. I have not found an R library that does fuzzy type 2 interval logic. So this is what we can do. We can use inheritance and build a fuzzy type 2 interval logic based on FRBS fuzzy type 1 logic. I will do that here but first let's master R object oriented programming.

Print this item


Posted by: Hassam
03-26-2018, 03:37 PM
Forum: Algorithmic Trading With R
- Replies (5)

R is a data science and statistical analysis programming language. R was developed in academia. Today R is very popular in the finance sector and many quants use it in analyzing financial market data. Excel used to be popular but it has limitations. R is very powerful as compared to Excel. If you are a trader, you should learn R. I am starting this thread in which I will introduce R if you don't know it. I will try to write a few posts every week and show you how to learn R. Once you learn R, I will show you how to use it in building algorithmic trading models. So stay tuned by subscribing to this thread if you want to learn R.

Print this item