admin管理员组

文章数量:1122832

Context: I tried to use the money from selling the stock to re-invest in the next buy.

Implementation: I want to use the variable cash and shares to remember the historical information. But seems my code doesn't work and cash and shares value are always 0.

How should I fix it?

ThinkScript Code:

input SMA_Length = 120;  # Length of the SMA
input initialCash = 10000;


# Calculate the Simple Moving Average
def SMA = Average(close, SMA_Length);

# Detect buy and sell signals based on slope transitions
def BuySignal = close > SMA;
def SellSignal = close < SMA;

def cash;
def shares;

shares = if BuySignal and IsNaN(shares[1]) then floor(initialCash/close)  # first trade
else if BuySignal then floor(cash[1]/close)
else if SellSignal then 0
else shares[1];

cash = if IsNaN(cash[1]) then initialCash # before first trade
else if BuySignal then 0
else if SellSignal then shares[1]*close
else cash[1];

# Add buy and sell orders
addOrder(OrderType.BUY_TO_OPEN, BuySignal, price = close, tradeSize = shares);
addOrder(OrderType.SELL_TO_CLOSE, SellSignal, price = close, tradeSize = shares);

addchartbubble(1, 10, "c:" + cash + "\n" + "s:" + shares + "\n" + "i:" + initialCash);

本文标签: recursioninitialized the recursive variable in thinkscriptStack Overflow