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 ....
WiseTrader Toolbox
#1 Selling Amibroker Plugin featuring:
Advanced Adaptive Indicators
Advanced Pattern Exploration
Neural Networks
And Much More ....
Exit for Amibroker (AFL)
Copy & Paste Friendly
Back
/* Plot(WMA(C,50),"",colorGold,styleThick|styleLine|styleDots); Plot(WMA(C,100),"",colorBrightGreen,styleThick|styleLine|styleDashed); Plot(WMA(C,170),"",colorYellow,styleLine); Plot(WMA(C,200),"",colorRed,styleLine|styleThick); //Plot(MA(C,10),"",colorAqua,styleLine); Plot(MA(C,25),"",colorYellow,styleLine|styleDashed|styleThick); */ Prd1=Param("ATR Period",4,1,20,1); Prd2=Param("Look Back",8,1,20,1); green = HHV(LLV(L,Prd1)+ATR(Prd1),Prd2); red = LLV(HHV(H,Prd1)-ATR(Prd1),Prd2); HighClosePercent = (H - C)*100/H; HighLowPercent = MA((H - L)*100/H,25); barColor=IIf(C>Green ,colorBrightGreen,IIf(C < RED,colorRed,IIf(HighClosePercent>5,colorYellow,IIf(HighLowPercent>5 AND ROC(C,1,True)<-3,colorRed,colorWhite)))); SetBarFillColor( IIf(C>Green AND ROC(C,1,True)<-4.5,colorBlue,colorBlack)); flowerOpen = O; flowerClose = C; flowerHigh= H; flowerLow = L; _SECTION_BEGIN("Price"); PlotOHLC( IIf(flowerOpen<flowerClose, flowerOpen, flowerClose),flowerHigh,flowerLow,IIf(flowerOpen<flowerClose, flowerClose, flowerOpen), "Close", barColor, styleNoTitle | styleCandle); //Plot (Close,"", IIf( C > O, ParamColor("Up Color", colorWhite ), ParamColor("Down Color", colorRed )),ParamStyle( "Style", styleCandle | styleThick, maskAll)); SetChartOptions(0,chartShowArrows|chartShowDates); _SECTION_END(); _SECTION_BEGIN("Background"); SetChartOptions(0,chartShowArrows|chartShowDates); if( ParamToggle("Tooltip shows", "All Values|Only Prices" ) ) { ToolTip=StrFormat("Open: %g\nHigh: %g\nLow: %g\nClose: %g (%.1f%%)\nVolume: "+NumToStr( V, 1 ), O, H, L, C, SelectedValue( ROC( C, 1 ))); } SetChartBkColor(ParamColor("Outer panel color ",colorBlack)); // color of outer border SetChartBkGradientFill( ParamColor("Inner panel color upper half",colorBlack),ParamColor("Inner panel color lower half",colorBlack),ParamColor("Titleblock",colorDarkGrey )); //color of inner panel _SECTION_END(); { // Data Path DataPath1 = ParamStr("DataPath ","Data"); _N(DataPath = "mrtq13-"+DataPath1 +"\\"); //this is the folder where data is put // Define Required Global Variables global TrailBarStart,PeakValue,TrailStopValue,EvenStopPS,ProfitStopPS,MaxLossPS; global TurnOver,TitleS,Qty,LeftoverCash,BuyValue,MarketValue,ReturnedTotalbuyprice,RawCashGain; global CashReturned,TotalbuypriceGain,PSRequiredGain,EvenStopPC,TrailPercent,Title_1,Title_2; global DBUY,TBUY,DSELL,TSELL,AlertByte,IDList,TotalEquity; // Set Core Global Variables _N(VersionStr="ManualStopSet V3.05"); SetBarsRequired(100000, 100000 ); BC = BarCount-1; BNUM = BarIndex(); DNUM = DateNum(); TNUM = TimeNum(); FirstBarVis = Status("firstvisiblebar"); LastBarVis = Status("lastvisiblebar")-1; SelectedBar = SelectedValue(BNUM); AlertByte = 2; Title_1=""; Title_2="";Tally=0; printf("SelectedBar:"+SelectedBar+"\n"); printf("BarCount:"+BC+"\n"); Overide="No"; //Diagnostics // Load ID-List (Trade Lists) // Make sure directory exists. fmkdir(DataPath); // Load ID-List. IDList=""; // Ensure IDList is defined as a string. (If file not exist 1st run). _N(IDListFile = DataPath + "ID-List"); fh = fopen( IDListFile, "r"); if( fh ) {// If exist, Get list. IDList = fgets(fh); fclose( fh ); } else { IDList="<END>,"; // If not exist, Write File when we create a trade. } // Determin EOD(0) or IntraDay(1) mode TimeFrame = Interval(); EODRT = IIf(TimeFrame>=inDaily,0,1); // Set Parameters // MSS Param //TotalEquity = Param("TotalEquity",0,0,10000000,0.01); BuyAt = Param("EntryPrice",0,0,10000,0.01); TotalShare=Param("ShareQuantity",0,0,7000,1); SellAtP = Param("ExitPrice",0,0,10000,0.01); CommisionX1=0;//CommisionX1 = Param("Commision",0,0,3000,0.01); StopLoss = Param("StopLoss",7,0,100,0.01); //Percentage of Cash TrailStop = Param("Fixed TrailingStop",8,0,100,0.01); //Percentage of HH/LL ProfitStop = Param("ProfitStop",10,0,100,0.01); //Percentage of Cash HoldingsAdj = Param("HoldingsAdj",0,-100,100,1); //Adj Calc Holdings MultiTrade = Param("MultiTrade",0,0,9,1); //View/Set Calcs for specific Multi Trade CreateTrade = ParamTrigger("Create Trade","<Create>"); RemoveTrade = ParamTrigger("Modify Trade<R>","<Remove>"); CloseTrade = ParamTrigger("Modify Trade<C>","<Close>"); OpenTrade = ParamTrigger("Modify Trade<O>","<Re-Open>"); TradeType = ParamToggle( "Long/Short", "Long|Short",0); //Totalbuyprice = Param("Totalbuyprice",300000,0,700000,0.01); // CLA Param DisplayPlot = ParamToggle("DisplayPlot","Single|Multi",0); TitleStyleT = ParamList("DisplayText","Detail/Tally|Tally|Detail|None"); TitleSlide = Param("TitleSlide",1,0,30,1); // Set Default BuyBar & BuyAt etc SellAt=SellAtP; if (SelectedBar == LastBarVis) SelectedBar = BC; BuyBar = SelectedBar; SellBar=BC; if (SellAt == 0) SellAt=C[SellBar]; if (BuyAt == 0) BuyAt=O[BuyBar]; } /////////////////////////////////////////////////////////////////////// // End of Initialize /////////////////////////////////////////////////////////////////////// _SECTION_BEGIN("Pivot"); nBars = Param("Number of bars", 15, 5, 40); LP=Param("LookBack Period",250,1,500,1); bShowTCZ = Param("Show TCZ", 0, 0, 1); nExploreBarIdx = 0; nExploreDate = 0; nCurDateNum = 0; DN = DateNum(); DT = DateTime(); bTCZLong = False; bTCZShort = False; nAnchorPivIdx = 0; ADX8 = ADX(8); if(Status("action")==1) { bDraw = True; bUseLastVis = 1; } else { bDraw = False; bUseLastVis = False; bTrace = 1; nExploreDate = Status("rangetodate"); for (i=LastValue(BarIndex());i>=0;i--) { nCurDateNum = DN[i]; if (nCurDateNum == nExploreDate) { nExploreBarIdx = i; } } } GraphXSpace=7; if (bDraw) { } aHPivs = H - H; aLPivs = L - L; aHPivHighs = H - H; aLPivLows = L - L; aHPivIdxs = H - H; aLPivIdxs = L - L; aAddedHPivs = H - H; aAddedLPivs = L - L; aLegVol = H - H; aRetrcVol = H - H; nHPivs = 0; nLPivs = 0; lastHPIdx = 0; lastLPIdx = 0; lastHPH = 0; lastLPL = 0; curPivBarIdx = 0; aHHVBars = HHVBars(H, nBars); aLLVBars = LLVBars(L, nBars); aHHV = HHV(H, nBars); aLLV = LLV(L, nBars); nLastVisBar = LastValue( Highest(IIf(Status("barvisible"), BarIndex(), 0))); curBar = IIf(nlastVisBar > 0 AND bUseLastVis, nlastVisBar, IIf(Status("action")==4 AND nExploreBarIdx > 0, nExploreBarIdx, LastValue(BarIndex()))); curTrend = ""; if (aLLVBars[curBar] < aHHVBars[curBar]) curTrend = "D"; else curTrend = "U"; if (curBar >= LP) { for (i=0; i<LP; i++) { curBar = IIf(nlastVisBar > 0 AND bUseLastVis, nlastVisBar-i, IIf(Status("action")==4 AND nExploreBarIdx > 0, nExploreBarIdx-i, LastValue(BarIndex())-i)); if (aLLVBars[curBar] < aHHVBars[curBar]) { if (curTrend == "U") { curTrend = "D"; curPivBarIdx = curBar - aLLVBars[curBar]; aLPivs[curPivBarIdx] = 1; aLPivLows[nLPivs] = L[curPivBarIdx]; aLPivIdxs[nLPivs] = curPivBarIdx; nLPivs++; } } else { if (curTrend == "D") { curTrend = "U"; curPivBarIdx = curBar - aHHVBars[curBar]; aHPivs[curPivBarIdx] = 1; aHPivHighs[nHPivs] = H[curPivBarIdx]; aHPivIdxs[nHPivs] = curPivBarIdx; nHPivs++; } } } } curBar = IIf(nlastVisBar > 0 AND bUseLastVis, nlastVisBar, IIf(Status("action")==4 AND nExploreBarIdx > 0, nExploreBarIdx, LastValue(BarIndex())) ); if (nHPivs >= 2 AND nLPivs >= 2) { lastLPIdx = aLPivIdxs[0]; lastLPL = aLPivLows[0]; lastHPIdx = aHPivIdxs[0]; lastHPH = aHPivHighs[0]; nLastHOrLPivIdx = Max(lastLPIdx, lastHPIdx); nAddPivsRng = curBar - nLastHOrLPivIdx; aLLVAfterLastPiv = LLV(L, nAddPivsRng); nLLVAfterLastPiv = aLLVAfterLastPiv[curBar]; aLLVIdxAfterLastPiv = LLVBars(L, nAddPivsRng); nLLVIdxAfterLastPiv = curBar - aLLVIdxAfterLastPiv[curBar]; aHHVAfterLastPiv = HHV(H, nAddPivsRng); nHHVAfterLastPiv = aHHVAfterLastPiv[curBar]; aHHVIdxAfterLastPiv = HHVBars(H, nAddPivsRng); nHHVIdxAfterLastPiv = curBar - aHHVIdxAfterLastPiv[curBar]; if (lastHPIdx > lastLPIdx) { /* There are at least two possibilities here. One is that the previous high was higher, indicating that this is a possible short retracement or one in the making. The other is that the previous high was lower, indicating that this is a possible long retracement in the working. However, both depend on opposing pivots. E.g., if I find higher highs, what if I have lower lows? If the highs are descending, then I can consider: - a lower low, and leave it at that - a higher high and higher low - a lower low and another lower high */ if (aHPivHighs[0] < aHPivHighs[1]) { if (nLLVAfterLastPiv < aLPivLows[0] AND (nLLVIdxAfterLastPiv - lastHPIdx - 1) >= 1 AND nLLVIdxAfterLastPiv != curBar ) { // -- OK, we'll add this as a pivot. // Mark it for plotting... aLPivs[nLLVIdxAfterLastPiv] = 1; aAddedLPivs[nLLVIdxAfterLastPiv] = 1; // ...and then rearrange elements in the // pivot information arrays for (j=0; j<nLPivs; j++) { aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)]; aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)]; } aLPivLows[0] = nLLVAfterLastPiv; aLPivIdxs[0] = nLLVIdxAfterLastPiv; nLPivs++; // -- Test whether to add piv given last piv is high // AND we have lower highs } // -- Here, the last piv is a high piv, and we have // higher-highs. The most likely addition is a // Low piv that is a retracement. } else { if (nLLVAfterLastPiv > aLPivLows[0] AND (nLLVIdxAfterLastPiv - lastHPIdx - 1) >= 1 AND nLLVIdxAfterLastPiv != curBar ) { // -- OK, we'll add this as a pivot. // Mark it for plotting... aLPivs[nLLVIdxAfterLastPiv] = 1; aAddedLPivs[nLLVIdxAfterLastPiv] = 1; // ...and then rearrange elements in the // pivot information arrays for (j=0; j<nLPivs; j++) { aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)]; aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)]; } aLPivLows[0] = nLLVAfterLastPiv; aLPivIdxs[0] = nLLVIdxAfterLastPiv; nLPivs++; // -- Test whether to add piv given last piv is high // AND we have lower highs } // -- The last piv is a high and we have higher highs // OR lower highs } /* **************************************************************** Still finding missed pivot(s). Here, the last piv is a low piv. **************************************************************** */ } else { // -- First case, lower highs if (aHPivHighs[0] < aHPivHighs[1]) { if (nHHVAfterLastPiv < aHPivHighs[0] AND (nHHVIdxAfterLastPiv - lastLPIdx - 1) >= 1 AND nHHVIdxAfterLastPiv != curBar ) { // -- OK, we'll add this as a pivot. // Mark that for plotting aHPivs[nHHVIdxAfterLastPiv] = 1; aAddedHPivs[nHHVIdxAfterLastPiv] = 1; // ...and then rearrange elements in the // pivot information arrays for (j=0; j<nHPivs; j++) { aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-(j+1)]; aHPivIdxs[nHPivs-j] = aHPivIdxs[nhPivs-(j+1)]; } aHPivHighs[0] = nHHVAfterLastPiv; aHPivIdxs[0] = nHHVIdxAfterLastPiv; nHPivs++; // -- Test whether to add piv given last piv is high // AND we have lower highs } // -- Second case when last piv is a low piv, higher highs // Most likely addition is high piv that is a retracement. // Considering adding a high piv as long as it is higher } else { // -- Where I have higher highs, if (nHHVAfterLastPiv > aHPivHighs[0] AND (nHHVIdxAfterLastPiv - lastLPIdx - 1) >= 1 AND nHHVIdxAfterLastPiv != curBar ) { // -- OK, we'll add this as a pivot. // Mark it for plotting... aHPivs[nHHVIdxAfterLastPiv] = 1; aAddedHPivs[nHHVIdxAfterLastPiv] = 1; // ...and then rearrange elements in the // pivot information arrays for (j=0; j<nHPivs; j++) { aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-(j+1)]; aHPivIdxs[nHPivs-j] = aHPivIdxs[nhPivs-(j+1)]; } aHPivHighs[0] = nHHVAfterLastPiv; aHPivIdxs[0] = nHHVIdxAfterLastPiv; nHPivs++; // -- Test whether to add piv given last piv is high // AND we have lower highs } } } // -- If there are at least two of each } /* **************************************** // -- Done with finding pivots ***************************************** */ if (bDraw) { // -- OK, let's plot the pivots using arrows PlotShapes( IIf(aHPivs==1, shapeDownArrow, shapeNone), colorRed, layer = 0, yposition = High, offset = -10); //PlotShapes( IIf(aHPivs==1, shapeSmallSquare, shapeNone), colorBlack, layer = 0, yposition = High, offset = 12); PlotShapes( IIf(aAddedHPivs==1, shapeDownArrow, shapeNone), colorRed,layer = 0, yposition = High, offset = -10); //PlotShapes( IIf(aAddedHPivs==1, shapeSmallSquare, shapeNone), colorBlack, layer = 0, yposition = High, offset = 12); //PlotShapes( IIf(aLPivs==1, shapeSmallSquare, shapeNone), colorBrightGreen, layer = 0, yposition = Low, offset = -9); //PlotShapes( IIf(aLPivs==1, shapeSmallSquare, shapeNone), colorBlack, layer = 0, yposition = Low, offset = -12); //PlotShapes( IIf(aAddedLPivs==1, shapeDownArrow, shapeNone), colorGold, layer = 0, yposition = Low, offset = -15); //PlotShapes( IIf(aAddedLPivs==1, shapeSmallSquare, shapeNone), colorBlack, layer = 0, yposition = Low, offset = -13); } _SECTION_END(); /////////////////////////////////////////////////////////////////////// // Define Procedures/Functions /////////////////////////////////////////////////////////////////////// procedure RemoveEntry(RemSym) { // Remove entry from IDList NewIDList = ""; for( i = 0; ( sym = StrExtract( IDList, i ) ) != "<END>"; i++ ) { if (sym != RemSym) {NewIDList = NewIDList + sym + ",";} } IDList = NewIDList+"<END>,"; fh = fopen( IDListFile, "w"); if( fh ) { fputs( IDList , fh ); fclose( fh ); } } procedure AddEntry(AddSym) { // Add entry to IDList IDList = AddSym + "," + IDList; printf(IDList); fh = fopen( IDListFile, "w"); if( fh ) { fputs( IDList , fh ); fclose( fh ); } } procedure DoCalculation(Sym) { // All variables should be global // printf("Calculating: "+Sym+"\n"); Turnover = (C*V); //For Display // Manual Flip (If Sell Selected before buy) // Mabie should also flip SellAt open/close. if (SellBar < BuyBar) { BuyBar1 = BuyBar;BuyBar=SellBar;SellBar=BuyBar1; BuyAt1 = BuyAt;BuyAt=SellAt;SellAt=BuyAt1; } // Calc Holding Stats Totalbuyprice=TotalShare*BuyAt; //CommisionX1=(Totalbuyprice*CommisionX1)/100; FinalBuyValue=Totalbuyprice+CommisionX1; // Calc Holding Stats Avail = Totalbuyprice-CommisionX1; Qty = (int(Avail/BuyAt))+HoldingsAdj; BuyValue = Qty*BuyAt; LeftoverCash = (Totalbuyprice-BuyValue)-CommisionX1; MarketValue = Qty*SellAt; RawCashGain = ((MarketValue)-(BuyValue))*((TradeType*-2)+1); //LongShortFlip CashReturned = RawCashGain-(CommisionX1*2); ReturnedTotalbuyprice = Totalbuyprice+CashReturned; TotalbuypriceGain = (CashReturned/Totalbuyprice)*100; // Total Percent Gained Trail_Ref = BC - SellBar; Range_Ref = SellBar - BuyBar+1; PeakValue = LastValue(Ref(HHV(H,Range_Ref),-Trail_Ref)); Peak_Ref = LastValue(Ref(HHVBars(H,Range_Ref),-Trail_Ref)); TrailBarStart = SellBar-Peak_Ref; TrailStopValue = PeakValue - (PeakValue * (TrailStop/100)); TrailPercent = 100-((Close[SellBar]/PeakValue)*100); // Calc Even Stop EvenStopValue = (Qty*BuyAt) + (CommisionX1*2); EvenStopPS = EvenStopValue/Qty; EvenStopPC = ((EvenStopPS/Buyat)*100)-100; // Calc Profit Stop ProfitStopCalc = FinalBuyValue*(ProfitStop/100); ProfitStopValue = FinalBuyValue+ ProfitStopCalc + (CommisionX1*2); ProfitStopPS = ProfitStopValue/Qty; PSRequiredGain = ((ProfitStopPS/BuyAt)*100)-100; // Calc Loss Stop MaxLossCalc = Totalbuyprice*(StopLoss/100); MaxLossValue = Totalbuyprice- MaxLossCalc + (CommisionX1*2); MaxLossPS = MaxLossValue/Qty; } procedure DisplayPlots(Sym,symid) { // Plot Vertical Buy Bar. (Blue) VLine = IIf(BuyBar==BNUM,1,0); //Plot (VLine ,"BuyBar", colorGrey40, styleHistogram | styleOwnScale,0,1); // Plot Vertical Sell Bar. (Blue) // VLine = IIf(SellBar==BNUM,1,0); // Plot (VLine ,"BuyBar", colorBlue, styleHistogram | styleOwnScale,0,1); //Plot MultiTrade Number PlotText(symid,Buybar-1,ProfitStopPS,colorRed,colorWhite); // Plot Horizontal Buy Bar. (Yellow) x0 = Buybar ; y0 = BuyAt; x1 = SellBar ; y1 = y0; Hline = LineArray(x0,y0,x1,y1,0); //Plot(HLine ,"BuyPrice",colorTeal ,ParamStyle("BuyStyle",styleLine|styleDashed,maskAll)); // Plot Trade Trend (BuyBar to SellBar/SellAT - Blue Dashed Line) x0 = Buybar ; y0 = BuyAt; x1 = Sellbar ; y1 = SellAt; // y1 = C[Sellbar]; Hline = LineArray(x0,y0,x1,y1,0); //Plot(HLine ,"TradeTrend",colorOrange,styleLine|styleDashed); // Plot Long/Short Trail Stop Trend x0 = TrailBarStart; y0=PeakValue; x1 = SellBar; y1 = C[SellBar]; Line = IIf((X1 > X0),LineArray(x0,y0,x1,y1,0),LineArray(x1,y1,x0,y0,0) ); //Reverse //Plot(Line,"TrailStop",colorViolet,styleLine|styleDots); // Plot TrailStop Horizontal (ColorViolet) x0 = Buybar ; y0 = TrailStopValue; x1 = SellBar ; y1=y0; Hline = LineArray(x0,y0,x1,y1,0); Plot(HLine ,"TrailStop",ParamColor( "TrailStopColor", colorSeaGreen ),ParamStyle("TrailStopStyle",styleDashed|styleThick,maskAll));; // Plot BreakEven Horizontal (ColorGreen) x0 = Buybar ; y0 = EvenStopPS; x1 = SellBar ; y1=y0; Hline = LineArray(x0,y0,x1,y1,0); Plot(HLine ,"EvenStop",ParamColor( "EvenStopColor", colorGrey50 ),ParamStyle("EvenStopStyle",styleLine|styleDashed|styleStaircase|styleThick|StyleHidden,maskAll)); // Plot ProfitStop Horizontal (ColorWhite) x0 = Buybar ; y0 = ProfitStopPS ; x1 = SellBar ; y1=y0; Hline = LineArray(x0,y0,x1,y1,0); Plot(HLine ,"ProfitStop",ParamColor( "ProfitStopColor", colorWhite ),ParamStyle("ProfitStopStyle",styleLine|styleStaircase|styleThick|StyleHidden,maskAll)); // Plot LossStop Horizontal (ColorRed) x0 = Buybar ; y0 = MaxLossPS; x1 = SellBar ; y1=y0; Hline = LineArray(x0,y0,x1,y1,0); Plot(HLine ,"StopLoss",ParamColor( "StopLossColor", colorRed ),ParamStyle("StopLossStyle",styleLine|styleStaircase|styleThick,maskAll)); }// End DisplayPlots WorkingDays = SellBar - BuyBar+1;//(SellBar-BuyBar); Maturestock = WorkingDays>=4; Immaturestock = WorkingDays<4; Totalbuyprice=TotalShare*BuyAt; //CommisionX1=(Totalbuyprice*CommisionX1)/100; FinalBuyValue=Totalbuyprice+CommisionX1; procedure CreateTitleDetail(Sym) { // Create Title Detail ssd = StrFormat("%.0f",DNUM[BuyBar]); ssD = StrRight(ssD,6); ssD = StrRight(ssD,2)+"-"+StrLeft(StrRight(ssD,4),2)+"-20"+StrLeft(ssD,2); _N(BuyDate = ssD ); //_N(BuyDate = StrLeft(ssD,10)); //_N(BuyDate = StrFormat("%.0f",DNUM[BuyBar])); _N(BuyTime = StrFormat("%.0f",TNUM[BuyBar])); _N(SellDate = StrFormat("%.0f",DNUM[SellBar]));_N(SellTime = StrFormat("%.0f",TNUM[SellBar])); _N(Title_1 = ""+ "\\c11 BuyDate: \\c11"+ BuyDate +//"/" + BuyTime + //"\n\\c29 SellBar: \\c23"+ SellBar+"\\c29 SellDT: \\c23"+ SellDate + "/" + SellTime + //"\n\\c38 Commision \\c38"+CommisionX1+ "\n\\c34 Entry Price: \\c34"+BuyAt+ //"\n\\c38 SellAt \\c01"+SellAt+ "\n\\c33 Share Quantity: \\c33"+TotalShare+ "\n\\c36 TotalBuyPrice: \\c36"+Totalbuyprice+ "\n"+EncodeColor(colorRose)+"-------------------------" + //"\n\\c21 BuyValue with Commission: \\c01: "+FinalBuyValue+ //"\n\\c21 LeftoverCash \\c01: "+LeftoverCash+ "\n\\c25 Current MarketValue \\c25: "+MarketValue/100+ "\n\\c54 Profit Gain \\c54: "+RawCashGain+ //"\n\\c21 CashReturned \\c01: "+ CashReturned + //"\n\\c21 ReturnedTotalbuyprice \\c01: "+ReturnedTotalbuyprice+ "\n\\c48 Profit Percentage \\c48: "+TotalbuypriceGain+"%"+ "\n"+EncodeColor(colorRose)+"-------------------------" + //"\n\\c21 PSRequiredGain \\c01: "+PSRequiredGain+"%"+ //"\n\\c29 EvenStop : " + Prec(EvenStopPC,4) + "%, " + EvenStopPS + "\n\\c44 ProfitTaking: " + ProfitStop + "%, " + ProfitStopPS + "\n\\c07 StopLoss : " + StopLoss + "%, " + MaxLossPS + "\n\\c51 TrailStop: \\c51" + TrailStop + "%, " + TrailStopValue + //"\n\\c08 Working Days " +"\\c02@ \\c07" + WorkingDays+WriteIf(Maturestock," \\c08[Mature]"," ")+WriteIf(Immaturestock,"\\c04[Immature]"," ")+ "\n"+EncodeColor(colorRose)+"-------------------------" + //"\n\\c29 TrailVariance: \\c01" +TrailPercent + "% "+ ""); }// End CreateTitle Totalbuyprice=TotalShare*BuyAt; CommisionX1=(Totalbuyprice*CommisionX1)/100; FinalBuyValue=Totalbuyprice+CommisionX1; procedure LoadID(FileName) {// Load ID printf("loading: '"+FileName+"'\n"); fh = fopen( FileName, "r"); if( fh ) {// File open for read TradeType = StrToNum(fgets( fh )); TotalShare= StrToNum(fgets( fh )); //StopLoss=StrToNum(fgets( fh )); TimeFrame = StrToNum(fgets( fh )); DBUY = StrToNum(fgets( fh )); TBUY = StrToNum(fgets( fh )); DSELL = StrToNum(fgets( fh )); TSELL = StrToNum(fgets( fh )); BuyAt = StrToNum(fgets( fh )); SellAt = StrToNum(fgets( fh )); HoldingsAdj = StrToNum(fgets( fh )); ProfitStop = StrToNum(fgets( fh )); StopLoss = StrToNum(fgets( fh )); TrailStop = StrToNum(fgets( fh )); Totalbuyprice = StrToNum(fgets( fh )); CommisionX1= StrToNum(fgets( fh )); AlertByte = StrToNum(fgets( fh )); fclose( fh ); TitleS="ReadFile"; }// End file open for read else {// File not found printf("File Not Found\n"); TitleS="Error"; }// End file not found }// End Load ID procedure SaveID(FileName) {// Write ID printf("saving: '"+FileName+"'\n"); fh = fopen( FileName, "w"); if( fh ) {// File open for write fputs( StrFormat("%.00f\n",TradeType ), fh ); //fputs( StrFormat("%.00f\n",StopLoss ), fh ); fputs( StrFormat("%.00f\n",TotalShare), fh ); fputs( StrFormat("%.00f\n",TimeFrame ), fh ); fputs( StrFormat("%.00f\n",DBUY ), fh ); fputs( StrFormat("%.00f\n",TBUY ), fh ); fputs( StrFormat("%.00f\n",DSELL ), fh ); fputs( StrFormat("%.00f\n",TSELL ), fh ); fputs( StrFormat("%.02f\n",BuyAt ), fh ); fputs( StrFormat("%.02f\n",SellAt ), fh ); fputs( StrFormat("%.02f\n",HoldingsAdj ), fh ); fputs( StrFormat("%.02f\n",ProfitStop ), fh ); fputs( StrFormat("%.02f\n",StopLoss ), fh ); fputs( StrFormat("%.02f\n",TrailStop ), fh ); fputs( StrFormat("%.02f\n",Totalbuyprice ), fh ); fputs( StrFormat("%.02f\n",CommisionX1 ), fh ); fputs( StrFormat("%.00f\n",AlertByte ), fh ); fclose( fh ); TitleS = "SaveFile"; }// End File open for write }// End WriteID /////////////////////////////////////////////////////////////////////// // End Define Procedures/Functions /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // Start core section. /////////////////////////////////////////////////////////////////////// { if (OpenTrade == 1) {// Open trade. AlertIf( 1, "", "Open trade", 0,3 ); IDName = Name()+"-"+MultiTrade; TrailName = DataPath + IDName; LoadID(TrailName); SellAt=0;DSELL=0;TSELL=0; SaveID(TrailName); }// End Open trade if (CloseTrade == 1) {// Close trade. AlertIf( 1, "", "Close trade", 0,3 ); IDName = Name()+"-"+MultiTrade; TrailName = DataPath + IDName; LoadID(TrailName); DSELL = DNUM[SelectedBar];TSELL = TNUM[SelectedBar]; SellAt=C[SelectedBar]; if (SellAtP != 0) {SellAt=SellAtP;} SaveID(TrailName); }// End Close trade if (RemoveTrade == 1) {// Remove Entry AlertIf( 1, "", "Remove trade", 0,3 ); IDName = Name()+"-"+MultiTrade; RemoveEntry(IDName); }// End Remove Entry if (CreateTrade == 1) {// Write Data AlertIf( 1, "", "Write trade", 0,3 ); // Set name & add to master index IDName = Name()+"-"+MultiTrade; RemoveEntry(IDName); AddEntry(IDName); TrailName = DataPath + IDName; // Write data to file DBUY = DNUM[BuyBar]; TBUY = TNUM[BuyBar]; DSELL = 0; TSELL = 0; SellAT = 0; TotalEquity = 0; SaveID(TrailName); }// End Write data // Calc & Display IDName = Name()+"-"+MultiTrade; printf("Current: "+IDName+"\n\n"); // Create Title Tally Header. Title_2 = "-------------------------\n";//"\\c09 SYMBOLS- GAIN\n\n"; if (DisplayPlot == 0) {// DisplayPlot // Plot Price & Volume. PlotForeign( GetBaseIndex(), GetBaseIndex(), colorAqua, styleLine | styleOwnScale); //Plot( Volume, _DEFAULT_NAME(), colorBlueGrey , styleHistogram | styleOwnScale | styleThick ); if (StrFind(IDList,Name()) == 0) {// Symbol not found in IDList, use selected. TitleS="NoFile"; DoCalculation(Name()); DisplayPlots(Name(),""); CreateTitleDetail(Name()); }// End Symbol not found else {// Symbol found in IDList. if (StrFind(IDList,IDName) == 0) {// Exact symbol not found in IDList, use selected. TitleS="NoFile"; DoCalculation(Name()); DisplayPlots(Name(),""); CreateTitleDetail(Name()); }// End Exact symbol not found }// End Symbol found }// End DisplayPlot flagX = 0; for( i = 0; ( sym = StrExtract( IDList, i ) ) != "<END>"; i++ ) {// Loop TrailName = DataPath + sym; symleft = StrLeft(sym, StrFind(sym,"-")-1); CurrentSym = Name(); symid = StrRight(sym, StrLen(sym)-StrFind(sym,"-")); // printf("SymLeft: "+symleft+" Current: "+CurrentSym+"\n\n"); // Set Ticker/Trade Environment. SetForeign(symleft); // Load & Do Calculation LoadID(TrailName); TimeFrameSet(TimeFrame); // after load //BuyBar = DBUY; // Calc Buy & Sell Bar // BuyBar = LastValue(DBUY)+LastValue(Cum((DBUY==DBUY) AND (DBUY<DBUY))); //BuyBar = LastValue(DBUY,True); BuyBar = LastValue(Cum(DNUM<DBUY))+LastValue(Cum((DNUM==DBUY) AND (TNUM<TBUY))); SellBar = LastValue(Cum(DNUM<DSELL))+LastValue(Cum((DNUM==DSELL) AND (TNUM<TSELL))); XBar = SellBar ; // Overide Sell //if ( (SelectedBar != BC) AND (sym == IDName ) AND (TitleS != "Error")) {SellBar = SelectedBar; SellAt = Close[SellBar];Overide=" @ "+SellBar+" $"+SellAt;} if (SellBar == 0) {SellBar=BC; SellAt = Close[SellBar];} // Use loaded Sell Price if (sym == IDName) {// Exact match, Overide Sell Price. if (SellAtP != 0) {SellAt = SellAtP;} }// End Exact match // Do the Trade Calcs DoCalculation(sym); //Doesn't actualy use passed symbol. // Determine Stops from LastBar/SelectedBar LongMode ProfitStopFlag = IIf( C[SellBar] >= ProfitStopPS ,True,False); EvenStopFlag = IIf( C[SellBar] >= EvenStopPS,True,False); StopLossFlag = IIf( C[SellBar] <= MaxLossPS,True,False); TrailStopFlag = IIf(TrailPercent >= TrailStop,True,False); // Generate Alerts Strings for Display PSD = WriteIf(ProfitStopFlag,"\\c15# ","\\c01. "); ESD = WriteIf(EvenStopFlag,"\\c15# ","\\c01. "); LSD = WriteIf(StopLossFlag,"\\c15# ","\\c01. "); TSD = WriteIf(TrailStopFlag,"\\c15# ","\\c01. "); WorkingDays = SellBar - BuyBar+1; NDays = XBar - BuyBar+1; BeforeEntry = DBUY > DNUM ; WorkingDays = IIf(BeforeEntry,-1 * (WorkingDays -1),WorkingDays ); Maturestock = WorkingDays>=4; BuyingDay = WorkingDays==1; Immaturestock = WorkingDays<4 AND DBUY<=DNUM AND WorkingDays!=1; MatureString ="\\c08 [Days" +"\\c02@\\c07" + WorkingDays+"] "+WriteIf(Maturestock," \\c08[Mature]","")+WriteIf(Immaturestock,"\\c04[Immature]","")+WriteIf(BuyingDay ,"\\c52[BuyingDay]","")+WriteIf(BeforeEntry ,"\\c04[BeforeEntry]",""); //MatureString =StrFormat(" %.0f ",DBUY)+ StrFormat(" %.0f ",SellBar )+"\\c08 [Days" +"\\c02@\\c07" + WorkingDays+"] "+WriteIf(Maturestock," \\c08[Mature]"," ")+WriteIf(Immaturestock,"\\c04[Immature]"," ")+WriteIf(BeforeEntry ,"\\c04[BeforeEntry]"," "); if(flagX ==0){ nid = sym ; } if (sym == IDName) { flagX = 1; nid = IDName; en = BuyAt; wd = StrToNum(StrFormat("%.0f",NDays )); awd = StrToNum(StrFormat("%.0f",WorkingDays)); } sss = StrFormat("%.0f",DBUY ); sss = StrRight(sss,6); sss = StrRight(sss,2)+"-"+StrLeft(StrRight(sss,4),2)+"-20"+StrLeft(sss,2)+"] " + MatureString ; // Create Title Tally Strings ListAlerts = PSD + ESD + LSD + TSD; Tally = Tally + CashReturned; Title_2 = Title_2 + " \\c02" + StrLeft(sym,StrLen(sym)-2) + ": [Buy " + sss + ""+ "\n\\c41 Entry @ "+BuyAt+ "\\c10 -- \\c33 NOS: \\c33"+TotalShare+ "\\c10 --\\c36 Value: \\c36"+Totalbuyprice+ "\n\\c44 Profit $" + StrFormat("%08.2f",CashReturned) + " \\c51 Percent: " + StrFormat("%+06.2f",TotalbuypriceGain) + "%\n"+ //"\\c44 ProfitTaking: " + ProfitStop + "%, " + ProfitStopPS + " \\c07 StopLoss : " + StopLoss + "%, " + MaxLossPS + " \\c51 TrailStop: \\c51" + TrailStop + "%, " + TrailStopValue + //"\n"+ EncodeColor(colorRose)+"-------------------------\n"; if (sym == IDName) {// Exact match, Create title. CreateTitleDetail(sym); }// End Exact match // Select Plot Display if (DisplayPlot == 1) {Plot(C,"Close:"+symleft,i+16,styleLine | styleOwnScale);} if ((DisplayPlot == 0) AND (symleft == CurrentSym)) {DisplayPlots(sym,symid);} // Cleanup TimeFrameRestore(); RestorePriceArrays(); }// End loop // End of Calc & Display // Dynamic Title TSpace = ""; for( i = 0; i<TitleSlide ; i++ ) {TSpace = TSpace + "\n";} HighLowPercent_2 = (H - L)*100/H; MAHighClosePercent = MA((H - C)*100/H,64); Title_Header =Name()+ " "+ WriteVal( SelectedValue( DateTime() ), formatDateTime) + " Open - "+O + " High - "+ H + " Low - "+ L +" Close - "+C + StrFormat(" (%.1f%%) ", SelectedValue( ROC( C, 1 ) )) + "\nVolume - " +V + " "+StrFormat("(%.1f%%) ", SelectedValue(ROC(V,1))) +" Average Volume(12) - " + MA(V,12) + "\nHC : "+StrFormat("(%.1f%%) ", HighClosePercent ) +" AHC(64): "+StrFormat("(%.1f%%) ", MAHighClosePercent )+ " AHL(25): "+StrFormat("(%.1f%%) ", HighLowPercent )+ " H-L: "+StrFormat("(%.1f%%) ", HighLowPercent_2 )+ "\\c36"; Title_NetProfitLoss = "-------------------------\n"+"\\c45 Net Profit/Loss : " + Tally + " " +EncodeColor(colorRose)+"\n"; Title_1 = ""; if (TitleStyleT == "Detail") {Title = Title_Header + Title_1;} if (TitleStyleT == "Tally") {Title = Title_Header + Title_2 + "\\c09 Tally:$" + Tally + " " ;} if (TitleStyleT == "Detail/Tally") {Title = Title_Header + Title_1+ "\n" + Title_NetProfitLoss + Title_2 ;} if (TitleStyleT == "None") {Title = Title_Header ;} // End Dynamic Title } if(flagX ==0){ nid = sym ; } /////////////////////////////////////////////////////////////////////// // End Core Section. /////////////////////////////////////////////////////////////////////// _SECTION_END(); nid = StrLeft(nid ,StrLen(nid )-2); xid = Name(); if(nid == xid){ if(awd <0){ wd = wd+awd; } wd = wd*(-1); for( i = 0; i<BarCount; i++ ){ local_C[i] = C[wd]; } for( i = wd; i<BarCount; i++ ){ local_C[i] = C[i]; } } else{ nid = ""; } z = BarIndex(); tz = StrFormat("%.0f",z); zt = StrToNum(tz); /* MyATR=ATR(14);//Enter ATR Average or use the 14 Day Moving Average of ATR MidRange=(H+L)/2;//Figure Used In Title for Middle of Trading Range if(nid == xid){ Plot (local_C- (MyATR*2),"",IIf(z<=wd-2,colorBlack,colorWhite), styleLine); Plot (local_C- (MyATR*1.5),"",IIf(z<=wd-2,colorBlack,colorWhite), styleLine); Plot (local_C- (MyATR*3),"",IIf(z<=wd-2,colorBlack,colorWhite),styleLine); } */ /* _SECTION_BEGIN("Stop loss7"); lookbackPeriod7 = Param("Lookback period7", 20, 7, 30); stoplossPercentage7 = 7;//Param("Stoploss Percentage7", 7, 7, 10); if(nid == xid){ Plot(HHV(local_C,lookbackPeriod7) - HHV(local_C,lookbackPeriod7) * (stoplossPercentage7 / 100), "Trailing stoploss7", IIf(z<=wd-2,colorBlack,colorRed), styleDashed|styleThick,0,0,0); } _SECTION_END(); _SECTION_BEGIN("Stop loss5"); lookbackPeriod5 = Param("Lookback period5", 20, 5, 30); stoplossPercentage5 = 5;//Param("Stoploss Percentage5", 5, 2, 10); if(nid ==xid){ Plot(HHV(local_C,lookbackPeriod5) - HHV(local_C,lookbackPeriod5) * (stoplossPercentage5 / 100), "Trailing stoploss5", IIf(z<=wd-2,colorBlack,colorYellow), styleDashed|styleThick,0,0,0); } _SECTION_END(); */ _SECTION_BEGIN("Stoploss Line"); if(nid == xid){ mf = Param("ATR multiplier",3,1,5,0.25); ap=Param("ATR Period",10,5,30,1); Lb=20;//Param("Lookback Period",20,10,40,1); ps=1;//ParamToggle("Use last low pivot","Use,Dont",1); //p1=ParamToggle("plot type","line,Dots",1); t1=HHV(local_C,Lb); t2=(mf*ATR(ap)); t3=Trough(local_C,2,1); t4=t1-t2; t5=Min(t4,t3); if(ps) { t6 = t1-t2; } else { t6=t5; } initial=t6; stop[ 0 ] = local_C[ 0 ]; for( i = 1 ; i < BarCount; i++) { if( local_C[ i ] > stop[ i - 1]) { temp = t6[ i ]; if( temp > stop[ i - 1 ] ) stop[ i ] = temp; else stop[ i ] = stop[ i - 1 ]; } else stop[ i ] = initial[ i ]; } Plot(stop,"ATR Stop",IIf(z<=wd-2,colorBlack,ParamColor( "Color", colorLightYellow)),IIf(wd<0,styleNoDraw,styleLine|styleDots|styleNoTitle)); } /////////////////here ATR ends//////////////////////////////////// _SECTION_END();