Created
April 8, 2016 16:15
-
-
Save parthasen/e0250d4c02185640445ec9bdbf3d6b25 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AFL CODE FOR TRADING (VERSION: V7) | |
********** | |
_SECTION_BEGIN("TRADE"); | |
Filename = _DEFAULT_NAME(); | |
SubmitOrders = True; | |
Tracing = False; | |
MarketON=093000; TradeON = 094000; TradeOFF =153000; MarketOFF=160000; LM=155500; | |
US_ON = TimeNum() >= 093000 AND TimeNum() <=160000; | |
US_OFF = TimeNum() > 160000 ;//day's over*/ | |
US_Trade_On=TimeNum() >= 094000 AND TimeNum() <=153000; | |
MarketLM=TimeNum() >=155500 AND Now( 4 )<=160000; | |
ABName=IBName=Name();//getfndata("Alias"); | |
//IBName =Name();//getfndata("Alias"); | |
LP=GetRTData("Last"); | |
BID=GetRTData("Bid"); | |
BIDSIZE=GetRTData("BidSize"); | |
ASK=GetRTData("Ask"); | |
ASKSIZE=GetRTData("AskSize"); | |
H52=GetRTData("52WeekHigh"); | |
L52=GetRTData("52WeekLow"); | |
CGFRY=GetRTData("Change"); | |
CHP=GetRTData("High"); | |
CLP=GetRTData("Low"); | |
CLD=GetRTData("Prev"); | |
TV=GetRTData("TotalVolume"); | |
LTV=GetRTData("TradeVolume"); | |
///Strategies | |
AA=C; | |
BB=H; | |
CC=L; | |
DD = Min( BB, CC ); | |
EE = 100 * DD/AA; | |
FF = MA( EE, 10 ); | |
GG = IIf( FF >= 2.15 OR FF <= 0.40, FF, 1 ); | |
HH = BB / ( BB + CC ); | |
II = MA( HH, 10 ); | |
JJ = 100 * GG * II; | |
x_temp_est = 0; | |
x_est_last = 0; | |
P_temp = 0; | |
P_last = 0; | |
Q = 0.022; | |
R = 0.617; | |
P = (H +L)/ 2; | |
z_real = EMA(EMA(C,20),4) ; | |
x_est_last = (z_real + TSF(C,20)); | |
for (i=0;i<BarCount;i++) | |
{ | |
x_temp_est = x_est_last; | |
P_temp = P_last + Q; | |
K = P_temp * (1.0/(P_temp + R)); | |
z_measured = z_real; | |
x_est = x_temp_est + K * (z_measured - x_temp_est); | |
P = (1- K) * P_temp; | |
P_last = P; | |
x_est_last = x_est; | |
} | |
"x_est_last:" + x_est_last; | |
B1=MA(C,20)>x_est_last; | |
S1= MA(C,20)<x_est_last; | |
B2=(JJ-Ref(JJ,-1))/(C-Ref(C,-1))>0; | |
S2=(JJ-Ref(JJ,-1))/(C-Ref(C,-1))<0; | |
periods =20; | |
Percent =0.4; | |
DaysBack = 0; | |
RABars = 0; //initialize | |
TotalBars = cum(1); //how many bars in database | |
FinalBar = lastvalue(TotalBars);//number value of last bar | |
EndDay = FinalBar - DaysBack;//for other than 0 DaysBack | |
StartDay = EndDay - periods+1;//starting point for line | |
Master1 = iif(TotalBars >= StartDay and TotalBars <= EndDay,1,0);//defined period | |
RABars = iif(Master1,ref(RABars,-1)+1,0); // daily counter in defined period | |
RABarKntr = iif(Master1,sum(RABars,periods),0); //Sum of daily counts | |
/* Regression Analysis Computations */ | |
TempMeanX = iif(RABarKntr == periods,sum(RABarKntr,periods),0); // Sum of individual day counters | |
MeanX1 = hhv(TempMeanX,TotalBars)/periods; // Final number divided by number of days | |
MeanX = lastvalue(MeanX1); | |
TempMeanY = iif(RABarKntr == periods, sum(c,periods),0); | |
MeanY1 = hhv(TempMeanY,TotalBars)/periods ; // Final sum divided by number of days | |
MeanY = lastvalue(MeanY1); | |
Slope1 = iif(TotalBars == EndDay,linregslope(c,periods),0); | |
Slope2 = iif(hhv(Slope1,FinalBar)>=0,hhv(slope1,FinalBar),llv(Slope1,FinalBar)); | |
slope = lastvalue(Slope2); | |
Intercept = MeanY -Slope * MeanX; | |
/* Linear Regression Line = Intercept plus the Slope times RABarKntr */ | |
LRLine = Intercept + Slope * RABarKntr; | |
"LRLine:" + LRLine; | |
LRPup=MA(C,4)>ValueWhen(LRLine,C);//* | |
"LRUp:" + LRPUp; | |
LRPdown=MA(C,4)<ValueWhen(LRLine,C);//* | |
"LRdown:" + LRPdown; | |
B3=Cross( MACD(2,8 ), Signal (4,10,2 ) )+Cross( StochK( 8, 2 ), StochD( 10,2,2))+ (RSI(4)>20 AND RSI(4)<75) | |
+Cross(EMA(C,2),EMA( C,8 ))+Cross(MA(OBV(),2),MA(OBV(),8))+Cross(MA(PDI(),2),MA(MDI(),8))+Cross(CCI(2),CCI(8)); | |
S3=Cross(Signal (4,10,2 ),MACD(2,8 ))+Cross(StochD( 10,2,2 ), StochK(8,2 ))+(RSI(4)>40 AND RSI(4)<90)+Cross(EMA(C,8),EMA( C,2 )) | |
+Cross(MA(OBV(),8),MA(OBV(),2))+Cross(MA(MDI(),8),MA(PDI(),2))+Cross(CCI(2),CCI(8)); | |
"B1:" + B1 + "B2"+ B2 +"B3:" + B3; | |
"S1:" + S1 + "S2"+ S2 +"S3:" + S3; | |
//Filtering condition | |
ZZPercent=0.5; | |
ZZ=Zig(C,ZZPercent); | |
ZZbottom=(ZZ<Ref(ZZ,-1));// AND (ZZ<Ref(ZZ,1)); | |
ZZtop=(ZZ>Ref(ZZ,-1));// AND (ZZ>Ref(ZZ,1)); | |
"ZZ"+Ref(ZZ,1)+"ZZbottom"+ZZbottom +"ZZtop"+ZZtop; | |
percdiff =0.2; /* peak detection threshold */ | |
fwdcheck = 1; | |
PK= Peak( H, percdiff, 1 ) == High; | |
TR= Trough( L, percdiff, 1 ) == Low; | |
mindistance = 0.2; | |
validdiff = percdiff/10; | |
xTr1 = ValueWhen( Tr, L, 1 ); | |
xTr2 = ValueWhen( Tr, L, 2 ); | |
xTr3 = ValueWhen( Tr, L, 3 ); | |
xTr4 = ValueWhen( Tr, L, 4 ); | |
xPK1=ValueWhen(PK,H,1); | |
xPK2=ValueWhen(PK,H,2); | |
xPK3=ValueWhen(PK,H,3); | |
xPK4=ValueWhen(PK,H,4); | |
valB=valuewhen(ZZbottom,C,1); | |
valT=valuewhen(ZZtop,C,1); | |
val=valuewhen(ZZbottom,C,1); | |
peakdiff = (ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 )+ValueWhen( PK, H, 2 )/ValueWhen( PK, H, 3 )+ValueWhen( PK, H, 3 )/ValueWhen( PK, H, 4 ))/3; | |
Troughdiff=(ValueWhen( tr, L, 1 )/ValueWhen( tr, L, 2 )+ValueWhen( tr, L, 2 )/ValueWhen( tr, L, 3 )+ValueWhen( tr, L, 3 )/ValueWhen( tr, L, 4 ))/3; | |
downline= O<(xPK1+xTr1)/2 AND xPK1<=xPK2 ;//* | |
upline= xTr1>=xTr2 AND O>(xPK1+xTr1)/2 AND C<xPK1*1.2; | |
"xTr1"+xTr1+"xTr2"+xTr2+"xPK1"+xPK1+"xPK2"+xPK2+"Downline"+downline+"upline"+upline; | |
/////1. Candle Based///////////////////////////////////////////////////////////////////// | |
SL = ( HHV( H, 26 ) + LLV( L, 26) )/2;// standard, base, or kijun-sen line | |
TL = ( HHV( H, 9 ) + LLV( L, 9 ) )/2;// turning, conversion, or tenkan-sen line | |
DL = Ref( C, 25 ); // delayed close price, or chikou span | |
Span1 = Ref( ( SL + TL )/2, -25 ); //Span1 and Span2 define the clouds | |
Span2 = Ref( (HHV( H, 52) + LLV(L, 52))/2, -25); | |
above = IIf(TL>Span1 AND TL>Span2,1,0); | |
within = IIf((TL>Span1 AND TL<Span2) OR (TL<Span1 AND TL>Span2) ,1,0); | |
below = IIf(TL<Span1 AND TL<Span2,1,0); | |
//ICHIMOKU=IIf((Cross(TL,SL) AND above),"STRONGbuy",IIf((Cross(TL,SL) AND within),"MEDIUMbuy",IIf((Cross(TL,SL) AND below),"WEAKbuy",IIf((Cross(SL,TL) AND below),"STRONGsell",IIf((Cross(SL,TL) AND within),"MEDIUMsell",IIf((Cross(SL,TL) AND above),"WEAKsell",0)))))); | |
ICHIMOKUbuy=IIf((Cross(TL,SL) AND above),3,IIf((Cross(TL,SL) AND within),2,IIf((Cross(TL,SL) AND below),1,0))); | |
ICHIMOKUsell=IIf((Cross(SL,TL) AND below),3,IIf((Cross(SL,TL) AND within),2,IIf((Cross(SL,TL) AND above),1,0))); | |
/* Candle Codes */ | |
len=15; | |
VolumeIdx = V / MA( V, len ); | |
AvgRange = Sum( abs(O-C),len )/len; | |
White = IIf((C>O) AND ((C-O)>=0.8*(H-L)),1,0) AND (C-O)>AvgRange; | |
Black = IIf((C<O) AND ((O-C)>=0.8*(H-L)),1,0) AND (O-C)>AvgRange; | |
Doji = IIf(abs(O-C)<=0.1*(H-L),1,0); | |
/* Dark Cloud Cover [Bear] */ | |
DCC = IIf(Ref(White, -1) AND Black AND C<=Ref(((H+L)/2),-1) AND O>Ref(C,-1), 1,0); | |
/* Piercing Line [Bull] */ | |
PL = IIf(Ref(Black, -1) AND White AND C>=Ref(((H+L)/2),-1) AND O<Ref(C,-1), 1,0); | |
/* Evening Doji Star [Bear] */ | |
EDS = IIf(Ref(White, -2) AND Ref(Doji, -1) AND Black AND C<=Ref(((H+L)/2),-2), 1,0); | |
/* Morning Doji Star [Bull] */ | |
MDS = IIf(Ref(Black, -2) AND Ref(Doji, -1) AND White AND C>=Ref(((H+L)/2),-2), 1,0); | |
/* Hammer [Bull] */ | |
HAM = IIf( (H-L > 1.5*AvgRange) AND (C > (H+L)/2) AND (O > C) AND (VolumeIdx > 2), 1, 0); | |
/* Bearish Engulfing */ | |
BRE = IIf(Black AND Ref(White, -1) AND (C < Ref(O, -1)) AND (O > Ref(C, -1)), 1,0); | |
/* Bullish Engulfing */ | |
BLE = IIf(White AND Ref(Black, -1) AND (C > Ref(O,-1)) AND (O < Ref(C,-1)), 1,0); | |
//34// | |
//########################################### | |
WhiteBody = C > O; | |
BigWhite = (Close - Open)/Open > 0.015 AND (Close - Open) * 2 > High - Low; | |
BlackBody = C < O; | |
BigBlack = (Open - Close)/Open > 0.015 AND (Open - Close) * 2 > High - Low; | |
Big = abs((Close - Open)/Open) > 0.014; | |
LongUpperShadow = H - Max(O,C) > (H - L)*0.67; | |
LongLowerShadow = Min(O,C) - L > (H - L)*0.67; | |
rng = abs((C-O)/O); | |
lowerShadow = Min(O,C) - L; | |
uppershadow = H - Max(O,C); | |
body = abs(O-C); | |
rngx = abs(H - L); | |
rngy = H-L; | |
shaven = lowerShadow < rngy*0.1; | |
ShavenBottom = L == Min(O,C); | |
ShavenHead = H == Max(O,C); | |
prevSize = abs(Ref(O,-1)-Ref(C,-1)); | |
currentSize = abs(O-C); | |
fwh = Ref(H,-4); | |
fwl = Ref(L,-4); | |
isPrevLargeWhite = Ref(big,-1) AND Ref(whitebody,-1); | |
SmallRealBody = rng < 0.003 AND rng >0; | |
Diff = abs((prevSize - currentSize) / currentSize); | |
DownTrend = (H < Ref(H,-1) AND L < Ref(L,-1)); | |
UpTrend = (H > Ref(H,-1) AND L > Ref(L,-1)); | |
isPrevUpTrend = Ref(uptrend,-1); | |
RealBodyGapUp = Min(O,C) > Max(Ref(O,-1),Ref(C,-1)); | |
RealBodyGapDown = Max(O,C) < Min(Ref(O,-1),Ref(C,-1)); | |
FallingWindow = Ref(downtrend,-1) AND GapDown(); | |
RisingWindow = Ref(uptrend,-1) AND GapUp(); | |
isfalling = bigblack AND fallingwindow; | |
isrising = bigwhite AND risingwindow; | |
rwh = Ref(H,-4); | |
rwl = Ref(L,-4); | |
isFallingBlack = Ref(fallingwindow,-1) AND Ref(blackbody,-1); | |
horw = Ref(H,-2); | |
windowOpen = C < horw; | |
opensInside = O < Ref(O,-1) AND O > Ref(C,-1); | |
similarSize = diff <= 0.25; | |
GapUpFromWhite = realBodyGapUp AND isPrevLargeWhite AND isPrevUptrend; | |
isPrevLargeBlack = Ref(big,-1) AND Ref(blackbody,-1); | |
isPrevDownTrend = Ref(downtrend,-1); | |
GapDownFromBlack = realBodyGapDown AND isPrevLargeBlack AND isPrevDowntrend; | |
isRisingWhite = Ref(risingwindow,-1) AND Ref(whitebody,-1); | |
lorw = Ref(L,-2); | |
windowOpenx = C > lorw; | |
Doji = C == O AND V > 0; | |
LongLeggedDoji = doji AND (H - L)/L > 0.01; | |
StarUp = smallRealBody AND gapUpFromWhite; | |
DojiStarUp = doji AND gapUpFromWhite; | |
DojiStarDown = doji AND gapDownFromBlack; | |
StarDown = smallRealBody AND gapDownFromBlack; | |
isPrevDownTrendx = Ref(downtrend,-3); | |
firstDoji = Ref(doji,-2); | |
secDojiLower = Ref(doji,-1) AND Ref(realBodyGapDown,-1); | |
isPrevUpTrendx = Ref(uptrend,-3); | |
secDojiHigher = Ref(doji,-1) AND Ref(realBodyGapUp,-1); | |
BeltHold = shavenbottom AND shavenhead AND big; | |
Engulfing = Max(O,C) > Ref(Max(O,C),-1) AND Min(O,C) < Ref(Min(O,C),-1); | |
UmbrellaLine = uppershadow < rngx*0.1 AND lowershadow > body*2; | |
//==================================================================================================== | |
//---------------------------------------- | |
// Bearish | |
//---------------------------------------- | |
// Kicker | |
KBR = Ref(O,-1) < Ref(C,-1) AND O <= Ref(O,-1) AND C <= O; | |
//Evening Doji Star | |
EveningDojiStar = Ref(dojiStarUp,-1) AND blackbody AND big AND C < Ref((O + C)/2,-2); | |
/* | |
A large white candlestick followed by a doji that gaps up from the | |
previous candles real body. This is followed by a third candlestick that is black and has a | |
close lower than the half way point of the first candlesticks real body. Must be preceeded by an uptrend. | |
*/ | |
// Evening Star | |
EveningStar = Ref(starUp,-1) AND blackbody AND big AND C < Ref((O + C)/2,-2); | |
/* | |
A large white candlestick followed by a small real body of either colour that gaps up from the | |
previous candles real body. This is followed by a third candlestick that is black and has a | |
close lower than the half way point of the first candlesticks real body. Must be preceeded by an uptrend. | |
*/ | |
// Grave Stone Doji | |
GraveStoneDoji = longleggeddoji AND L == C AND Ref(uptrend,-1); | |
/* | |
A doji with no lower shadow and an extremenly long upper shadow. Must be preceeded by an uptrend. | |
*/ | |
//Bear 3 Formation | |
Bear3Formation = bigblack AND C < Ref(C,-4) AND | |
Ref(H,-1) <= fwh AND Ref(L,-1) >= fwl AND | |
Ref(H,-2) <= fwh AND Ref(L,-2) >= fwl AND | |
Ref(H,-3) <= fwh AND Ref(L,-3) >= fwl AND | |
Ref(isfalling, -4); | |
/*A strong black candle in a falling window, followed by three | |
candles that fall within the high/low range of the strong black candle, followed | |
by another strong black candle that closes below the close of the first black candle. | |
This is a bearish confirmation.*/ | |
//Bearish Abandoned Baby | |
BearishAbandonedBaby = EveningDojiStar AND Ref(GapUp(),-1) AND GapDown(); | |
/* | |
An evening doji star where there is a gap between the lower shadow of the doji and | |
the upper shadows of the prior and next candle. | |
*/ | |
//Bearish Belt Hold | |
BearishBeltHold = belthold AND blackbody AND Ref(uptrend,-1); | |
/* | |
A large black candle with a shaven head and bottom preceeded by an uptrend. | |
*/ | |
//Bearish Counter Attack | |
BearishCounterAttack = Ref(big AND whitebody,-1) AND O > Ref(H,-1) AND C == Ref(C,-1) AND big AND blackbody AND Ref(uptrend,-1); | |
/* | |
A large white candle followed by a black candle which opens sharply higher but closes | |
at the prior black candles close. Must be preceeded by an uptrend. | |
*/ | |
// Bearish Harami Cross | |
BearishHaramiCross = doji AND Ref(C,-1) > O AND Ref(O,-1) < O AND Ref(big AND whitebody,-1) AND Ref(uptrend,-1); | |
/* A doji preceded by and contained within the real body of a big white candlestick in an uptrend */ | |
// Bearish Harami | |
BearishHarami = Ref(big AND whitebody,-1) AND smallRealBody AND Min(O,C) > Ref(O,-1) AND Max(O,C) < Ref(C,-1) AND Ref(uptrend,-1); | |
/* A small candlestick preceded by and whose real body is contained within, the real body of a big white candlestick in an uptrend*/ | |
// Bearish Separating Line | |
BearishSeparatingLine = Ref(whitebody AND big,-1) AND blackbody AND big AND O == Ref(O,-1) AND Ref(downtrend,-1); | |
/* A white candlestick followed by a black candlestick with the same opening price. Continues the previous downtrend. */ | |
// Dark Cloud Cover | |
DarkCloudCover = Ref(bigwhite,-1) AND blackbody AND O > Ref(H,-1) AND C <= Ref((O+C)/2,-1) AND C > Ref(O,-1) AND Ref(uptrend,-1); | |
/* A strong white candle in an uptrend followed by a black candle that opens above the high of the white candle and closes at least 50 percent into the white candles real body. Note that if the black candle completely | |
engulfs the white candles real body then this is not Dark Cloud Cover but a Bearish Engulfing Pattern. */ | |
// Engulfing Bear | |
EngulfingBear = Ref(whitebody,-1) AND blackbody AND engulfing AND Ref(uptrend,-1); | |
/* This bar is black and its real body engulfs the previous bars white real body. Must be preceeded by an uptrend. | |
*/ | |
//Hamging Man | |
HangingMan = umbrellaline AND uptrend AND Ref(uptrend,-1); | |
/* The same as a hammer except must be preceeded by an uptrend. */ | |
//Shooting Star | |
ShootingStar = smallRealBody AND shaven AND realBodyGapUp AND longuppershadow AND Ref(uptrend,-1); | |
/* | |
A small body that closes near the bottom of its range and | |
has a long upper shadow. There must be a real body gap up from the previous sessions candle. This | |
pattern occurs only after an uptrend. | |
*/ | |
//Three Black Crows | |
ThreeBlackCrows = (big AND blackbody) AND Ref(big AND blackbody, -1) AND Ref(big AND blackbody, -2) AND O < Ref(O,-1) AND Ref(O,-1) < Ref(O,-2) AND Ref(uptrend,-4); | |
/* | |
The last three candlesticks are large and black. Each opens within or lower than the | |
previous candles real body.Must be preceeded by an uptrend. | |
*/ | |
// Tri-Star Bottom | |
TriStarBottom = firstDoji AND secDojiLower AND doji AND realBodyGapUp AND isPrevDownTrendx; | |
/* | |
A doji followed by a lower doji which is followed by another doji that is higher than the | |
second doji. Must be preceeded by a downtrend. | |
*/ | |
//Tweezer Tops | |
TweezerTops = H == Ref(H,-1) AND Ref(big AND whitebody,-1) AND Ref(uptrend,-2); | |
/* A large candle followed by a candle with the same high. Must be preceeded by an uptrend. */ | |
// Upside Gap Two Crows | |
UpsideGapTwoCrows = Ref(big AND whitebody,-2) AND Ref(realBodyGapUp,-1) AND Ref(smallRealBody,-1) AND Ref(blackbody,-1) AND engulfing AND blackbody AND C > Ref((O+C)/2,-2) AND Ref(uptrend,-2); | |
/* A strong white candle followed by a small black candle which gaps above the previous | |
candles real body, followed by a black candle which engulfs the previous black candle. Preceeded by an uptrend. */ | |
//---------------------------------------- | |
// Bullish | |
//---------------------------------------- | |
// Kicker | |
KBL = Ref(O,-1) > Ref(C,-1) AND O >= Ref(O,-1) AND C > O; | |
// Morning Star | |
MorningStar = Ref(starDown,-1) AND whitebody AND big AND C > Ref((O + C)/2,-2); | |
/* | |
A large black candlestick followed by a small real body of either colour, | |
that gaps below the previous black candles real body, with a third white candlestick, that has a close | |
higher than the half way point of the first black candlestick. Must be preceeded by a downtrend. | |
*/ | |
// Morning Doji Star | |
MorningDojiStar = Ref(dojiStarDown,-1) AND whitebody AND big AND C > Ref((O + C)/2,-2); | |
/* | |
A large black candlestick followed by a doji that gaps below its real body, with a third | |
white candlestick, that has a close at least half of the way up the black candlestick. Must be preceeded by a | |
downtrend. | |
*/ | |
// Bull 3 Formation | |
Bull3Formation = bigwhite AND C > Ref(C,-4) AND | |
Ref(H,-1) <= rwh AND Ref(L,-1) >= rwl AND | |
Ref(H,-2) <= rwh AND Ref(L,-2) >= rwl AND | |
Ref(H,-3) <= rwh AND Ref(L,-3) >= rwl AND | |
Ref(isrising, -4); | |
/* | |
A strong white candle in a rising window, followed by three | |
candles that fall within the high/low range of the strong white candle, followed | |
by another strong white candle that closes above the close of the first white candle. | |
This is confirmation of the Bullish trend." | |
*/ | |
// Bullish Abandoned Baby | |
BullishAbandonedBaby = morningdojistar AND Ref(GapDown(),-1) AND GapUp(); | |
/* | |
A morning doji star where there is a gap between the lower shadow of the doji and | |
the prior and next candle. | |
*/ | |
// Bullish Belt Hold | |
BullishBeltHold = belthold AND whitebody AND Ref(downtrend,-1); | |
/* | |
A large white candle with no upper or lower shadow preceeded by a downtrend. | |
*/ | |
// Bullish Counter Attack | |
BullishCounterAttack = Ref(big AND blackbody,-1) AND O < Ref(H,-1) AND C == Ref(C,-1) AND big AND whitebody AND Ref(downtrend,-1); | |
/* | |
A large black candle followed by a white candle which opens sharply lower but closes at the | |
prior white candles close. Must be preceeded by a downtrend | |
*/ | |
// Bullish Harami Cross | |
BullishHaramiCross = doji AND Ref(O,-1) > O AND Ref(C,-1) < O AND Ref(big AND blackbody,-1) AND Ref(downtrend,-1); | |
/* | |
A doji preceded by and contained within the real body of a big | |
black candlestick in a downtrend. | |
*/ | |
// Bullish Harami | |
BullishHarami = Ref(big AND blackbody,-1) AND smallRealBody AND Min(O,C) > Ref(C,-1) AND Max(O,C) < Ref(O,-1) AND Ref(downtrend,-1); | |
/* | |
A small candlestick, preceded by, and whose body is contained within a big black | |
candlestick in a downtrend | |
*/ | |
// Bullish Separating Line | |
BullishSeparatingLine = Ref(blackbody AND big,-1) AND whitebody AND big AND O == Ref(O,-1) AND Ref(uptrend,-1); | |
/* | |
A black candlestick followed by a white candlestick with the same opening price. Continues | |
the previous uptrend. | |
*/ | |
//Dragonfly Doji | |
DragonflyDoji = longleggeddoji AND H==C AND Ref(downtrend,-1); | |
/*A doji with no upper shadow AND a long lower shadow preceeded by a downtrend.*/ | |
// Engulfing Bull | |
EngulfingBull = Ref(blackbody,-1) AND whitebody AND engulfing AND Ref(downtrend,-1); | |
/* | |
This bar is white and its real body engulfs the previous bars black real body. Must be | |
preceeded by a downtrend. | |
*/ | |
// Hammer | |
Hammer = umbrellaline AND Ref(downtrend,-1); | |
/* | |
The upper shadow is less than ten percent of the range | |
and the lower shadow is more than two times the size of the body. Must be preceeded by a downtrend. | |
*/ | |
//Inverted Hammer | |
InvertedHammer = smallRealBody AND shaven AND realBodyGapDown AND longuppershadow AND Ref(downtrend,-1); | |
/* | |
An upside down Hammer that appears after a downtrend | |
*/ | |
//Piercing Line | |
PiercingLine = Ref(bigblack,-1) AND whitebody AND O < Ref(L,-1) AND C >= Ref((O+C)/2,-1) AND C < Ref(O,-1) AND Ref(downtrend,-1); | |
/* | |
A stong black candle followed by a white candle that opens below the low of | |
the prior black candle but closes more than halfway into the black candles real body. Preceeded by a downtrend. Note that if the | |
white candle engulfs the prior black candles real body then this is a Bullish Engulfing Pattern not a Piercing Pattern | |
*/ | |
// SeperatingLines | |
SeperatingLines = O == Ref(O,-1) AND (blackbody AND Ref(whitebody,-1) OR whitebody AND Ref(blackbody,-1)); | |
/* | |
a black candlestick is followed by a white candlestick, or a white with a black,and they have the same opening prices. | |
*/ | |
//Three White Soldiers | |
ThreeWhiteSoldiers = (whitebody AND big) AND Ref(whitebody AND big,-1) AND Ref(whitebody AND big,-2) AND O > Ref(O,-1) AND Ref(O,-1) > Ref(O,-2); | |
/* | |
The last three candlesticks are large and white. Each opens within or higher than the | |
previous candles real body. | |
*/ | |
// Tri-Star Top | |
TriStarTop = firstDoji AND secDojiHigher AND doji AND realBodyGapDown AND isPrevUpTrendx; | |
/* | |
A doji followed by a higher doji which is followed by another doji that is lower than the | |
second doji. Must be preceeded by an uptrend. | |
*/ | |
// Tweezer Bottoms | |
TweezerBottoms = L == Ref(L,-1) AND Ref(big AND blackbody,-1) AND Ref(downtrend,-2); | |
/* A large candle followed by a candle with the same Low. Must be preceeded by a downtrend. */ | |
//---------------------------------------- | |
// Continuation | |
//---------------------------------------- | |
// Downward Gapping Tasuki | |
DownwardGappingTasuki = isFallingBlack AND whitebody AND opensInside AND C > Ref(O,-1) AND windowOpen AND similarSize; | |
/* A black candle that gaps down followed by a similarly sized white candle that opens Inside the black candles real body AND closes above it. */ | |
//Upward Gapping Tasuki | |
UpwardGappingTasuki = isRisingWhite AND blackbody AND opensInside AND C < Ref(O,-1) AND windowOpenx AND similarSize; | |
/* A white candle that gaps up followed by a similarly sized black candle that opens Inside the white candles real body AND closes below it; */ | |
//Inverted Black Hammer | |
InvertedBlackHammer = blackbody AND InvertedHammer; | |
STS = /*Bears*/ | |
WriteIf(KBR, "Bearish Kicker", | |
WriteIf(EveningDojiStar, "Evening Doji Star", | |
WriteIf(EveningStar, "Evening Star", | |
WriteIf(GraveStoneDoji, "Grave Stone Doji", | |
WriteIf(Bear3Formation, "Bear 3 Formation", | |
WriteIf(BearishAbandonedBaby, "Bearish Abandoned Baby", | |
WriteIf(BearishBeltHold, "Bearish Belt Hold", | |
WriteIf(BearishCounterAttack, "Bearish Counter Attack", | |
WriteIf(BearishHaramiCross, "Bearish Harami Cross", | |
WriteIf(BearishHarami, "Bearish Harami", | |
WriteIf(BearishSeparatingLine, "BearishSeparatingLine", | |
WriteIf(DarkCloudCover, "DarkCloudCover", | |
WriteIf(EngulfingBear, "Engulfing Bear", | |
WriteIf(HangingMan, "Hanging Man", | |
WriteIf(ShootingStar, "Shooting Star", | |
WriteIf(ThreeBlackCrows, "Three Black Crows", | |
WriteIf(TriStarBottom, "TriStar Bottom", | |
WriteIf(TweezerTops, "Tweezer Tops", | |
WriteIf(UpsideGapTwoCrows, "UpsideGapTwoCrows", | |
/*Bulls*/ | |
WriteIf(KBL, "Bullish Kicker", | |
WriteIf(MorningStar, "Morning Star", | |
WriteIf(MorningDojiStar, "Morning Doji Star", | |
WriteIf(Bull3Formation, "Bull 3 Formation", | |
WriteIf(BullishAbandonedBaby, "Bullish Abandoned Baby", | |
WriteIf(BullishBeltHold, "Bullish Belt Hold", | |
WriteIf(BullishCounterAttack, "Bullish Counter Attack", | |
WriteIf(BullishHaramiCross, "Bullish Harami Cross", | |
WriteIf(BullishHarami, "Bullish Harami", | |
WriteIf(BullishSeparatingLine, "Bullish Separating Line", | |
WriteIf(DragonflyDoji, "Dragonfly Doji", | |
WriteIf(EngulfingBull, "Engulfing Bull", | |
WriteIf(Hammer, "Hammer", | |
WriteIf(InvertedHammer, "Inverted Hammer", | |
WriteIf(PiercingLine, "Piercing Line", | |
WriteIf(SeperatingLines, "Seperating Lines", | |
WriteIf(ThreeWhiteSoldiers, "Three White Soldiers", | |
WriteIf(TriStarTop, "Tri-Star Top", | |
WriteIf(TweezerBottoms, "Tweezer Bottoms","")))))))))))))))))))))))))))))))))))))); | |
candlesell = IIf(KBR OR EveningDojiStar OR EveningStar OR GraveStoneDoji OR Bear3Formation OR BearishAbandonedBaby | |
OR BearishBeltHold OR BearishCounterAttack OR BearishHaramiCross OR BearishHarami OR BearishSeparatingLine | |
OR DarkCloudCover OR EngulfingBear OR HangingMan OR ShootingStar OR ThreeBlackCrows OR TriStarBottom | |
OR TweezerTops OR UpsideGapTwoCrows,1,0);//weight 2 | |
candlebuy=IIf( MorningStar OR MorningDojiStar OR Bull3Formation | |
OR BullishAbandonedBaby OR BullishBeltHold OR BullishCounterAttack OR BullishHaramiCross | |
OR BullishHarami OR BullishSeparatingLine OR DragonflyDoji OR EngulfingBull OR Hammer OR InvertedHammer | |
OR PiercingLine OR SeperatingLines OR ThreeWhiteSoldiers OR TriStarTop OR TweezerBottoms OR KBL, 1, 0); | |
candleAbuy=ICHIMOKUbuy+candlebuy; //Max value 6 and min 0 | |
candleAsell=ICHIMOKUsell+candlesell; | |
"Candle Buy"+candleAbuy+"candle Sell"+candleAsell; | |
filterb=B1+B2+B3+LRPup+candleAbuy; | |
filters=S1+S2+S3+LRPdown+candleAsell; | |
"FilterB"+filterb+"FilterS"+filters; | |
FB=upline AND filterb>filters+2;//filters; | |
FSS=downline AND filters>filterb+2;//filterb; | |
"BUY**"+FB+"Sell**"+FSS; | |
AddColumn(filterb,"filter B",1); | |
AddColumn(filters,"filter S",1); | |
//Buysig=(InWatchList(12) AND Ref(C,-1)>Ref(O,-1) AND FB) OR (InWatchList(18) AND O>EMA(C,4)) OR (InWatchList(64) AND ROC(C,120)<-2 AND ROC(C,20)<ROC(C,60) AND ROC(C,4)<0) ;//AND O>valB AND O<valT;// second data | |
//Sellsig=(inwatchlist(9) AND Ref(C,-1)<Ref(O,-1) AND FSS) OR (InWatchList(19) AND C<EMA(O,4));// AND O>valT ; | |
Buysig=(InWatchList(12) AND FB) OR (InWatchList(18) AND O>EMA(C,12)) OR (InWatchList(64) AND ROC(C,120)<-2 AND ROC(C,20)<ROC(C,60) AND ROC(C,4)<0) ;//AND O>valB AND O<valT;// second data | |
Sellsig=(inwatchlist(9) AND FSS) OR (InWatchList(19) AND C<EMA(O,12));// AND O>valT ; | |
//****** | |
Buy=Buysig ; | |
Short=Sellsig ; | |
Sell=0; | |
Cover=0; | |
LastBuy = LastValue(Buy); | |
LastShort = LastValue(Short); | |
LastShortPrice=LastValue(ShortPrice); | |
LastBuyPrice=LastValue(BuyPrice); | |
PrevDT = StaticVarGet("DateTime"+ABName); | |
DT = LastValue(DateTime()); | |
NewBar = DT != PrevDT; | |
StaticVarSet("DateTime"+ABName,DT); | |
if( NewBar ) StaticVarSetText("OrderID"+ABName,""); | |
LastBuy = LastValue(Buy); | |
LastShort = LastValue(Short); | |
IBPosSize=0; | |
ibc = GetTradingInterface("IB"); | |
IBcStatus = ibc.IsConnected(); | |
IBPosSize = ibc.GetPositionSize( IBName ); | |
IBcStatusString = WriteIf(IBCStatus==0,"TWS Not Found",WriteIf(IBCStatus==1,"Connecting to TWS",WriteIf(IBCStatus==2,"TWS OK",WriteIf(IBCStatus==3,"TWS OK (msgs)","")))); | |
printf("Net Liquidity or balance:"); | |
liqCAD=ibc.GetAccountValue("[CAD]NetLiquidation"); | |
printf("Net Liquidation USD :"); | |
CashBalanceStr = ibc.GetAccountValue("[USD]NetLiquidationByCurrency"); | |
printf("Net Liquidation CAD:"); | |
CashBalanceCAD = ibc.GetAccountValue("[CAD]NetLiquidationByCurrency"); | |
printf("Available Funds USD:"); | |
USDaf=ibc.GetAccountValue("[USD]AvailableFunds"); | |
printf("Available Fund CAD:"); | |
CADaf=ibc.GetAccountValue("[CAD]AvailableFunds"); | |
printf("Total Cash Balance USD:"); | |
USDtcb=ibc.GetAccountValue("[USD]TotalCashBalance"); | |
printf("Total Cash Balance CAD:"); | |
CADtcb=ibc.GetAccountValue("[CAD]TotalCashBalance"); | |
printf("AvailableFunds CAD:"); | |
availablefundstr=ibc.GetAccountValue("[CAD]AvailableFunds"); | |
printf("Excess Liquidity CAD:"); | |
excessfundstr=ibc.GetAccountValue("[CAD]ExcessLiquidity"); | |
printf("MaintenanceMarginReqCAD:"); | |
marginfundUSD=ibc.GetAccountValue("[CAD]MaintMarginReq"); | |
printf("Equity With Loan Value CAD:"); | |
loanfundUSD=ibc.GetAccountValue("[CAD]EquityWithLoanValue"); | |
printf("Buying Power CAD or excessfund:"); | |
excessfundCAD=ibc.GetAccountValue("[CAD]BuyingPower"); | |
if (liqCAD == "") | |
Balance = 0; | |
else | |
Balance = StrToNum(liqCAD); | |
if (excessfundCAD =="") | |
excessfund = 0; | |
else | |
excessfund = StrToNum(excessfundCAD); | |
AccountCutout =excessfund<10000; | |
function stockprice() | |
{base=1; | |
for(i=0;i<=LastValue(C);i++){ | |
base++; | |
} | |
roundoff=int(base/5)*5; | |
return lastvalue(roundoff); | |
} | |
base=stockprice(); | |
printf("\n"+"Roundoff Price"+base); | |
IBOrderSize =(int((Balance*0.01 + excessfund*0.01)/base)/100)*100;//(int((Balance*0.02 + excessfund*0.03)/base)/100)*100; | |
printf("\n"+"unfiltered Order size"+IBOrderSize); | |
ordersize=IIf(IBOrderSize<(Balance*0.085/base) AND IBOrderSize>(Balance*0.02/base) AND AccountCutout==0 ,IBOrderSize,0); | |
printf("\n"+"Maximum Order size"+Balance*0.085/base); | |
printf("\n"+"Minimum Order size"+Balance*0.02/base); | |
printf("\n"+"Actual:"+ordersize+"\n"); | |
//openpos = ibc.GetPositionList(); | |
pendinglist=ibc.GetPendingList( 0, "Pending" ); | |
averageprice=0; | |
OldOrderID = StaticVarGetText("OrderID"+ABName); | |
if (OldORderID == "" && (LastBuy || LastShort)) | |
{ | |
StaticVarSetText("OrderID"+ABName,"DUMMY"); | |
} | |
tqqq=Foreign("TQQQ","Close");//2% | |
sqqq=Foreign("SQQQ","Close");//0.5% | |
retTQQQ120=ROC(tqqq,120); | |
retTQQQ60=ROC(tqqq,60); | |
retTQQQ20=ROC(tqqq,20); | |
retSQQQ120=ROC(sqqq,120); | |
retSQQQ60=ROC(sqqq,60); | |
retSQQQ20=ROC(sqqq,20); | |
if( IBcStatus ) | |
{ | |
OrderID = StaticVarGetText("OrderID"+ABName); | |
BuyPending=ibc.IsOrderPending(OrderID); | |
SellPending=ibc.IsOrderPending(OrderID); | |
averageprice=ibc.GetPositionInfo(Name(), "Avg. cost"); | |
//IBPosSize = ibc.GetPositionSize( IBName ); | |
// printf("average price:"+"\n"+averageprice); | |
//printf("position list:"+"\n"+IBPosSize); | |
stoplossS=C-Max(ATR(5)*15,MA(C,200)*0.004); | |
stoplossC=C+Max(ATR(5)*15,MA(C,200)*0.004); | |
minSProfit= (LastValue(GetRTData("Bid"))-ibc.GetPositionInfo(Name(), "Avg. cost"))*abs(IBPosSize)>5; | |
minCProfit= (LastValue(ibc.GetPositionInfo(Name(), "Avg. cost"))-GetRTData("Ask"))*abs(IBPosSize)>5; | |
minSloss=(LastValue(stoplossS)-ibc.GetPositionInfo(Name(), "Avg. cost")*0.99)*abs(IBPosSize)>5; | |
minCloss=(LastValue(stoplossC)-ibc.GetPositionInfo(Name(), "Avg. cost")*1.01)*abs(IBPosSize)>5; | |
B1= LastBuy AND ibc.GetPositionSize(Name())==0 AND LastValue(MarketON); | |
SS1= LastShort AND ibc.GetPositionSize(Name())==0 AND LastValue(MarketON);//short sell | |
/*BWTQQQ1=LastValue(retTQQQ120)<-2 AND LastValue(retTQQQ20)>LastValue(retTQQQ60)*0.95 AND LastValue(ibc.GetPositionSize("TQQQ"))==0; | |
BWTQQQ2=LastValue(retTQQQ120)<-3 AND LastValue(retTQQQ20)>LastValue(retTQQQ60)*0.95 AND LastValue(ibc.GetPositionSize("TQQQ"))>1; | |
BWSQQQ1=LastValue(retSQQQ120)<-2 AND LastValue(retSQQQ20)>LastValue(retSQQQ60)*0.95 AND LastValue(ibc.GetPositionSize("SQQQ"))==0; | |
BWSQQQ2=LastValue(retSQQQ120)<-3 AND LastValue(retSQQQ20)>LastValue(retSQQQ60)*0.95 AND LastValue(ibc.GetPositionSize("SQQQ"))>1;*/ | |
S1= InWatchList(33) AND LastValue(minSProfit) AND ibc.GetPositionSize(Name())>0; | |
S2= InWatchList(32) AND LastValue(minSProfit) AND ibc.GetPositionSize(Name())>0; | |
S3= InWatchList(31) AND LastValue(minSProfit) AND ibc.GetPositionSize(Name())>0; | |
S4=InWatchList(30) AND LastValue(minSProfit) AND ibc.GetPositionSize(Name())>0; | |
S5= (InWatchList(64 ) OR InWatchList(18)) AND LastValue(C)>averageprice*1.2 AND LastValue(minSProfit) AND ibc.GetPositionSize(Name())>0; | |
S6= InWatchList(17) AND minSloss AND ibc.GetPositionSize(Name())>0; | |
//S5=LastValue(MarketLM) AND LastValue(C)>(averageprice*0.998) AND ibc.GetPositionSize(Name())>0; | |
//S6=LastValue(C)<(averageprice*0.965) AND ibc.GetPositionSize(Name())>0; | |
C1= InWatchList(33) AND LastValue(minCProfit) AND ibc.GetPositionSize(Name())<0; | |
C2= InWatchList(32) AND LastValue(minCProfit) AND ibc.GetPositionSize(Name())<0; | |
C3= InWatchList(31) AND LastValue(minCProfit) AND ibc.GetPositionSize(Name())<0; | |
C4= InWatchList(30) AND LastValue(minCProfit) AND ibc.GetPositionSize(Name())<0; | |
C5=(InWatchList(64) OR InWatchList(19)) AND LastValue(C)<averageprice*0.8 AND LastValue(minCProfit) AND ibc.GetPositionSize(Name())<0; | |
C6=InWatchList(17) AND minCloss AND ibc.GetPositionSize(Name())<0; | |
//C5=LastValue(MarketLM) AND LastValue(C)<(averageprice*1.002) AND ibc.GetPositionSize(Name())<0; | |
//C6=LastValue(C)>(averageprice*1.035) AND ibc.GetPositionSize(Name())<0; | |
size=IIf( (LastBuy OR LastShort),ordersize,abs(IBPosSize)); | |
if(B1 AND AccountCutout==0) //BUY | |
{ | |
OID= ibc.PlaceOrder( Name(), "BUY",Size, "MKT",0, 0, "Day", True); | |
ORderStatus = ibc.GetStatus( OID, True); | |
if(ORderStatus == "Filled"){ | |
StaticVarSetText("OrderID"+ABName,OID); | |
} | |
for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
if (SubmitOrders) | |
{ | |
for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
tradetime=GetPerformanceCounter()/1000; | |
while ((GetPerformanceCounter()/1000 - tradetime) <5) // give up after 5 seconds | |
{ | |
ibc.Reconnect(); //Refreshes ibc, and gets accurate status | |
//ORderStatus = ibc.GetStatus( OID, True); | |
if (ORderStatus == "PreSubmitted" || ORderStatus == "Submitted" || ORderStatus == "Filled") | |
break; | |
} | |
} | |
} | |
if((C1 OR C2 OR C3 OR C4 OR C5 OR C6) ) //Cover C5 and C6 | |
{ | |
OID= ibc.PlaceOrder( Name(), "BUY",Size, "MKT",0, 0, "Day", True); | |
ORderStatus = ibc.GetStatus( OID, True); | |
if(ORderStatus == "Filled"){ | |
StaticVarSetText("OrderID"+ABName,OID); | |
} | |
for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
if (SubmitOrders) | |
{ | |
for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
tradetime=GetPerformanceCounter()/1000; | |
while ((GetPerformanceCounter()/1000 - tradetime) <5) // give up after 5 seconds | |
{ | |
ibc.Reconnect(); //Refreshes ibc, and gets accurate status | |
//ORderStatus = ibc.GetStatus( OID, True); | |
if (ORderStatus == "PreSubmitted" || ORderStatus == "Submitted" || ORderStatus == "Filled") | |
break; | |
} | |
} | |
} | |
if(SS1 AND AccountCutout==0 ) //SHORT SELL | |
{ | |
OID= ibc.PlaceOrder( Name(), "SELL",Size, "MKT",0, 0, "Day", True); | |
ORderStatus = ibc.GetStatus( OID, True); | |
if(ORderStatus == "Filled"){ | |
StaticVarSetText("OrderID"+ABName,OID); | |
} | |
//for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
if (SubmitOrders) | |
{ | |
for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
tradetime=GetPerformanceCounter()/1000; | |
while ((GetPerformanceCounter()/1000 - tradetime) <5) // give up after 5 seconds | |
{ | |
ibc.Reconnect(); //Refreshes ibc, and gets accurate status | |
//ORderStatus = ibc.GetStatus( OID, True); | |
if (ORderStatus == "PreSubmitted" || ORderStatus == "Submitted" || ORderStatus == "Filled") | |
break; | |
} | |
} | |
} | |
if((S1 OR S2 OR S3 OR S4 OR S5 OR S6 ) ) //sell // or S6 or S5 | |
{ | |
OID= ibc.PlaceOrder( Name(), "SELL",Size, "MKT",0, 0, "Day", True); | |
ORderStatus = ibc.GetStatus( OID, True); | |
if(ORderStatus == "Filled"){ | |
StaticVarSetText("OrderID"+ABName,OID); | |
} | |
//for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
if (SubmitOrders) | |
{ | |
for (dummy=0; dummy<40; dummy++) ibc.Sleep(50); //Usually takes up to about a second for TWS to get acknowledgement from IB | |
tradetime=GetPerformanceCounter()/1000; | |
while ((GetPerformanceCounter()/1000 - tradetime) <5) // give up after 5 seconds | |
{ | |
ibc.Reconnect(); //Refreshes ibc, and gets accurate status | |
//ORderStatus = ibc.GetStatus( OID, True); | |
if (ORderStatus == "PreSubmitted" || ORderStatus == "Submitted" || ORderStatus == "Filled") | |
break; | |
} | |
} | |
} | |
ibc.ClearList(4);//error list clearing | |
/*j=0; | |
for( i = 0; ( symbol = StrExtract( pendinglist, i ) ) != ""; i++ ) //pending cancellation | |
{ | |
if(symbol==Name())//getfndata("Alias") | |
{ | |
j++; | |
} | |
} | |
if(j>1){ | |
for( i = 1;i<j; i++ ){ | |
ibc.CancelAllPendingOrders(name()); | |
} | |
}*/ | |
// Note LastOrderID will remain "" while waiting for price improvement so we may skip entering for the whole of the bar | |
LastOrderID = StaticVarGetText("OrderID"+ABName); | |
ORderStatus = ibc.GetStatus( LastOrderID , True ); | |
if( ORderStatus != "" ) StaticVarSetText("OrderStatus"+ABName,ORderStatus); | |
} | |
else IBPosSize = 0; | |
LastOrderID = StaticVarGetText("OrderID"+ABName); | |
ORderStatus = StaticVarGetText("OrderStatus"+ABName); | |
/*Title = Filename+":"+ABName+"\n"+" Trading Mode:"+WriteIf( SubmitOrders," -Create and Transmit"," - Create Only")+"\n"+" Last Signal: "+WriteIf(LastBuy,"BUY",WriteIf | |
(LastShort,"SHORT","NoSignal"))+"\n"+" IB Status: "+IBcStatusString+"\n"+" Last OrderID:"+LastOrderID+","+"\n"+" OrderStatus:"+ORderStatus+WriteIf(ORderStatus=="Error",ibc.GetLastError( LastOrderID | |
),"")+"," + "LastTime: "+DateTimeToStr(LastValue(DateTime()))+"\n";*/ | |
Filter=(Buy OR Short) AND (InWatchList(12) OR InWatchList(9) OR InWatchList(17)) AND LastOrderID!="DUMMY" ; | |
AddTextColumn(FullName(),"name",200); | |
AddColumn(Buy,"Buy",1.0); | |
AddColumn(Balance,"Cash",1.2); | |
AddColumn(excessfund,"excessfund",1.2); | |
AddColumn(IIf(SubmitOrders,Asc("Y"),Asc("N")),"Transmit",formatChar); | |
AddColumn(IIf(Buy,Asc("L"),IIf(Short,Asc("S"),Asc(" "))),"Buy/Sell",formatChar); | |
AddColumn(IBOrderSize,"Qty",1.0); | |
AddColumn(IIf(Buy,BuyPrice,ShortPrice),"Entry",1.5); | |
AddTextColumn(IBcStatusString,"IBC Status",1.0); | |
AddTextColumn(LastOrderID,"LastOID",1.0); | |
AddTextColumn(ORderStatus,"OrderStatus",1.0); | |
AFL CODE FOR SELECTION (V7) | |
***************** | |
****************************** | |
_SECTION_BEGIN("FILTER"); | |
Filename = _DEFAULT_NAME(); | |
Plot(C , "algotrade ", colorBlue, styleLine); | |
SetBarsRequired( 200, 0 ); | |
bi = Inrange=BarIndex(); | |
//arrayitem = SelectedValue( bi ) - bi[ 0 ]; | |
//"Close at selected bar:" + Close[ arrayitem ]; | |
BC12=BarCount-12; | |
//lastNbars( http://www.amibroker.com/kb/2014/12/31/drawing-indicators-on-a-subset-of-visible-bars/ | |
roc12=ROC(C,12); | |
"ROC last 12 bars:" + roc12; | |
//bi120=bi[120]-bi[0] | |
newPeriod = ND= Day() != Ref( Day(), -1 ); | |
Time = Now( 4 ); | |
Seconds = int( Time % 100 ); | |
Minutes = int( Time / 100 % 100 ); | |
Hours = int( Time / 10000 % 100 ); | |
//beta and correlation | |
IndexNDX="$NDX"; | |
IndexOEX="$OEX"; | |
indexSPX="$SPX"; | |
IndexRUT="$RUT"; | |
P_NDX=Foreign(IndexNDX,"C",1); | |
//PH=Foreign(IndexNDX,"H",1); | |
//PL=Foreign(IndexNDX,"L",1); | |
P_OEX=Foreign(IndexOEX,"C",1); | |
P_SPX=Foreign(IndexSPX,"C",1); | |
PH_SPX=Foreign(IndexOEX,"H",1); | |
PL_SPX=Foreign(IndexOEX,"L",1); | |
P_RUT=Foreign(IndexRUT,"C",1); | |
tqqq=Foreign("TQQQ","Close");//2% | |
sqqq=Foreign("SQQQ","Close");//0.5% | |
vix=Foreign("VIX","Close"); | |
retTQQQ120=ROC(tqqq,120); | |
retTQQQ60=ROC(tqqq,60); | |
retTQQQ20=ROC(tqqq,20); | |
retSQQQ120=ROC(sqqq,120); | |
retSQQQ60=ROC(sqqq,60); | |
retSQQQ20=ROC(sqqq,20); | |
retRUT120=ROC(P_RUT,120); | |
retRUT60=ROC(P_RUT,60); | |
retRUT20=ROC(P_RUT,20); | |
retVIX120=ROC(vix,120); | |
retVIX60=ROC(vix,60); | |
retVIX20=ROC(vix,20); | |
retNDX120=ROC(P_NDX,120); | |
retNDX60=ROC(P_NDX,60); | |
retNDX20=ROC(P_NDX,20); | |
retOEX120=ROC(P_OEX,120); | |
retOEX60=ROC(P_OEX,60); | |
retOEX20=ROC(P_OEX,20); | |
retSPX120=ROC(P_SPX,120); | |
retSPX60=ROC(P_SPX,60); | |
retSPX20=ROC(P_SPX,20); | |
Beta=((20* Sum(ROC( C,60) * ROC(P_SPX,60),20)) - (Sum(ROC(C,60),20) * Sum(ROC( P_SPX,60),20))) / ((20* Sum((ROC(P_SPX,60)^2 ),20)) - (Sum(ROC(P_SPX,60),20)^2 )); | |
cons=(MA(Beta,50)>0.6 AND Correlation(P_SPX,C,50)>0.6); | |
downline=retNDX60<0 AND retSQQQ20>0 AND retSQQQ20>retTQQQ20 AND Trough( P_SPX,0.2, 1 )<Trough( PL_SPX,0.2, 2) AND MA(P_SPX,20)>LastValue(Trough( P_SPX, 2, 1 )) AND Peak( P_SPX,0.2, 1 )<Peak( P_SPX,0.2, 2 );//* | |
upline=retNDX60>0 AND retTQQQ20>0 AND retSQQQ20<retTQQQ20 AND MA(P_SPX,20)>LastValue(Peak( P_SPX,0.2, 1 )*0.99) and MA(P_SPX,20)<LastValue(Peak( P_SPX,0.2, 1 )*1.05) AND Peak( P_SPX,0.2, 1 )> Peak( P_SPX,0.2, 2 ) AND Trough( P_SPX, 0.2, 1 )>Trough( P_SPX, 0.2, 2); | |
//AND retVIX20>0 AND retOEX20<0.2 AND retSPX20<0.2 AND retRUT20<0.2 AND | |
//AND retVIX120<0 retOEX20>0.3 AND retSPX20>0.2 AND retRUT20>0.2 AND | |
"Index :" + P_SPX; | |
"Trough 1 :" + Trough( P_SPX,0.2, 1); | |
"Trough 2 :" + Trough( P_SPX,0.2, 2); | |
"Peak 1:" + LastValue(Peak( P_SPX, 0.2, 1 )); | |
"Peak 2:" + LastValue(Peak( P_SPX, 0.2, 2 )); | |
"Peak 1 0.99 :" + LastValue(Peak( P_SPX, 0.2, 1 )*0.99); | |
"Peak 1 1.05 :" + LastValue(Peak( P_SPX, 0.2, 1 )*1.05); | |
AddColumn(downline,"downline",1); | |
AddColumn(upline,"upline",1); | |
filterb=upline AND cons AND roc12>0.01 AND InWatchList(4); | |
filters=downline AND cons AND roc12<-0.01 AND InWatchList(6); | |
AddColumn(filterb,"filter B",1); | |
AddColumn(filters,"filter S",1); | |
listnumS = 9;// we use this watchlist for selecting to sels short US stocks | |
// erase the watchlist when we process very first symbol | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
oldlist = CategoryGetSymbols( categoryWatchlist, listnumS); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( oldlist, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, listnumS); | |
} | |
} | |
if ( LastValue( Cum( filters AND Status( "barinrange" ) ) ) ) | |
CategoryAddSymbol( "", categoryWatchlist, listnumS); | |
listnumB = 12; // we use this watchlist for selecting US stocks to buy | |
// erase the watchlist when we process very first symbol | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
oldlist = CategoryGetSymbols( categoryWatchlist, listnumB); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( oldlist, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, listnumB); | |
} | |
} | |
if ( LastValue( Cum( filterb AND Status( "barinrange" ) ) ) ) | |
CategoryAddSymbol( "", categoryWatchlist, listnumB ); | |
_SECTION_BEGIN("HOLDING"); | |
Filename = _DEFAULT_NAME(); | |
Plot(C , "algotrade ", colorBlue, styleLine); | |
//////HOLDING distribution | |
ibc = GetTradingInterface("IB"); | |
IBcStatus = ibc.IsConnected(); | |
IBPosSize=0; | |
oldlist = 13; //holding stocks manual load !! after market | |
OPTlesslist=14 ;//option less holding | |
OPTlist=15;//list of option hedged stocks and index options | |
newlist=16;//intraday list, each day this list to copy to 13 of next day using text file manually | |
intradaylist=17; | |
weightlistBUY=18; | |
weightlistSELL=19; | |
specialETF=64; | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
list = CategoryGetSymbols( categoryWatchlist, newlist); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( list, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, newlist); | |
CategoryRemoveSymbol( sym, categoryWatchlist, intradaylist); | |
CategoryRemoveSymbol( sym, categoryWatchlist,OPTlist); | |
} | |
} | |
symbol=""; | |
i=0; | |
// erase the watchlist when we process very first symbol | |
for( i = 0; ( symbol = StrExtract(ibc.GetPositionList(), i,',' ) ) != ""; i++ ) | |
{ | |
CategoryAddSymbol( symbol, categoryWatchlist, newlist); | |
CategoryAddSymbol( symbol, categoryWatchlist, intradaylist); | |
printf(symbol + ","); | |
} | |
for( j = 0; ( symbol0 = StrExtract(CategoryGetSymbols( categoryWatchlist,newlist,0 ), j,',' ) ) != ""; j++ ) | |
{ | |
len=StrLen(symbol0); | |
thissymbol=StrMid(symbol0,0,3); | |
if(len>5) | |
{ | |
CategoryRemoveSymbol( symbol0, categoryWatchlist,intradaylist); | |
CategoryAddSymbol(thissymbol, categoryWatchlist, OPTlist); | |
} | |
} | |
for( j = 0; ( symbol0 = StrExtract(CategoryGetSymbols( categoryWatchlist,OPTlist,0 ), j,',' ) ) != ""; j++ ) | |
{ | |
CategoryRemoveSymbol( symbol0, categoryWatchlist,intradaylist); | |
} | |
for( j = 0; ( symbol0 = StrExtract(CategoryGetSymbols( categoryWatchlist,weightlistBUY,0 ), j,',' ) ) != ""; j++ ) | |
{ | |
CategoryRemoveSymbol( symbol0, categoryWatchlist,intradaylist); | |
} | |
for( j = 0; ( symbol0 = StrExtract(CategoryGetSymbols( categoryWatchlist,weightlistSELL,0 ), j,',' ) ) != ""; j++ ) | |
{ | |
CategoryRemoveSymbol( symbol0, categoryWatchlist,intradaylist); | |
} | |
for( j = 0; ( symbol0 = StrExtract(CategoryGetSymbols( categoryWatchlist,specialETF,0 ), j,',' ) ) != ""; j++ ) | |
{ | |
CategoryRemoveSymbol( symbol0, categoryWatchlist,intradaylist); | |
} | |
p=0; | |
for( ; ( symbol = StrExtract(CategoryGetSymbols( categoryWatchlist,intradaylist,0 ), p,',' )) != ""; ) | |
{ | |
p++; | |
} | |
printf("Total Number of tradable in portfolio"+p+"\n"); | |
printf("\n"+"Tradable holding:"+"\n"+CategoryGetSymbols( categoryWatchlist,intradaylist,0)); | |
ibc.CancelAllPendingOrders(); | |
//////VOLUME////// | |
VolGrade=IIf(V/MA(V,100)>2,3,IIf(V/MA(V,100)>=1.5 AND V/MA(V,100)<2,2,IIf(V/MA(V,100)>=0.8 AND V/MA(V,100)<1.5,1,0))); | |
AddColumn(VolGrade,"Vol grade",1.2); | |
IBcStatus = ibc.IsConnected(); | |
averageprice=ibc.GetPositionInfo(Name(), "Avg. cost"); | |
/*sp=IIf(VolGrade>=3,averageprice*1.0035,IIf(VolGrade==2,averageprice*1.0025,IIf(VolGrade==1,averageprice*1.0015,averageprice))); | |
cp=IIf(VolGrade>=3,averageprice*0.9965,IIf(VolGrade==2,averageprice*0.9975,IIf(VolGrade==1,averageprice*0.9985,averageprice))); | |
sp1=sp>=averageprice*1.0035 OR cp<=averageprice*0.9965; | |
sp2=(sp<averageprice*1.0035 AND sp>=averageprice*1.0025) AND (cp>averageprice*0.9965 AND cp<=averageprice*0.9975) ; | |
sp3=(sp<averageprice*1.0025 AND sp>=averageprice*1.0015) AND (cp>averageprice*0.9975 AND cp<=averageprice*0.9985) ; | |
sp4=(sp<averageprice*1.0015 AND sp>averageprice) AND (cp>averageprice*0.9985 AND cp<averageprice);*/ | |
sp1=VolGrade>=3; | |
sp2=VolGrade==2; | |
sp3=VolGrade==1; | |
sp4=VolGrade==0; | |
FilterH24=InWatchList(17) AND sp1; | |
FilterH23=InWatchList(17) AND sp2; | |
FilterH12=InWatchList(17) AND sp3; | |
FilterH00=InWatchList(17) AND sp4; | |
listnumH24 = 30; // we use watchlist 11 for storing sell stocks | |
// erase the watchlist when we process very first symbol | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
oldlist = CategoryGetSymbols( categoryWatchlist, listnumH24); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( oldlist, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, listnumH24 ); | |
} | |
} | |
if ( LastValue( Cum( FilterH24 AND Status( "barinrange" ) ) ) ) | |
CategoryAddSymbol( "", categoryWatchlist, listnumH24 ); | |
listnumH23 = 31; // we use watchlist 11 for storing sell stocks | |
// erase the watchlist when we process very first symbol | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
oldlist = CategoryGetSymbols( categoryWatchlist, listnumH23); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( oldlist, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, listnumH23); | |
} | |
} | |
if ( LastValue( Cum( FilterH23 AND Status( "barinrange" ) ) ) ) | |
CategoryAddSymbol( "", categoryWatchlist, listnumH23); | |
listnumH12 = 32; // we use watchlist 11 for storing sell stocks | |
// erase the watchlist when we process very first symbol | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
oldlist = CategoryGetSymbols( categoryWatchlist, listnumH12); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( oldlist, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, listnumH12); | |
} | |
} | |
if ( LastValue( Cum( FilterH12 AND Status( "barinrange" ) ) ) ) | |
CategoryAddSymbol( "", categoryWatchlist, listnumH12); | |
listnumH00 = 33; // we use watchlist 11 for storing sell stocks | |
// erase the watchlist when we process very first symbol | |
if ( Status( "stocknum" ) == 0 ) | |
{ | |
// retrieve watchlist members | |
oldlist = CategoryGetSymbols( categoryWatchlist, listnumH00); | |
// iterate through the list and remove tickers | |
for ( i = 0; ( sym = StrExtract( oldlist, i ) ) != ""; i++ ) | |
{ | |
CategoryRemoveSymbol( sym, categoryWatchlist, listnumH00); | |
} | |
} | |
if ( LastValue( Cum( FilterH00 AND Status( "barinrange" ) ) ) ) | |
CategoryAddSymbol( "", categoryWatchlist, listnumH00); | |
Range = 10; | |
//Filter= ((FilterB+FilterS)==1) AND Filt1 AND !Name()=="$NDX" ; | |
Filter= (filterb +filters)>0 AND !Name()=="$NDX" ; | |
AddColumn(C,"Price",1.2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment