Stock Portfolio Organizer

The ultimate porfolio management solution.

Shares, Margin, CFD's, Futures and Forex
EOD and Realtime
Dividends and Trust Distributions
And Much More ....
For Portfolio Manager Click Here

WiseTrader Toolbox

#1 Selling Amibroker Plugin featuring:

Advanced Adaptive Indicators
Advanced Pattern Exploration
Neural Networks
And Much More ....
Find Out More Here

Trend Lines for Amibroker (AFL)

Copy & Paste Friendly
_SECTION_BEGIN("Money-Line");

//-- Am I Smart-- ???
//-- Simulate MT4 Platform

MA_Mode    = ParamList("Method:", "Simple,Exponential,Smooth,Linear Weighted",2);
MA_Price   = ParamList("Applied To:", "Close,Open,High,Low,Median Price,Typical Price,Weighted Price");
MA_Period  = Param("Period:", 88, 1, 9999 );
MA_Shift   = Param("Shift", 0, -10, 10 );

cColor    = ParamColor("Color", colorYellow);
iStyle    = ParamStyle("Style", styleNoLabel, maskAll);
iWidth    = Param("Width", 3, 1,100);
ZOrder    = Param("ZOrder",1, -10, 10);

switch (MA_Price)
{
   case "Open"   : p = Open;        break;
   case "High"   : p = High;        break;
   case "Low"   : p = Low;         break;
   case "Median Price"  : p = (H+L)/2;     break;
   case "Typical Price"  : p = (H+L+C)/3;   break;
   case "Weigthed Price"  : p = (H+L+C+C)/4; break;
   default:     p = Close;       break;
}


switch (MA_Mode)
{
   case "Exponential":   iMA = EMA( P, MA_Period );  break;
   case "Linear Weighted":  iMA = WMA( P, MA_Period );   break;
   case "Smooth":  iMA = Wilders( P, MA_Period ); break;
   default:  iMA = MA( P, MA_Period );   break;
}

ShortName = _DEFAULT_NAME();
if (MA_Shift !=0)
   ShortName = ShortName + "x"+MA_Shift; 

Plot( iMA, ShortName, cColor, iStyle, Null, Null, MA_Shift, ZOrder , iWidth );
_SECTION_END();




_SECTION_BEGIN("Support / Ressistent");

sr=ParamToggle("Plot Supp/Res lines","No|Yes" ,1);
Per=Param("Sensitivity",1,0.5,5,0.5);
g=Param("No.of Lines",3,1,5,1);
x=Cum(1);
Pk1=PeakBars(H,per,1)== 0;
Tk1=TroughBars(L,per,1)== 0;

px1=LastValue(ValueWhen(pk1,x,1));
px2=LastValue(ValueWhen(Pk1,x,2));
px3=LastValue(ValueWhen(Pk1,x,3));
px4=LastValue(ValueWhen(pk1,x,4));
px5=LastValue(ValueWhen(Pk1,x,5));

tx1=LastValue(ValueWhen(Tk1,x,1));
tx2=LastValue(ValueWhen(Tk1,x,2));
tx3=LastValue(ValueWhen(Tk1,x,3));
tx4=LastValue(ValueWhen(Tk1,x,4));
tx5=LastValue(ValueWhen(Tk1,x,5));

XT1 =LastValue(ValueWhen(pk1,H,1));XT1c =LastValue(ValueWhen(pk1,Max(C,O),1));
XT2 =LastValue(ValueWhen(Pk1,H,2));XT2c =LastValue(ValueWhen(pk1,Max(C,O),2));
XT3 =LastValue(ValueWhen(Pk1,H,3));XT3c =LastValue(ValueWhen(pk1,Max(C,O),3));
XT4 =LastValue(ValueWhen(pk1,H,4));XT4c =LastValue(ValueWhen(pk1,Max(C,O),4));
XT5 =LastValue(ValueWhen(Pk1,H,5));XT5c =LastValue(ValueWhen(pk1,Max(C,O),5));

