Thư viện AFL
Thư viện AFL
Mô-đun trong ngày V2.0 được đơn giản hóa với Mục tiêu, Dừng lỗ, Bảng điều khiển PNL và Điều khiển AllinOneAlert - Mã AFL Amibroker

Mô-đun trong ngày V2.0 được đơn giản hóa với Mục tiêu, Dừng lỗ, Bảng điều khiển PNL và Điều khiển AllinOneAlert - Mã AFL Amibroker

Đây là một mô-đun đơn giản giúp chuyển đổi bất kỳ chiến lược Kết thúc nến nào thành mô-đun trong ngày. Với các điều khiển Mục tiêu, Dừng lỗ, Cảnh báo và Bảng điều khiển PNL. Mã này làm giảm sự phức tạp của mã hóa mà phần lớn các nhà giao dịch trong ngày gặp phải khi xây dựng một hệ thống giao dịch đơn giản với nhiều biện pháp kiểm soát khác nhau.

Các tính năng của mô-đun

Mô-đun trong ngày với lệnh cắt lỗ và quản lý mục tiêu

Cảnh báo tất cả trong một (Cảnh báo mũi tên, Cảnh báo nhãn, Cảnh báo bằng giọng nói, Cảnh báo âm thanh, Cảnh báo qua email, Cảnh báo Telegram)

Bảng điều khiển lãi/lỗ

Kéo và thả vào bất kỳ mô-đun nghỉ ngơi trong ngày nào trong chiến lược kết thúc nến đơn giản của bạn sẽ đảm nhiệm việc này.

Kiểm soát trong ngày dựa trên thời gian với số lần vào/ra – Giới hạn

Các bước sử dụng mô-đun

  1. Tải xuống Mã AFL và lưu trữ dưới dạng Intraday.afl trong bất kỳ Thư mục Công thức Amibroker nào.

  2. Đảm bảo chiến lược của bạn có các thông số Mua, bán, bán khống, trang trải. Áp dụng hệ thống giao dịch của bạn trên biểu đồ trống và kéo và thả Intraday.afl lên trên hệ thống giao dịch của bạn

  3. nếu chiến lược của bạn không có biến ngắn và biến bao gồm, hãy sử dụng biến ngắn =0; và bìa = 0; trong mã của bạn trước khi kéo và thả

  4. Chỉ sử dụng mã trên Chiến lược đầu nến và không sử dụng mã trên hệ thống giao dịch dựa trên khó khăn

  5. Tránh gây ra bất kỳ sự chậm trễ giao dịch nào trong chiến lược của bạn vì nó đã được xử lý bên trong mô-đun

Mã AFL Amibroker – Mô-đun trong ngày

Liên quan

Mã nguồn (.afl)
//Intraday Module - Readymade Module (Drag and Drop on top of your trading strategy)
//Built in Target and Stoploss Based Exit (Touch based Exit)
//Regular Exit(Close of Candle) and Time Based Exit(Close of Candle)

//Warning : Use the Module only on top of End of candle strategy 
//Avoid giving any delay in your strategy as it is already handles inside the module

//Coded by Rajandran R - Founder - Marketcalls / Co-Founder - Algomojo
//Coded on 12th Jan 2022
//Website - www.marketcalls.in / www.algomojo.com
//Version - 2.0


_SECTION_BEGIN("Marketcalls - All in One Alerts Module");

//For 6.17 or higher version users Telegram Modern Alert mehtod will be used
//For lower version users VBscript based Telegram Alert (Legacy Method is used)
AmiVersion = 6.17;  

// Send Alerts even if Amibroker is minimized or Chart is not active
RequestTimedRefresh(1, False); 

//Initialization

ArrowAlerts = ParamToggle("Arrow Alerts","Enable|Disable",1);
LabelAlerts = ParamToggle("Label Alerts","Enable|Disable",0);
SoundAlerts = ParamToggle("Sound Alerts","Enable|Disable",0);
EmailAlerts = ParamToggle("Mail Alerts","Enable|Disable",0);
VoiceAlerts = ParamToggle("Voice Alerts","Enable|Disable",0);
PopUpAlerts = ParamToggle("PopUp Alerts","Enable|Disable",0);
TelegramAlerts = ParamToggle("Telegram Alerts","Enable|Disable",0);
TelegramAPI_ID = ParamStr("Telegram Bot API Key","1734928163:AAEiZ_64DJmk7jtosP1hkRywz1savZWUHAY");  //Get the Bot API key via BotFather in Telgram
TelgramCHAT_ID = ParamStr("Telegram Channel ID","@quantalerts2021");  //Channel ID example : @marketcalls_in
tradedelay = Param("Execution Delay",0,0,1); // 0 - Alerts with No Delay (Touch Based Strategies), 1- Alerts with 1 Bar Delay (EOD of Candle - Next Bar Open based Alerts)
AlertName = ParamStr("Alert Name","Strategy Alerts");
fontsize = Param("Font Size",10,10,40,1);


