Please, can any body tell how this afl code get into working condition in amibrokar

#1
DEAR ALL MEMBERS IAM KRISHNA,
I GOT A AFL CODE FROM GOOGLE SEARCH. BUT I DONT KNOW HOW USE THIS IN AMIBROKAR, PLEASE ANY BODY HELP ME, HOW I USE THIS IN AMIBROKAR

Friends,
images also attached pease help me.
THANKS TO ALL,
KRISHNA.

SECTION_BEGIN("Sup / Res Lines");
SRswitch = ParamToggle("Sup / Res Lines","On,Off");
CHLswitch = ParamToggle("Hi Low / Close","Hi Low,Close");
NoLines = Param("No of Lines",3,1,10,1);
Sen = Param("Sensitivity",5,1,100,1);
Rcolor=ParamColor( "Res Color", colorDarkGreen );
Rstyle=ParamStyle( "Res Style", styleLine );
Scolor=ParamColor( "Sup Color", colorBrown );
Sstyle=ParamStyle( "Sup Style", styleLine );
y=0;
x=0;
for( i = 1; i < NoLines+1 ; i++ )
{
Y=LastValue(Peak(IIf(CHLswitch,C,H),Sen,i));
x=BarCount - 1 - LastValue(PeakBars(IIf(CHLswitch,C,H),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Rcolor, Rstyle );
Y=LastValue(Trough(IIf(CHLswitch,C,L),Sen,i));
x=BarCount - 1 - LastValue(TroughBars(IIf(CHLswitch,C,L),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Scolor, Sstyle );
}
_SECTION_END();

_SECTION_BEGIN("Detecting double tops and bottoms");
/* Detecting double tops and bottoms*/
percdiff = 5; /* peak detection threshold */
fwdcheck = 5; /* forward validity check */
mindistance = 10;
validdiff = percdiff/400;
PK= Peak( H, percdiff, 1 ) == High;
TR= Trough( L, percdiff, 1 ) == Low;
x = Cum( 1 );
XPK1 = ValueWhen( PK, x, 1 );
XPK2 = ValueWhen( PK, x, 2 );
xTR1 = ValueWhen( Tr, x, 1 );
xTr2 = ValueWhen( Tr, x, 2 );
peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
Troughdiff=ValueWhen( tr, L, 1 )/ValueWhen( tr, L, 2 );
doubletop = PK AND abs( peakdiff - 1 ) < validdiff AND (Xpk1 -Xpk2)>mindistance AND High > HHV( Ref( H, fwdcheck ), fwdcheck - 1 );
doubleBot=tr AND abs( troughdiff - 1 ) < validdiff AND (Xtr1 -Xtr2)>mindistance AND Low < LLV( Ref( L, fwdcheck ), fwdcheck - 1 );
Buy = doubletop;
Sell = doublebot;
 

Attachments

KelvinHand

Well-Known Member
#2
Re: Please, can any body tell how this afl code get into working condition in amibro

DEAR ALL MEMBERS IAM KRISHNA,
I GOT A AFL CODE FROM GOOGLE SEARCH. BUT I DONT KNOW HOW USE THIS IN AMIBROKAR, PLEASE ANY BODY HELP ME, HOW I USE THIS IN AMIBROKAR

Friends,
images also attached pease help me.
THANKS TO ALL,
KRISHNA.

SECTION_BEGIN("Sup / Res Lines");
SRswitch = ParamToggle("Sup / Res Lines","On,Off");
CHLswitch = ParamToggle("Hi Low / Close","Hi Low,Close");
NoLines = Param("No of Lines",3,1,10,1);
Sen = Param("Sensitivity",5,1,100,1);
Rcolor=ParamColor( "Res Color", colorDarkGreen );
Rstyle=ParamStyle( "Res Style", styleLine );
Scolor=ParamColor( "Sup Color", colorBrown );
Sstyle=ParamStyle( "Sup Style", styleLine );
y=0;
x=0;
for( i = 1; i < NoLines+1 ; i++ )
{
Y=LastValue(Peak(IIf(CHLswitch,C,H),Sen,i));
x=BarCount - 1 - LastValue(PeakBars(IIf(CHLswitch,C,H),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Rcolor, Rstyle );
Y=LastValue(Trough(IIf(CHLswitch,C,L),Sen,i));
x=BarCount - 1 - LastValue(TroughBars(IIf(CHLswitch,C,L),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Scolor, Sstyle );
}
_SECTION_END();

_SECTION_BEGIN("Detecting double tops and bottoms");
/* Detecting double tops and bottoms*/
percdiff = 5; /* peak detection threshold */
fwdcheck = 5; /* forward validity check */
mindistance = 10;
validdiff = percdiff/400;
PK= Peak( H, percdiff, 1 ) == High;
TR= Trough( L, percdiff, 1 ) == Low;
x = Cum( 1 );
XPK1 = ValueWhen( PK, x, 1 );
XPK2 = ValueWhen( PK, x, 2 );
xTR1 = ValueWhen( Tr, x, 1 );
xTr2 = ValueWhen( Tr, x, 2 );
peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
Troughdiff=ValueWhen( tr, L, 1 )/ValueWhen( tr, L, 2 );
doubletop = PK AND abs( peakdiff - 1 ) < validdiff AND (Xpk1 -Xpk2)>mindistance AND High > HHV( Ref( H, fwdcheck ), fwdcheck - 1 );
doubleBot=tr AND abs( troughdiff - 1 ) < validdiff AND (Xtr1 -Xtr2)>mindistance AND Low < LLV( Ref( L, fwdcheck ), fwdcheck - 1 );
Buy = doubletop;
Sell = doublebot;


1. do some reading on the user guide


2. copy the code into the formula editor

3. Verify Syntax.


4. No Problem, run.
 
#3
Re: Please, can any body tell how this afl code get into working condition in amibro

_SECTION_BEGIN("Sup / Res Lines");
SRswitch = ParamToggle("Sup / Res Lines","On,Off");
CHLswitch = ParamToggle("Hi Low / Close","Hi Low,Close");
NoLines = Param("No of Lines",3,1,10,1);
Sen = Param("Sensitivity",5,1,100,1);
Rcolor=ParamColor( "Res Color", colorDarkGreen );
Rstyle=ParamStyle( "Res Style", styleLine );
Scolor=ParamColor( "Sup Color", colorBrown );
Sstyle=ParamStyle( "Sup Style", styleLine );
y=0;
x=0;
for( i = 1; i < NoLines+1 ; i++ )
{
Y=LastValue(Peak(IIf(CHLswitch,C,H),Sen,i));
x=BarCount - 1 - LastValue(PeakBars(IIf(CHLswitch,C,H),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Rcolor, Rstyle );
Y=LastValue(Trough(IIf(CHLswitch,C,L),Sen,i));
x=BarCount - 1 - LastValue(TroughBars(IIf(CHLswitch,C,L),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Scolor, Sstyle );
}
_SECTION_END();

_SECTION_BEGIN("Detecting double tops and bottoms");
/* Detecting double tops and bottoms*/
percdiff = 5; /* peak detection threshold */
fwdcheck = 5; /* forward validity check */
mindistance = 10;
validdiff = percdiff/400;
PK= Peak( H, percdiff, 1 ) == High;
TR= Trough( L, percdiff, 1 ) == Low;
x = Cum( 1 );
XPK1 = ValueWhen( PK, x, 1 );
XPK2 = ValueWhen( PK, x, 2 );
xTR1 = ValueWhen( Tr, x, 1 );
xTr2 = ValueWhen( Tr, x, 2 );
peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
Troughdiff=ValueWhen( tr, L, 1 )/ValueWhen( tr, L, 2 );
doubletop = PK AND abs( peakdiff - 1 ) < validdiff AND (Xpk1 -Xpk2)>mindistance AND High > HHV( Ref( H, fwdcheck ), fwdcheck - 1 );
doubleBot=tr AND abs( troughdiff - 1 ) < validdiff AND (Xtr1 -Xtr2)>mindistance AND Low < LLV( Ref( L, fwdcheck ), fwdcheck - 1 );
Buy = doubletop;
Sell = doublebot;
 
#4
Re: Please, can any body tell how this afl code get into working condition in amibro

SetChartOptions(0,chartShowDates);
SetChartBkColor(16);
GraphXSpace=Param("GraphXSpace",10,-100,100,1);
SetBarFillColor(IIf(O>C,24,19));
Plot(C,"Price",IIf(O>C,32,34),64);
dtn=DateNum();
haC=EMA((O+H+L+C)/4,3); haO=AMA(Ref(haC,-1),0.5);
haH=Max(H,Max(haC,haO)); haL=Min(L,Min(haC,haO));
//==============================
_SECTION_BEGIN("HL Pivots");
//==============================
psh= ParamToggle("Pivot Shapes","Off|On",1);
plb= ParamToggle("Pivot Labels","Off|On",1);
snd= ParamToggle("Sound Alerts","Off|On",1);
lbk= Param("Hi Lo Lookback",350,50,5000,10);
nbz= Param("Swing Bars",20,5,150,1);
tht= Param("Hi Label Adjust",0.65,0.10,5,0.05)*ATR(5);
lbk= Min(BarCount-1,Lbk);
bc=BarCount-1;
//================
xH=H-H; xL=L-L; yH=H-H; yL=L-L; xR=H-H; xS=L-L;
xrb=0; xSb=0; yR0=0; yS0=0; xR0=0; xS0=0; xx=0;
xHH= HHVBars(H,nbz); xLL= LLVBars(L,nbz);
yHH= HHV(H,nbz); yLL= LLV(L,nbz);
viz= Status("BarVisible");
vbz= LastValue(Highest(IIf(viz,BarIndex(),0)));
_TRACE("Last visible bar: "+ vbz);
bct= (BarCount-1); dir = "";
if(xLL[bc]<xHH[bc]) { dir="D"; } else { dir="U"; }
for(i=0; i<lbk; i++) { bc=bct-i;
if(xLL[bc]<xHH[bc]) { if(dir=="U"){dir="D";
xx=bc-xLL[bc]; xL[xx]=1;
yL[xSb]=L[xx]; xS[xSb]=xx; xSb++; }
} else { if(dir=="D") { dir = "U";
xx=bc-xHH[bc]; xH[xx]=1; yH[xrb]=H[xx]; xR[xrb]=xx;xrb++; }}}
xP= 0; yP= 0; xS0= xS[0]; yS0=yL[0]; xR0= xR[0]; yR0= yH[0];
if(xS0>xR0) { xP=bc-xHH[bc]; yP= yHH[bc];
if(yR0<yP AND xP>xS0 AND xP<bc) { xH[xP]=1;
for(j=0; j<xrb; j++) { yH[xrb-j]= yH[xrb-(j+1)];
xR[xrb-j]= xR[xrb-(j+1)]; }
yH[0]= yP; xR[0]= xP; xrb++; }
} else { xP= bc-xLL[bc]; yP= yLL[bc];
if(yS0>yP AND xP>xR0 AND xP<bc) { xL[xP]=1;
for(j=0; j<xSb; j++) { yL[xSb-j]= yL[xSb-(j+1)]; xS[xSb-j]= xS[xSb-(j+1)]; }
yL[0]=yP; xS[0]=xP; xSb++; }}
ushp=shapeHollowUpArrow; dshp=shapeHollowDownArrow;
if(psh) { PlotShapes(xH*dshp,42,0,H,-10); PlotShapes(xL*ushp,43,0,L,-10); }
if(snd) {
AlertIf(xL==1,"SOUND C:\\Windows\\Media\\Windows XP Startup.wav","Audio alert",2);
AlertIf(xH==1,"SOUND C:\\Windows\\Media\\Ringin.wav","Audio alert",2); }
Buy=(xL); Sell=(xH); Cover=(xL); Short=(xH); Long=Flip(Buy,Sell); Shrt=Flip(Sell,Buy);
SellPrice=ValueWhen(Sell,H,1); BuyPrice= ValueWhen(Buy,L,1);
if(plb) {
for(i=0; i<BarCount; i++) {
if(Buy )PlotText("\n\n"+ StrRight(NumToStr(L,6.2),5),i-1,L,43,16);
if(Sell)PlotText(StrRight(NumToStr(H,6.2),5),i-1,H+tht,32,16); }
}
_SECTION_END();
//===========================
_SECTION_BEGIN("Sup / Res Lines");
SRswitch = ParamToggle("Sup / Res Lines","On,Off");
CHLswitch = ParamToggle("Hi Low / Close","Hi Low,Close");
NoLines = Param("No of Lines",3,1,10,1);
Sen = Param("Sensitivity",5,1,100,1);

Rcolor=ParamColor( "Res Color", colorGreen );
Rstyle=ParamStyle( "Res Style", styleLine );

Scolor=ParamColor( "Sup Color", colorBrown );
Sstyle=ParamStyle( "Sup Style", styleLine );

y=0;
x=0;

for( i = 1; i < NoLines+1 ; i++ )
{
Y=LastValue(Peak(IIf(CHLswitch,C,H),Sen,i));
x=BarCount - 1 - LastValue(PeakBars(IIf(CHLswitch,C,H),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Rcolor, Rstyle );

Y=LastValue(Trough(IIf(CHLswitch,C,L),Sen,i));
x=BarCount - 1 - LastValue(TroughBars(IIf(CHLswitch,C,L),Sen,i));
Line = LineArray( x, y, Null, y, 1 );
Plot( IIf(SRswitch,Null,Line), "", Scolor, Sstyle );
}
_SECTION_END();

_SECTION_BEGIN("Background");
SetChartOptions(0,chartShowArrows|chartShowDates);
priceTitle=StrFormat("---- {{NAME}} ---------- {{VALUES}}");
Title ="Averages" + priceTitle;

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)); // color of inner panel
_SECTION_END();
 

a1b1trader

Well-Known Member
#5
Re: Please, can any body tell how this afl code get into working condition in amibro

Hi Krishna
The AFL you have posted is showing error
and it seems that you have not posted the complete AFL, as well.
So please post the correct and complete AFL.
Thanks
 
Last edited:
#6
Re: Please, can any body tell how this afl code get into working condition in amibro

Hi MOHHMED SALEH
Thanks for the post.

When I tried it on nifty,it shows a narrow chart not very pleasing to look at or understand.

secondly,as I understand,all support resistance work best on higher timeframes
say 4hrly or daily very good,weekly great.


what about this code does it work on intraday charts like 15m or 30m or 60m ?
please comment
regards
 
#7
Re: Please, can any body tell how this afl code get into working condition in amibro

DEARFRIENDS,
This is KRISHNA.
THANKS TO ALL MEMBERS, YOU GIVEN VALUEBLE REPLYS.
Iam totally new to amibrokar technicals, Now too i could not understand how to put the afl code. So any body please tell step to step how to put the above afl code in amibrokar pleaseeeeee, Dont think other wise.
Please help.
 
#8
Re: Please, can any body tell how this afl code get into working condition in amibro

Sir/Medam please help me

This is KRISHNA.

THANKS TO ALL MEMBERS, YOU GIVEN VALUEBLE REPLYS.
Iam totally new to amibrokar technicals, Now too i could not understand how to put the afl code. So any body please tell step to step how to put the above afl code in amibrokar pleaseeeeee, Dont think other wise.
Please help.
 

hmsanil

Active Member
#9
Re: Please, can any body tell how this afl code get into working condition in amibro

Sir/Medam please help me

This is KRISHNA.

THANKS TO ALL MEMBERS, YOU GIVEN VALUEBLE REPLYS.
Iam totally new to amibrokar technicals, Now too i could not understand how to put the afl code. So any body please tell step to step how to put the above afl code in amibrokar pleaseeeeee, Dont think other wise.
Please help.

Hi

TO CREATE AND SAVE FORMULA

1. Copy the code

2. Go to amibroker>Analysis>Formula Editor

3.Paste the code

4.Save the formula Editor by File>Save as (GIVE THE FORMULA NAME AS U WANT)


U have saved the afl indicator successfully.

TO INSERT AND VIEW INDICATOR

Go to Amibroker> View>Charts>Custom

Browse the afl which u have saved

Double click or (Right click>Insert) the indicator.

It will show on the screen

Thats it

If u need further help, i can do it on team viewer.

Thanks
 
#10
Re: Please, can any body tell how this afl code get into working condition in amibro

Please can any one help me sir, below given afl code is showing error how can we clear the error:)


_SECTION_BEGIN("KS Auto");
// V1.0
//
// Parameters to control whether you're just testing, or running live
// and whether the orders are created in TWS but not transmitted to IB, or
created AND transmitted.

AutoTradingParam = True; //ParamToggle("AutoTrading","Off|On",0);
SubmitOrders = True; //ParamToggle("Create or Transmit","Create
Only|Create AND Transmit",False);
Tracing = False;

BaseRiskPcnt = 1.00; // Percent of account risk per trade
AccountCutout = 75000; // Stop trading if account falls to $X
// This exploration, by design, allows multiple
positions to be placed simultaneously
// (although only 1 entry per bar), so it is highly
desirable to have a safety
// mechanism to stop trading if there is a sequence
of losing trades, OR there is a
// bug in the trading rules or AFL that are creating
continuous losing trades.


///////////////////////////////////////////////////////////////////////
//
//
// This AFL file is designed to run as a Scan or Exploration with Run Every
check box ticked.
// Choose a time interval suitable to the trading concept.
// The AFL file then runs every X periods and if a signal is found it submits a
Parent Order AND a Bracket Order to IB.
// It does not attempt to track the status of the orders subsequently as that
would add another order of complexity AND risk.
//
// Additionally, this example code does not enter the market immediately, it
waits for confirmation of the next bar moving in the
// desired direction before entering, i.e. it is important that the
Exploration is run freqently enough so that it checks
// many times during the next bar whether the desired movement has
occurred. for example, for 10 Minute bars,
// it would be a good idea to have the Exploration run every 30 or 60
seconds.
// Any other entry technique would require different coding, e.g. an
immediate entry would probably simplify the coding.
//
// Static variables are used to keep track of desired entries from one
iteration of the Exploration to the next.
//
//
///////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////
// LIMITATIONS and WARNINGS:
// Don't use PARAMs in Auto-Trading Scans or Explorations because any PARAM
change runs the formula once on the current chart
// every time the PARAM dialogbox is opened, which is probably NOT what you
want.
//
// AB keeps static variables in memory between each run of an Exploration. So
if you need
// to reset everything and re-start auto-trading then you MUST proceed as
follows:
//
// Either restart AB, or
// Edit this exploration to change Auto-Trading Off, run it once, then
edit the file again
// and run it again. The AFL will recognise this and clear
any Status codes to ensure
// correct operation in Auto vs non-Auto mode.
//
// THIS CODE RELIES ON PREFERENCES MENU/INTRADAY "START time of interval" radio
box turned ON.
// This is used to detect when a bar is complete, so that the trading
rules know when to do their calculations.
// This technique is NOT designed to handle intrabar entry signals
//
// NOTE this AFL file was originally written for trading currencies, hence
there are one OR two currency specific items
// that may need editing, in particular position sizes are rounded to the
nearest $10,000. Check the comments.
//
///////////////////////////////////////////////////////////////////////


// Function to provide voice warning whenever any new trades are created

function SayNotTooOften( text, Minperiod )
{
elapsed=GetPerformanceCounter()/1000;
Lastelapsed = Nz( StaticVarGet("lastsaytime") );

if( elapsed - Lastelapsed > Minperiod )
{
StaticVarSet("lastsaytime", elapsed );
Say( text );
}
}

// Interactive Brokers ticker symbols may have unwanted characters for our
static variable names. Remove them.

ABName = StrMid(Name(),0,3) + StrMid(Name(),4,3);
IBName = Name();

AutoTrading = StaticVarGet("AutoTrading"+ABName);
if( IsNull( AutoTrading ) )
StaticVarSet("AutoTrading"+ABName,0);

if ( AutoTrading==0 && AutoTradingParam )
{
// About to start AutoTrading after it's been off, so clear all order
statuses.
StaticVarSetText("OrderID"+ABName,"");
StaticVarSetText("OrderIDLMT"+ABName,"");
StaticVarSetText("OrderIDSTP"+ABName,"");
StaticVarSetText("OrderStatus"+ABName,"");
StaticVarSetText("OrderLMTStatus"+ABName,"");
StaticVarSetText("OrderStatusSTP"+ABName,"");
}
if ( AutoTrading && AutoTradingParam==0 )
{
// About to stop AutoTrading after it's been on, so clear all order statuses.

StaticVarSetText("OrderID"+ABName,"");
StaticVarSetText("OrderIDLMT"+ABName,"");
StaticVarSetText("OrderIDSTP"+ABName,"");
StaticVarSetText("OrderStatus"+ABName,"");
StaticVarSetText("OrderLMTStatus"+ABName,"");
StaticVarSetText("OrderStatusSTP"+ABName,"");
}

if (AutoTradingParam)
StaticVarSet("AutoTrading"+ABName,1);
else
StaticVarSet("AutoTrading"+ABName,0);

AutoTrading = StaticVarGet("AutoTrading"+ABName);

Filename = _DEFAULT_NAME();

// Your trading conditions here
ShortCond1 = 0;//Whatever your trading rules say
BuyCond1 = 0;//Whatever your trading rules say
ShortCond2 = 0;//Whatever your trading rules say
BuyCond2 = 0;//Whatever your trading rules say
Short = ShortCond1 OR ShortCond2;
Buy = BuyCond1 OR BuyCond2;

// Following lines required because I'll only enter once the price moves in my
desired direction
ShortPrice = Min(Ref(C,-1),Open); //Or as appropriate for your trading rules.
BuyPrice = Max(Ref(C,-1),Open); //Or as appropriate for your trading rules.

Sell=Cover=0;

// Following variables for exits are mostly for backtesting. Not all are used
in Autotrading.

ISLARC=3; // Initial Stop Loss multiplier x ATR. Set as appropriate for your
trading rules.
ISL=ATR(20)*ISLARC;

TSLARC=ISLARC; // Trailing Stop Loss multiplier x ATR. Set as appropriate for
your trading rules.
TSL=ATR(20)*TSLARC;

PSLARC=0.5; // Take Profit multiplier x ATR. Set as appropriate for your
trading rules.
PSL=ATR(20)*PSLARC;

nBars = 15; // Exit after n Bars. Set as appropriate for your trading rules.

ShortISLPrice=ShortPrice+Ref(ISL,-1);
ShortPSLPrice=ShortPrice-Ref(PSL,-1);
BuyISLPrice=BuyPrice-Ref(ISL,-1);
BuyPSLPrice=BuyPrice+Ref(PSL,-1);

// Set some variables for the right edge of the chart for the Auto-Trading
code.
LastShortPrice=LastValue(ShortPrice);
LastBuyPrice=LastValue(BuyPrice);
LastShortISLPrice=LastValue(ShortISLPrice);
LastShortPSLPrice=LastValue(ShortPSLPrice);
LastBuyISLPrice=LastValue(BuyISLPrice);
LastBuyPSLPrice=LastValue(BuyPSLPrice);
LastATR=LastValue(Ref(ATR(20),-1));

// Stop Losses used only for Backtest mode, however this script with Automation
in it
// is not really suitable for backtesting so don't even try.
ApplyStop(stopTypeLoss,stopModePoint,Ref(ISL,-1),1,False,0);
ApplyStop(stopTypeNBar,stopModeBars,nBars,0,True);
ApplyStop(stopTypeProfit,stopModePoint,Ref(PSL,-1),1,False,0);
ApplyStop(stopTypeTrailing,stopModePoint,Ref(TSL,-1),1,False,0);

/////////////////// Automation Code //////////////////

// First check if we've just started a new bar. THIS CODE RELIES ON
PREFERENCES/INTRADAY SET TO START OF Interval.

PrevDT = StaticVarGet("DateTime"+ABName);
DT = LastValue(DateTime());
NewBar = DT != PrevDT;
StaticVarSet("DateTime"+ABName,DT);

if( NewBar )
{
// Clear all status so we can place a new order on each bar. Later, the
Status variables are checked to ensure
// that we place no more than 1 order on each bar.

StaticVarSetText("OrderID"+ABName,"");
StaticVarSetText("OrderIDLMT"+ABName,"");
StaticVarSetText("OrderIDSTP"+ABName,"");
StaticVarSetText("OrderStatus"+ABName,"");
StaticVarSetText("OrderLMTStatus"+ABName,"");
StaticVarSetText("OrderStatusSTP"+ABName,"");
}

LastBuy = LastValue(Buy);
LastShort = LastValue(Short);

Filter=Buy OR Short;

IBPosSize=0;

ibc = GetTradingInterface("IB");
IBcStatus = ibc.IsConnected();

IBcStatusString = WriteIf(IBCStatus==0,"TWS Not Found",
WriteIf(IBCStatus==1,"Connecting to TWS",
WriteIf(IBCStatus==2,"TWS OK",
WriteIf(IBCStatus==3,"TWS OK (msgs)",""))));

// Work out how much money there is and adjust risk size

CashBalanceStr = ibc.GetAccountValue("NetLiquidationByCurrency");
if (CashBalanceStr == "")
CashBalance = 0;
else
CashBalance = StrToNum(CashBalanceStr);

// Note CashBalance is in AUD for my account, so following calculations are all
in AUD.
// If trading instruments denominated in multiple currencies, e.g. FX, you will
need to adjust this code.
// It is possible to dynamically lookup the IB FX price
// but too extensive for me to include the code here

PositionRisk = BaseRiskPcnt/100*CashBalance;
PositionSize = PositionRisk / Ref(ISL,-1);
IBOrderSize = int(LastValue(PositionSize)/10000)*10000; // Round to nearest
$10k - designed for FX ************

OldOrderID = StaticVarGetText("OrderID"+ABName);
if (AutoTrading == 0 && OldORderID == "" && (LastBuy || LastShort))
{
// If there would have been an order during Autotrading, then create a
dummy OID to test all other code paths
// e.g. logging, explore output etc.
StaticVarSetText("OrderID"+ABName,"DUMMY");
}

if( IBcStatus AND AutoTrading AND (CashBalance > AccountCutout))
{
OrderID = StaticVarGetText("OrderID"+ABName);
OrderIDLMT = StaticVarGetText("OrderIDLMT"+ABName);
OrderIDSTP = StaticVarGetText("OrderIDSTP"+ABName);

IBPosSize = ibc.GetPositionSize( IBName );
// Only enter once the price moves in my desired direction, otherwise wait
until next run of the exploration
// and check again, and again., ...
if( LastBuy AND OrderID == "" AND (LastValue(C) <= (LastBuyPrice)))
{
OID = ibc.PlaceOrder( IBName, "Buy", IBOrderSize, "TRAIL", 0, TickSize,

"DAY", False, TickSize/0.0001, "outsideRTH" );
// _TRACE("# Pos: 0, PrevOID: "+OrderID+", Buy 1, NewOID: "+OID);
OIDLMT = ibc.PlaceOrder( IBName, "Sell", IBOrderSize, "LMT",
LastBuyPSLPrice, 0,
"GTC", False, TickSize/0.0001, "outsideRTH",
OID);
OIDSTP = ibc.PlaceOrder( IBName, "Sell", IBOrderSize, "STP", 0,
LastBuyISLPrice,
"GTC", SubmitOrders, TickSize/0.0001,
"outsideRTH", OID);

for (dummy=0; dummy<40; dummy++)
ibc.Sleep(50); //Usually takes up to about a second for TWS to get
acknowledgement from IB
StaticVarSetText("OrderID"+ABName,OID);
StaticVarSetText("OrderIDLMT"+ABName,OIDLMT);
StaticVarSetText("OrderIDSTP"+ABName,OIDSTP);
SayNotTooOften("There is an order to be checked",30);

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

// Wait until order actually PreSubmitted - this will prevent
submitting another order too quickly
// hopefully stops TWS/IB getting in a knot

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;
}
}
}

// Only enter once the price moves in my desired direction, otherwise wait
until next run of the exploration
// and check again, and again., ...
else if( LastShort AND OrderID == "" AND (LastValue(C) >=
(LastShortPrice)))
{
OID = ibc.PlaceOrder( IBName, "Sell", IBOrderSize, "TRAIL", 0,
TickSize,
"DAY", False, TickSize/0.0001, "outsideRTH" );
// _TRACE("# Pos: 0, PrevOID: "+OrderID+", Sell 1, NewOID: "+OID);

OIDLMT = ibc.PlaceOrder( IBName, "Buy", IBOrderSize, "LMT",
LastShortPSLPrice, 0,
"GTC", False, TickSize/0.0001, "outsideRTH",
OID);
OIDSTP = ibc.PlaceOrder( IBName, "Buy", IBOrderSize, "STP", 0,
LastShortISLPrice,
"GTC", SubmitOrders, TickSize/0.0001,
"outsideRTH", OID);
for (dummy=0; dummy<40; dummy++)
ibc.Sleep(50); //Usually takes up to about a second for TWS to get
acknowledgement from IB
StaticVarSetText("OrderID"+ABName,OID);
StaticVarSetText("OrderIDLMT"+ABName,OIDLMT);
StaticVarSetText("OrderIDSTP"+ABName,OIDSTP);
SayNotTooOften("There is an order to be checked",30);

if (SubmitOrders)
{
//Usually takes about a second for TWS to get acknowledgement from
IB, so delay for 2 secs for safety
for (dummy=0; dummy<40; dummy++)
ibc.Sleep(50);

// Wait until order actually PreSubmitted - this will prevent
submitting another order too quickly
// hopefully stops TWS/IB getting in a knot

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;
}
}
}

// Note LastOrderID will remain "" while waiting for price improvement so
we may skip entering for the whole of the bar
LastOrderID = StaticVarGetText("OrderID"+ABName);
LastOrderIDLMT = StaticVarGetText("OrderIDLMT"+ABName);
LastOrderIDSTP = StaticVarGetText("OrderIDSTP"+ABName);

ORderStatus = ibc.GetStatus( LastOrderID , True );
if( ORderStatus != "" )
StaticVarSetText("OrderStatus"+ABName,ORderStatus);

ORderLMTStatus = ibc.GetStatus( LastOrderIDLMT , True );
if( ORderLMTStatus != "" )
StaticVarSetText("OrderLMTStatus"+ABName,ORderLMTStatus);

ORderSTPStatus = ibc.GetStatus( LastOrderIDSTP , True );
if( ORderSTPStatus != "" )
StaticVarSetText("OrderStatusSTP"+ABName,ORderSTPStatus);
}
else IBPosSize = 0;

LastOrderID = StaticVarGetText("OrderID"+ABName);
ORderStatus = StaticVarGetText("OrderStatus"+ABName);
LastOrderIDLMT = StaticVarGetText("OrderIDLMT"+ABName);
ORderLMTStatus = StaticVarGetText("OrderLMTStatus"+ABName);
LastOrderIDSTP = StaticVarGetText("OrderIDSTP"+ABName);
ORderSTPStatus = StaticVarGetText("OrderSTPStatus"+ABName);

Title = Filename+":"+ABName+"\n"+
" Trading Mode: "+WriteIf( AutoTrading,"ON"+WriteIf( SubmitOrders," -
Create AND Transmit"," - Create Only"),"OFF")+"\n"+
" Last Signal: "+WriteIf(LastBuy,"BUY",WriteIf
(LastShort,"SHORT","NoSignal"))+"\n"+
" IB Status: "+IBcStatusString+"\n"+
" Last OrderID,LMT,STP:
"+LastOrderID+","+LastOrderIDLMT+","+LastOrderIDSTP+"\n"+
" OrderStatus,LMT,STP:
"+ORderStatus+WriteIf(ORderStatus=="Error",ibc.GetLastError( LastOrderID
),"")+","+ORderLMTStatus+","+ORderSTPStatus+"\n"+
" LastTime: "+DateTimeToStr(LastValue(DateTime()))+"\n"+
" IBPosSize: "+NumToStr(IBPosSize,1.0);

AddColumn(CashBalance,"Cash",1.2);
AddColumn(IIf(AutoTrading,Asc("Y"),Asc("N")),"AT",formatChar);
AddColumn(IIf(SubmitOrders,Asc("Y"),Asc("N")),"Transmit",formatChar);
AddColumn(Ref(ATR(20),-1),"ATR(20)",1.6);
AddColumn(BuyCond1 OR ShortCond1,"Cond1",1.0);
AddColumn(IIf(Buy,Asc("L"),IIf(Short,Asc("S"),Asc(" "))),"L/S",formatChar);
AddColumn(PositionRisk,"Risk",1.2);
AddColumn(int(LastValue(PositionSize)/10000)*10000,"PosSize",1.0); //
Assumes FX *******************
AddColumn(IBOrderSize,"Qty",1.0);
AddColumn(IIf(Buy,BuyPrice,ShortPrice),"Entry",1.5);
AddColumn(ISLARC,"ISLARC",1.2);
AddColumn(IIf(Buy,BuyISLPrice,ShortISLPrice),"Loss Stop",1.5);
AddColumn(IIf(Buy,BuyPSLPrice,ShortPSLPrice),"Profit Take",1.5);

AddTextColumn(IBcStatusString,"IBC Status",1.0);
AddTextColumn(LastOrderID,"LastOID",1.0);
AddTextColumn(ORderStatus,"OrderStatus",1.0);


//
// The following code writes all the above AddColumn to permanent logfile,
where Filter occurs on last bar
//

if (Filter[BarCount-1] && OldOrderID == "" && LastOrderID != "") // No order
previously in place for this bar, this execution created one
{
fh = fopen( "TWSTrade.log", "a");
if( fh )
{
fputs( Now(), fh );
fputs( ", ", fh );

fputs( "Ticker: ", fh );

fputs( IBName, fh );
fputs( ", ", fh );

fputs( "BarTime: ", fh );

fputs( DateTimeToStr(DT), fh );
fputs( ", ", fh);

qs = StrFormat("Cash: %.2f, ",
CashBalance);
fputs( qs, fh );

fputs( "AT: ", fh );
if (AutoTrading) fputs( "Y, " , fh );
else fputs( "N, " , fh );

fputs( "Submit: ", fh );
if (SubmitOrders) fputs( "Transmit, " , fh );
else fputs( "Create_Only, " , fh );

if (LastBuy) fputs( "Buy, ", fh);
else if (LastShort) fputs( "Short, ", fh);
else fputs( "Not_Valid, ", fh);

qs = StrFormat("%.0f, ",
IBOrderSize );
fputs( qs, fh );

if (LastBuy)
qs = StrFormat("Entry: %.5f, ISLARC: %.2f, Stop: %.5f, Profit: %.5f, ",
LastBuyPrice, ISLARC, LastBuyISLPrice, LastBuyPSLPrice);
else
qs = StrFormat("Entry: %.5f, ISLARC: %.2f, Stop: %.5f, Profit: %.5f, ",
LastShortPrice, ISLARC, LastShortISLPrice, LastShortPSLPrice);
fputs( qs, fh );

fputs( "IBC Status: ", fh );
fputs( IBCStatusString, fh );
fputs( ", ", fh);

fputs( "LastOID: ", fh );
fputs( LastOrderID, fh );
fputs( ", ", fh);

fputs( "OrderStatus: ", fh );
fputs( ORderStatus, fh );
fputs( ", ", fh);

if (ORderStatus=="Error")
fputs( ibc.GetLastError( LastOrderID ), fh);
fputs( ", ", fh);

fputs( "\n", fh );

fclose( fh );
}
}
_SECTION_END();