YT1 =LastValue(ValueWhen(tk1,L,1));YT1c =LastValue(ValueWhen(tk1,Min(O,C),1));
YT2 =LastValue(ValueWhen(tk1,L,2));YT2c =LastValue(ValueWhen(tk1,Min(O,C),2));
YT3 =LastValue(ValueWhen(tk1,L,3));YT3c =LastValue(ValueWhen(tk1,Min(O,C),3));
YT4 =LastValue(ValueWhen(tk1,L,4));YT4c =LastValue(ValueWhen(tk1,Min(O,C),4));
YT5 =LastValue(ValueWhen(tk1,L,5));YT5c =LastValue(ValueWhen(tk1,Min(O,C),5));

pk1=IIf(x>px1 AND g>=1 AND sr,XT1,Null);pk1c=IIf(x>px1 AND g>=1 AND sr,XT1c,Null);
Col1=IIf( LastValue(C)>pk1, ColorRGB(46,139,87), ColorRGB(180,20,20) );
Plot(pk1,"",31,1);PlotOHLC(0,pk1,pk1c,0,"",Col1,styleCloud|styleNoLabel,Null, Null, Null, -1);
pk2=IIf(x>px2 AND g>=2 AND sr,XT2,Null);pk2c=IIf(x>px2 AND g>=2 AND sr,XT2c,Null);
Col2=IIf( LastValue(C)>pk2, ColorRGB(47,79,79), ColorRGB(180,40,40) );
Plot(pk2,"",31,1);PlotOHLC(0,pk2,pk2c,0,"",Col2,styleCloud|styleNoLabel,Null, Null, Null, -2);
pk3=IIf(x>px3 AND g>=3 AND sr,XT3,Null);pk3c=IIf(x>px3 AND g>=3 AND sr,XT3c,Null);
Col3=IIf( LastValue(C)>pk3, ColorRGB(0,100,0),ColorRGB(180,60,60));
Plot(pk3,"",31, 1);PlotOHLC(0,pk3,pk3c,0,"",Col3,styleCloud|styleNoLabel,Null, Null, Null, -3);
pk4=IIf(x>px4 AND g>=4 AND sr,XT4,Null);pk4c=IIf(x>px4 AND g>=4 AND sr,XT4c,Null);
Col4=IIf( LastValue(C)>pk4, ColorRGB(107,142,35), ColorRGB(180,80,80));
Plot(pk4,"",31,1);PlotOHLC(0,pk4,pk4c,0,"",Col4,styleCloud|styleNoLabel,Null, Null, Null, -4);
pk5=IIf(x>px5 AND g>=5 AND sr,XT5,Null);pk5c=IIf(x>px5 AND g>=5 AND sr,XT5c,Null);
Col5=IIf( LastValue(C)>pk5, ColorRGB(85,107,47), ColorRGB(180,100,100));
Plot(pk5,"",31,1);PlotOHLC(0,pk5,pk5c,0,"",Col5,styleCloud|styleNoLabel,Null, Null, Null, -5);
tl1=IIf(x>tx1 AND g>=1 AND sr,YT1,Null);tl1c=IIf(x>tx1 AND g>=1 AND sr,YT1c,Null);
Col1=IIf( LastValue(C)>tl1, ColorRGB(46,139,87), ColorRGB(180,20,20)  );
Plot(tl1,"",1,1);PlotOHLC(0,tl1,tl1c,0,"",Col1,styleCloud|styleNoLabel,Null, Null, Null, -1);
tl2=IIf(x>tx2 AND g>=2 AND sr,YT2,Null);tl2c=IIf(x>tx2 AND g>=2 AND sr,YT2c,Null);
Col2=IIf( LastValue(C)>YT2, ColorRGB(47,79,79), ColorRGB(180,40,40));
Plot(tl2,"",1,1);PlotOHLC(0,tl2,tl2c,0,"",Col2,styleCloud|styleNoLabel,Null, Null, Null, -2);
tl3=IIf(x>tx3 AND g>=3 AND sr,YT3,Null);tl3c=IIf(x>tx3 AND g>=3 AND sr,YT3c,Null);
Col3=IIf( LastValue(C)>YT3, ColorRGB(0,100,0), ColorRGB(180,60,60) );
Plot(tl3,"",1,1);PlotOHLC(0,tl3,tl3c,0,"",Col3,styleCloud|styleNoLabel,Null, Null, Null, -3);
tl4=IIf(x>tx4 AND g>=4 AND sr,YT4,Null);tl4c=IIf(x>tx4 AND g>=4 AND sr,YT4c,Null);
Col4=IIf( LastValue(C)>YT4, ColorRGB(107,142,35), ColorRGB(180,80,80) );
Plot(tl4,"",1,1);PlotOHLC(0,tl4,tl4c,0,"",Col4,styleCloud|styleNoLabel,Null, Null, Null, -4);
tl5=IIf(x>tx5 AND g>=5 AND sr,YT5,Null);tl5c=IIf(x>tx5 AND g>=5 AND sr,YT5c,Null);
Col5=IIf( LastValue(C)>YT5, ColorRGB(85,107,47), ColorRGB(180,100,100));
Plot(tl5,"",1,1);PlotOHLC(0,tl5,tl5c,0,"",Col5,styleCloud|styleNoLabel,Null, Null, Null, -5);

