有網友問了個問題,希望能夠計算場中所有商品的損益,如果賺到一定金額或賠到一定金額,就全部一起出場, 想要實現這樣的功能,是有一點難度的,需要在一些條件下才能成立
想要能夠加總所有股票的數值,就會需要用到getsymbolfield這個函數,才能夠同時抓到所有不同商品的數值,如果要計算損益,在交易功能內,最方便的就是使用position、filled、filledavgprice這些函數來做計算,但很可惜的是,getsymbolfield無法支援抓到這幾個函數的值,讓想要實現這個功能變得很複雜,不過,還是想了兩個可能的解決方式,一個要在盤前設定、一個要在盤中設定
1.盤前設定
如果你在開盤前就決定要進哪些股票,且是一開盤就進場,這個方式適合你,只要在盤前設定好商品,跟達到多少損益要出場,開盤後就可以全自動監控了
input: stock1("2330.tw","股票代碼1"); input: stock2("3481.tw","股票代碼2"); input: stock3("2436.tw","股票代碼3"); input: stock4("3189.tw","股票代碼4"); input: profitex(3000,"獲利多少出場"); input: lostex(3000,"虧損多少出場"); vars: i(0); vars: intraBarPersist totalprofit(0); if date<>date[1] then begin i=0; totalprofit=0; end; //進場 if date<>date[1] and position=0 then setposition(1,market); //紀錄數值 array: entryP[4](0); //抓開盤價 entryP[1]=getsymbolfield(stock1,"open","D"); entryP[2]=getsymbolfield(stock2,"open","D"); entryP[3]=getsymbolfield(stock3,"open","D"); entryP[4]=getsymbolfield(stock4,"open","D"); array: symbolofstock[20](0); //抓現在價格 symbolofstock[1]=getsymbolfield(stock1,"close"); symbolofstock[2]=getsymbolfield(stock2,"close"); symbolofstock[3]=getsymbolfield(stock3,"close"); symbolofstock[4]=getsymbolfield(stock4,"close"); //出場 totalprofit=(array_sum(symbolofstock,1,4)-array_sum(entryp,1,4))*1000; if position<>0 then begin if (totalprofit>=profitex or totalprofit<-lostex) then setposition(0,market); end; // print(totalprofit,"損益");
2.盤中設定
這個方式應該可以適合所有情況,但較麻煩點,需要盯著盤中一有新商品進場,就先暫停策略,然後人工添加股票,這個方式除了添加股票代碼之外,還需要加入進場價格,但在計算上,較不會有錯誤
input: stock1("2330.tw","股票代碼1"); input: stock1_p(490,"進場價"); input: stock2("3481.tw","股票代碼2"); input: stock2_p(490,"進場價"); input: stock3("2436.tw","股票代碼3"); input: stock3_p(490,"進場價"); input: stock4("3189.tw","股票代碼3"); input: stock4_p(490,"進場價"); input: profitex(6000,"獲利多少出場"); input: lostex(6000,"虧損多少出場"); vars: intraBarPersist totalprofit(0); if date<>date[1] then begin totalprofit=0; end; //進場 if date<>date[1] and position=0 then setposition(1,market); //紀錄數值 array: entryP[4](0); //進場價 entryP[1]=stock1_p; entryP[2]=stock2_p; entryP[3]=stock3_p; entryP[4]=stock4_p; array: symbolofstock[20](0); //抓現在價格 symbolofstock[1]=getsymbolfield(stock1,"close"); symbolofstock[2]=getsymbolfield(stock2,"close"); symbolofstock[3]=getsymbolfield(stock3,"close"); symbolofstock[4]=getsymbolfield(stock4,"close"); //出場 totalprofit=(array_sum(symbolofstock,1,4)-array_sum(entryp,1,4))*1000; if position<>0 then begin if (totalprofit>=profitex or totalprofit<-lostex) then setposition(0,market); end;
發佈留言
很抱歉,必須登入網站才能發佈留言。