Stochastic - page 6

 
king1898:

in this picture, two arrows should produce two signals but my ea can't send, why? 

As we don't see all your code it's difficult to say. You can print your buffers values to check and compare.
 
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
//-------------------------------------------------------------------


//-------------------------------------------------------------------
#include <Trade\Trade.mqh>
//--- input parameters
input int      StopLoss=-100;      // Stop Loss$
//input int      TakeProfit=100;   // Take Profit
//input int      KD_Period=9;     // KD Period
input int      K_Period=9;     // K Period
input int      D_Period=3;     // D Period
//input int      MA_Period=8;      // Moving Average Period
input int      EA_Magic=12345;   // EA Magic Number
//input double   Adx_Min=22.0;     // Minimum ADX Value
//---
//---input double Lot=0.01;   // Lots to Trade
input double MaxPosition=3.00;  //Max position
input double P1=0.12;    //P1 position1
input double P2=0.32;
input double P3=0.77;
input double P4=1.92;
input double P5=2.85;
input double P6=3.57;
//
input double PF1=10;     //PF1 profit1
input double PF2=50;
input double PF3=100;
input double PF4=500;
input double PF5=800;
input double PF6=1500;

//

//--- Other parameters
int KDHandle; // handle for our stochastic indicator
//int maHandle;  // handle for our Moving Average indicator
double K[],D[]; // Dynamic arrays to hold the values of K,D values for each bars
//double maVal[]; // Dynamic array to hold the values of Moving Average for each bars
double p_close; // Variable to store the close value of a bar
int STP, TKP;   // To be used for Stop Loss & Take Profit values
double TTL_profit;  //to be used for Total profit
//double hisBuyLot=0.05;
//double hisSellLot=0.05;
double TTLBuy_position;
double TTLSell_position;
int Buytimes;  //to be use for buy times
int Selltimes; // to be used for sell times
bool special_close_p=false;
double special_profit=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Get handle for KD indicator
   KDHandle=iStochastic(NULL,0,K_Period,D_Period,3,MODE_SMA,STO_LOWHIGH);
//--- Get the handle for Moving Average indicator
//   maHandle=iMA(_Symbol,_Period,MA_Period,0,MODE_EMA,PRICE_CLOSE);
//--- What if handle returns Invalid Handle
   if(KDHandle<0)
     {
      Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!!");
      return(-1);
     }

//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
   //STP = StopLoss;
   //TKP = TakeProfit;
   //if(_Digits==5 || _Digits==3)
   //  {
   //   STP = STP*10;
   //   TKP = TKP*10;
   //  }
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Release our indicator handles
   IndicatorRelease(KDHandle);
//   IndicatorRelease(maHandle);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Do we have enough bars to work with
   if(Bars(_Symbol,_Period)<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }  

// We will use the static Old_Time variable to serve the bar time.
// At each OnTick execution we will check the current bar time with the saved one.
// If the bar time isn't equal to the saved time, it indicates that we have a new tick.

   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;

// copying the last bar time to the element New_Time[0]
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) // ok, the data has been copied successfully
     {
      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time
        {
         IsNewBar=true;   // if it isn't a first call, the new bar has appeared
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);
         Old_Time=New_Time[0];            // saving bar time
        }
     }
   else
     {
      Alert("Error in copying historical times data, error =",GetLastError());
      ResetLastError();
      return;
     }

//--- EA should only check for new trade if we have a new bar
   if(IsNewBar==false)
     {
      return;
     }

//--- Do we have enough bars to work with
   int Mybars=Bars(_Symbol,_Period);
   if(Mybars<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }

//--- Define some MQL5 Structures we will use for our trade
   MqlTick latest_price;      // To be used for getting recent/latest price quotes
   MqlTradeRequest mrequest;  // To be used for sending our trade requests
   MqlTradeResult mresult;    // To be used to get our trade results
   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar
   ZeroMemory(mrequest);      // Initialization of mrequest structure
/*
     Let's make sure our arrays values for the Rates, KD Values 
     is store serially similar to the timeseries array
*/
// the rates arrays
   ArraySetAsSeries(mrate,true);
// the KD Kvalues array
   ArraySetAsSeries(K,true);
// the KD Dvalues array
   ArraySetAsSeries(D,true);
// the ADX values arrays
//   ArraySetAsSeries(adxVal,true);
// the MA-8 values arrays
//   ArraySetAsSeries(maVal,true);


//--- Get the last price quote using the MQL5 MqlTick Structure
   if(!SymbolInfoTick(_Symbol,latest_price))
     {
      Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
      return;
     }