GfxSetOverlayMode(1);
GfxSetTextColor(10); 
GfxSelectFont("Old English Text MT", 12, 300, False, False, 0); 



_SECTION_END();



_SECTION_BEGIN("Trend lines");

SetChartOptions(0, chartShowArrows | chartShowDates);
SetChartBkColor(ParamColor("Outer Panel", colorBlack));
SetChartBkGradientFill(ParamColor("Upper Chart", colorDarkGrey), ParamColor("Lower Chart", colorDarkGrey));
GraphXSpace = Param("GraphXSpace", 10, 0, 100, 1);

colorHighliter = IIf(C >= O, ColorRGB(0, 128, 0), ColorRGB(128, 0, 0));

//Demand Point
colorDemandPoint = ParamColor("Demand Line", ColorRGB(0, 128, 255));
DemandPoint = (Ref(L, -1) < Ref(L, -2)) & (L < Ref(L, -1)) & (L < Ref(L, 1)) & (Ref(L, 1) < Ref(L, 2));

//Supply Point
colorSupplyPoint = ParamColor("Supply Line", ColorRGB(255, 128, 0));
SupplyPoint = (Ref(H, -1) > Ref(H, -2)) & (H > Ref(H, -1)) & (H > Ref(H, 1)) & (Ref(H, 1) > Ref(H, 2));

CountTrendBars = 0;
CurrentBar = BarCount - 1;
dx0 = dx1 = dy0 = dy1 = 0;
sx0 = sx1 = sy0 = sy1 = 0;
for (i = 0; i < BarCount; i++) {
	CurrentBar = (BarCount - 1) - i;
	if (DemandPoint[CurrentBar]) {
		if (dx1 == 0 & dy1 == 0) {
			dx1 = CurrentBar;
			dy1 = L[CurrentBar];
		} else {
			dx0 = CurrentBar;
			dy0 = L[CurrentBar];
		}
		if (dx0 != 0 & dx1 != 0 & dy0 != 0 & dy1 != 0) {
			if (dy0 < dy1) {
				a = (-dy0 + dy1) / (-dx0 + dx1);
				b = dy0 - dx0 * a;
				for (j = dx1; j < BarCount; j++) {
					if (j != dx1) {
						y2 = a * j + b;
						if (C[j] < y2) {
							dy1 = y2;
							dx1 = j;
							colorHighliter[j] = ColorRGB(128, 0, 128);
							CountTrendBars[j] = dx1 - dx0 - 1;
							break;
						}
					}
				}
				if (dy1 != y2) {
					dy1 = y2;
					dx1 = BarCount - 1;
				}
				Plot(LineArray(dx0, dy0, dx1, dy1, 0), "", colorDemandPoint, styleLine, Null, Null, 0, 0, 2);
			}
			dx1 = dx0;
			dy1 = dy0;
			dx0 = dy0 = 0;
		}	
	}
	if (SupplyPoint[CurrentBar]) {
		if (sx1 == 0 & sy1 == 0) {
			sx1 = CurrentBar;
			sy1 = H[CurrentBar];
		} else {
			sx0 = CurrentBar;
			sy0 = H[CurrentBar];
		}
		if (sx0 != 0 & sx1 != 0 & sy0 != 0 & sy1 != 0) {
			if (sy0 > sy1) {
				a = (-sy0 + sy1) / (-sx0 + sx1);
				b = sy0 - sx0 * a;
				for (j = sx1; j < BarCount; j++) {
					if (j != sx1) {
						y2 = a * j + b;
						if (C[j] > y2) {
							sy1 = y2;
							sx1 = j;
							colorHighliter[j] = ColorRGB(128, 128, 0);
							CountTrendBars[j] = sx1 - sx0 - 1;
							break;
						}
					}
				}
				if (sy1 != y2) {
					sy1 = y2;
					sx1 = BarCount - 1;
				}
				Plot(LineArray(sx0, sy0, sx1, sy1, 0), "", colorSupplyPoint, styleLine, Null, Null, 0, 0, 2);
			}
			sx1 = sx0;
			sy1 = sy0;
			sx0 = sy0 = 0;
		}	
	}	
}

