엘리엇 파동 이론에 기반한 거래 전략 - 페이지 19

 
글쎄, 아주 상세하지 않습니다 ;). 표준 편차 는 예측 가격에서 관찰된 가격의 표준 편차(RMS)입니다. 즉, 당신은 예측을 고려하고, 무슨 일이 일어났는지 보고, 예측에 따라 일어났어야 할 일과 비교하고 나서야 결론을 내립니다. 이것은 프로세스를 반복하는 이유 중 하나입니다.
MT4에 내장된 지표를 사용하면 예측 가격에 대해 이동 평균을 선택했음을 자동으로 나타냅니다. 다른 것을 선택할 수 있습니다. RMS를 계산하는 것과 동일한 알고리즘이 정확합니다. 제곱합의 제곱근을 자유도로 나눈 값입니다.

행운을 빕니다.
 
Vladislav, 이전 페이지에 나와 있고 지금까지 당신이 논박하지 않은 내 가정으로 판단하여 최적의 포물선을 찾기 위해 우리는 가격 시리즈의 점에서 가장 짧은 거리를 찾고 있습니다. 가격 필드가 잠재적으로 포물선에 상대적이라고 가정하는 바로 이 포물선(직렬의 점에서 포물선으로 그린 수직선의 길이)입니다. 이것은 3차 방정식을 풀어야 하기 때문에 명백한 이유로 계산을 복잡하게 만듭니다. 나는 최적의 포물선을 찾는 이 방법이 회귀 방법을 사용하여 최적의 포물선을 찾는 것과 비교하여 얼마나 정당화되는지 다시 한번 이해하고 싶습니다. 계산되나요? 최적의 포물선을 찾기 위한 회귀 방법의 실제 적용 가능성 측면에서 추정할 수 있습니까? 이 방법은 어떤 이유로 인해 몇 가지 실험적 연구의 결과로 폐기되었습니까(그러면 무엇입니까?), 또는 연구 결과 최적의 포물선을 찾는 더 복잡한 방법이 반전에 대한 결론의 정확도가 더 높다는 결론에 도달했습니다. 방법 사이에 근본적인 차이가 없는 반면에? 결국, 최적의 포물선을 결정하기 위해 다양한 방법을 사용하는 방식의 차이가 최종 결과에 얼마나 영향을 미칠 것인지를 첫 눈에 확인하기는 어렵습니다. 물론 다른 방법으로 찾은 포물선의 계수가 다를 것이라는 점을 이해하지만 최종 결과가 얼마나 더 많이 달라지는지 이해하기 위해 얼마나 더 중요한지 이해하고 싶습니다.
 
수렴과 관련하여 - 근사 오차를 추정할 수 있는 급수의 항이 있다는 것을 잊지 마십시오. 따라서 급수의 무한한 수의 항이 필요하지 않습니다.

Vladislav, 나는 또한 당신의이 권장 사항을 올바르게 이해하고 있는지 명확히하고 싶습니다.
다음은 테일러 공식입니다.