//--- Get the details of the latest 3 bars,default period,
   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)
     {
      Alert("Error copying rates/history data - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }

//--- Copy the new values of our indicators to buffers (arrays) using the handle
   if(CopyBuffer(KDHandle,0,0,2,K)<0 || CopyBuffer(KDHandle,1,0,2,D)<0)
     {
      Alert("Error copying Stochastic KD indicator Buffers - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }
//     
   double Buy_order=0.02;  //Buy order 
   double Sell_order=0.02;
   
//--- we have no errors, so continue
//--- Do we have positions opened already?
   bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variables to hold the result of Sell opened position

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
         //Print("here - " , PositionsTotal());
         Print("1-Buy_opened - Total Buy position is ", PositionGetDouble(POSITION_VOLUME));
         TTLBuy_position=PositionGetDouble(POSITION_VOLUME);
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell
         //Print("here - " , PositionsTotal());
         Print("1-Sell_opened - Total Sell position is ", PositionGetDouble(POSITION_VOLUME));
         TTLSell_position=PositionGetDouble(POSITION_VOLUME);
        }
     }

// Copy the bar close price for the previous bar prior to the current bar, that is Bar 1
   p_close=mrate[1].close;  // bar 1 close price
   


/*
    1. Check for a long/Buy Setup : k/d cross 20 
*/
//--- Declare bool type variables to hold our Buy Conditions
   bool Buy_Condition_1 = (K[0]>=D[0] && K[1]<=D[1]); // k>=D and K1<=D1
   bool Buy_Condition_2 = (K[1]<=20 && D[0]<=20); // k1<=20 and d<=20

   
//--- Check buy condition   
   if(Buy_Condition_1 && Buy_Condition_2)
     {
         Print("Buy-1:When buy OK, K0 is:",K[0]," D0 is:",D[0]," K1 is:",K[1]," D1 is:",D[1]);
 

Thank angevoyageur !

I print out these variables cache and I said before, is the same, at the time it should be sent the signal, but K / D value is wrong, but look program it is corrent, whether this is an bug in MQL5 do?

 
king1898:

Thank angevoyageur !

I print out these variables cache and I said before, is the same, at the time it should be sent the signal, but K / D value is wrong, but look program it is corrent, whether this is an bug in MQL5 do?

The question is a base question, is there a problem in checking bar time in below part?

//--- Do we have enough bars to work with
   if(Bars(_Symbol,_Period)<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }  

// We will use the static Old_Time variable to serve the bar time.
// At each OnTick execution we will check the current bar time with the saved one.
// If the bar time isn't equal to the saved time, it indicates that we have a new tick.

   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;

// copying the last bar time to the element New_Time[0]
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) // ok, the data has been copied successfully
     {
      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time
        {
         IsNewBar=true;   // if it isn't a first call, the new bar has appeared
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);
         Old_Time=New_Time[0];            // saving bar time
        }
     }
   else
     {
      Alert("Error in copying historical times data, error =",GetLastError());
      ResetLastError();
      return;
     }

//--- EA should only check for new trade if we have a new bar
   if(IsNewBar==false)
     {
      return;
     }

//--- Do we have enough bars to work with
   int Mybars=Bars(_Symbol,_Period);
   if(Mybars<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }
 
king1898:

This is a base question, is there have problem in checking bar time?

Who can help me? Thanks in advance!
 
king1898:
Who can help me? Thanks in advance!

Thanks angevoyageur

i checked your another reply, may be you are right:  Yes, signal on closed candle is better, as signal on current can be false signal. Although there are traders who trade on open candle, probably with some filters.

i will try to test! 

 

Forum on trading, automated trading systems and testing trading strategies

Indicators: Stochastic Oscillator

newdigital, 2013.10.09 07:23

Pinpointing Forex Trend Trade Entries with Stochastics

  • An uptrend is made up of higher highs and higher lows. Traders can use Stochastics to find excellent risk to reward entries at those low support points in the trend.
  • A downtrend is made up of lower highs and lower lows. Forex traders can use Stochastics to find excellent risk to reward entries at these resistance high points
  • Stochastics can be used to alert a forex trader to either tighten stops, reduce the position size, or take profit once in a trend trade

By far, traders who trade in the direction of the predominant daily trend have a higher percentage of success than those who trade the counter trend. One of the biggest attractions of the Forex market it is characterized by long trends that afford traders the potential to make hundreds of pips if they have timed their entries with precision and used protective stops to limit risk.


But How Can Traders Find Where to Enter with a Risk for Maximum Gain?

The mantra, “the trend is your friend until it ends,” can be found in many trading books, but it seems that many forex traders have not made the trend their friend and in some cases, the trend has become the enemy. Rather than being on the receiving end of those pips afforded to traders who have correctly entered the trend, many traders have been on the “giving” end of the trade losing pips while fighting the trend.

As people have turned to online dating services to meet their ideal match, forex traders can turn to stochastics as a way of making the trend the their friend again.


In an uptrend on a daily chart, stochastics %K and %D lines moving below the horizontal ‘20’ reference line and coming back above the 20 line indicates that the profit-taking correction is coming to an end. The stochastic crossing up also tells us that buyers are beginning to enter the market again. In addition, this shows that there is good support.

How to Trade the Trend Using Stochastics

Patience is the name of the game when attempting to trade with the trend. Getting into the trend too early can expose traders to large drawdowns. Getting in too late reduces the amount of profit before the swing is completed.

Use the stochastics indicator to find that “Goldilocks” entry of not too early and not too late. Once a strong uptrend is found, wait for stochastics with the settings of 15, 5, 5 to move into the oversold region below the 20 horizontal reference line. Next, wait for the %K and %D lines to move back above the 20 line. Enter long with a stop placed a few pips below the last low. Set a limit for at least twice the size of the stop.


Once in an uptrend position, traders will attempt to squeeze as much profit as possible. Traders usually take profits on their open position or trail stops once stochastics moves into the overbought region. It is important to note that a forex currency pair can continue to make new highs even though stochastics is in the overbought region.

So next time you see a trend and you do not know how to make it your “friend”, let the stochastics indicator introduce you! Once these swings are highlighted by stochastics, stop placement becomes easier as well. stochastics crossovers in an uptrend can help you pinpoint your entries to join the major trend.


 

Forum on trading, automated trading systems and testing trading strategies

Something Interesting

Sergey Golubev, 2016.03.28 14:13

This is very good EA for newbies - for the traders who are learning Stochastic indicator about how it works. EA is trading on overbought/oversold levels of Stochastic indicator with the following parameters which were coded to be inside this EA:

  • the parameters of Stochastic indicator which were coded inside this EA: 5/3/3
  • overbought/oversold levels to be coded in EA: 80/20
ea_Stochastic_system - expert for MetaTrader 4
  • "Advisor analyzes the readings of the indicator Stochastic has, signal for buying is the intersection of the main and signal indicator lines in the oversold zone, a signal for the intersection of sales is the main indicator and signal lines in the overbought zone."

The coder proposed set file for this EA so we may use this EA on EURUSD M15 timeframe according to this set file/parameters.

I backtested EA just to see how it works - please find backtesting results and some charts with the ideas about overbought/oversold levels:






 

Hi

I have recently encountered a problem regarding stochastic.

I trade with an EA I wrote myself. One of the conditions to enter a trade for sell is that Stoch Main at bar 1 < Stoch Signal Bar 1.

From the attached file for a GBPUSD, we can see that at 10:00, Stoch Main Bar 1 > Stoch Signal Bar 1, but a trdae for sell was open.

The formula I used for Stochstic is

      double StochMain1T30 = iStochastic(NULL,30,10,10,3,MODE_EMA,0,MODE_MAIN,1); // T30 MODE_MAIN

      double StochSignal1T30 = iStochastic(NULL,30,10,10,3,MODE_EMA,0,MODE_SIGNAL,1); // T30 MODE_SIGNAL

One possibility I suspect is that based on the above StochMain1T30 < StochSignal1T30, but this is not what we see on the chart.

Can help me explain the above?

I have called Oanda, the broker, they told me that the position was not open by them and it was open by the EA.

Thank you.

Files:
 

Forum on trading, automated trading systems and testing trading strategies

Something Interesting to Read April 2014

Sergey Golubev, 2014.04.14 20:48

Theory Of Stochastic Processes : With Applications to Financial Mathematics and Risk Theory



This book is a collection of exercises covering all the main topics in the modern theory of stochastic processes and its applications, including finance, actuarial mathematics, queuing theory, and risk theory.

The aim of this book is to provide the reader with the theoretical and practical material necessary for deeper understanding of the main topics in the theory of stochastic processes and its related fields.

The book is divided into chapters according to the various topics. Each chapter contains problems, hints, solutions, as well as a self-contained theoretical part which gives all the necessary material for solving the problems. References to the literature are also given.

The exercises have various levels of complexity and vary from simple ones, useful for students studying basic notions and technique, to very advanced ones that reveal some important theoretical facts and constructions.

This book is one of the largest collections of problems in the theory of stochastic processes and its applications. The problems in this book can be useful for undergraduate and graduate students, as well as for specialists in the theory of stochastic processes.


Reason: