kilroy 發表於 14-6-1 22:49
Hi,
1.
謝謝K 大, 過去兩個星期 我已經不斷嘗試了無數次, K大的語法都用上, 但都無法做到我希望的結果
請大大再幫忙, 看看我的語法要怎樣修改才可以:
1. 設定 "Sell" 只會出現在 "Buy" 成立了之後
2. 把 trailling stop 的語法寫進策略裡
假設以下是一個10分k 策略
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
// 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////////////////////////////////////////////////
TimeFrameSet( 30 * in1Minute );
BuySignal1 = C < MA (C, 15);
TimeFrameRestore();
BuySignal = C> Ref(C,-1);
sellSignal = Ref(C,-1) >C;
TimeFrameRestore();
Buy = BuySignal & TimeFrameExpand(BuySignal1 , N*in1Minute) ;
Sell =sellSignal & TimeFrameExpand(BuySignal2 , N*in1Minute);
Short = 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=10000; // 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(ISL,-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));
/////////////////// 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);
LastSell = LastValue(Sell);
LastShort = LastValue(Short);
Filter=Buy OR Sell;
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 || LastSell))
{
// 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 == "" )
{
OID = ibc.PlaceOrder( IBName, "Buy", 1, "MKT", 0, TickSize,
"DAY", submitorders, TickSize/0.0001, "outsideRTH" );
// _TRACE("# Pos: 0, PrevOID: "+OrderID+", Buy 1, NewOID: "+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);
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;
}
}
}
else if( LastSell AND OrderID == "" )
{
OID = ibc.PlaceOrder( IBName, "Sell", 1, "MKT", 0, TickSize,
"DAY", SubmitOrders, TickSize/0.0001, "outsideRTH" );
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);
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); |