The code can plot arrows to show there are BUY or Sell signals; however, there are no buy or sell actions if I want to auto trade the code. Any hint?
I am using AutoTrader Basic Flow, and Modified Renko Chart as the code base. Basically, the code is almost the same but adding several lines to add intervals:
( Interval(1) == -500 AND ChartPeriod == "500T" ) OR
( Interval(1) == -1000 AND ChartPeriod == "1000T" )
correct symbol to trade and generate signals:
Buy = C > O;
Short = C < O;
Sell = Short;
Cover = Buy;
Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy );
Short = ExRem( Short, Cover ); Cover = ExRem( Cover, Short );
There is the code:
_N(SectionName = "AutoTrader Basic Flow");
_N(Ver = "Ver1_0");
_SECTION_BEGIN(SectionName);
EnableTextOutput(False); // prevents incidental text from being displayed in the interpretation
Filename = StrLeft(_DEFAULT_NAME(),StrLen(_DEFAULT_NAME())-2) + " " + Ver; // the name of the program and is displayed on the title line
// CAUTION: VarPfx is used to make the static variables unique tp prevent bizarre results if you use multiple versions of the trading program simultaneously.
VarPfx = Filename + Ver + Name();
_N(Title = Filename + StrFormat(" - {{DATE}} \nOpen %g, Hi %g, Lo %g, Close %g Vol %g " + " {{VALUES}}", O, H, L, C, V ));
RequestTimedRefresh(1);
SetChartOptions(0, chartShowDates);
pAutoTrading = ParamToggle("AutoTrade", "Off|Running"); // turns auto trading on and off
Pause = ParamToggle("Pause trading", "Run|Pause"); // pause trading
DebugOn = ParamToggle("DebugView","Off|Running",0); // Dumps trade data to an output window
closetime = Param("Close time (hhmmss)", 160000, 0, 245959, 1500); // end trading at the time specified
// The chart period below must agree with the chart before AutoTrading will connect to TWS.
// the following lines define the acceptable periods that auto trading will work with.
// To add a period simply add the period to the existing ParmList separated by a comma AND then add an interval test to the IF statement.
ChartPeriod = ParamList("Chart Period", "500T,1000T,1,3,5,7,10,15,20,30,Hour,Day", 0); // chart period must agree with this setting for auto trading to work
if( ( Interval(1) == -500 AND ChartPeriod == "500T" ) OR
( Interval(1) == -1000 AND ChartPeriod == "1000T" ) OR
( Interval() == 60 AND ChartPeriod == "1" ) OR
( Interval() == 60 * 3 AND ChartPeriod == "3" ) OR
( Interval() == 60 * 5 AND ChartPeriod == "5" ) OR
( Interval() == 60 * 7 AND ChartPeriod == "7" ) OR
( Interval() == 60 * 10 AND ChartPeriod == "10" ) OR
( Interval() == 60 * 15 AND ChartPeriod == "15" ) OR
( Interval() == 60 * 20 AND ChartPeriod == "20" ) OR
( Interval() == 60 * 30 AND ChartPeriod == "30" ) OR
( Interval() == inHourly AND ChartPeriod == "Hour" ) OR
( Interval() == inDaily AND ChartPeriod == "Day" ) ) IntervalOK = True;
else IntervalOK = False;
pContracts = Param("Contracts", 1, 1, 1000, 1); // definethe default number of contracts to order
OrderType = ParamList("Order type", "STP,LMT,MKT", 2); // select type of ofder to send
tick = Param("Tick size", 2500, 0, 2500, 0.0001); // amount from current price the stop order will be set
tMult = Param("Tick multiplier", 1, 1, 1000, 1); // tick * multiplier is used in placeOrder
tickMult = tick * tMult;
// The symbol on the chart must agree with the symbol selected from this list before AutoTrading will connect to TWS
// Note on modifyin this. The symbol must match exactly what is in the AB symbol directory.
// You can see below that ZG has spaces and the exact number of spaces is required.
// To add a new line just copy a line and replace the things between the "..." with the new symbol.
// The last line ends with "); and that is required so don't mess it up.
// To change the ticker list you may remove a line but refer to ParamList if you have trouble. The spacing has to be exactly what the AB database has.
// The ticker list is a string separated by commas. If you separate them so they fit on another line you must close the string, add a + to indicate
// the string continues on the next line. The string must be closed with a " and the ParamList must be closed with a );
sTicker = ParamList("Symbol to trade",
"ESU9-GLOBEX-FUT," +
"TFZ8-NYBOT-FUT," +
"DXZ8-NYBOT-FUT," +
"NDZ8-NYBOT-FUT," +
"NQZ8-NYBOT-FUT," +
"ZG AUG 08-ECBOT-FUT," +
"EUR.USD-IDEALPRO-CASH," +
"IWM-ISLAND-STK," +
"TWM,UWM," +
"QID,QLD,QQQQ");
ManualBuy = ParamTrigger("Manual buy", "Buy"); // allows user to buy the default number of contracts
ManualSell = ParamTrigger("Manual Sell", "Sell"); // allows user to sell the default number of contracts
CancelAll = ParamTrigger("Cancel all pending orders", "Cancel all"); // user can cancel all orders that have not been filled
CloseAll = ParamTrigger("Close all", "Close all"); // cancel all pending orders and close all open positions
Reset = ParamTrigger("Reset", "Reset"); // resets the auto trading variables
StaticVarSet(VarPfx + "AutoTrading", pAutoTrading );
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ############### Initilization Initilization Initilization Initilization Initilization ########################################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
sysTime = Now(4); // time offset from New York
sysTimeStr = NumToStr(SysTime, 1.0, False);
barTime = TimeNum();
// assign values to the following constants
// trigger states used by the program
fNone = 0; // no orders are being processed
mCancel = 1; // the user has manually selected cancel all open orders
mClose = 2; // the user has manually selected close all trades
mBuy = 3; // the user has manually placed a buy order
mSell = 4; // theuser has manually placed a sell order
pBuy = 5; // the users system has generated a buy order
pSell = 6; // the users system has generated a sell order
pShort = 7; // the users system has generated a short order
pCover = 8; // the users system has generated a cover order
// order states set by the program
ordNone = 20; // there are no open orders being processed
ordCancelBuy = 21; // an open buy order is being cancelled and is waiting for a "Cancelled" status from TWS
ordCancelSell = 22; // an open sell order is being cancelled and is waiting for a "Cancelled" status from TWS
ordSell = 23; // an open sell order is being processed and is waiting for a "Filled" status from TWS
ordBuy = 24; // an open buy order is being processed and is waiting for a "Filled" status from TWS
ordCover = 25; // an open cover order is being processed and is waiting for a "Filled" status from TWS
ordShort = 26; // an open short order is being processed and is waiting for a "Filled" status from TWS
ordCancelAll = 27; // a cancel all order is being processed and is waiting for a "Cancelled" status from TWS
ordCloseAll = 28;
ordManBuy = 29; // a manual buy order is being processed and is waiting for a "Filled" status from TWS
ordManSell = 30; // a manual sell order is being processed and is waiting for a "Filled" status from TWS
// initializes the static variables when the program starts and when the user presses Reset.
if (Reset OR Nz(StaticVarGet(VarPfx + "SystemInitialized"), True)) // init static vars when indicator starts
{
StaticVarSet(VarPfx + "SystemInitialized", True);
// pause = True; // used to artifically pause the system on init.
// initialize auto trading vars
StaticVarSet(VarPfx + "OrderState", ordNone); // contains the order state being processed, normal is none
StaticVarSetText(VarPfx + "ordID", ""); // an active order being processed, blank when no orders are active
StaticVarSet(VarPfx + "GetStatus", False); // a flag informs the program that statis is being requested for an active order
StaticVarSet(VarPfx + "WaitForConfirm", False); // waiting for the number of contracts to agree with the order that was placed
StaticVarSetText(VarPfx + "EOD", ""); // used to control order processing at the close of trading hours
} // end of power up or reset initialize
// make variables available to the system and trading code
OrderState = StaticVarGet(VarPfx + "OrderState"); // the current order state
numPositions = Nz(StaticVarGet(VarPfx + "numPositions")); // the number of positions currently held on TWS
GetStatus = StaticVarGet(VarPfx + "GetStatus"); // the condition of the status flag, true if waiting for status from TWS
ordID = StaticVarGetText(VarPfx + "ordID"); // ID of the order beign processed
WaitForConfirm = StaticVarGet(VarPfx + "WaitForConfirm"); // flag used to tell the program to wait for TWS to update the number of positions
LastC = LastValue(Close); // this is the last tick that was received from the broker data feed
errorMsg = "None"; // used to hold the TWS error message
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ################################ Functions Functions Functions Functions Functions Functions ######################################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// converts the trade states to displayable text
function fCvtState(s) // conberts the states to strings for file or trace
{
temp = "";
// prog trigger states
if(s==fNone) temp = "NoTrigger";
else if(s==pBuy) temp = "ProgBuy";
else if(s==pSell) temp = "ProgSell";
else if(s==pShort) temp = "ProgShort";
else if(s==pCover) temp = "ProgCover";
// order states
else if(s==ordNone) temp = "OrdNone";
else if(s==ordBuy) temp = "OrdBuy";
else if(s==ordSell) temp = "OrdSell";
else if(s==ordShort) temp = "OrdShort";
else if(s==ordCover) temp = "OrdCover";
else if(s==ordCancelBuy) temp = "OrdCancelBuy";
else if(s==ordCancelSell) temp = "OrdCancelSell";
else if(s==ordCancelAll) temp = "OrdCancelAll";
else if(s==ordCloseAll) temp = "OrdCloseAll";
else if(s==ordManBuy) temp = "ordManBuy";
else if(s==ordManSell) temp = "OrdManSell";
// manual triggers
else if(s==mCancel) temp = "Cancel";
else if(s==mClose) temp = "CloseAll";
else if(s==mBuy) temp = "ManBuy";
else if(s==mSell) temp = "ManSell";
// error state
else
{
temp = "Invalid state";
if(DebugOn) _TRACE("#, Invalid state=" + NumToStr(s, 1.0));
}
return temp;
}
// take hhmmss string and convert to hh:mm:ss
function fFormatTime(time)
{
tFmt = "";
Len = StrLen(time);
if(Len == 5) tFmt = StrLeft(time,1) + ":" + StrMid(time,1,2) + ":" + StrRight(time, 2);
else tFmt = StrLeft(time,2) + ":" + StrMid(time,2,2) + ":" + StrRight(time, 2);
return tFmt;
}
// this handles the errors returned on the GetStatus command.
function fErrorProcessor(msg)
{
msgid = "";
if(StrLeft(msg, 2) == "ID")
{
offset1 = StrFind(msg, "Error ");
temp = StrMid(msg, offset1 + 5, offset1 + 5);
Offset2 = StrFind(temp, ".");
msgid = StrLeft(temp, Offset2 - 1);
if(DebugOn) _TRACE("#, ErrorMessage = " + msgid);
}
return msgid;
}
if(DebugOn) _TRACE("#, Post Init A, Positions=" + NumToStr(StaticVarGet(VarPfx + "numPositions"), 1.0) +
", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID +
", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0));
_SECTION_END();
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ################### Trading system indicators Trading system indicators Trading system indicators #####################
// ################### This section of the code uses AB indicators to define the trade timing. #####################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
_SECTION_BEGIN("System");
// ##############################################################################################################################################################
// ################ System Parameters
// ##############################################################################################################################################################
Buy = Sell = Short = Cover = 0; // make sure all arrays are set empty
// ##############################################################################################################################################################
// ################ Signal calculations - add your indicator and calculations here
// ##############################################################################################################################################################
// Modified Renko Chart with custom date axis
// and high/low winks
// Loosely based on Renko chart formula by G. Kavanagh
// from AmiBroker on-line formula library (id=521)
// Modifications & fixes TJ 2014
function FillRun( dir, num, changedir )
{
global i, j, modified, dt, RKC, RKO, RKD, RKH, RKL;
for ( x = 1; x <= num AND j < BarCount - 1; x++ )
{
j++;
extra = ( changedir AND x == 1 ) * dir;
RKC[ j ] = RKC[ j - 1 ] + dir + extra;
RKO[ j ] = RKC[ j - 1 ] + IIf( modified, 0, extra );
RKD[ j ] = dt[ i ];
RKH[ j ] = High[ i - 1 ];
RKL[ j ] = Low[ i - 1 ];
}
}
SetBarsRequired( sbrAll, sbrAll );
Brick = Param( "Brick Size", 0.001, 0.0001, 1.00, 0.001 );
reverse2 = 2;
intra = 1;//ParamToggle( "Intraday", "No|Yes", 0 );
modified = ParamToggle( "Modified", "No|Yes", 0 );
// Convert the closing price to rising and falling rounded bricks
CF = ceil( C / Brick );
CR = floor( C / Brick );
// initialize first element
j = 0;
RKC[j] = CF[0];
RKO[j] = CF[0] + 1;
RKD = 0;
RKH = 0;
RKL = 0;
dt = IIf( intra, floor( TimeNum() / 100 ), DateNum() );
dir = -1; // 1 is up, -1 is down
// Loop to produce the Renko values in number of bricks
for ( i = 1; i < BarCount - 1; i++ )
{
if ( j >= BarCount )
break; // no more room -> finish
if ( CF[i] <= RKC[j] - 1 AND dir < 0 ) // Continue down
{
num = RKC[j] - CF[i];
FillRun( dir, num, False );
}
else
if ( CR[i] >= RKC[j] + reverse2 AND dir < 0 ) // Change down to up
{
num = CR[i] - RKC[j];
dir = 1;
FillRun( dir, num, True );
}
else
if ( CR[i] >= RKC[j] + 1 AND dir > 0 ) // Continue Up
{
num = CR[i] - RKC[j];
FillRun( dir, num, False );
}
else
if ( CF[i] <= RKC[j] - reverse2 AND dir > 0 ) // Change up to down
{
num = RKC[j] - CF[i];
dir = -1;
FillRun( dir, num, True );
}
}
// move the chart to right end of chart space, ie last brick on last bar position
delta = BarCount - 1 - j;
RKC = Ref( RKC, -delta );
RKO = Ref( RKO, -delta );
RKD = Ref( RKD, -delta );
RKH = Ref( RKH, -delta );
RKL = Ref( RKL, -delta );
C = RKC * Brick;
O = RKO * Brick;
H = IIf( modified, RKH, Max( C, O ) );
L = IIf( modified, RKL, Min( C, O ) );
Buy = C > O;
Short = C < O;
Sell = Short;
Cover = Buy;
Buy = ExRem( Buy, Sell ); Sell = ExRem( Sell, Buy );
Short = ExRem( Short, Cover ); Cover = ExRem( Cover, Short );
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ##################### PLOT INDICATORS PLOT INDICATORS PLOT INDICATORS PLOT INDICATORS PLOT INDICATORS ##################################
// ##################### Change the following lines to display your system as you see fit. ##################################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
Plot( C, "", IIf( C > O, colorGreen, colorRed ), styleCandle );
PlotShapes( shapeUpArrow * Buy, colorGreen, 0, O );
PlotShapes( shapeDownArrow * Sell, colorRed, 0, O );
PlotShapes( shapeHollowUpArrow * Cover, colorGreen, 0, O, -30 );
PlotShapes( shapeHollowDownArrow * Short, colorRed, 0, O, -30 );
xnum = floor( RKD / 100 );
XChange = IIf( xnum != Ref( xnum, -1 ), 1, Null );
Plot( XChange, "", colorGrey50, styleHistogram | styleOwnScale, 0, 1 );
// Draw renko-date axis
MonthNames = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
fvb = FirstVisibleValue( BarIndex() );
lvb = LastVisibleValue( BarIndex() );
for ( i = fvb; i < lvb; i++ )
{
if ( XChange[ i ] )
{
if ( intra )
datetext = StrFormat( "%02gh", floor ( RKD[ i ] / 100 ) );
else
if ( ( xnum[ i ] % 100 ) == 1 )
datetext = StrFormat( "%04.0f", 1900 + ( xnum[ i ] / 100 ) );
else
datetext = StrExtract( MonthNames, ( xnum[ i ] % 100 ) - 1 );
PlotText( datetext , i, LowestVisibleValue( Low ), colorGrey50, colorWhite, -20 );
}
}
Title = Name() + StrFormat( " - 20%06.0f", RKD % 1000000 ) + " - Renko Chart : Last Value = " + RKC * Brick + " H: " + RKH + " L: " + RKL + ", Brick Size = " + Brick;
GraphXSpace = 5;
_SECTION_END();
_SECTION_BEGIN(SectionName + "AT"); // Dont change anything in this section unless you know exactly what you are doing.
// ##############################################################################################################################################################
// ################ DO NOT CHANGE THE NEXT 4 LINES -- last values changes the array signal to a binary signal to provide a trigger for the auto trade logic
// ##############################################################################################################################################################
// displays the signal value in the interpretation window
printf("\nBuy = " + NumToStr(Buy, 1.0) +
" Sell = " + NumToStr(Sell, 1.0) +
" Short = " + NumToStr(Short, 1.0) +
" Cover = " + NumToStr(Cover, 1.0) + "\n");
BuyInd = LastValue(Buy); // convert the buy signal to a pulse used by the trading logic
ShortInd = LastValue(Short); // convert the short signal to a pulse used by the trading logic
SellInd = LastValue(Sell); // convert the sell signal to a pulse used by the trading logic
CoverInd = LastValue(Cover); // convert the cover signal to a pulse used by the trading logic
if(DebugOn) _TRACE("#, Indicators 2, Static, BuyInd = " + NumToStr(BuyInd, 1.0) +
", SellInd = " + NumToStr(SellInd, 1.0) +
", ShortInd = " + NumToStr(ShortInd, 1.0) +
", CoverInd = " + NumToStr(CoverInd, 1.0) );
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ###################################### MANUAL BUY MANUAL BUY MANUAL BUY MANUAL BUY MANUAL BUY ###################################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
function fManBuyPositions(ib, oState, OID, positions)
{
if(DebugOn) _TRACE("#, ManBuy top, positions=" + NumToStr(positions, 1) + ", contracts=" + NumToStr(pContracts, 1));
newState = oState;
// this function closes all open trades
orderID = "";
orderID = ib.PlaceOrder(sTicker, "Buy", pContracts, "MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");
if(orderID != "")
{
ordType = "ManBuy";
newState = ordManBuy;
StaticVarSet(VarPfx + "TargetPositions", positions + pContracts);
StaticVarSetText(VarPfx + "ordID", orderID );
StaticVarSet(VarPfx + "GetStatus", True);
StaticVarSet(VarPfx + "WaitForConfirm", True);
if(DebugOn) _TRACE("#, ManBuy " + ordType + ", " + fFormatTime(sysTimeStr) + ", OrderID" + orderID + ", OrderState=" + fCvtState(newState) +
", Close=" + NumToStr(LastValue(Close), 1.2));
}
return newState; // return the type of order that was made
}
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ################################# MANUAL SELL MANUAL SELL MANUAL SELL MANUAL SELL MANUAL SELL ###################################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
function fManSellPositions(ib, oState, OID, positions) // we are neither long or short
{
if(DebugOn) _TRACE("#, ManSel1 top, positions=" + NumToStr(positions, 1) + ", contracts=" + NumToStr(pContracts, 1));
newState = oState;
orderID = "";
orderID = ib.PlaceOrder(sTicker, "SELL", pContracts, "MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");
if(orderID != "")
{
ordType = "ManSell";
newState = ordManSell;
StaticVarSet(VarPfx + "TargetPositions", positions - pContracts);
StaticVarSetText(VarPfx + "ordID", orderID);
StaticVarSet(VarPfx + "GetStatus", True);
StaticVarSet(VarPfx + "WaitForConfirm", True);
if(DebugOn) _TRACE("#, ManSel1, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderID=" + orderID +
", OrderState=" + fCvtState(newState) + ", Close=" + NumToStr(LastValue(Close), 1.2));
}
return newState; // return the type of order that was made
}
// ##############################################################################################################################################################
// ##############################################################################################################################################################
// ###################################### CANCEL CANCEL CANCEL CANCEL CANCEL CANCEL ######################################
// ##############################################################################################################################################################
// ##############################################################################################################################################################
function fCancelPositions(ib, oState, OID, positions) // we are neither long or short
// trigger - trg defines the type of order
{
newState = oState;
// this if statement prevents making multiple orders - subsequent orders are ignored
if( oState == ordSell OR oState == ordShort)
{
if(OID != "") // used to cancel a sell order that has not been filled
{
newState = ordCancelSell;
ordType = "CancelSell";
ib.CancelOrder(OID);
StaticVarSet(VarPfx + "GetStatus", True);
if(DebugOn) _TRACE("#, Cancel 1, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState =" + fCvtState(newState) +
", OrderID=" + OID);
}
}
else if(oState == ordBuy OR oState == ordCover)
{
if(OID != "") // used to cancel a buy order that has not been filled
{
newState = ordCancelBuy;
ordType = "CancelBuy";
ib.CancelOrder(OID);
StaticVarSet(VarPfx + "GetStatus", True);
if(DebugOn) _TRACE("#, Cancel 2, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) +
", OrderID=" + OID);
}
}
return newState; // return the type of order that was made
}