//Stop Loss & Targets
for (i = 0; i < BarCount; i++) {
	CurrentBar = (BarCount - 1) - i;
	if (colorHighliter[CurrentBar] == ColorRGB(128, 0, 128)) {
		StopLoss = 0;
		for (j = CurrentBar - CountTrendBars[CurrentBar]; j <= CurrentBar; j++) {
			StopLoss = Max(H[j], StopLoss);
		}
		if (CurrentBar - (BarCount - 1) != 0) {
			t1 = C[CurrentBar] - (StopLoss - C[CurrentBar]);
			t2 = C[CurrentBar] - ((StopLoss - C[CurrentBar]) * 1.272);
			t3 = C[CurrentBar] - ((StopLoss - C[CurrentBar]) * 1.618);
			Plot(LineArray(CurrentBar, StopLoss + 0.01, BarCount - 1, StopLoss + 0.01, 0), "", ColorRGB(255, 0, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, C[CurrentBar], BarCount - 1, C[CurrentBar], 0), "", ColorRGB(255, 255, 0), styleDots, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, t1, BarCount - 1, t1, 0), "", ColorRGB(0, 255, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, t2, BarCount - 1, t2, 0), "", ColorRGB(0, 255, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, t3, BarCount - 1, t3, 0), "", ColorRGB(0, 255, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			PlotText("Stop Loss\n@" + WriteVal(StopLoss + 0.01, 1.2), BarCount, StopLoss + 0.01, ColorRGB(255, 255, 255));
			PlotText("T1 @" + WriteVal(t1, 1.2), BarCount, t1, ColorRGB(255, 255, 255));
			PlotText("T2 @" + WriteVal(t2, 1.2), BarCount, t2, ColorRGB(255, 255, 255));
			PlotText("T3 @" + WriteVal(t3, 1.2), BarCount, t3, ColorRGB(255, 255, 255));
		}
		break;
	}
	if (colorHighliter[CurrentBar] == ColorRGB(128, 128, 0)) {
		StopLoss = 9999;
		for (j = CurrentBar - CountTrendBars[CurrentBar]; j <= CurrentBar; j++) {
			StopLoss = Min(L[j], StopLoss);
		}
		if (CurrentBar - (BarCount - 1) != 0) {
			t1 = C[CurrentBar] + (C[CurrentBar] - StopLoss);
			t2 = C[CurrentBar] + ((C[CurrentBar] - StopLoss) * 1.272);
			t3 = C[CurrentBar] + ((C[CurrentBar] - StopLoss) * 1.618);
			Plot(LineArray(CurrentBar, StopLoss - 0.01, BarCount - 1, StopLoss - 0.01, 0), "", ColorRGB(255, 0, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, C[CurrentBar], BarCount - 1, C[CurrentBar], 0), "", ColorRGB(255, 255, 0), styleDots, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, t1, BarCount - 1, t1, 0), "", ColorRGB(0, 255, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, t2, BarCount - 1, t2, 0), "", ColorRGB(0, 255, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			Plot(LineArray(CurrentBar, t3, BarCount - 1, t3, 0), "", ColorRGB(0, 255, 0), styleDots | styleNoLabel, Null, Null, 0, 0, 1);
			PlotText("Stop Loss\n@" + WriteVal(StopLoss - 0.01, 1.2), BarCount, StopLoss - 0.01, ColorRGB(255, 255, 255));
			PlotText("T1 @" + WriteVal(t1, 1.2), BarCount, t1, ColorRGB(255, 255, 255));
			PlotText("T2 @" + WriteVal(t2, 1.2), BarCount, t2, ColorRGB(255, 255, 255));
			PlotText("T3 @" + WriteVal(t3, 1.2), BarCount, t3, ColorRGB(255, 255, 255));
		}		
		break;
	}
}

//Price
SetBarFillColor(colorHighliter);
Plot(C, "Close", IIf(colorHighliter == ColorRGB(128, 0, 128), ColorRGB(255, 0, 255), IIf(colorHighliter == ColorRGB(128, 128, 0), ColorRGB(255, 255, 0), IIf(C > O, ColorRGB(0, 255, 0), IIf(C < O, ColorRGB(255, 0, 0), ColorRGB(255, 255, 255))))), styleCandle, Null, Null, 0, 0, 1);

//Volume
/*colorVolume = ParamColor("Volume Area", ColorRGB(0, 0, 0));
Plot(Volume, "", colorVolume, styleArea | styleOwnScale | styleNoLabel, Null, Null, 0, 0, 1);*/

Title = Name() + " - {{INTERVAL}} - {{DATE}} - Open = " + NumToStr(O, 1.2) + ", High = " + NumToStr(H, 1.2) + ", Low = " + NumToStr(L, 1.2) + ", Close = " + NumToStr(C, 1.2) + " (" + WriteVal(ROC(C, 1), 1.2) + "%)"; /*, Volume = " + WriteVal(Volume, 1.2);*/
_SECTION_END();



_SECTION_BEGIN("Manual Tester");
// Manual Tester.afl
// Ручной тестер для AmiBroker

if(TickSize == 0)
{
    PopupWindow("\nУкажите в свойствах символа (Symbol -> Information) параметр TickSize!", "Error");
}
else
{
    // параметры
    StartX = Param("Buttons X", 30, 0, 1000, 5);
    StartY = Param("Buttons Y", 20, 0, 1000, 5);
    Spread = Param("Spread (pips)", 0, 0, 1000) * TickSize;
    ScanMode = ParamList("Scan Mode", "Test|Clear all signals|Save to file|Load from file", 0);
    fileName = ParamStr("File path", "E://Программы/AmiBroker/Tester/Trades.txt");

    // инициализация
    BarDateTime = DateTime();
    Buy = Sell = Short = Cover = 0;
    BuyPrice = SellPrice = ShortPrice = CoverPrice = C;

    // режим выполнения кода
    formulaAction = Status("ActionEx");

    // -------------- РЕЖИМ ИНДИКАТОРА ---------------

    if(formulaAction == actionIndicator)
    {
        // парамеры графика
        RequestTimedRefresh(1);
        GfxSetOverlayMode(0); 
        GfxSetBkMode(1);

        // размер кнопок и расстояние между ними
        CellHeight = 24; 
        CellWidth = 70;
        CellXSpace = 10;

        // цвета кнопок
        BorderColor = colorBlack;
        InactiveButtonColor = colorCustom6;
        ActiveButtonColor = colorRed;

        // номер активной кнопки
        ActiveButton = StaticVarGet("ActiveButton");

        // парамеры рисования кнопок
        GfxSelectPen(BorderColor, 2);
        GfxSelectFont( "Tahoma", 11 , 700);

        // отрисовка кнопок
        for(btn = 1; btn <= 6; btn++)
        {
            if(ActiveButton == btn)
            {
                GfxSelectSolidBrush(ActiveButtonColor);
                GfxSetTextColor(colorWhite);
            }
            else
            {
                GfxSelectSolidBrush(InactiveButtonColor);
                GfxSetTextColor(ColorRGB(40,40,40));
            }

            CellX = StartX + (btn - 1) * (CellWidth + CellXSpace);
            GfxRectangle(CellX, StartY, CellX + CellWidth, StartY + CellHeight);

            switch(btn)
            {
            case 1:
                BtnText = "Buy";
                break;
            case 2:
                BtnText = "Sell";
                break;
            case 3:
                BtnText = "Short";
                break;
            case 4:
                BtnText = "Cover";
                break;
            case 5:
                BtnText = "Clear";
                break;
            case 6:
                BtnText = "Clear All";
                break;
            }

            GfxDrawText(BtnText, CellX, StartY, CellX + CellWidth, StartY + CellHeight, 32+1+4);
        }

        // обработка нажатия левой кнопки
        if(GetCursorMouseButtons() & 8)
        {
            // координаты курсора в пикселах 
            px = GetCursorXPosition(1); 
            py = GetCursorYPosition(1);

            buttonPressed = False;

            if(py >= StartY AND py <= StartY + CellHeight)
            {
                for(btn = 1; btn <= 6; btn++)
                {
                    CellX = StartX + (btn - 1) * (CellWidth + CellXSpace);
                    if(px >= CellX AND px <= CellX + CellWidth)
                    {
                        // активация или деактивация кнопки
                        if(ActiveButton == btn)
                            StaticVarSet("ActiveButton", 0);
                        else
                            StaticVarSet("ActiveButton", btn);

                        buttonPressed = True;

                        break;
                    }
                }
            }

            // нажата кнопка "Clear All"
            if(buttonPressed == True AND StaticVarGet("ActiveButton") == 6)
            {
                for(i = 0; i < BarCount; i++)
                {
                    StaticVarRemove(Name() + "Buy"   + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "Sell"  + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "Short" + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "Cover" + DateTimeToStr(BarDateTime[i]));

                    StaticVarRemove(Name() + "BuyPrice"   + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "SellPrice"  + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "ShortPrice" + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "CoverPrice" + DateTimeToStr(BarDateTime[i]));
                }

                StaticVarSet("ActiveButton", 0);
            } 

            // запись сделки в статическую переменную
            if(buttonPressed == False)
            {
                // координаты курсора цена/дата 
                x = GetCursorXPosition(0); 
                y = GetCursorYPosition(0);
                y = round(y / TickSize) * TickSize;    // округление до TickSize

                // Buy
                if(ActiveButton == 1)
                {
                    VarBuy = Name() + "Buy" + DateTimeToStr(x);
                    VarBuyPrice = Name() + "BuyPrice" + DateTimeToStr(x);

                    StaticVarSet(VarBuy, 1);
                    StaticVarSet(VarBuyPrice, y);
                }

                // Sell
                if(ActiveButton == 2)
                {
                    VarSell = Name() + "Sell" + DateTimeToStr(x);
                    VarSellPrice   = Name() + "SellPrice" + DateTimeToStr(x);

                    StaticVarSet(VarSell, 1);
                    StaticVarSet(VarSellPrice, y);
                }

                // Short
                if(ActiveButton == 3)
                {
                    VarShort = Name() + "Short" + DateTimeToStr(x);
                    VarShortPrice = Name() + "ShortPrice" + DateTimeToStr(x);

                    StaticVarSet(VarShort, 1);
                    StaticVarSet(VarShortPrice, y);
                }

                // Cover
                if(ActiveButton == 4)
                {
                    VarCover   = Name() + "Cover" + DateTimeToStr(x);
                    VarCoverPrice = Name() + "CoverPrice" + DateTimeToStr(x);

                    StaticVarSet(VarCover, 1);
                    StaticVarSet(VarCoverPrice, y);
                }

                // Clear
                if(ActiveButton == 5)
                {
                    VarBuy = Name() + "Buy" + DateTimeToStr(x);
                    VarBuyPrice = Name() + "BuyPrice" + DateTimeToStr(x);

                    VarSell = Name() + "Sell" + DateTimeToStr(x);
                    VarSellPrice = Name() + "SellPrice" + DateTimeToStr(x);

                    VarShort = Name() + "Short" + DateTimeToStr(x);
                    VarShortPrice = Name() + "ShortPrice" + DateTimeToStr(x);

                    VarCover = Name() + "Cover" + DateTimeToStr(x);
                    VarCoverPrice = Name() + "CoverPrice" + DateTimeToStr(x);

                    StaticVarRemove(VarBuy);
                    StaticVarRemove(VarSell);
                    StaticVarRemove(VarShort);
                    StaticVarRemove(VarCover);

                    StaticVarRemove(VarBuyPrice);
                    StaticVarRemove(VarSellPrice);
                    StaticVarRemove(VarShortPrice);
                    StaticVarRemove(VarCoverPrice);        
                }

                StaticVarSet("ActiveButton", 0);    // деактивация кнопки после выполнения действия
            }
        }

        // копирование сделок из статических переменных в торговые массивы
        for(i = 0; i < BarCount; i++)
        {
            BuySig   = StaticVarGet(Name() + "Buy"   + DateTimeToStr(BarDateTime[i]));
            SellSig  = StaticVarGet(Name() + "Sell"  + DateTimeToStr(BarDateTime[i]));
            ShortSig = StaticVarGet(Name() + "Short" + DateTimeToStr(BarDateTime[i]));
            CoverSig = StaticVarGet(Name() + "Cover" + DateTimeToStr(BarDateTime[i]));

            if(BuySig)
            {
                Buy[i] = 1;
                BuyPrice[i] = StaticVarGet(Name() + "BuyPrice" + DateTimeToStr(BarDateTime[i])) + spread;
            }

            if(SellSig)
            {
                Sell[i] = 1;
                SellPrice[i]  = StaticVarGet(Name() + "SellPrice"  + DateTimeToStr(BarDateTime[i]));
            }

            if(ShortSig)
            {
                Short[i] = 1;
                ShortPrice[i] = StaticVarGet(Name() + "ShortPrice" + DateTimeToStr(BarDateTime[i]));
            }

            if(CoverSig)
            {
                Cover[i] = 1;
                CoverPrice[i] = StaticVarGet(Name() + "CoverPrice" + DateTimeToStr(BarDateTime[i])) + spread;
            }
        }

        // ------ Отрисовка стрелок
        PlotShapes(Buy * shapeUpArrow, colorLime, 0, BuyPrice, -8);
        PlotShapes(Sell * shapeDownArrow, colorCustom12, 0, SellPrice, -8);
        PlotShapes(Short * shapeHollowDownArrow, colorCustom12, 0, ShortPrice, -8);
        PlotShapes(Cover * shapeHollowUpArrow, colorLime, 0, CoverPrice, -8);
    }

    // -------------- РЕЖИМ ТЕСТИРОВАНИЯ ИЛИ СКАНИРОВАНИЯ ---------------

    if(formulaAction == actionScan OR formulaAction == actionBacktest)
    {
        // тестирование
        if(ScanMode == "Test")
        {
            // настройки тестера
            SetOption("InitialEquity", 10000);
            SetOption("AllowPositionShrinking", False);
            SetOption("ReverseSignalForcesExit", True);
            SetOption("AllowSameBarExit", True);
            SetOption("ActivateStopsImmediately", True);
            SetOption("MaxOpenPositions", 100);
            SetOption("PriceBoundChecking", False);
            SetOption("FuturesMode", True);
            SetOption("CommissionMode", 2);
            SetOption("CommissionAmount", 0);
            SetTradeDelays(0, 0, 0, 0);

            PositionSize = 100;
            MarginDeposit = 100;
            RoundLotSize = 1;
            PointValue = 1/TickSize;

            // чтение сделок из статических переменных
            for(i = 0; i < BarCount; i++)
            {
                BuySig   = StaticVarGet(Name() + "Buy"   + DateTimeToStr(BarDateTime[i]));
                SellSig  = StaticVarGet(Name() + "Sell"  + DateTimeToStr(BarDateTime[i]));
                ShortSig = StaticVarGet(Name() + "Short" + DateTimeToStr(BarDateTime[i]));
                CoverSig = StaticVarGet(Name() + "Cover" + DateTimeToStr(BarDateTime[i]));

                if(BuySig)
                {
                    Buy[i] = 1;
                    BuyPrice[i] = StaticVarGet(Name() + "BuyPrice" + DateTimeToStr(BarDateTime[i])) + spread;
                }

                if(SellSig)
                {
                    Sell[i] = 1;
                    SellPrice[i]  = StaticVarGet(Name() + "SellPrice"  + DateTimeToStr(BarDateTime[i]));
                }

                if(ShortSig)
                {
                    Short[i] = 1;
                    ShortPrice[i] = StaticVarGet(Name() + "ShortPrice" + DateTimeToStr(BarDateTime[i]));
                }

                if(CoverSig)
                {
                    Cover[i] = 1;
                    CoverPrice[i] = StaticVarGet(Name() + "CoverPrice" + DateTimeToStr(BarDateTime[i])) + spread;
                }
            }
        }

        // очистка статических переменных
        if(ScanMode == "Clear all signals")
        {
            for(i = 0; i < BarCount; i++)
            {
                StaticVarRemove(Name() + "Buy"   + DateTimeToStr(BarDateTime[i]));
                StaticVarRemove(Name() + "Sell"  + DateTimeToStr(BarDateTime[i]));
                StaticVarRemove(Name() + "Short" + DateTimeToStr(BarDateTime[i]));
                StaticVarRemove(Name() + "Cover" + DateTimeToStr(BarDateTime[i]));

                StaticVarRemove(Name() + "BuyPrice"   + DateTimeToStr(BarDateTime[i]));
                StaticVarRemove(Name() + "SellPrice"  + DateTimeToStr(BarDateTime[i]));
                StaticVarRemove(Name() + "ShortPrice" + DateTimeToStr(BarDateTime[i]));
                StaticVarRemove(Name() + "CoverPrice" + DateTimeToStr(BarDateTime[i]));
            }

            StaticVarSet("ActiveButton", 0); 
        }

        // сохранение сделок в файл
        if(ScanMode == "Save to file")
        {
            // количество цифр после запятой
            digits = Max(log10(1/TickSize), 0);

            // открытие файла для записи
            fh = fopen(fileName, "w");
        
            if(fh)
            {
                for(i = 0; i < BarCount; i++)
                {
                    BuySig   = StaticVarGet(Name() + "Buy"   + DateTimeToStr(BarDateTime[i]));
                    SellSig  = StaticVarGet(Name() + "Sell"  + DateTimeToStr(BarDateTime[i]));
                    ShortSig = StaticVarGet(Name() + "Short" + DateTimeToStr(BarDateTime[i]));
                    CoverSig = StaticVarGet(Name() + "Cover" + DateTimeToStr(BarDateTime[i]));

                    if(BuySig)
                    {
                        Price  = StaticVarGet(Name() + "BuyPrice"  + DateTimeToStr(BarDateTime[i]));
                        fputs(Name() + "Buy," + DateTimeToStr(BarDateTime[i]) + "," + NumToStr(Price, digits/10, False) + "\n", fh);
                    }

                    if(SellSig)
                    {
                        Price  = StaticVarGet(Name() + "SellPrice"  + DateTimeToStr(BarDateTime[i]));
                        fputs(Name() + "Sell," + DateTimeToStr(BarDateTime[i]) + "," + NumToStr(Price, digits/10, False) + "\n", fh);
                    }

                    if(ShortSig)
                    {
                        Price = StaticVarGet(Name() + "ShortPrice" + DateTimeToStr(BarDateTime[i]));
                        fputs(Name() + "Short," + DateTimeToStr(BarDateTime[i]) + "," + NumToStr(Price, digits/10, False) + "\n", fh);
                    }

                    if(CoverSig)
                    {
                        Price = StaticVarGet(Name() + "CoverPrice" + DateTimeToStr(BarDateTime[i]));
                        fputs(Name() + "Cover," + DateTimeToStr(BarDateTime[i]) + "," + NumToStr(Price, digits/10, False) + "\n", fh);
                    }
                }

                fclose(fh);
            }
            else
                PopupWindow("\n\nОшибка открытия или создания файла " + fileName + "\n\nСоздайте указанный каталог", "Export Error", 60);
        }

        // загрузка сделок из файла
        if(ScanMode == "Load from file")
        {
            // открытие файла для чтения
            fh = fopen(fileName, "r");

            if(fh)
            {
                // очистка графика от сигналов
                for(i = 0; i < BarCount; i++)
                {
                    StaticVarRemove(Name() + "Buy"   + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "Sell"  + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "Short" + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "Cover" + DateTimeToStr(BarDateTime[i]));

                    StaticVarRemove(Name() + "BuyPrice"   + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "SellPrice"  + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "ShortPrice" + DateTimeToStr(BarDateTime[i]));
                    StaticVarRemove(Name() + "CoverPrice" + DateTimeToStr(BarDateTime[i]));
                }

                StaticVarSet("ActiveButton", 0);

                // чтение сигналов из файла
                while(! feof(fh))
                {
                    // чтение строки из файла
                    stringTrade = fgets(fh);
                    
                    // парсинг
                    sName = StrExtract(stringTrade, 0);
                    sSig = StrExtract(stringTrade, 1);
                    sDate = StrExtract(stringTrade, 2);
                    sPrice = StrExtract(stringTrade, 3);

                    VarSig = sName + sSig + sDate;
                    VarPrice = sName + sSig + "Price" + sDate;

                    // запись в статические переменные
                    StaticVarSet(VarSig, 1);
                    StaticVarSet(VarPrice, StrToNum(sPrice));
                }

                fclose(fh);
            }
            else
                PopupWindow("\n\nОшибка открытия файла " + fileName + "\n\nУказанный файл не существует.", "Import error", 60);
        }
    }
}
_SECTION_END();
Back