포물선 함수 f(x)=Ax^2+B의 도함수를 고려하십시오.
f'(x)=2Ax,
f''(x)=2A,
f'''(x)=0, 세 번째 이상의 모든 도함수는 0으로 바뀝니다.
그런 다음 Taylor 공식에 따르면 시리즈는 처음 세 개의 항으로만 구성됩니다. 이 경우 Taylor 급수에서 함수 f(x)=Ax^2+B의 확장은 정확할 것입니다(즉, 확장 오류의 마지막 항이 사라집니다). 다음으로 우리는 최적 포물선에 의한 가격 계열의 근사의 품질을 평가해야 합니다. 즉, 우리에게 주요 요구 사항은 일련의 근사 오류가 수렴해야 한다는 것입니다(즉, 오류의 합이 유한 수로 수렴). 그리고 계산된 근사 오차를 확장의 세 번째 항과 비교하여 간단히 결정할 수 있습니다. 내 말이 맞나 안 맞나? 즉, 포물선과 표본 자체를 선택할 때 a에서 x까지의 간격에 있는 표본 값에 대해 근사 오차의 표준 편차가 계열의 세 번째 항의 값을 초과해서는 안 된다는 기준을 사용합니다. ? 전략에서 동일한 원칙을 따르고 있습니까?
그건 그렇고, 여기에는 약간의 불일치가 있습니다. 우리는 가격 가능성 속성을 사용하여 포물선을 최적화하고(포물선에 수직을 통해) 일반적인 방식으로 근사 오차를 추정합니다.
여기서 무슨 문제가 있습니까? 최적 포물선에 대한 검색과 근사 오차 추정치를 일치시키는 방법은 무엇입니까?
 
다시 해 봅시다. 통합 솔루션에서 멀어지고 있습니다. 궤도가 포물선이라는 사실은 필드의 잠재력에서 따르지만 내가 3차 방정식을 풀고 있다는 아이디어는 어디서 얻었습니까? 나는 적분 방법을 사용합니다. 추정치는 잠재적 필드의 기능을 고려합니다. 실제로 이것은 단순히 접근 방식을 단순화합니다. 이제 나는 당신이 스스로 답을 찾는 데 필요한 몇 가지 질문을 할 것입니다. 당신은 무엇을 찾고 있으며 어떤 형태로 결과를 얻고 싶습니까? 나는 반전 영역의 투영을 찾는 작업을 스스로 설정했습니다. 따라서 이를 위해서는 근사 방법(합리적으로 선택)과 이 근사의 오차를 추정하는 방법을 선택해야 했습니다. 이러한 방법은 관련이 있습니다. 당신은 나를 비난하지 않지만 내가 개발하고 시스템이 작성된 알고리즘에 대해서는 설명하지 않겠습니다. 그러나 여기에 기본 원칙이 있습니다. 따라서 원칙에 대해 - 투영의 구성(실제로 이것은 현재 근사를 기반으로 하는 외삽임)은 근사 함수의 순서를 정당화하고, 이는 차례로 오류를 결정하는 방법입니다. 필드의 가능성을 고려하여 우리는 근사의 순서와 우리의 근사가 충족해야 하는 주요 법칙에 대해 결론을 내림과 동시에 우리의 근사가 여전히 적절하다고 간주될 수 있는 최대 허용 오차를 추정합니다. 연구를 시작할 때 약간의 불확실한 상황에 직면하게 될 것입니다. 요점은 근사치의 기초가 여러 가지 방법으로 선택될 수 있다는 것입니다(이것은 고차 추세가 낮은 차수의 추세로 나뉘고 그 반대의 경우도 마찬가지입니다. 낮은 차수의 추세에서 더 높은 차수의 추세를 만들기 위해 여기에서 품질 기준이 필요합니다. 이를 기반으로 구성된 근사치에서 최상의 근사치를 선택할 수 있습니다 외삽법(조건을 동등하게 잘 충족시키는 몇 가지 근사치가 있을 수 있음 - 여러 가능성이 있음 - 교차 영역을 제공하거나 없음 - 시장에서 평평한 범위를 볼 수 있음). 나는 그러한 기준으로 기능적 위치 에너지의 최소값을 선택했습니다(이는 또한 가격 필드의 잠재력의 결과이기도 합니다). 근사값을 작성하는 방법 - 이것이 2차 형식이라는 것을 이미 이해했습니다. 포물선을 찾거나 다르게 생각할 수 있습니다. 포물선을 찾고 있다면 (나는 그렇지 않습니다) 표준 배송에서 표준 편차 알고리즘을 사용할 수 있습니다. 그런 다음 포물선 값에서 실제 가격을 빼야 합니다. 그런 다음 포물선을 만들려면 세 개의 점이 필요합니다. 그리고 대부분의 경우 2차 함수에 의한 스플라인 근사를 사용해야 할 것입니다. 모든 가격이 전체 샘플링 시간 동안 동일한 포물선에 놓여 있다는 것은 사실이 아닙니다. 이동하여 근사화할 수 있습니다. 평가해야 합니다. 어쩌면 더 좋을 수도 있습니다. 그런 다음 신뢰 구간 을 평가합니다. 볼린저 밴드는 여기에서 신뢰 구간으로 간주될 수 있다고 생각합니다. 일반적으로 질문이 많습니다. 이 접근 방식을 사용하면 이미 만들어진 알고리즘 중 일부를 사용할 수 있습니다. 더 나아가 - 일단 근사치를 선택하면 이 궤적을 미래로 계속할 수 있습니다(멀수록 결과의 신뢰성이 떨어짐). 나는 또한 다른 일을합니다. 나는 근사를 구성하는 기간을 선택합니다(전체 표본이 아니라 약 2/3, 나는 마지막 1/3을 외삽하고 우리가 신뢰에서 떨어지지 않는다면 얻은 실제 가격과 비교합니다 간격, 다음 우리는 추가 외삽을 위해 이 근사치를 사용하지만 이것은 이미 반복 알고리즘의 안정성을 개선하기 위한 구현 및 방법에 적용됩니다.


행운을 빕니다.
 
좋은 게시물 :)
 
안녕하세요 vsem님

A mozet sdelajem vse vmeste konstruktivnuju rabotu?
Skazem, napisat' sovmestno indikator, katoryj begajet 4erez vsiu istoriju do teku4ej ceny i s4ityvajet Elliot waves :)))
Developery MT4 tol'ko pablogodorit za takoje.

Neskol'ko moix idej dlia na4ala:

1) V samom na4ale istoriji opredelit' v kakuju storonu cena 또는 FLAT
2) jesli FLAT, zdiom poka probivajutsia granicy flata, tokda smotrim v kakuju storonu dvigajetsia cena, tak opredelajem na4alo ods4iota, s4itajem tol'ko 1-2-3 i ABC volny
3) is4em tol'ko "basic" Elliot Wave patterny 1-2-3 i 1-2-3-4-5 + ABC volny after okon4anija dvizenija ceny(trend)
4) Jesli imejem "failed Elliot Wave", zna4it ploxoj ods4iot i tot kusok istroriji nada jes4io raz peresmatret' nas4iot v kakuju storonu dvigajetsia cena v intervale pabolshe. teku4
5) k etim grafikam xorosho goditsia cifra Fibonacci, sami posmotrite s indikatorom MT4 v istoriji ot Elliot Wave 1 na4ala do na4ala Elliot Wave 4 - http://www.market-harmonics.com/elliott_wave2.htm

Dopolnitel'no dlia poniatija o 4iom re4' pro4itaite http://www.elliottician.com/showpage.asp?p=47 i postaraites' ponat' kak smotritsia "기본 엘리엇 웨이브 패턴". ruskom sdes'에 대한 전체 설명: http://www.alpari-idc.ru/ru/textbook/tech_an/ew/

V rezultate kod indikatora patom mozno podkrutit' k novoj versiji MT4 kak standartnyj indikator :)
 
따라서 원칙에 대해 - 투영의 구성(실제로 이것은 현재 근사를 기반으로 하는 외삽임)은 근사 함수의 순서를 정당화하고, 이는 차례로 오류를 결정하는 방법입니다.

그래서 당신은 아마 다음을 할 것입니다.
1단계. 우리는 샘플을
2단계. 선형 회귀 채널로 근사합니다.
3단계. 근사 오류 찾기
4단계. 우리는 오류 그래프를 분석합니다. 우리는 근사 함수의 차수가 더 높아야 하거나, 많은 오류가 발산하거나 시작을 위한 일부가 있는 경우(계산 자동화 알고리즘이 완전히 이해될 때까지) 이 샘플을 연속 함수로 전혀 근사할 수 없다는 가정을 얻습니다. 허용 신뢰 구간 을 벗어나 눈에 보이는 강한 편차 .
5단계. 포물선(또는 무엇이든)에 맞게 1-4단계를 반복합니다.
6단계. 우리는 오류를 추정하고 오류가 합리적인 한계를 초과하면 이 샘플을 버립니다. 오류 그래프에 합리적인 구조가 있는 경우 샘플에 대한 정보, 근사 방법 및 근사 함수에 대한 추가 정보를 일부 배열에 저장합니다.
7단계. 또한 가능한 모든 샘플을 반복적으로 살펴보고 각 샘플에 대한 근사 함수의 최적 변형을 검색한 후 요구 사항을 극도로 만족시키는 샘플에서 멈춥니다. 당신이 추천한 근사 함수를 구성하는 방법을 전체 샘플이 아니라 2/3에서만 사용하고 근사 결과를 테스트하기 위해 마지막 3분의 1을 남겨두는 것이 자연적으로 바람직합니다(이것은 매우 귀중한 제안입니다!).
8단계. 우리는 미래에 계속되는 가격 차트에 극단적인 근사치를 그립니다. 당연히 각 근사에 대해 신뢰 구간이 구축됩니다.
9단계. 따라서 간격의 경계가 교차하는 위치를 봅니다. 우리는 대략적인 날짜를 설정합니다.
10단계. 가격이 반전 영역에 접근하면 적분 오차 추정 방법을 사용하여 추세 반전 확률을 계산합니다. 아마도 모든 근사 채널에 대해 회전 추정치를 평균화해야 할 것입니다. 선형 회귀 채널의 경우 추가 매개변수로 사용하려면 Hurst 계수도 계산해야 합니다. Murray의 수준을 살펴보는 것도 좋은 생각입니다. 따라서 우리는 보류 중인 주문을 내리고 최소한의 위험으로 중지를 결정할 가능성이 높습니다.
물론이 모든 것을 계산할 Expert Advisor는 매우 광범위 할 것입니다 (6000 라인이 포함되어 있다고 말했습니다)! 그리고 지금까지는 각 샘플에 대한 자동 의사 결정 측면에서 모든 것이 명확하지 않습니다. 글쎄, 나는 당신이이 알고리즘을 프로그래밍하려고 시도하기 시작해야한다고 생각합니다. 그러면 실험을하면서 이론적인 수준에서도 이해하기 어려운 것을 이해하는 것이 가능할 것입니다. 그러나 실험 중에 명확해질 것입니다. 그 자체로. 실제로 계산 시간은 상당히 중요합니다. 당신은 첫 번째 옵션이 약한 기계에서 30-40분 동안 효과가 있다고 말했습니다. 즉, P4 2.4GHz에서 대략 10분 동안 분 계산을 예상해야 합니다.

근사화 방법에 대해 다음과 같은 흥미로운 매뉴얼을 찾았습니다.
 
옳은. 알고리즘을 구현하는 과정에서 다른 모든 것을 알게 될 것이라고 생각합니다.

추신: 포물선 자체가 필요하지 않으므로 도함수를 즉시 근사할 수 있습니다. 회귀 계수는 필요한 것입니다(여기서 Taylor 시리즈의 출처 ;)). 그러면 궤적의 모양에 신경 쓰지 않을 것입니다. 가장 중요한 것은 신뢰 구간을 정확하게 추정하는 것입니다. 내가 추천한 문헌을 주의 깊게 보십시오. 정보가 충분히 있습니다.

행운을 빕니다.
 
옳은.....

기다리다... :)
 
solandr, kak-to dumaju 4to ninado nikakix tam neuironnyx setej, skol'ko ja programiroval, vsio bylo pros4e :)

투표 odin iz moix staryx mql3:

/*[[
Name := Elliot wave recognization 
Author := Copyright © 2004, T-1000, Lithuania
Notes := Searches for Elliot wave patterns and places markers on chart
Link := irc://irc.omnitel.net/forex
Update on every tick := Yes 
Enable Alerts := Yes 
Disable alert once hit := Yes 
Lots := 0.1
Stop Loss := 70
Take Profit := 150
Trailing Stop := 35
]]*/


/*

An Impulse pattern moves in the direction of the underlying trend and is made up of five waves, or moves. 
Each wave is labeled at its endpoint. The Elliott Wave Principle identifies an Impulse wave when:

   1. Wave 2 does not fall below the starting price of wave 1.
   2. Wave 3 is not the shortest wave by price movement when comparing to wave 1 and wave 5.
   3. Wave 4 does not overlap the range of wave 1. 

*/

Defines: MaxBars(200),RetracementBars(100),EWPeriod(10),NoisePips(30),MinTakeProfit(50),SARstep(0.0015),SARmax(0.0100);
Defines: MaxTrades(1),AntiStopLoss(0),Slippage(5),DelayedBidsTimeout(172800),BidStopPoints(60),BidLimitPoints(50),TrailingStep(10),IncrementLots(1),MinMoney(0),MiniForexMode(1);
vars: counter(0),counter2(0),ComputedPricesCount(0),StartMoney(0);
vars: EW1(0),EW2(0),EW3(0),EW4(0),EW5(0);
vars: LastEW1(0),LastEW2(0),LastEW3(0),LastEW4(0),LastEW5(0);
vars: EW0MARK(0),EW1MARK(0),EW2MARK(0),EW3MARK(0),EW4MARK(0),EW5MARK(0),EW3ORDERMARK(0),ORDERMARK(0),ORDERANGLE(0),ORDERSKIP(0),ORDERPRICE(0),ORDERCOUNT(0),MinTakeProfitPtS(0);
vars: MaxPrice(0),MinPrice(0),WaveAngle(0),tempval(0),tempval2("");
vars: EW1MARKTIME(0),EW2MARKTIME(0),EW3MARKTIME(0),EW4MARKTIME(0),EW5MARKTIME(0),EW5PRICE(0),ENTRYPRICE(0),LASTENTRYPRICE(0);
vars: EW1MARKARROW(0),EW2MARKARROW(0),EW3MARKARROW(0),EW4MARKARROW(0),EW5MARKARROW(0);
vars: EW1MARKBAR(0),EW2MARKBAR(0),EW3MARKBAR(0),EW4MARKBAR(0),EW5MARKBAR(0);
vars: MaxPriceBar(0),MinPriceBar(0),BarsShift(0),BarsCount(0),init(0),prevbars(0),CalcBarDiff(0);
vars: ParabolicSAR(0),SARAngle(0),MA(0),MA2(0),ShortMA(0),LongMA(0),TrailingStopPoint(0),Trace(0),MACD(0),ShortMACD(0),MACDAngle(0),ShortMACDAngle(0);
vars: TradingPrice(0),TotalLots(0),TradesCount(0),StartDeposit(0),BuyStopLoss(0),SellStopLoss(0),BuyBidStopLoss(0),SellBidStopLoss(0);
vars: BuyLimitStopLoss(0),SellLimitStopLoss(0),TrailingStopLoss(0),BidStopPts(0),BidLimitPts(0),OrderType(0),LastBidTime(0),BadOrder(0),CloseBadOrder(0);
vars: LastBadTime(0),OrderRecovery(0),LastOp(0),LastOldOp(0),BuyOp(0),SellOp(0),EntryTrail(0),StopLossTrail(0);
vars: Bears(0),Bulls(0),BearsAngle(0),BullsAngle(0);
vars: Pivot(0),SupportLevel1(0),SupportLevel2(0),ResistanceLevel1(0),ResistanceLevel2(0);
vars: tmpPivot(0),tmpSupportLevel1(0),tmpSupportLevel2(0),tmpResistanceLevel1(0),tmpResistanceLevel2(0);
vars: RSI(0),CCI(0),ShortRSI(0),PriceLevel(0),LastPriceLevel(0),FiboLevel(0);
vars: EWOscillator(0),EWLevel(0),ShortPeriod(0),LongPeriod(0),LastEW(0);

if  Bars < MaxBars * 2 + RetracementBars + 1
then
exit;


if init = 0
then
{
EW0MARK = 0;
EW1MARK = 0;
EW2MARK = 0;
EW3MARK = 0;
EW4MARK = 0;
EW5MARK = 0;
ORDERMARK = 0;
TotalLots = Lots;
prevbars = 0;
if BidStopPts < BidStopPoints then BidStopPts = BidStopPoints;
if BidLimitPts < BidLimitPoints then BidLimitPts = BidLimitPoints;
BidStopPts = BidStopPts * Point;
BidLimitPts = BidLimitPts * Point;
StartDeposit = MinMoney;
if StartDeposit = 0 then StartMoney=Balance
else StartMoney = StartDeposit;
Print(AccountName,"(#",AccountNumber,") ",Symbol," Elliot Wave Retracement analizer loaded.");
init = 1;
}

if StopLoss > 0 then
{
BuyStopLoss=PriceAsk- StopLoss * Point;
SellStopLoss=PriceBid + StopLoss * Point;  
BuyBidStopLoss = BuyStopLoss + BidstopPts;
SellBidStopLoss = SellStopLoss - BidstopPts;
BuyLimitStopLoss=PriceAsk - StopLoss * Point - BidLimitPts;
SellLimitStopLoss=PriceBid + StopLoss * Point + BidLimitPts;  
}

// Adjust remaining money in loss
if Balance < StartMoney then 
{
//StartMoney=Balance;
TotalLots = Lots;
}

// Check if we have automated incremental Lots calculation
if IncrementLots > 0 and (FreeMargin / StartMoney > 2) then 
{
if MiniForexMode = 1 then TotalLots = Normalize(FreeMargin / StartMoney * Lots - 0.1,1);
if MiniForexMode = 0 then TotalLots = Normalize(FreeMargin / StartMoney * Lots - 1,0); // forex type account cannot have part of lots
if TotalLots < Lots then TotalLots = Lots;
}

/**************************************************** Indicators ********************************************************/
if Bars != prevbars 
// Save extra CPU when making signals because we do not have new price in chart in test mode
then 
{

Bears=iBearsPower(RetracementBars,MODE_HIGH,0);
Bulls=iBullsPower(RetracementBars,MODE_LOW,0);
RSI=iRSI(RetracementBars,0);
CCI=iCCI(MaxBars,0);
ShortRSI=iRSI(RetracementBars/5,0);
ParabolicSAR=iSAR(SARstep,SARmax,0);
MA=iMA(MaxBars,MODE_EMA,0);
MA2=iMA(MaxBars,MODE_SMA,0);
ShortMA=iMA(RetracementBars,MODE_EMA,0);
LongMA=iMA(MaxBars*2,MODE_LWMA,0);
MACD=iMACD(RetracementBars,MaxBars,RetracementBars,MODE_EMA,0);
ShortMACD=iMACD(RetracementBars/5,RetracementBars,RetracementBars/5,MODE_EMA,0);

MaxPriceBar = Highest (MODE_CLOSE,MaxBars+1, MaxBars*2);
MinPriceBar = Lowest (MODE_CLOSE, MaxBars+1, MaxBars*2);


if MaxPriceBar < MinPriceBar 
//and EW0MARK = 0
// first Elliot Wave would be UP
then
WaveAngle = 1; 

if MinPriceBar < MaxPriceBar 
//and EW0MARK = 0
// first Elliot Wave would be DOWN
then
WaveAngle = 2; 

MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];
if WaveAngle = 1 then FiboLevel = (MaxPrice - MinPrice) / (Open - MinPrice)  * 100
else FiboLevel = (MaxPrice - MinPrice) / (MaxPrice - Open ) * 100;

//LastPriceLevel=0;

if Bars > prevbars
then
{
ORDERANGLE = 0; 
Pivot=0;
SupportLevel1=0;
SupportLevel2=0;
ResistanceLevel1=0;
ResistanceLevel2=0;
LastPriceLevel=PriceLevel;

for counter=RetracementBars downto 0
Begin
MaxPriceBar = Highest (MODE_CLOSE,MaxBars+1+counter, MaxBars);
MinPriceBar = Lowest (MODE_CLOSE, MaxBars+1+counter, MaxBars);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];
/*
Pivot point (Pivot) = (H + L + C) / 3
First resistance level (R1) = (2 * P) - L
First support level (S1) = (2 * P) - H
Second resistance level (R2) = P + (R1 - S1)
Second support level (S2) = P - (R1 - S1)

H, L, C are the previous High, Low and Close.


*/

tmpPivot=(MaxPrice+MinPrice+Open[counter+MaxBars]) / 3;
tmpResistanceLevel1=(2 * tmpPivot) - MinPrice;
tmpSupportLevel1=(2 * tmpPivot) - MaxPrice;
tmpResistanceLevel2=tmpPivot + (tmpResistanceLevel1 - tmpSupportLevel1);
tmpSupportLevel2=tmpPivot - (tmpResistanceLevel1 - tmpSupportLevel1);

Pivot=Pivot + tmpPivot;
ResistanceLevel1=ResistanceLevel1 + tmpResistanceLevel1;
SupportLevel1=SupportLevel1 + tmpSupportLevel1;
ResistanceLevel2=ResistanceLevel2 + tmpResistanceLevel2;
SupportLevel2=SupportLevel2 + tmpSupportLevel2;
if counter < MaxBars
then
{
Pivot=Pivot / 2;
ResistanceLevel1=ResistanceLevel1 / 2;
SupportLevel1=SupportLevel1 / 2;
ResistanceLevel2=ResistanceLevel2 / 2;
SupportLevel2=SupportLevel2 / 2;
}
End;


if WaveAngle = 1 
then
PriceLevel = (Open / Point - SupportLevel2 / Point) / (ResistanceLevel2 / Point - SupportLevel2 / Point) * 100;

if WaveAngle = 2 
then
PriceLevel = -(ResistanceLevel2 / Point - Open / Point) / (ResistanceLevel2 / Point - SupportLevel2 / Point) * 100 ;


if PriceLevel >151
or PriceLevel < -151
then
{
ComputedPricesCount=Normalize(PriceLevel / 100,0);
if ComputedPricesCount < 0 then ComputedPricesCount = -ComputedPricesCount;
ComputedPricesCount=(2 + ComputedPricesCount) * MaxBars;
//Print(TimeToStr(time[shift]),": ",Symbol," Price Level is over limit:",PriceLevel," Increasing Prices Count to:",ComputedPricesCount);
if Bars <= ComputedPricesCount + MaxBars + 1
then  exit;//Avoid out of range computing
 
ORDERANGLE = 0; 
Pivot=0;
SupportLevel1=0;
SupportLevel2=0;
ResistanceLevel1=0;
ResistanceLevel2=0;

for counter=RetracementBars downto 0
Begin
MaxPriceBar = Highest (MODE_CLOSE,ComputedPricesCount+1+counter, ComputedPricesCount);
MinPriceBar = Lowest (MODE_CLOSE, ComputedPricesCount+1+counter, ComputedPricesCount);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];
/*
Pivot point (Pivot) = (H + L + C) / 3
First resistance level (R1) = (2 * P) - L
First support level (S1) = (2 * P) - H
Second resistance level (R2) = P + (R1 - S1)
Second support level (S2) = P - (R1 - S1)

H, L, C are the previous High, Low and Close.
*/

tmpPivot=(MaxPrice+MinPrice+Open[counter+ComputedPricesCount]) / 3;
tmpResistanceLevel1=(2 * tmpPivot) - MinPrice;
tmpSupportLevel1=(2 * tmpPivot) - MaxPrice;
tmpResistanceLevel2=tmpPivot + (tmpResistanceLevel1 - tmpSupportLevel1);
tmpSupportLevel2=tmpPivot - (tmpResistanceLevel1 - tmpSupportLevel1);

Pivot=Pivot + tmpPivot;
ResistanceLevel1=ResistanceLevel1 + tmpResistanceLevel1;
SupportLevel1=SupportLevel1 + tmpSupportLevel1;
ResistanceLevel2=ResistanceLevel2 + tmpResistanceLevel2;
SupportLevel2=SupportLevel2 + tmpSupportLevel2;
if counter < MaxBars
then
{
Pivot=Pivot / 2;
ResistanceLevel1=ResistanceLevel1 / 2;
SupportLevel1=SupportLevel1 / 2;
ResistanceLevel2=ResistanceLevel2 / 2;
SupportLevel2=SupportLevel2 / 2;
}
End;


if WaveAngle = 1 
then
PriceLevel = (Open / Point - SupportLevel2 / Point) / (ResistanceLevel2 / Point - SupportLevel2 / Point) * 100;

if WaveAngle = 2 
then
PriceLevel = -(ResistanceLevel2 / Point - Open / Point) / (ResistanceLevel2 / Point - SupportLevel2 / Point) * 100 ;

}


MoveObject("Pivot",OBJ_HLINE,Time,Pivot,Time[MaxBars],Pivot,White,1,STYLE_SOLID);
MoveObject(" ResistanceLevel2",OBJ_HLINE,Time,ResistanceLevel2,Time[MaxBars],ResistanceLevel2,Blue,1,STYLE_SOLID);
MoveObject(" SupportLevel2",OBJ_HLINE,Time,SupportLevel2,Time[MaxBars],SupportLevel2,Blue,1,STYLE_SOLID);
MoveObject(" ResistanceLevel1",OBJ_HLINE,Time,ResistanceLevel1,Time[MaxBars],ResistanceLevel1,Red,1,STYLE_SOLID);
MoveObject(" SupportLevel1",OBJ_HLINE,Time,SupportLevel1,Time[MaxBars],SupportLevel1,Red,1,STYLE_SOLID);

if MaxPriceBar < MinPriceBar
then
MoveObject("Fibo",OBJ_FIBO,Time,ResistanceLevel2,Time[MaxBars],SupportLevel2,Green,1,STYLE_DOT)
else
MoveObject("Fibo",OBJ_FIBO,Time,SupportLevel2,Time[MaxBars],ResistanceLevel2,Green,1,STYLE_DOT);

}
/*
if WaveAngle = 1 
and PriceLevel > 0
and PriceLevel < 50
then
WaveAngle = 2;

if WaveAngle = 2 
and PriceLevel < 0
and PriceLevel > -50
then
WaveAngle = 1;

*/
/*
if EW3MARK = 1 then 
{
//Print("EW0MARK:",EW0MARK," EW1MARK:",EW1MARK," EW2MARK:",EW2MARK," EW3MARK:",EW3MARK," EW3MARKBAR=",EW3MARKBAR," EW4MARK:",EW4MARK," EW0:",EW5PRICE," EW1:",EW1," EW2:",EW2," EW3:",EW3);
//Print("EW1MARKBAR:",EW1MARKBAR," EW2MARKBAR:",EW2MARKBAR," EW3MARKBAR:",EW3MARKBAR," EW3MARKBAR=",EW3MARKBAR," EW4MARK:",EW4MARK," EW0:",EW5PRICE," EW1:",EW1," EW2:",EW2," EW3:",EW3);
Print(TimeToStr(time),  
": EW0=",TimeToStr(EW5MARKTIME),
" ",EW5,
" EW1=",TimeToStr(EW1MARKTIME),
" ",EW1,
" EW2=",TimeToStr(EW2MARKTIME),
" ",EW2,
" EW3=",TimeToStr(EW3MARKTIME),
" ",EW3
);
}
*/

// Reallign Elliot Wave marked bars
if EW0MARK > 0 then EW5MARKBAR = 0;
if EW1MARK > 0 then EW1MARKBAR = 0;
if EW2MARK > 0 then EW2MARKBAR = 0;
if EW3MARK > 0 then EW3MARKBAR = 0;
if EW4MARK > 0 then EW4MARKBAR = 0;
if EW5MARK > 0 then EW5MARKBAR = 0;
if EW0MARK > 0 or EW5MARK > 0 then 
for counter = 0 to Bars -1
{
if EW5MARKBAR > 0 then break; // reallign finished
tempval = time[counter];

if EW5MARK = 0 and tempval = EW5MARKTIME then EW5MARKBAR = counter;
if EW1MARK > 0 and tempval = EW1MARKTIME then EW1MARKBAR = counter;
if EW2MARK > 0 and tempval = EW2MARKTIME then EW2MARKBAR = counter;
if EW3MARK > 0 and tempval = EW3MARKTIME then EW3MARKBAR = counter;
if EW4MARK > 0 and tempval = EW4MARKTIME then EW4MARKBAR = counter;
if EW5MARK > 0 and tempval = EW5MARKTIME then EW5MARKBAR = counter;
}
CalcBarDiff=(time[0]-time[Bars-1])/60/Period - Bars + 1;

if Bars < MaxBars+2
or (EW1MARK = 1 and EW1MARKBAR = 0)
or (EW2MARK = 1 and EW2MARKBAR = 0)
or (EW3MARK = 1 and EW3MARKBAR = 0)
or (EW4MARK = 1 and EW4MARKBAR = 0)
or (EW0MARK = 1 and EW5MARKBAR = 0)
or (EW5MARK = 1 and EW5MARKBAR = 0)
or EW1MARKBAR > Bars - 1
or EW2MARKBAR > Bars - 1
or EW3MARKBAR > Bars - 1
or EW4MARKBAR > Bars - 1
or EW5MARKBAR > Bars - 1 
then
{
if Bars > MaxBars+2
and prevbars < Bars
then
{
//prevbars=Bars;
/*
Print("Bars:",Bars," EW1MARKBAR:",EW1MARKBAR," EW2MARKBAR:",EW2MARKBAR," EW3MARKBAR:",EW3MARKBAR," EW3MARKBAR=",EW3MARKBAR," EW4MARKBAR:",EW4MARKBAR," EW5MARKBAR:",EW5MARKBAR);
Print(TimeToStr(time),  
": EW0=",TimeToStr(EW5MARKTIME),
" ",EW5,
" EW1=",TimeToStr(EW1MARKTIME),
" ",EW1,
" EW2=",TimeToStr(EW2MARKTIME),
" ",EW2,
" EW3=",TimeToStr(EW3MARKTIME),
" ",EW3
);
//print(time[1]," ",time[Bars-1]," ",time[100]," ",time[1]-time[Bars-1]," ",(time[1]-time[Bars-1])/60/Period, " ", time[0] - EW5MARKTIME);
*/
if EW0MARK = 1 and EW1MARK = 0 then print("ERROR: Bars:",Bars-1," EW0 Bar:", EW5MARKBAR, " EW0 Time:",TimeToStr(EW5MARKTIME), " Calculated EW0 Time:",TimeToStr(time[EW5MARKBAR])," EW0 Bars Diff:",(EW5MARKTIME-time[EW5MARKBAR])/60/Period);
if EW1MARK = 1 and EW2MARK = 0 then print("ERROR: Bars:",Bars-1," EW1 Bar:", EW1MARKBAR, " EW1 Time:",TimeToStr(EW1MARKTIME), " Calculated EW1 Time:",TimeToStr(time[EW1MARKBAR])," EW1 Bars Diff:",(EW1MARKTIME-time[EW1MARKBAR])/60/Period);
if EW2MARK = 1 and EW3MARK = 0 then print("ERROR: Bars:",Bars-1," EW2 Bar:", EW2MARKBAR, " EW2 Time:",TimeToStr(EW2MARKTIME), " Calculated EW2 Time:",TimeToStr(time[EW2MARKBAR])," EW2 Bars Diff:",(EW2MARKTIME-time[EW2MARKBAR])/60/Period);
if EW3MARK = 1 and EW4MARK = 0 then print("ERROR: Bars:",Bars-1," EW3 Bar:", EW3MARKBAR, " EW3 Time:",TimeToStr(EW3MARKTIME), " Calculated EW3 Time:",TimeToStr(time[EW3MARKBAR])," EW3 Bars Diff:",(EW3MARKTIME-time[EW3MARKBAR])/60/Period);
if EW4MARK = 1 and EW5MARK = 0 then print("ERROR: Bars:",Bars-1," EW4 Bar:", EW4MARKBAR, " EW4 Time:",TimeToStr(EW4MARKTIME), " Calculated EW4 Time:",TimeToStr(time[EW4MARKBAR])," EW4 Bars Diff:",(EW4MARKTIME-time[EW4MARKBAR])/60/Period);
if EW5MARK = 1 and EW0MARK = 0 then print("ERROR: Bars:",Bars-1," EW5 Bar:", EW5MARKBAR, " EW5 Time:",TimeToStr(EW5MARKTIME), " Calculated EW5 Time:",TimeToStr(time[EW5MARKBAR])," EW5 Bars Diff:",(EW5MARKTIME-time[EW5MARKBAR])/60/Period);
}
EW0MARK=0;
EW1MARK=0;
EW1=0;
EW1MARKTIME=0;
EW1MARKBAR=0;
EW2MARK=0;
EW2=0;
EW2MARKTIME=0;
EW2MARKBAR=0;
EW3MARK=0;
EW3=0;
EW3MARKTIME=0;
EW3MARKBAR=0;
EW4MARK=0;
EW4=0;
EW4MARKTIME=0;
EW4MARKBAR=0;
EW5MARK=0;
EW5=0;
EW5MARKTIME=0;
EW5MARKBAR=0;
ORDERMARK=0;
exit;
}


if EW0MARK = 0 and EW1MARK = 0 then 
{
EW0MARK = 0;
EW1MARK = 0;
EW1MARKBAR = 0;
EW1MARKTIME = 0;
EW2MARK = 0;
EW2MARKBAR = 0;
EW2MARKTIME = 0;
EW3MARK = 0;
EW3MARKBAR = 0;
EW3MARKTIME = 0;
EW4MARK = 0;
EW4MARKBAR = 0;
EW4MARKTIME = 0;
EW5MARK = 0;
EW5MARKBAR = 0;
EW5MARKTIME = 0;
}

MaxPriceBar = Highest (MODE_CLOSE,MaxBars+1, MaxBars);
MinPriceBar = Lowest (MODE_CLOSE, MaxBars+1, MaxBars);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];
//MaxPriceBar=time[MaxPriceBar];
//MinPriceBar=time[MinPriceBar];


if EW0MARK = 1 and EW2MARK = 0 and EW3MARK = 0
// Recalculate EW entry point while have only Elliot Wave [I]
then
{
MaxPriceBar = Highest (MODE_CLOSE,MaxBars+1, MaxBars);
MinPriceBar = Lowest (MODE_CLOSE, MaxBars+1, MaxBars);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];
if (WaveAngle = 1 and MinPrice < EW5PRICE)
or (WaveAngle = 2 and MaxPrice > EW5PRICE)
then
 {
if EW5MARKBAR <= MaxBars then
{
DelArrow(EW5MARKTIME,EW5PRICE + StopLoss / 2 * Point);
DelArrow(EW5MARKTIME,EW5PRICE - StopLoss / 2 * Point);
}
EW0MARK=0;
 }
}

/*
if WaveAngle = 1 and Close[counter] > MaxPrice then print("Counter:",counter, " MaxPrice:",MaxPrice);
if WaveAngle = 2 and Close[counter] < MaxPrice then print("Counter:",counter, " MinPrice:",MinPrice);

/*
//Reallign Elliot wave entry point
if WaveAngle = 1 and MaxPriceBar < RetracementBars then WaveAngle = 2
else
if WaveAngle = 2 and MinPriceBar < RetracementBars then WaveAngle = 1;
*/

//print("PriceLevel:",PriceLevel);

if (EW0MARK = 0)
//or (MaxPriceBar > MinPriceBar and WaveAngle = 1)
//or (MaxPriceBar < MinPriceBar and WaveAngle = 2)
then
{
EW0MARK=1;
EW1MARK=0;
EW2MARK=0;
EW3MARK=0;
EW4MARK=0;
EW5MARK=0;


if WaveAngle = 1
// try to mark first Elliot Wave
then
{
EW5=MinPrice;
EW5MARKBAR=MinPriceBar;
EW5MARKTIME=time[MinPriceBar];
EW5PRICE=MinPrice;
EW1=MinPrice;
//SetArrow(EW5MARKTIME,EW5PRICE,128,White);
SetArrow(EW5MARKTIME,EW5PRICE - StopLoss / 2 * Point,384,White);
Comment("\nEWTrend=Possible UP",
"\nLastTime=",TimeToStr(time[0]),
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print(Symbol," EW0 Time:",TimeToStr(EW5MARKTIME),": EW0:",EW5," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}

if WaveAngle = 2
// try to mark first reversed Elliot Wave
then
{
EW5=MaxPrice;
EW5MARKBAR=MaxPriceBar;
EW5MARKTIME=time[MaxPriceBar];
EW5PRICE=MaxPrice;
EW1=MaxPrice;
//SetArrow(EW5MARKTIME,EW5PRICE,128,Violet);
SetArrow(EW5MARKTIME,EW5PRICE + StopLoss / 2 * Point,384,Violet);
Comment("\nEWTrend=Possible DOWN",
"\nLastTime=",TimeToStr(time[0]),
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print(Symbol," EW0 Time:",TimeToStr(EW5MARKTIME),": EW0:",EW5," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}
//print ("waveangle=",WaveAngle);
}


//if IsTesting and EW3MARK = 1 then print("EW0MARK:",EW0MARK," EW1MARK:",EW1MARK," EW2MARK:",EW2MARK," EW3MARK:",EW3MARK," EW4MARK:",EW4MARK);

BarsShift=EW5MARKBAR;

/*
if EW5MARKBAR > MaxBars 
then  // reset EW count start entry 
{
EW0MARK=0;
if WaveAngle = 1 then DelArrow(EW5MARKTIME,EW5PRICE + StopLoss / 2 * Point);
if WaveAngle = 2 then DelArrow(EW5MARKTIME,EW5PRICE - StopLoss / 2 * Point);
}
*/


if EW0MARK=1 and EW2MARK=0 and EW3MARK=0
// and EW5MARKBAR > BarsCount
then
for counter=BarsShift - 1 downto 1
Begin

BarsCount = BarsShift - counter;
MaxPriceBar = Highest (MODE_CLOSE,EW5MARKBAR , BarsCount);
MinPriceBar = Lowest (MODE_CLOSE,EW5MARKBAR , BarsCount);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];



if WaveAngle = 1 and MaxPrice > EW1 and MaxPriceBar < EW5MARKBAR then 
{
EW1 = MaxPrice;
if EW1MARKBAR <= MaxBars then
DelArrow(EW1MARKTIME , Open[counter] + StopLoss / 2 * Point);
EW1MARKTIME=time[MaxPriceBar];
//print("EW1=",EW1);
}
if WaveAngle = 2 and MinPrice < EW1 and MinPriceBar < EW5MARKBAR  then 
{
if EW1MARKBAR <= MaxBars then
DelArrow(EW1MARKTIME , Open[counter] - StopLoss / 2 * Point);
EW1MARKTIME=time[MinPriceBar];
EW1 = MinPrice;
//print("EW1=",EW1);
}

/*
if IsTesting and (counter = BarsShift-1 or counter = 1) then
{
if WaveAngle = 1 then print("BarCount:",BarsCount ," Counter:",counter," Price:",Close[counter]," MaxPrice: ",MaxPrice," MaxPriceBar:",MaxPriceBar);
if WaveAngle = 2 then print("BarCount:",BarsCount ," Counter:",counter," Price:",Close[counter]," MinPrice:",MinPrice," MinPriceBar:",MinPriceBar);
print("Bars:",Bars-1," EW0 Bar:", EW5MARKBAR, " EW0 Time:",TimeToStr(EW5MARKTIME), " Calculated EW0 Time:",TimeToStr(time[EW5MARKBAR])," EW0 Bars Diff:",(EW5MARKTIME-time[EW5MARKBAR])/60/Period);
print("Bars:",Bars-1," EW1 Bar:", EW1MARKBAR, " EW1 Time:",TimeToStr(EW1MARKTIME), " Calculated EW1 Time:",TimeToStr(time[EW1MARKBAR])," EW1 Bars Diff:",(EW1MARKTIME-time[EW1MARKBAR])/60/Period);
print("WaveAngle:",WaveAngle," EW1MARK:",EW1MARK," EW0:",EW5PRICE," EW1:",EW1);
}
*/
if WaveAngle = 1
and Close[EW5MARKBAR] + NoisePips * Point < Close[counter]
and MaxPrice <= Close[counter]
and EW1 > Close[EW5MARKBAR] + NoisePips * Point
and EW1 <= close[counter]
then
{
if EW1MARKBAR <= MaxBars then
DelArrow(EW1MARKTIME , Open[counter] + StopLoss / 2 * Point);
if Close[counter] > MaxPrice then 
{
EW1 = Close[counter];
EW1MARKTIME=time[counter];
}
EW1MARK=1;
EW2=EW1;
EW1MARKTIME=time[counter];
EW1MARKBAR=counter;
//SetArrow(EW1MARKTIME,Open[counter] + StopLoss / 2 * Point,129,White);
Comment("\nEWTrend=Possible UP",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print("EW1 Time:",TimeToStr(EW1MARKTIME),": EW1:",EW1," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}

if WaveAngle = 2 
and Close[EW5MARKBAR] - NoisePips * Point > Close[counter]
and MinPrice >= Close[counter]
and EW1 < Close[EW5MARKBAR] - NoisePips * Point
and EW1 >= close[counter]
then
{
if EW1MARKBAR <= MaxBars then
DelArrow(EW1MARKTIME , Open[counter] - StopLoss / 2 * Point);
if Close[counter] < MinPrice then 
{
EW1 = Close[counter];
EW1MARKTIME=time[counter];
}
EW1MARK=1;
EW2=EW1;
EW1MARKBAR=counter;
//SetArrow(EW1MARKTIME,Open[counter] - StopLoss / 2 * Point,129,Violet);
Comment("\nEWTrend=Possible DOWN",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print("EW1 Time:",TimeToStr(EW1MARKTIME),": EW1:",EW1," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}


if EW1MARK = 1 and counter < EW1MARKBAR 
and (WaveAngle = 1 and Close[counter] < EW1 - NoisePips * Point 
 or (WaveAngle = 2 and Close[counter] > EW1 + NoisePips * Point)) 
then // Wave 1 ended
{
EW3MARK=1;
break;
}


End;


if EW0MARK=1 and EW2MARK=0 and EW3MARK=1
then
{
EW3MARK=0;
if WaveAngle = 1 
 then
 { 
if EW1MARKBAR <= MaxBars then
DelArrow(EW1MARKTIME, EW1 + StopLoss / 2 * Point);
SetArrow(EW1MARKTIME, EW1 + StopLoss / 2 * Point,129,White);
 }
 else
 { 
if EW1MARKBAR <= MaxBars then
DelArrow(EW1MARKTIME, EW1 - StopLoss / 2 * Point);
SetArrow(EW1MARKTIME, EW1 - StopLoss / 2 * Point,129,Violet);
 }
}

BarsShift=EW1MARKBAR;
if Bars < BarsShift then exit;

// Check for failed Elliot Wave 1
if (EW3MARK=0 and EW1MARK=1 and EW2MARK=0 and WaveAngle = 1 and EW1 < EW5PRICE - NoisePips * Point)
or (EW3MARK=0 and EW1MARK=1 and EW2MARK=0 and WaveAngle = 2 and EW1 > EW5PRICE + NoisePips * Point)
then
 {
 for counter=1 to EW5MARKBAR
 {
 DelArrow(time[counter] , Close[counter] + StopLoss / 2 * Point);
 DelArrow(time[counter] , Close[counter] - StopLoss / 2 * Point);
 }
 EW0MARK=0;
 EW1MARK=0;
 EW2MARK=0;
 EW3MARK=0;
 EW4MARK=0;
 EW5MARK=0;
}

if EW1MARK=1 and EW3MARK=0
then
for counter=BarsShift - 1 downto 1
Begin
BarsCount = BarsShift - counter;
MaxPriceBar = Highest (MODE_CLOSE,EW1MARKBAR , BarsCount);
MinPriceBar = Lowest (MODE_CLOSE,EW1MARKBAR , BarsCount);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];

if WaveAngle = 1 and MinPrice < EW2 and MinPriceBar < EW5MARKBAR then 
{
if EW2MARKBAR <= MaxBars then
DelArrow(EW2MARKTIME , Open[counter] - StopLoss / 2 * Point);
EW2 = MinPrice;
EW2MARKTIME=time[MinPriceBar];
}
if WaveAngle = 2 and MaxPrice > EW2 and MaxPriceBar < EW5MARKBAR then 
{
if EW2MARKBAR <= MaxBars then
DelArrow(EW2MARKTIME , Open[counter] + StopLoss / 2 * Point);
EW2 = MaxPrice;
EW2MARKTIME=time[MaxPriceBar];
}
if WaveAngle = 1 
and Close[EW1MARKBAR] - NoisePips * Point > Close[counter]
and MinPrice >= Close[counter]
and EW2 < Close[EW1MARKBAR] - NoisePips * Point
and EW2 > close[counter]
then
{
if EW2MARKBAR <= MaxBars then
DelArrow(EW2MARKTIME , Open[counter] - StopLoss / 2 * Point);
if Close[counter] < MinPrice then 
{
EW2 = Close[counter];
EW2MARKTIME=time[counter];
}
EW3=EW2;
EW2MARK=1;
EW2MARKBAR=counter;
EW3MARKBAR=EW2MARKBAR;
//SetArrow(EW2MARKTIME,Open[counter] - StopLoss / 2 * Point,130,White);
Comment("\nEWTrend=Possible UP",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print("EW2 Time:",TimeToStr(EW2MARKTIME),": EW2:",EW2," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}

if WaveAngle = 2 
and Close[EW1MARKBAR] + NoisePips * Point < Close[counter]
and MaxPrice <= Close[counter]
and EW2 > Close[EW1MARKBAR] + NoisePips * Point
and EW2 < close[counter]
then
{
if EW2MARKBAR <= MaxBars then
DelArrow(EW2MARKTIME , Open[counter] + StopLoss / 2 * Point);
if Close[counter] > MaxPrice then 
{
EW2 = Close[counter];
EW2MARKTIME=time[counter];
}
EW3=EW2;
EW2MARK=1;
EW2MARKBAR=counter;
EW3MARKBAR=EW2MARKBAR;
//SetArrow(EW2MARKTIME,Open[counter] + StopLoss / 2 * Point,130,Violet);
Comment("\nEWTrend=Possible DOWN",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print("EW2 Time:",TimeToStr(EW2MARKTIME),": EW2:",EW2," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}


// Check for failed Elliot Wave 2
if (EW3MARK=0 and EW2MARK=1 and WaveAngle = 1 and EW2 < EW5 - NoisePips * Point)
or (EW3MARK=0 and EW2MARK=1 and WaveAngle = 2 and EW2 > EW5 + NoisePips * Point)
then
 {
 for counter=1 to EW5MARKBAR
 {
 DelArrow(time[counter] , Close[counter] + StopLoss / 2 * Point);
 DelArrow(time[counter] , Close[counter] - StopLoss / 2 * Point);
 }
 EW0MARK=0;
 EW1MARK=0;
 EW2MARK=0;
 EW3MARK=0;
 EW4MARK=0;
 EW5MARK=0;
Comment("\nEWTrend=Recalculating..",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nEW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
/*
 Print(TimeToStr(time),": ",Symbol," Elliot Wave 2 failed, reverting retracement trend vector. ");
 Print("Old EW0=",TimeToStr(EW5MARKTIME),
" ",EW5,
" EW1=",TimeToStr(EW1MARKTIME),
" ",EW1,
" EW2=",TimeToStr(EW2MARKTIME),
" ",EW2,
" EW3=",TimeToStr(EW3MARKTIME),
" ",EW3
);
*/
/*
 MaxPriceBar = Highest (MODE_CLOSE,EW1MARKBAR + MaxBars+1 ,MaxBars);
 MinPriceBar = Lowest (MODE_CLOSE,EW1MARKBAR + MaxBars+1 ,MaxBars);
 MaxPrice = Close[MaxPriceBar];
 MinPrice = Close[MinPriceBar];

 tempval=EW5;
 EW3=EW2;
 EW2=EW1;
 if WaveAngle = 1 then EW5 = MinPrice;
 if WaveAngle = 2 then EW5 = MaxPrice;
 EW5PRICE=EW5;
 EW1=tempval;
 
 
 tempval=EW5MARKTIME;
 if WaveAngle = 1 then EW5MARKTIME = time[MinPriceBar];
 if WaveAngle = 2 then EW5MARKTIME = time[MaxPriceBar];
 EW3MARKTIME=EW2MARKTIME;
 EW2MARKTIME=EW1MARKTIME;
 EW1MARKTIME=tempval;
 
 tempval=EW5MARKBAR;
 if WaveAngle = 1 then EW5MARKBAR = MinPriceBar;
 if WaveAngle = 2 then EW5MARKBAR = MaxPriceBar;
 EW5MARKBAR=EW1MARKBAR;
 EW3MARKBAR=EW2MARKBAR;
 EW2MARKBAR=EW1MARKBAR;
 EW1MARKBAR=tempval;

if Bars < EW1MARKBAR + MaxBars+1 then
// Check if we have not enough prices for estimating EW0
{
EW5=Close[Bars-1];
EW5PRICE=EW5;
EW5MARKTIME=time[Bars-1];
EW5MARKBAR=Bars-1;
}

 EW4=0;
 EW4MARKTIME=0;

//print(TimeToStr(time),": ",TimeToStr(EW5MARKTIME)," ",EW5MARKBAR," ",EW5 + StopLoss / 2 * Point);
//print(time, " ",EW1MARKTIME," ",EW5MARKTIME," ",Period);
//print(TimeToStr(time), " ",TimeToStr(EW1MARKTIME)," ",TimeToStr(EW5MARKTIME)," ",Period);

 if WaveAngle = 1 then 
 {
// WaveAngle = 2;
Comment("\nEWTrend=Recalculating..",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nEW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
 SetArrow(EW5MARKTIME,EW5 + StopLoss / 2 * Point,128,Violet);
 SetArrow(EW1MARKTIME,EW1 - StopLoss / 2 * Point,129,Violet);
 SetArrow(EW2MARKTIME,EW2 + StopLoss / 2 * Point,130,Violet);
 SetArrow(EW3MARKTIME,EW3 - StopLoss / 2 * Point,131,Violet);
 }
 else 
 {
// WaveAngle = 1;
Comment("\nEWTrend=Recalculating..",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nEW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
 SetArrow(EW5MARKTIME,EW5 - StopLoss / 2 * Point,128,White);
 SetArrow(EW1MARKTIME,EW1 + StopLoss / 2 * Point,129,White);
// print(TimeToStr(EW1MARKTIME)," ",TimeToStr(time[EW1MARKBAR])," ",EW1 + StopLoss / 2 * Point);
// Print("EW0 Time:",TimeToStr(EW5MARKTIME),": EW0:",EW5," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);

 SetArrow(EW2MARKTIME,EW2 - StopLoss / 2 * Point,130,White);
 SetArrow(EW3MARKTIME,EW3 + StopLoss / 2 * Point,131,White);
 }
 /*
 Print("\nEWTrend=Recalculating..",
 "EW0=",TimeToStr(EW5MARKTIME),
" ",EW5,
" EW1=",TimeToStr(EW1MARKTIME),
" ",EW1,
" EW2=",TimeToStr(EW2MARKTIME),
" ",EW2,
" EW3=",TimeToStr(EW3MARKTIME),
" ",EW3,
" Pivot ",Pivot,
" Resistance Level I ",ResistanceLevel1,
" Support Level I ",SupportLevel1,
" Resistance Level II ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
 */
 break;
}  
End;


if EW2MARK=1 and EW3MARK=0
then
{
if WaveAngle = 2 
 then
 { 
if EW2MARKBAR <= MaxBars then
DelArrow(EW2MARKTIME, EW2 + StopLoss / 2 * Point);
SetArrow(EW1MARKTIME, EW1 - StopLoss / 2 * Point,129,Violet);
SetArrow(EW2MARKTIME, EW2 + StopLoss / 2 * Point,130,Violet);
 }
 else
 { 
if EW2MARKBAR <= MaxBars then
DelArrow(EW2MARKTIME, EW2 - StopLoss / 2 * Point);
SetArrow(EW1MARKTIME, EW1 + StopLoss / 2 * Point,129,White);
SetArrow(EW2MARKTIME, EW2 - StopLoss / 2 * Point,130,White);
 }
}

BarsShift=EW1MARKBAR;
if Bars < BarsShift then exit;

if EW2MARK = 1 and EW4MARK = 0
// and EW4MARK = 0 
then
for counter=BarsShift - 1 downto 1
Begin

BarsCount = BarsShift - counter;
MaxPriceBar = Highest (MODE_CLOSE,EW1MARKBAR , BarsCount);
MinPriceBar = Lowest (MODE_CLOSE,EW1MARKBAR , BarsCount);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];

if WaveAngle = 1 and MaxPrice > EW3 and MaxPriceBar < EW2MARKBAR then 
{
EW3 = MaxPrice;
EW3MARKTIME=time[MaxPriceBar];
EW3MARKBAR=MaxPriceBar;
if EW3MARKBAR <= MaxBars then
DelArrow(EW3MARKTIME , Open[counter] + StopLoss / 2 * Point);
//print("EW3=",EW3);
}

if WaveAngle = 2 and MinPrice < EW3 and MinPriceBar < EW2MARKBAR  then 
{
if EW3MARKBAR <= MaxBars then
DelArrow(EW3MARKTIME , Open[counter] - StopLoss / 2 * Point);
EW3MARKTIME=time[MinPriceBar];
EW3MARKBAR=MinPriceBar;
EW3 = MinPrice;
//print("EW3=",EW3);
}


/*
if IsTesting and (counter = BarsShift-1 or counter = 1) then
{
if WaveAngle = 1 then print("BarCount:",BarsCount ," Counter:",counter," Price:",Close[counter]," MaxPrice: ",MaxPrice," MaxPriceBar:",MaxPriceBar);
if WaveAngle = 2 then print("BarCount:",BarsCount ," Counter:",counter," Price:",Close[counter]," MinPrice:",MinPrice," MinPriceBar:",MinPriceBar);
print("Bars:",Bars-1," EW2 Bar:", EW2MARKBAR, " EW2 Time:",TimeToStr(EW2MARKTIME), " Calculated EW2 Time:",TimeToStr(time[EW2MARKBAR])," EW2 Bars Diff:",(EW2MARKTIME-time[EW2MARKBAR])/60/Period);
print("Bars:",Bars-1," EW3 Bar:", EW3MARKBAR, " EW3 Time:",TimeToStr(EW3MARKTIME), " Calculated EW3 Time:",TimeToStr(time[EW3MARKBAR])," EW3 Bars Diff:",(EW3MARKTIME-time[EW3MARKBAR])/60/Period);
print("WaveAngle:",WaveAngle," EW3MARK:",EW3MARK," EW4MARK:",EW4MARK," EW0:",EW5PRICE," EW1:",EW1," EW2:",EW2," EW3:",EW3);
}
/*
if WaveAngle = 1 and Close[counter] > MaxPrice then print("Counter:",counter, " MaxPrice:",MaxPrice);
if WaveAngle = 2 and Close[counter] < MaxPrice then print("Counter:",counter, " MinPrice:",MinPrice);
*/

if WaveAngle = 1 
and EW1 + NoisePips * Point < Close[counter]
and MaxPrice <= Close[counter]
and EW3 > EW2 + NoisePips * Point
and EW3 < close[counter]
then
{
if EW3MARKBAR <= EW5MARKBAR then
DelArrow(EW3MARKTIME , Open[counter] + StopLoss / 2 * Point);
EW3 = Close[counter];
EW3MARKTIME=time[counter];
EW3MARK=1;
EW4=EW3;
EW3MARKBAR=counter;
//SetArrow(time[counter],Open[counter] + StopLoss / 2 * Point,131,White);
//print("EW0 date:",TimeToStr(EW5MARKTIME)," EW1 date:",TimeToStr(EW1MARKTIME)," EW2 date:",TimeToStr(EW2MARKTIME)," EW3 date:",TimeToStr(EW3MARKTIME));
Comment("\nEWTrend=UP",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nEW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print("EW3 Time:",TimeToStr(EW3MARKTIME),": EW3:",EW3," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}

if WaveAngle = 2 
and EW1 - NoisePips * Point > Close[counter]
and MinPrice >= Close[counter]
and EW3 < EW2 - NoisePips * Point
and EW3 > close[counter]
then
{
if EW3MARKBAR <= EW5MARKBAR then
DelArrow(EW3MARKTIME , Open[counter] - StopLoss / 2 * Point);
EW3 = Close[counter];
EW3MARKTIME=time[counter];
EW3MARK=1;
EW4=EW3;
EW4MARKTIME=time[counter];
EW3MARKBAR=counter;
//SetArrow(time[counter],Open[counter],131,Violet);
Comment("\nEWTrend=DOWN",
"\nEW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nEW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nEW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nEW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
//Print("EW3 Time:",TimeToStr(EW3MARKTIME),": EW3:",EW3," WaveAngle:",WaveAngle," MaxPriceBar:",MaxPriceBar," MinPriceBar:",MinPriceBar);
}

/*
if EW3MARK = 1 and counter < EW3MARKBAR and (WaveAngle = 1 and Close[counter] < EW3 - NoisePips * Point 
or (WaveAngle = 2 and Close[counter] > EW3 + NoisePips * Point)) 
then // Wave 1 ended
{
EW4MARK=1;
break;
}
*/

End;

//Check if we have failed EW 3 and it falls bellow EW Wave 1
if (EW3MARK=1 and WaveAngle = 1 and Open < EW2)
or (EW3MARK=1 and WaveAngle = 2 and Open > EW2)
then
 {
Comment("\nEWTrend=Recalculating..",
"\nLast EW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nLast EW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nLast EW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nLast EW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
 EW0MARK=0;
 EW1MARK=0;
 EW2MARK=0;
 EW3MARK=0;
 EW4MARK=0;
 EW5MARK=0;
 ORDERMARK=0;
 for counter=1 to EW2MARKBAR
{
    if close[counter] = EW3
    then
    {
    DelArrow(time[counter] , Close[counter] + StopLoss / 2 * Point);
 DelArrow(time[counter] , Close[counter] - StopLoss / 2 * Point);
 break;
 }
 }

 if WaveAngle = 1 then SetArrow(time,Ask,251,Red);
 if WaveAngle = 2 then SetArrow(time,Bid,251,Red);
 LastEW5=EW5Price;
 LastEW1=EW1;
 LastEW2=EW2;
 LastEW3=EW3;
 //Print(TimeToStr(time),": ",Symbol," Elliot Wave 3 failed, recalculating EW0...");

 }

if EW3MARK = 1 and EW4MARK = 0 then
{
EWOscillator = iCustom("ElliotOscillator",EWPeriod,0,RetracementBars,MODE_FIRST,0);
EWLevel = iCustom("ElliotWaves",EWPeriod,0,RetracementBars,MODE_FIRST,0);
}

if EWOscillator != 0 and EWLevel != 0 and EW3MARK = 1 and EW4MARK = 0 then
{
//print("EW0MARK:",EW0MARK," EW1MARK:",EW1MARK," EW2MARK:",EW2MARK," EW3MARK:",EW3MARK," EW4MARK:",EW4MARK);
//Print(TimeToStr(time[0]),": EW1MARKBAR:",EW1MARKBAR," EW2MARKBAR:",EW2MARKBAR," EW3MARKBAR:",EW3MARKBAR," EW3MARKBAR=",EW3MARKBAR," EW4MARK:",EW4MARK);
Print(TimeToStr(time[0]),": EW3 START - Open:",Open," EW0:",EW5PRICE," EW1:",EW1," EW2:",EW2," EW3:",EW3," WaveAngle:",WaveAngle," Price Level:",PriceLevel," Last Price Level:",LastPriceLevel," Max/Min Level:",FiboLevel);
Print(TimeToStr(time[0]),": EW3 START - Pivot:",Pivot," Resistance Level I:",ResistanceLevel1," Support Level I:",SupportLevel1," Resistance Level II:",ResistanceLevel2," Support Level II:",SupportLevel2);
EW3ORDERMARK=0;
LastOp=0;

 if EW3 > Pivot 
 then
 { 
if EW3MARKBAR <= MaxBars then
DelArrow(EW3MARKTIME, EW3 + StopLoss / 2 * Point);
SetArrow(EW3MARKTIME, EW3 + StopLoss / 2 * Point,131,White);
DelArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point);

if EW3 > ResistanceLevel1 
and FiboLevel > 99 
and ResistanceLevel2 - ResistanceLevel1 < SupportLevel1 - SupportLevel2
and BullsAngle = 1
then
{
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,246,White); //UP
  EW3ORDERMARK=1;
  LastOp=1;
}   
else
if EW3 > ResistanceLevel1 
and FiboLevel > 100 
and FiboLevel < 130 
then
{
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,White); // UP
  EW3ORDERMARK=1;
  LastOp=2;
} 
else
if EW2 > SupportLevel1 
and FiboLevel > 80 
and FiboLevel < 130 
and PriceLevel > 65
then
{
  if Open > (MaxPrice + MinPrice) * 2 / 3
  or (MACDAngle = 2 and FiboLevel > 100)
  then
  {
   if PriceLevel > 87.5 // Murrey 7/8 support/resistance line
   //and FiboLevel < 112.5 // Murrey 8/8+1 support/resistance line
   and BullsAngle = 1
   and BearsAngle = 1
   then 
   {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,White); // UP
  EW3ORDERMARK=3;
  LastOp=3;
   }
   else 
   {
    if MA < LongMA
    then
    {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,White); // UNSTABLE UP
  EW3ORDERMARK=1;
  LastOp=4;
  }
  else
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,SkyBlue); // UNSTABLE DOWN, POSSIBLE UP
  EW3ORDERMARK=2;
  LastOp=5;
  };
   };
  }
  else
  if FiboLevel > 100 // Over Murrey 8/8 support/resistance line
  then
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,SkyBlue); // POSSIBLE UP
  EW3ORDERMARK=1;
  LastOp=6;
  }
  else
  if FiboLevel = 100 // Murrey 8/8 support/resistance line
  then
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,SkyBlue); // POSSIBLE RESIST DOWN
  EW3ORDERMARK=12;
  LastOp=7;
  };
} 
else 
if FiboLevel > 70 
and FiboLevel < 150 
and PriceLevel < 60
//and Bid > EW3 + Slippage * Point
then
{
  if (FiboLevel = 100) // Murrey 8/8 support/resistance line
  and MACDAngle = 1
  then
  {
  SetArrow(EW3MARKTIME, EW3 - (StopLoss / 2 + NoisePips) * Point,196,SkyBlue); //TEMP UP, REVERT TO DOWN
  EW3ORDERMARK=13;
  LastOp=8;
  }
  else
  {
  SetArrow(EW3MARKTIME, EW3 - (StopLoss / 2 + NoisePips) * Point,198,White); //UP
  EW3ORDERMARK=3;
  LastOp=9;
  }
} 
else
if PriceLevel > 65 
and MA < Open
then
{
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,White); // DOWN
  EW3ORDERMARK=4;
  LastOp=10;
}; 
 }
 else
 { 
if EW3MARKBAR <= MaxBars then
DelArrow(EW3MARKTIME, EW3 - StopLoss / 2 * Point);
SetArrow(EW3MARKTIME, EW3 - StopLoss / 2 * Point,131,Violet);
DelArrow(EW3MARKTIME, EW3 - (StopLoss / 2 + NoisePips) * Point);
if EW3 < SupportLevel1 
and FiboLevel > 99 
and ResistanceLevel2 - ResistanceLevel1 < SupportLevel1 - SupportLevel2 
and BearsAngle = 2
then
   {
 SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,248,Violet); // DOWN
 EW3ORDERMARK=11;
 LastOp=21;
   } 
else
if EW3 < SupportLevel1  
and FiboLevel < 130 
and FiboLevel > 100 
then
{
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,Violet); // DOWN
  EW3ORDERMARK=11;
  LastOp=22;
} 
else
if EW2 < ResistanceLevel1 
and FiboLevel > 80 
and FiboLevel < 130 
and PriceLevel < -65
    then
{
  if Open < (MaxPrice + MinPrice) * 3 / 2
  or (MACDAngle = 2 and FiboLevel > 100)
  then
  {
   if PriceLevel < -87.5 // Murrey 7/8 support/resistance line
   //and FiboLevel < 112/5 // Murrey 8/8+1 support/resistance line
   and BullsAngle = 2
   and BearsAngle = 2
   then 
   {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,Violet); // DOWN
  EW3ORDERMARK=13;
  LastOp=23;
   }
   else
   {
    if MA > LongMA
    then
    {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,Violet); // UNSTABLE DOWN
  EW3ORDERMARK=11;
  LastOp=24;
}
else
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,OrangeRed); // UNSTABLE UP, POSSIBLE DOWN
  EW3ORDERMARK=12;
  LastOp=25;
  };  
   };
   
  }
  else
  if FiboLevel > 100 // Over Murrey 8/8 support/resistance line
  then
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,202,OrangeRed); // POSSIBLE DOWN
  EW3ORDERMARK=11;
  LastOp=26;
  }
  else
  if FiboLevel = 100 // Murrey 8/8 support/resistance line
  then
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,OrangeRed); // POSSIBLE RESIST AND UP
  EW3ORDERMARK=2;
  LastOp=27;
  };  
} 
else 
if FiboLevel > 70 
and FiboLevel < 150 
and PriceLevel > -60
//and Ask < EW3 - Slippage * Point
then
{
  if (FiboLevel = 100) // Murrey 8/8 support/resistance line
  and MACDAngle = 2
  then
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,198,OrangeRed); //TEMP DOWN, REVERT TO UP
  EW3ORDERMARK=3;
  LastOp=28;
  }
  else
  {
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,196,Violet); //DOWN
  EW3ORDERMARK=13;
  LastOp=29;
  }
} 
else
if PriceLevel < -65 
and MA > Open
then
{
  SetArrow(EW3MARKTIME, EW3 + (StopLoss / 2 + NoisePips) * Point,200,Violet); // UP
  EW3ORDERMARK=14;
  LastOp=30;
}; 

 }
 EW4MARK=1;
 EW4MARKTIME=EW3MARKTIME;
 EW4MARKBAR=EW3MARKBAR;
}

if EW3MARK=1  
and ((WaveAngle = 1 and EW3 - Open > EW1 - EW2 )
or (WaveAngle = 2 and Open - EW3 > EW2 - EW1 ))
then
{
//Print(TimeToStr(time),": ",Symbol," Elliot Wave 3 retracement ended. Last EW3:",EW3," Last EW3 Time:",TimeToStr(EW3MARKTIME)," Order Stop:",TrailingStopPoint);
//Alert(TimeToStr(time),": ",Symbol," Elliot Wave 3 retracement ended. Last EW3:",EW3," Last EW3 Time:",TimeToStr(EW3MARKTIME)," Order Stop:",TrailingStopPoint);
Comment("\nEWTrend=Recalculating..",
"\nLast EW0=",TimeToStr(EW5MARKTIME),
"    ",EW5,
"\nLast EW1=",TimeToStr(EW1MARKTIME),
"    ",EW1,
"\nLast EW2=",TimeToStr(EW2MARKTIME),
"    ",EW2,
"\nLast EW3=",TimeToStr(EW3MARKTIME),
"    ",EW3,
"\nPivot                             ",Pivot,
"\nResistance Level I            ",ResistanceLevel1,
"\nSupport Level I                ",SupportLevel1,
"\nResistance Level II          ",ResistanceLevel2,
"\nSupport Level II              ",SupportLevel2,
"\nPrice Level                   ",PriceLevel,"%"
);
EW0MARK=0;
EW1MARK=0;
EW2MARK=0;
EW3MARK=0;
EW4MARK=0;
EW5MARK=0;
ORDERMARK=0;
 }


if prevbars > 0 and EW3ORDERMARK=99
    and Bars != prevbars
and ((PriceLevel > 0 and LastPriceLevel <= 0) 
  or (PriceLevel < 0 and LastPriceLevel >= 0))
//   and CCI < 200
then
{
 ENTRYPRICE=Open;
 if ParabolicSAR < Open then { ORDERANGLE=1; ENTRYPRICE=Pivot;MinTakeProfitPtS=ResistanceLevel2;};
 if ParabolicSAR > Open then { ORDERANGLE=11; ENTRYPRICE=Pivot;MinTakeProfitPtS=SupportLevel2;} 
 Trace = 1;
    //print(TimeToStr(time),": Trace:",Trace," ORDERMARK:",ORDERMARK," ORDERANGLE:",ORDERANGLE," Price: ",Ask," Commodity Channel Index ",CCI," Pivot ",Pivot," Resistance Level I ",ResistanceLevel1," Support Level I ",SupportLevel1," Resistance Level II ",ResistanceLevel2," Support Level II ",SupportLevel2," Price Level ",PriceLevel," Last Price Level ",LastPriceLevel);    
LastOp=0;
ORDERMARK=1;
ORDERCOUNT=0;
if WaveAngle = 1 then SARAngle = 1;
if WaveAngle = 2 then SARAngle = 2;
for counter = 1 to 10
Begin
tempval =iSAR(SARstep,SARmax,counter);
//print("Price:",Close[counter]," SAR:",tempval);
if (WaveAngle = 1 and tempval > Close[counter])
then
SARAngle = 2;
if (WaveAngle = 2 and tempval < Close[counter])
then
SARAngle = 1;
End;

 if WaveAngle = 1 then print(TimeToStr(time),": Support/Resistance cross at price:",Open," WaveAngle: UP SAR:",ParabolicSAR, " SARAngle:",SarAngle," PriceLevel: ",PriceLevel," LastPriceLevel: ",LastPriceLevel);
 if WaveAngle = 2 then print(TimeToStr(time),": Support/Resistance cross at price:",Open," WaveAngle: DOWN SAR:",ParabolicSAR, " SARAngle:",SarAngle," PriceLevel: ",PriceLevel," LastPriceLevel: ",LastPriceLevel);  
 Print(TimeToStr(time[0]),": Support/Resistance - Pivot:",Pivot," Resistance Level I:",ResistanceLevel1," Support Level I:",SupportLevel1," Resistance Level II:",ResistanceLevel2," Support Level II:",SupportLevel2);
 Print(" Support/Resistance - EW0MARK:",EW0MARK," EW1MARK:",EW1MARK," EW2MARK:",EW2MARK," EW3MARK:",EW3MARK," EW3MARKBAR=",EW3MARKBAR," EW4MARK:",EW4MARK," EW0:",EW5PRICE," EW1:",EW1," EW2:",EW2," EW3:",EW3);
     SetArrow(time,Open,254,Blue);

if WaveAngle = 1 
then
{ 
if EW0MARK = 1 
and EW1MARK=1
and EW2MARK=0
then
ORDERANGLE=2;

if EW0MARK = 1 
and EW1MARK=1
and EW2MARK=1
and EW3MARK=0
then
ORDERANGLE=23;

if EW0MARK = 1 
and EW1MARK=1
and EW2MARK=1
and EW3MARK=1
then
ORDERANGLE=4;
}

if WaveAngle = 2 
then
{ 
if EW0MARK = 1 
and EW1MARK=1
and EW2MARK=0
then
ORDERANGLE=21;

if EW0MARK = 1 
and EW1MARK=1
and EW2MARK=1
and EW3MARK=0
then
ORDERANGLE=22;

if EW0MARK = 1 
and EW1MARK=1
and EW2MARK=1
and EW3MARK=1
then
ORDERANGLE=3;
}
LastOp = 1;
}

if ORDERMARK > 9990
then
{
 ORDERANGLE=WaveAngle;
 if ORDERCOUNT > TradesCount 
    and EW3 <= Open
 then ORDERCOUNT = TradesCount;   
if WaveAngle = 1 and Open - TakeProfit * Point > EW1 then ORDERMARK = 1; // Additional Orders handling
if WaveAngle = 2 and Open + TakeProfit * Point < EW1 then ORDERMARK = 1; // Additional Orders handling

}
if WaveAngle = 1 then SARAngle = 1;
if WaveAngle = 2 then SARAngle = 2;
for counter = 1 to RetracementBars
Begin
tempval =iSAR(SARstep,SARmax,counter);
//print("Price:",Close[counter]," SAR:",tempval);
if (WaveAngle = 1 and tempval > Close[counter])
then
SARAngle = 2;
if (WaveAngle = 2 and tempval < Close[counter])
then
SARAngle = 1;
End;

if WaveAngle = 1 then MACDAngle = 1;
if WaveAngle = 2 then MACDAngle = 2;
for counter = 1 to RetracementBars
Begin
tempval=iMACD(RetracementBars/5,RetracementBars,RetracementBars/5,MODE_EMA,counter);
//print("MACD:",tempval);
if WaveAngle = 1
then
{
  if tempval > 0 and tempval < MACD then MACDAngle = 1;
  if tempval < 0 or tempval > MACD then MACDAngle = 2;
}  

if WaveAngle = 2 
then
{
  if tempval > 0 or tempval < MACD then MACDAngle = 1;
  if tempval < 0 and tempval > MACD then MACDAngle = 2;
}  
End;

ShortMACDAngle = MACDAngle;

if WaveAngle = 1 then MACDAngle = 1;
if WaveAngle = 2 then MACDAngle = 2;
for counter = 1 to RetracementBars
Begin
tempval=iMACD(RetracementBars,MaxBars,RetracementBars,MODE_EMA,counter);
//print("MACD:",tempval);
if WaveAngle = 1 
then
{
  if tempval > 0 and tempval < MACD then MACDAngle = 1;
//  if tempval < 0 or tempval > MACD then MACDAngle = 2;
  if tempval > MACD then MACDAngle = 2;
}  

if WaveAngle = 2 
then
{
  if tempval > 0 or tempval < MACD then MACDAngle = 1;
//  if tempval < 0 and tempval > MACD then MACDAngle = 2;
  if tempval > MACD then MACDAngle = 2;
}  
End;

MaxPriceBar = Highest (MODE_CLOSE,MaxBars+1, RetracementBars);
MinPriceBar = Lowest (MODE_CLOSE, MaxBars+1, RetracementBars);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];

     if WaveAngle = 1 then
     {
  BearsAngle=1;
  BullsAngle=1;
  for counter=1 to RetracementBars
  {
       tempval=iBearsPower(RetracementBars,MODE_HIGH,counter);
//          if tempval < 0 or tempval > Bears then BearsAngle=2;
          if tempval > Bears then BearsAngle=2;
   tempval=iBullsPower(RetracementBars,MODE_LOW,counter); 
//      if tempval < 0 or tempval > Bulls then BullsAngle=2;
      if tempval > Bulls then BullsAngle=2;
  }
 } 
     if WaveAngle = 2 then
     {
  BearsAngle=2;
  BullsAngle=2;
  for counter=1 to RetracementBars
  {
       tempval=iBearsPower(RetracementBars,MODE_HIGH,counter);
//          if tempval > 0 or tempval < Bears then BearsAngle=1;
          if tempval < Bears then BearsAngle=1;
   tempval=iBullsPower(RetracementBars,MODE_LOW,counter); 
//      if tempval > 0 or tempval < Bulls then BullsAngle=1;
      if tempval < Bulls then BullsAngle=1;
  }
} 

if EW3ORDERMARK > 0
  then
  {  
  ORDERCOUNT=0;
          ORDERMARK=1;
  if EW3ORDERMARK = 1 
//  and Bid > EW3 + Slippage * Point
//     and Open >= EW3
//  and Bid > EW3 + NoisePips * Point
  then 
  {
 ORDERANGLE=4;
      }  

  if EW3ORDERMARK = 2
//     and Open >= EW3
//  and Ask < EW3 - NoisePips * Point
  then 
  {
  ORDERANGLE = 3;    
      }  

  if EW3ORDERMARK = 3
//     and Open >= EW3
//  and Bid > EW3 + NoisePips * Point
  then 
  {
  ORDERANGLE = 2;    
      }  

  if EW3ORDERMARK = 4 
//  and Ask < EW3 - NoisePips * Point
  then 
  {
  ORDERANGLE = 22;
      }  
  if EW3ORDERMARK = 11 
//  and Ask < EW3 - Slippage * Point
//     and Open >= EW3
//  and Ask < EW3 - NoisePips * Point
  then 
  {
  ORDERANGLE = 23;    
      }  

  if EW3ORDERMARK = 12
//     and Open >= EW3
//  and Bid > EW3 + NoisePips * Point
  then 
  {
  ORDERANGLE = 22;  
      }  
      
  if EW3ORDERMARK = 13
//     and Open >= EW3
//  and Ask < EW3 - NoisePips * Point
  then 
  {
  ORDERANGLE = 21;  
      }  

  if EW3ORDERMARK = 14 
//  and Ask < EW3 - NoisePips * Point
  then 
  {
  ORDERANGLE = 3;    
      }  
  //EW3ORDERMARK=0; 
   }  

MaxPriceBar = Highest (MODE_CLOSE,MaxBars+1, MaxBars);
MinPriceBar = Lowest (MODE_CLOSE, MaxBars+1, MaxBars);
MaxPrice = Close[MaxPriceBar];
MinPrice = Close[MinPriceBar];

if EW2MARK = 1 and EW3MARK = 0 then
{
If WaveAngle = 1 
and Bid > EW2 + NoisePips * Point
and Bid > SupportLevel1 + NoisePips * Point
and ((EW2 - SupportLevel1 > 0 and (EW2 - SupportLevel1) / 2 < NoisePips * 2 / 2) or (SupportLevel1 - EW2 > 0 and (SupportLevel1 - EW2) / 2 < NoisePips * 2 / 2))
and EW1 - Bid > MinTakeProfit * Point + NoisePips * Point + Slippage
then
{
 ENTRYPRICE=SupportLevel1;
 ORDERMARK=1;
 SetArrow(time,Low,196,Violet);
 Print(TimeToStr(time),": ",Symbol," Elliot Wave 2 collision with Support Level 1 detected. Last EW2:",EW2," Last EW2 Time:",TimeToStr(EW2MARKTIME)," Recommended action: BUYLIMIT at ", ENTRYPRICE, " with T/P at ",EW1 - NoisePips * Point);
 Alert(TimeToStr(time),": ",Symbol," Elliot Wave 2 collision with Support Level 1 detected. Last EW2:",EW2," Last EW2 Time:",TimeToStr(EW2MARKTIME)," Recommended action: BUYLIMIT at ", ENTRYPRICE, " with T/P at ",EW1 - NoisePips * Point);
 Print(TimeToStr(time[0]),Symbol," : Elliot Wave 2 collision - Pivot:",Pivot," Resistance Level I:",ResistanceLevel1," Support Level I:",SupportLevel1," Resistance Level II:",ResistanceLevel2," Support Level II:",SupportLevel2);
}

If WaveAngle = 2 
and Ask < EW2 - NoisePips * Point
and Ask < SupportLevel1 - NoisePips * Point
and ((EW2 - SupportLevel1 > 0 and (EW2 - SupportLevel1) / 2 < NoisePips * 2 / 2) or (SupportLevel1 - EW2 > 0 and (SupportLevel1 - EW2) / 2 < NoisePips * 2 / 2))
and Ask - EW1 > MinTakeProfit * Point + NoisePips * Point + Slippage
then
{
 ENTRYPRICE=SupportLevel1;
 ORDERMARK=2;
 SetArrow(time,High,198,Violet);
 Print(TimeToStr(time),": ",Symbol," Elliot Wave 2 collision with Resistance Level 1 detected. Last EW2:",EW2," Last EW2 Time:",TimeToStr(EW2MARKTIME)," Recommended action: BUYLIMIT at ", ENTRYPRICE, " with T/P at ",EW1 - NoisePips * Point);
 Alert(TimeToStr(time),": ",Symbol," Elliot Wave 2 collision with Resistance Level 1 detected. Last EW2:",EW2," Last EW2 Time:",TimeToStr(EW2MARKTIME)," Recommended action: BUYLIMIT at ", ENTRYPRICE, " with T/P at ",EW1 - NoisePips * Point);
 Print(TimeToStr(time[0]),Symbol," : Elliot Wave 2 collision - Pivot:",Pivot," Resistance Level I:",ResistanceLevel1," Support Level I:",SupportLevel1," Resistance Level II:",ResistanceLevel2," Support Level II:",SupportLevel2);
}
}
}


/************************************ Aggressive Anti Stop Loss - revert to Take Profit ********************************/


If (CloseBadOrder = 2 and OrderRecovery=0) 
   and AntiStopLoss = 1
   and (CurTime-LastBadTime) > 300
   and Open <=MinPrice
   then
   // Compensating BUY order for last bad trade
 {
 LastOp = 3;
 BuyOp = 1;
 SellOp = 0;
  CloseBadOrder = 0; 
  OrderRecovery = 1;
 SetArrow(time,Bid,233,Yellow);
  exit;
 }


If (CloseBadOrder = 1 and OrderRecovery=0) 
   and (CurTime-LastBadTime) > 300
   // Compensating SELL order for last bad trade
   and Open <=MinPrice
   then
 {
 LastOp = 4;
 BuyOp = 0;
 SellOp = 1;
  CloseBadOrder = 0; 
  OrderRecovery = 1;
 SetArrow(time,Bid,234,Yellow);
  exit;
 }


/*********** Open Orders handling: Trailingstops, Delayed Orders Expire, Aggressive Anti Stop Loss logics ***************/

if OrderRecovery = 0 then TradesCount = 0;

if OrderRecovery = 0
and IsTradeAllowed then
for counter = 1 to TotalTrades
{
if (OrderValue(counter,VAL_SYMBOL) = Symbol)
then  // we have pending current currency orders, 
{
TradesCount = TradesCount + 1 ; // calculate trades for current market symbol
}

  OrderType = OrderValue(counter,VAL_TYPE);
    if  FreeMargin < 10
    and IsTesting then
// MetaTrader test do not close orders in with no money test mode
{
       Print("Out of money, I AM BROKEN:( Exiting..");
    If (OrderType = OP_SELL) then CloseOrder(OrderValue(counter,VAL_TICKET),OrderValue(counter,VAL_LOTS),PriceAsk,OrderValue(counter,VAL_SWAP),Yellow);
    If (OrderType = OP_BUY) then CloseOrder(OrderValue(counter,VAL_TICKET),OrderValue(counter,VAL_LOTS),PriceBid,OrderValue(counter,VAL_SWAP),Yellow);
          SetArrow(time,PriceAsk+BidStopPoints,77,Yellow);
   exit;    
  } 

if StopLoss = 0 then TrailingStopLoss = OrderValue(counter,VAL_OPENPRICE)
else TrailingStopLoss = OrderValue(counter,VAL_STOPLOSS);

   If (OrderType = OP_BUY) and OrderValue(counter,VAL_SYMBOL)=Symbol then
   {
// This is our buy order, lets check for prices

   if (TrailingStop) > 0 then
// We have Trailing Stop enabled, arrange our bids
      {
      // Here we check the trailing stop at open position.
      // Trailing stop ( Stop Loss) of the BUY position is being
      // kept at level 15 points below the market.
//            print("ParabolicSAR:",ParabolicSAR, " StopLossTrail:",TrailingStopLoss," MA:",MA);

      If (PriceBid - (TrailingStop + TrailingStep) * Point) > OrderValue(counter,VAL_OPENPRICE)
      // If the profit (current Bid-OpenPrice) more than TrailingStop pips
      // and the last StopLoss exceeds TrailingStep points from Trailingstop
      then
     {
         // we have won already not less than 'TrailingStop' pips!
            // move the trailing stop (Stop Loss) to the level 'TrailingStop' from the market
            StopLossTrail=TrailingStopLoss;
//            print("ParabolicSAR:",ParabolicSAR, " StopLossTrail:",StopLossTrail," MA:",MA);
            
            if Open - ((TrailingStep + TrailingStop) * Point) > OrderValue(counter,VAL_OPENPRICE)
               and StopLossTrail < OrderValue(counter,VAL_OPENPRICE)
               and Open + (TrailingStop * Point) >= OrderValue(counter,VAL_TAKEPROFIT)
   then
// We have won already take profit-trailingstop pips! Set Stop Loss to take profit minimum
   {
            ModifyOrder(OrderValue(counter,VAL_TICKET),OrderValue(counter,VAL_OPENPRICE),
                        OrderValue(counter,VAL_OPENPRICE) + (TrailingStop * Point),OrderValue(counter,VAL_TAKEPROFIT),Blue);
          SetArrow(time,PriceBid,105,Blue);
          exit;
                }        
else
            if ParabolicSAR -
사유: