Hướng dẫn php trading bot

(PECL trader >= 0.2.0)

Nội dung chính

  • Description
  • Return Values
  • Key Takeaways
  • What Is a Trading Robot?
  • Algorithmic Trading Strategies
  • Backtesting and Optimization
  • Live Execution
  • The Bottom Line

Nội dung chính

  • Description
  • Return Values
  • Key Takeaways
  • What Is a Trading Robot?
  • Algorithmic Trading Strategies
  • Backtesting and Optimization
  • Live Execution
  • The Bottom Line

trader_emaExponential Moving Average

Description

trader_ema(array $real, int $timePeriod = ?): array

Parameters

real

Array of real values.

timePeriod

Number of period. Valid range from 2 to 100000.

Return Values

Returns an array with calculated data or false on failure.

Ash Christos

4 years ago

This method works fine. If you're finding that the EMA and SMA results are the same, the precision setting might still be the default or not tuned to your use case. (For example floats with more than 3 levels, sathoshi's, etc)

# this is needed for 0.00XXXXZ levels
ini_set( 'trader.real_precision', '8' );

andy at siliconrockstar dot com

3 years ago

The trader_ema() function works correctly if you understand what the second argument is. The second argument is used to group the values into overlapping periods. Within the periods, the numbers undergo a simple average calculation.

So if you call trader_ema($array, 6), and your array only has six values, you're going to get back a simple average, because there is no previous data to weight the value.

If you call trader_ema($array, 3), then your six array values will be grouped into four overlapping groups of three, and you'll get back four values, each representing the EMA for that period.

Below is the output of trader_ema(array(1,2,2,1,3,4), 3) and trader_sma(array(1,2,2,1,3,4), 3). You can see the first value is the same for both the EMA and SMA calculations.

trader_ema(array(1,2,2,1,3,4), 3)

array(4) {
  [2]=>
  float(1.6666666667)
  [3]=>
  float(1.3333333333)
  [4]=>
  float(2.1666666667)
  [5]=>
  float(3.0833333333)
}

trader_sma(array(1,2,2,1,3,4), 3)

array(4) {
  [2]=>
  float(1.6666666667)
  [3]=>
  float(1.6666666667)
  [4]=>
  float(2)
  [5]=>
  float(2.6666666667)
}

kazemi dot milad at gmail dot com

4 years ago

trader_ema in wrong calculate value
this return just simple moving avrage
for get ema correct use this code
$number is data array and $n is number of period
example:
$number[0]    => last value
$number[n]    =>first value

function exponentialMovingAverage(array $numbers, int $n): array
{
    $numbers=array_reverse($numbers);
    $m   = count($numbers);
    $α   = 2 / ($n + 1);
    $EMA = [];

    // Start off by seeding with the first data point
    $EMA[] = $numbers[0];

    // Each day after: EMAtoday = α⋅xtoday + (1-α)EMAyesterday
    for ($i = 1; $i < $m; $i++) {
        $EMA[] = ($α * $numbers[$i]) + ((1 - $α) * $EMA[$i - 1]);
    }
    $EMA=array_reverse($EMA);
    return $EMA;
}

manoj dot monu23 at gmail dot com

8 years ago

the trader_ema() function does'nt work correctly , it calculate just average of last period entries. Follow the following code for trader_ema:
function EMACalculator($limit,$array)
{
    $EMA_previous_day = $array[0];
    //print_r($array);
    $multiplier1 = (2/$limit+1);
    $EMA[]=array();
    $EMA = $array[0];
    $Close= $array[1];

        while($limit)
{   
    //echo"EMA is $EMA\n";
    $EMA = ($Close - $EMA_previous_day) * $multiplier1 + $EMA_previous_day;
    $EMA_previous_day= $EMA;

        $limit--;
}
return $EMA;
}
where $limit accept the period of ema  and $array : accept array of data for ema calculation.

Anonymous

3 years ago

As noted,  this function simply doesnt work.  It returns MA values.

Many traders aspire to become algorithmic traders but struggle to code their trading robots properly. These traders will often find disorganized and misleading algorithmic coding information online, as well as false promises of overnight prosperity. However, one potential source of reliable information is from Lucas Liew, creator of the online algorithmic trading course AlgoTrading101. The course has garnered over 30,000 students since its launch in 2014.

Liew's program focuses on presenting the fundamentals of algorithmic trading in an organized way. He is adamant about the fact that algorithmic trading is “not a get-rich-quick scheme.” Outlined below are the basics of what it takes to design, build, and maintain your own algorithmic trading robot (drawn from Liew and his course).

Key Takeaways

  • Many aspiring algo-traders have difficulty finding the right education or guidance to properly code their trading robots.
  • AlgoTrading101 is a potential source of reliable instruction and has garnered more than 30,000 since its 2014 launch.
  • A trading algo or robot is computer code that identifies buy and sell opportunities, with the ability to execute the entry and exit orders.
  • In order to be profitable, the robot must identify regular and persistent market efficiencies.
  • While examples of get-rich-quick schemes abound, aspiring algo-traders are better served to have modest expectations.

Rise of the Robo Advisors

What Is a Trading Robot?

At the most basic level, an algorithmic trading robot is a computer code that has the ability to generate and execute buy and sell signals in financial markets. The main components of such a robot include entry rules that signal when to buy or sell, exit rules indicating when to close the current position, and position sizing rules defining the quantities to buy or sell.

Obviously, you’re going to need a computer and an internet connection to become an algorithmic trader. After that, a suitable operating system is needed to run MetaTrader 4 (MT4), which is an electronic trading platform that uses the MetaQuotes Language 4 (MQL4) for coding trading strategies. Although MT4 is not the only software one could use to build a robot, it has a number of significant benefits.

One advantage is that, while MT4’s main asset class is foreign exchange (FX), the platform can also be used to trade equities, equity indices, commodities, and Bitcoin using contracts for difference (CFDs). Other benefits of using MT4 (as opposed to other platforms) are that it is easy to learn, it has numerous available FX data sources, and it’s free.

Algorithmic Trading Strategies

One of the first steps in developing an algorithmic strategy is to reflect on some of the core traits that every algorithmic trading strategy should have. The strategy should be market prudent in that it is fundamentally sound from a market and economic standpoint. Also, the mathematical model used in developing the strategy should be based on sound statistical methods.

Next, determine what information your robot is aiming to capture. In order to have an automated strategy, your robot needs to be able to capture identifiable, persistent market inefficiencies. Algorithmic trading strategies follow a rigid set of rules that take advantage of market behavior, and the occurrence of one-time market inefficiency is not enough to build a strategy around. Further, if the cause of the market inefficiency is unidentifiable, then there will be no way to know if the success or failure of the strategy was due to chance or not.

With the above in mind, there are a number of strategy types to inform the design of your algorithmic trading robot. These include strategies that take advantage of the following (or any combination thereof):

  • Macroeconomic news (e.g., non-farm payroll or interest rate changes)
  • Fundamental analysis (e.g., using revenue data or earnings release notes)
  • Statistical analysis (e.g., correlation or co-integration)
  • Technical analysis (e.g., moving averages)
  • The market microstructure (e.g. arbitrage or trade infrastructure)

Preliminary research focuses on developing a strategy that suits your own personal characteristics. Factors such as personal risk profile, time commitment, and trading capital are all important to think about when developing a strategy. You can then begin to identify the persistent market inefficiencies mentioned above. Having identified a market inefficiency, you can begin to code a trading robot suited to your own personal characteristics.

Backtesting and Optimization

Backtesting focuses on validating your trading robot, which includes checking the code to make sure it is doing what you want and understanding how the strategy performs over different time frames, asset classes, or market conditions, especially in so-called "black swan" events such as the 2007-2008 financial crisis.

Now that you have coded a robot that works, you'll want to maximize its performance while minimizing the overfitting bias. To maximize performance, you first need to select a good performance measure that captures risk and reward elements, as well as consistency (e.g., Sharpe ratio).

Meanwhile, an overfitting bias occurs when your robot is too closely based on past data; such a robot will give off the illusion of high performance, but since the future never completely resembles the past, it may actually fail. Training with more data, removing irrelevant input features, and simplifying your model may help prevent overfitting.

Live Execution

You are now ready to begin using real money. However, aside from being prepared for the emotional ups and downs that you might experience, there are a few technical issues that need to be addressed. These issues include selecting an appropriate broker and implementing mechanisms to manage both market risks and operational risks, such as potential hackers and technology downtime.

Before going live, traders can learn a lot through simulated trading, which is the process of practicing a strategy using live market data but not real money.

It is also important at this step to verify that the robot’s performance is similar to that experienced in the testing stage. Finally, monitoring is needed to ensure that the market efficiency that the robot was designed for still exists. 

The Bottom Line

It is entirely plausible for inexperienced traders to be taught a strict set of guidelines and become successful. However, aspiring traders should remember to have modest expectations.

Liew stresses that the most important part of algorithmic trading is “understanding under which types of market conditions your robot will work and when it will break down” and “understanding when to intervene.” Algorithmic trading can be rewarding, but the key to success is understanding. Any course or teacher promising high rewards without sufficient understanding should be a major warning sign to stay away.