Hi
My doubt is that BarsSince didn't work in real-time trade such as Interactive broker(IB)
The code below, I apply BarSince function to entry buy/short in only early trend once I apply it to real-time auto trade. Assuming signal have occurred over specific BarsSince, the system will ignore. you can copy my code to test run in backtest or explore.
{
//initialize data
SetOption( "InitialEquity", 50000 );
SetOption( "CommissionMode", 3 );
SetOption( "MaxOpenPositions", 1 );
SetOption( "CommissionAmount", 50 );
SetOption( "Futuresmode", True );
SetOption( "AllowPositionShrinking", True );
SetOption( "AllowSameBarExit", False );
SetOption( "PriceBoundChecking", False );
SetOption( "ReverseSignalForcesExit", False );
SetOption( "UsePrevBarEquityForPosSizing", False );
TickSize = 0.1;
PointValue = 200;
RoundLotSize = 1;
MarginDeposit = 10000; // Bath(Thai currency unit)
SetOption( "InterestRate", 0 );
SetOption( "MinPosValue", 0 );
SetOption( "MinShares", RoundLotSize );
SetTradeDelays( 1, 1, 1, 1 );
SetOption( "ExtraColumnsLocation", 1 );
Buy = Sell = Short = Cover = 0;
BuyPrice = SellPrice = ShortPrice = CoverPrice = Open;
}
{
// 1 future contact
SetPositionSize( 1, spsShares );
SetPositionSize( 50, spsPercentOfEquity);
}
function ATRTrailByChandelier(dayPeriod,multiplier){
linex= HHV( H, dayPeriod ) ;
trailStop= linex - (multiplier* ATR( dayPeriod ));
return trailStop;
}
{
//Indicator setup
aPeriod = 50; aFactor = 3.5;
bPeriod = 100; bFactor = 6;
atrail = ATRTrailByChandelier( aPeriod, aFactor);
btrail = ATRTrailByChandelier( bPeriod, bFactor );
rsiUp = 55;
risDown = 43;
nBarsX = 3;
}
{
//Trade Logic setup
buyCon1 = RSI() > rsiUp; //buyCon1=1;
buyCon2 = C > atrail AND C > btrail ;
xBuy = buyCon1 AND buyCon2 ;
buyCon_ExremItself = ExRem( xBuy, !xBuy );
nBars_buyCon = BarsSince( buyCon_ExremItself );
Buy = xBuy AND( nBars_buyCon < nBarsX );
//*******************************************************************
sellCon1 = RSI() < risDown; //sellCon1=1;
sellCon2 = C < atrail AND C < btrail ;
xSell = sellCon1 AND sellCon2;
sellCon_ExremItself = ExRem( xSell, !xSell );
nBars_sellCon = BarsSince( sellCon_ExremItself );
Sell = xSell AND nBars_sellCon < nBarsX;
Short = Sell;
Cover = Buy;
}
{
// EXREM
ApplyExRem = 0;//0 is don't apply exrem
if( ApplyExRem == 1 ) // barssince not work
{
Buy = ExRem( Buy, Short );
Short = ExRem( Short, Buy );
}
else
if( ApplyExRem == 2 ) // barssince not work due to removed Buy since the first
{
buy = ExRem( Buy, Sell );
Sell = ExRem( Sell, Buy );
Short = ExRem( Short, Cover );
Cover = ExRem( Cover, Short );
}
}
{
//Explore
Filter = 1;
//Filter = Buy OR Sell OR Short OR Cover ;
AddColumn( Buy, "Buy" , 1 );
//AddColumn( buyCon1, "Buy#RSI" , 1 );
//AddColumn( buyCon2, "Buy#CDL" , 1 );
AddColumn( xBuy, "xBuy", 1 );
AddColumn( buyCon_ExremItself, "buyCon2EX", 1 );
AddColumn( Sell, "Sell", 1 );
//AddColumn( sellCon1, "Sell#RSI", 1 );
//AddColumn( sellCon2, "Sell#CDL", 1 );
AddColumn( xSell, "xSell", 1 );
AddColumn( sellCon_ExremItself, "sellCon2EX", 1 );
AddColumn( Short, "Short", 1 );
AddColumn( Cover, "Cover", 1 );
AddColumn( nBars_buyCon, "BarSiceBuy", 1 );
AddColumn( nBars_sellCon, "BarSiceSell", 1 );
AddColumn( Close, "C", 1.2 );
AddColumn( atrail, "atrail", 1.2 );
AddColumn( btrail, "btrail", 1.2 );
AddColumn( RSI(), "RSI", 1.2 );
}
The 3 figures below show the result of code in backtest and explore.
The signal entry as long as bars is less than 3 bars since the first trigger happened.
I tested in backtest function, my code is work absolutely.
Unfortunately, I use it in realtime-auto trade, my order was executed immediately in the next bar despite that fact that, The signal condition has occurred too long to enter.
The code below is sample implemented with MT4 smart bridge
CAF_MT4_SetPortPosition is funton to send order , you are unnessary in code below, just only sample in my real-time auto trade
#include<ATRTrailByChandelier.afl>
//Fix time frame to trade
//TimeFrameSet(in5Minute);
_SECTION_BEGIN( "Price" );
SetChartOptions( 0, chartShowArrows | chartShowDates );
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) );
Plot( C, "Close", ParamColor( "Color", colorDefault ), styleNoTitle | ParamStyle( "Style" ) | GetPriceStyle() );
_SECTION_END();
_SECTION_BEGIN( "Autotrade Configulation" );
////////////////////////////////// initialized user variable (must change) ///////////////////////////////
{
_N( symbol = "S50_DUMMY" );
_N( systemName = "Ohlunla" ); //Can't use " ^ " in the name
_N( key = "your key" );
_N( ip = "127.0.0.1" );
port = 5500;
lotSize = 1;
}
printf( "Trade: " + symbol + "\n" );
{
SetBarsRequired( -2, 0 );
//////////////////////////////////////// auto trade Logic ////////////////////////////////////////
{
//Indicator setup
aPeriod = 50;
aFactor = 3.5;
bPeriod = 100;
bFactor = 6;
atrail = ATRTrailByChandelier( aPeriod, aFactor, true );
btrail = ATRTrailByChandelier( bPeriod, bFactor, true );
rsiUp = 55;
risDown = 43;
nBarsX = 3;
}
{
//Trade Logic setup
buyCon1 = RSI() > rsiUp; //buyCon1=1;
buyCon2 = C > atrail AND C > btrail ;
xBuy = buyCon1 AND buyCon2 ;
buyCon_ExremItself = ExRem( xBuy, !xBuy );
nBars_buyCon = BarsSince( buyCon_ExremItself );
Buy = xBuy AND( nBars_buyCon < nBarsX );
//*******************************************************************
sellCon1 = RSI() < risDown; //sellCon1=1;
sellCon2 = C < atrail AND C < btrail ;
xSell = sellCon1 AND sellCon2;
sellCon_ExremItself = ExRem( xSell, !xSell );
nBars_sellCon = BarsSince( sellCon_ExremItself );
Sell = xSell AND nBars_sellCon < nBarsX;
Short = Sell;
Cover = Buy;
}
{
//Configure to send signal to smart bridge
BuyCondition = Buy;
SellCondition = Sell;
ShortCondition = Short;
CoverCondition = Cover;
ApplyExRem = 0;
//0 is don't apply exrem
if( ApplyExRem == 1 )
{
BuyCondition = ExRem( BuyCondition, ShortCondition );
ShortCondition = ExRem( ShortCondition, BuyCondition );
}
else
if( ApplyExRem == 2 )
{
BuyCondition = ExRem( BuyCondition, SellCondition );
SellCondition = ExRem( SellCondition, BuyCondition );
ShortCondition = ExRem( ShortCondition, CoverCondition );
CoverCondition = ExRem( CoverCondition, ShortCondition );
}
{
// Using Flip to expand signal as portfolio position
BuySignal = Flip( BuyCondition, SellCondition );
SellSignal = 0;
ShortSignal = Flip( ShortCondition, CoverCondition );
CoverSignal = 0;
}
}
//////////////////////////////// Set Portfolio Position ///////////////////////////////
{
contact = 2;
targetPosition = LastValue( Ref( ( BuySignal - ShortSignal ), -1 ) ); // Don't forget to delay your signal
targetPosition = targetPosition * contact;
}
//////////////////////////////// initialized system variable (not change) ////////////////////////////////
{
RequestTimedRefresh( 1 );
nowTime = LastValue( DateTime() );
dateAll = DateTime();
lb = LastValue( BarIndex() ); //last bar index
_N( autoTradeStatus = "Offline" );
timeTemp = StaticVarGet( systemName + "timeTemp" );
nowBar = StaticVarGet( systemName + "nowBar" );
dow = Now( 9 );
weekEnd = IIf( ( dow == 1 OR dow == 7 ), 1, 0 );
marketOpen1 = 094500;//09:45:00;
marketClose1 = 123000;
marketOpen2 = 141500;
marketClose2 = 165500;
marketON = True;
//( ( Now( 4 ) >= marketOpen1 AND Now( 4 ) < marketClose1 ) OR( Now( 4 ) >= marketOpen2 AND Now( 4 ) < marketClose2 ) ) AND NOT weekEnd;
marketOFF = NOT marketON ;
sAutoTrading = Nz( StaticVarGet( "sAutoTrading" ) ); // Model Status Turn on or Turn off save in Static Variable "ExampleSystem"
ATonTrigger = ParamTrigger( "Start AutoTrading", "START" ); // Turn on Button in Parameter
AToffTrigger = ParamTrigger( "Stop AutoTrading", "STOP" ); // Turn off Button in Parameter
Reset = ParamTrigger( "Reset", "Reset" ); // Make a reset for model
if( ATonTrigger ) // Set Turn on in Static Variable "ExampleSystem"
{
StaticVarSet( "sAutoTrading", 1 );
_TRACEF( "Model Start" );
}
if( AToffTrigger ) // Set Turn off in Static Variable "ExampleSystem"
{
StaticVarSet( "sAutoTrading", 0 );
_TRACEF( "Model Stop" );
}
if( reset ) // Reset all Static Variable (not delete clear value only)
{
StaticVarSet( systemName + "timeTemp", 0, True );
StaticVarSet( systemName + "nowBar", 0 , True );
StaticVarSet( "sAutoTrading", 0 , True );
_TRACEF( "!CLEAR!" );
_TRACEF( "Model Reset" );
}
printf( NumToStr( Now( 5 ), formatDateTime ) );
printf( "\n#####################\n" );
if( StaticVarGet( "sAutoTrading" ) )
{
printf( "System ON" );
}
else
{
printf( "System OFF" );
}
printf( WriteIF( marketOn, "\nMarket ON", "\nMarket OFF" ) );
}
//////////////////////////////// system action (can change carefully) ////////////////////////////////
//Do only when Model Turn On
{
if( StaticVarGet( "sAutoTrading" ) )
{
autoTradeStatus = "Stand By";
//Do only market on
if( LastValue( marketON ) )
{
autoTradeStatus = "Ready";
//do when time change (last time save in Static Variable "ExampleSystemtimeTemp")
if( Now( 5 ) != timeTemp )
{
autoTradeStatus = "Action";
//if do save now time in Static Variable "ExampleSystemtimeTemp"
StaticVarSet( systemName + "timeTemp", Now( 5 ), True );
///////////////////////////////////// action in realtime before check last bar /////////////////////////////////////
/////////////////////////////////// end action in realtime before check last bar ///////////////////////////////////
//do when bar change (last bar time save in Static Variable "ExampleSystemnowBar")
if( dateAll[lb] != nowBar )
{
//if do save now bar in Static Variable "ExampleSystemnowBar"
StaticVarSet( systemName + "nowBar", dateAll[lb], True );
///////////////////////////////////////// action once last bar (on last bar) /////////////////////////////////////////
CAF_MT4_SetPortPosition( symbol, key, ip, port, targetPosition );
//if(targetPosition>0)
//_TRACE("#Action Send order withTargetPosition: "+NumToStr(targetPosition ));
/////////////////////////////////////// end action once last bar (on last bar) ///////////////////////////////////////
}
///////////////////////////////////// action in realtime after check last bar ////////////////////////////////////
/////////////////////////////////// end action in realtime after check last bar //////////////////////////////////
}
}
}
}
{
// interpretation
printf( "\nAutotrade Status = " + autoTradeStatus );
printf( "\n#####################" );
printf( "\nTarget Portfolio = %g", targetPosition );
}
_SECTION_END();
{
// manual sending
testSendOder = ParamTrigger( "Test Send Order Manually", "Test" );
target = Param( "target", 0, -100, 100 );
if( testSendOder )
{
_TRACEF( "#Send order manually : NowPort = %g", CAF_MT4_SetPortPosition( symbol, key, ip, port, target ) );
}
}
}
Can I apply BarsSince funtion in realtime -autotrade?
What other way can I use to prevent late signal to entry in realtime-autotrade?