//User Defined Function -> Created using VBscript
EnableScript("VBScript"); 

<% 

Public Sub Telegram(Message_Text)


sAPI_ID = AFL.Var("TelegramAPI_ID")
sChat_ID = AFL.Var("TelgramCHAT_ID")
sMSG = Message_Text

'URL to open....
sUrl = "https://api.telegram.org/bot" & sAPI_ID & "/sendMessage"
'POST Request to send.
sRequest = "text=" & sMSG & "&chat_id=" & sChat_ID


set oHTTP = CreateObject("Microsoft.XMLHTTP")
oHTTP.open "POST", sUrl,false
oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oHTTP.setRequestHeader "Content-Length", Len(sRequest)
oHTTP.send sRequest
HTTPPost = oHTTP.responseText


'Store response 
'msgbox(objXmlHttpMain.responseText)
'response.Write (objXmlHttpMain.responseText) 

End Sub 

%> 

tg = GetScriptObject(); 



function SignalArrowPlots(iBuy,iSell,iShort,iCover)
{
/* Plot Buy and Sell Signal Arrows */

PlotShapes(IIf(iBuy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(iBuy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(iBuy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(iShort, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(iShort, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(iShort, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(iSell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(iCover * shapestar, colorRed, 0, Low, -12);

}

function SignalTextLabels(iBuy,iSell,ishort,iCover)
{


for( i = 0; i < BarCount; i++ ) 
 {  
if( iBuy[i] ) PlotTextSetFont("Long Entry","Arial", fontsize,i,L[i],colorWhite,colorGreen,-30);
if( iSell[i] ) PlotTextSetFont("Long Exit","Arial", fontsize,i,H[i],colorWhite,colorGreen,30);
if( ishort[i] ) PlotTextSetFont("Short Entry","Arial", fontsize,i,H[i],colorWhite,colorRed,50);
if( iCover[i] ) PlotTextSetFont("Short Exit","Arial", fontsize,i,L[i],colorWhite,colorRed,-50);


}

}



//Buy and Sell Order Functions

function BuyAlerts(AlertBuy,AlertCover,Message)
{

if(SoundAlerts)
{
	if(AlertBuy AND !AlertCover)
	{
		AlertIf(AlertBuy,"SOUND C:\\Windows\\Media\\Ding.wav",Message,1,flag=1+2);
	}
	
	if(!AlertBuy AND AlertCover)
	{
		AlertIf(AlertCover,"SOUND C:\\Windows\\Media\\Ding.wav",Message,4,flag=1+2);
	}
	
	if(AlertBuy AND AlertCover)
	{
		AlertIf(AlertBuy AND AlertCover,"SOUND C:\\Windows\\Media\\Ding.wav",Message,5,flag=1+2);
		
	}

}

if(EmailAlerts)
{

	if(AlertBuy AND !AlertCover)
	{
		AlertIf(AlertBuy,"EMAIL",Message,1,flag=1+2);
	}
	
	if(!AlertBuy AND AlertCover)
	{
		AlertIf(AlertCover,"EMAIL",Message,4,flag=1+2);
	}
	
	if(AlertBuy AND AlertCover)
	{
		AlertIf(AlertBuy AND AlertCover,"EMAIL",Message,5,flag=1+2);
	}



}

if(VoiceAlerts)
{
	if(AlertBuy AND !AlertCover)
	{
		Say("Buy Signal");
	}
	
	if(!AlertBuy AND AlertCover)
	{
		Say("Cover Signal");
	}
	
	if(AlertBuy AND AlertCover)
	{
		Say("Buy and Cover Signal");
	}


}

if(PopUpAlerts)
{
	if(AlertBuy AND !AlertCover)
	{
		PopupWindow("Buy Signal",Message);
	}
	
	if(!AlertBuy AND AlertCover)
	{
		PopupWindow("Cover Signal",Message);
	}
	
	if(AlertBuy AND AlertCover)
	{
		PopupWindow("Buy and Cover Signal",Message);
	}


}

if(TelegramAlerts)
{	
	if(Version() >= AmiVersion)
	{
	//call the modern Internet Function
	ih = InternetOpenURL("https://api.telegram.org/bot"+TelegramAPI_ID+"/sendMessage?chat_id="+TelgramCHAT_ID+"&text="+Message ); 
	InternetClose(ih);
	}
	else
	{
	//call the legacy method
	tg.Telegram(Message);
	}

}



}



function SellAlerts(AlertShort,AlertSell,Message)
{
if(SoundAlerts)
{
	if(AlertShort AND !AlertSell)
	{
	AlertIf(AlertShort,"SOUND C:\\Windows\\Media\\Ding.wav",Message,3,flag=1+2);
	}
	
	if(!AlertShort AND AlertSell)
	{
	AlertIf(AlertSell,"SOUND C:\\Windows\\Media\\Ding.wav",Message,2,flag=1+2);
	}
	
	if(AlertShort AND AlertSell)
	{
	AlertIf(AlertShort AND AlertSell,"SOUND C:\\Windows\\Media\\Ding.wav",Message,6,flag=1+2);
	}

}
if(EmailAlerts)
{

	if(AlertShort AND !AlertSell)
	{
		AlertIf(AlertShort,"EMAIL",Message,3,flag=1+2);
	}
	
	if(!AlertShort AND AlertSell)
	{
		AlertIf(AlertSell,"EMAIL",Message,2,flag=1+2);
	}
	
	if(AlertShort AND AlertSell)
	{
		AlertIf(AlertShort AND AlertSell,"EMAIL",Message,6,flag=1+2);
	}

}

if(VoiceAlerts)
{
	if(AlertShort AND !AlertSell)
	{
		Say("Short Signal");
	}
	
	if(!AlertShort AND AlertSell)
	{
		Say("Sell Signal");
	}
	
	if(AlertShort AND AlertSell)
	{
		Say("Short and Sell Signal");
	}

}

if(PopUpAlerts)
{
	if(AlertShort AND !AlertSell)
	{
		PopupWindow("Short Signal",Message);
	}
	
	if(!AlertShort AND AlertSell)
	{
		PopupWindow("Sell Signal",Message);
	}
	
	if(AlertShort AND AlertSell)
	{
		PopupWindow("Short and Sell Signal",Message);
	}

}

if(TelegramAlerts)
{
	if(Version()>=AmiVersion)
	{
	ih = InternetOpenURL("https://api.telegram.org/bot"+TelegramAPI_ID+"/sendMessage?chat_id="+TelgramCHAT_ID+"&text="+Message ); 
	InternetClose(ih);
	}
	else
	{
	//call the legacy method
	tg.Telegram(Message);
	}
}

} //end of function

function AllinOneAlerts(iBuy,iSell,iShort,iCover)
{


//Configure Trade Execution Delay


AlertBuy = lastvalue(Ref(iBuy,-tradedelay));
AlertSell = lastvalue(Ref(iSell,-tradedelay));
AlertShort = lastvalue(Ref(iShort,-tradedelay));
AlertCover = lastvalue(Ref(iCover,-tradedelay));

//Static Varibales for Alert Protection

static_name_ = Name()+GetChartID()+interval(2)+AlertName;

BuyMessage = 	"Buy Signal in "+Name()+" Buy Price :"+BuyPrice;
CoverMessage =  "Cover Signal in "+Name()+" Cover Price :"+CoverPrice;
BuyCoverMessage = 	"Buy and Cover Signal in "+Name()+" Stop and Reverse Buy @ :"+BuyPrice;

ShortMessage =  "Short Signal in "+Name()+" Short Price :"+ShortPrice;
SellMessage = 	"Sell Signal in "+Name()+" Sell Price :"+SellPrice;
ShortSellMessage = 	"Short and Sell Signal in "+Name()+" Stop and Reverse Short @ :"+ShortPrice;

if(ArrowAlerts)
{
SignalArrowPlots(iBuy,iSell,iShort,iCover);
}
if(LabelAlerts)
{
SignalTextLabels(iBuy,iSell,ishort,iCover);
}



//Enable Dual Alert Protection using Static Variables
         
	if (AlertBuy==True AND AlertCover == True AND StaticVarGet(static_name_+"buyCoverAlerts")==0)
    {
		// Stop and Reverse Long Entry 
		BuyAlerts(AlertBuy,AlertCover,BuyCoverMessage);
		StaticVarSet(static_name_+"buyCoverAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if ((AlertBuy != True OR AlertCover != True))
    {   
    StaticVarSet(static_name_+"buyCoverAlerts",0);
    }
            
    if (AlertBuy==True AND AlertCover != True AND StaticVarGet(static_name_+"buyAlerts")==0)
    {
		// Long Entry 
		BuyAlerts(AlertBuy,AlertCover,BuyMessage);
		StaticVarSet(static_name_+"buyAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertBuy != True)
    {   
		StaticVarSet(static_name_+"buyAlerts",0);
                
    }
    
    if (AlertSell==true AND AlertShort != True AND StaticVarGet(static_name_+"sellAlerts")==0)
    {     
		// Long Exit 
		SellAlerts(AlertShort,AlertSell,SellMessage);
		StaticVarSet(static_name_+"sellAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertSell != True )
    {   
		StaticVarSet(static_name_+"sellAlerts",0);
    }
            
    if (AlertShort==True AND AlertSell==True AND  StaticVarGet(static_name_+"ShortSellAlerts")==0)
    {
		// Stop and Reverse Short Entry
		SellAlerts(AlertShort,AlertSell,ShortSellMessage);
		StaticVarSet(static_name_+"ShortSellAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if ((AlertShort != True OR AlertSell != True))
    {   
        StaticVarSet(static_name_+"ShortSellAlerts",0);
    }
                
    if (AlertShort==True  AND  AlertSell != True AND StaticVarGet(static_name_+"ShortAlerts")==0)
    {
		// Short Entry
		SellAlerts(AlertShort,AlertSell,ShortMessage);
		StaticVarSet(static_name_+"ShortAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertShort != True )
    {   
        StaticVarSet(static_name_+"ShortAlerts",0);
    }
    if (AlertCover==true AND AlertBuy != True AND StaticVarGet(static_name_+"CoverAlerts")==0)
    {
		// Short Exit
		BuyAlerts(AlertBuy,AlertCover,CoverMessage);
		StaticVarSet(static_name_+"CoverAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertCover != True )
    {   
        StaticVarSet(static_name_+"CoverAlerts",0);
    }
       

}        
        
        
      


    
_SECTION_END();




_SECTION_BEGIN("Marketcalls Intraday - Module ");



//Remove Excessive Signals
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

//Intraday Trading Controls

LimitTrades = Param("Limit No of Trades",2,1,100,1);
TickSz = Param("Tick Size",0.05);
StartTradeTime = ParamTime("Start Time","09:30");
EndTradeTime = ParamTime("End Time","15:00");
ExitTradeTime = ParamTime("Squareoff Time","15:15");

RiskControl = ParamToggle("Enable Stop and Target","Enable|Disable",1);
mode = ParamList("Stop and Target Mode","Points|Percentage|Volatility");
stops = Param("Stoploss",50,0.05,1000,0.05);
target = Param("Targets",100,0.05,1000,0.05);

//Multipliers, iLength & iATR used for computing Volatility stops and Targets
multiplier = Param("Volatility Multiplier",1.5,0.25,20,0.25);
ilength = Param("ATR Length",10,1,100,1);
iATR = ATR(ilength);

//Signal Executes on Close of the Candle
SignalDelay = Param("Signal Delay",1,0,10,1);

newday = Day() != Ref(Day(),-1);

//Targets and Stops are Not Enabled
if(!Riskcontrol)
{



Buy = Buy AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
Sell = Sell OR TimeNum() >= ExitTradeTime;

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

Short = Short AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
Cover = Cover OR TimeNum() >= ExitTradeTime;

Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

SetTradeDelays(0,0,0,0); //No Trade Delays provided

Buy = Ref(Buy,-SignalDelay);
sell = Ref(sell,-SignalDelay);
short = Ref(Short,-SignalDelay);
cover = Ref(cover,-SignalDelay);

BuyPrice = ValueWhen(Buy,Open);
SellPrice = ValueWhen(Sell,Open);
ShortPrice = ValueWhen(Short,Open);
CoverPrice = ValueWhen(Cover,Open);


buycontinue = Flip(Buy,Sell);
shortcontinue = Flip(short,cover);


}
buystop = buytarget = shortstop = shorttarget = Null;
//Targets and Stops are Enabled
if(Riskcontrol)
{

SetTradeDelays(0,0,0,0); //No Trade Delays provided

Buy = Buy AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
iSell = Sell OR TimeNum() >= ExitTradeTime;

Buy = Ref(Buy,-SignalDelay);
iSell = Ref(iSell,-SignalDelay);



BuyPrice = ValueWhen(Buy,Open);

if(mode=="Points")
{
BuyStop = BuyPrice - stops;
BuyTarget = BuyPrice + target;

}


if(mode=="Percentage")
{
BuyStop1 = (100-stops)/100*BuyPrice; 
BuyTarget1 = (100+target)/100*BuyPrice;

//Round it of to nearest Tick Size
BuyStop = TickSz * round(Buystop1/TickSz);
BuyTarget = TickSz * round(BuyTarget1/TickSz);

}

if(mode=="Volatility")
{

BuyStop = ValueWhen(Buy,BuyPrice - iATR * Multiplier);
BuyTarget = ValueWhen(Buy,BuyPrice + iATR * Multiplier);

}

Sell = isell OR Cross(H,BuyTarget) OR Cross(Buystop,L);


Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

//Regular Exit - Open of Next Bar
//Time Based Exit - Open of Next Bar
//Target Hit - BuyTarget
//Stop Hit - Buystop


SellPrice = ValueWhen(Sell, IIf(Cross(H,BuyTarget),BuyTarget,
								IIf(Cross(Buystop,L),Buystop,Open)));
								

short = short AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
iCover = cover OR TimeNum() >= ExitTradeTime;

short = Ref(short,-SignalDelay);
iCover = Ref(iCover,-SignalDelay);

shortPrice = ValueWhen(short,Open);


if(mode=="Points")
{
ShortStop = ShortPrice + stops;
ShortTarget = ShortPrice - target;

}


if(mode=="Percentage")
{
ShortStop1 = (100+stops)/100*ShortPrice; 
ShortTarget1 = (100-target)/100*ShortPrice;

//Round it of to nearest Tick Size
ShortStop = TickSz * round(ShortStop1/TickSz);
ShortTarget = TickSz * round(ShortTarget1/TickSz);

}

if(mode=="Volatility")
{

ShortStop = ValueWhen(short,ShortPrice + iATR * Multiplier);
ShortTarget = ValueWhen(short,ShortPrice - iATR * Multiplier);

}

cover = icover OR Cross(H,Shortstop) OR Cross(ShortTarget,L);


Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);



CoverPrice = ValueWhen(Cover, IIf( Cross(ShortTarget,L),ShortTarget,
								IIf(Cross(H,Shortstop),Shortstop,Open)));




}


Buy = Buy AND Sum(Buy OR Short, BarsSince(newday) + 1) <= LimitTrades;
Short = Short AND Sum(Buy OR Short, BarsSince(newday) + 1) <= LimitTrades;

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);


buycontinue = Flip(Buy,Sell);
shortcontinue = Flip(short,cover);

AllinOneAlerts(Buy,Sell,Short,Cover);



//Plot Stops and Targets - only if the trade is continue

Plot(IIf(buycontinue OR Sell, BuyStop,Null),"BuyStops",colorRed,styleDashed | styleThick);
Plot(IIf(buycontinue OR Sell, Buytarget,Null),"BuyTarget",colorGreen,styleDashed | styleThick);

Plot(IIf(shortcontinue OR cover, ShortStop,Null),"ShortStops",colorRed,styleDashed | styleThick);
Plot(IIf(shortcontinue OR cover, Shorttarget,Null),"ShortTarget",colorGreen,styleDashed | styleThick);





//Dashboard Controls.


_SECTION_BEGIN("Trading Dashboard");

strg_name = ParamStr("Strategy Name","Simple Trading System");
fontsize = Param("Font Size",14,12,36,1);

GfxSelectFont("BOOK ANTIQUA", fontsize, 400);
GfxSetBkMode(1);  //Transparent Mode
GfxSetTextColor(colorWhite);

//build dyanmic dashboard colors based on the ongoing trades
color = IIf(buycontinue,colorGreen,IIf(shortcontinue,colorRed,colorGrey40));

GfxSelectPen(colorWhite);
GfxSelectSolidBrush(SelectedValue(color));

width = Status("pxchartwidth"); //output will be in terms of number of pixels
height = Status("pxchartheight");

//GfxRoundRect(20,height-150,320,height-30,15,15);

GfxGradientRect(20,height-150,320,height-30,SelectedValue(color),colorBlack);

sigstatus = WriteIf(buycontinue,"Buy Signal",WriteIf(shortcontinue,"Short Signal","No Trade - Relax"));
PNL =  IIf(buycontinue,Close-buyprice,IIf(shortcontinue,ShortPrice-close,Null));
GfxTextOut(strg_name,30,height-130);
GfxTextOut(sigstatus+" : "+IIf(buycontinue,BuyPrice,IIf(shortcontinue,ShortPrice,Null)),30,height-110);
GfxTextOut("Profit/Loss : "+SelectedValue(Prec(PNL,2)),30,height-90);




_SECTION_END();

Hướng dẫn: Copy đoạn mã trên, mở AmiBroker Formula Editor, dán vào và lưu lại với tên tương ứng.