Hi, new to the trading world.
I tried to use the money from selling the stock to re-invest in the next buy. But seems my code doesn't work. How should I fix it?
I tried to use the money from selling the stock to re-invest in the next buy. But seems my code doesn't work. How should I fix it?
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 = open[-1], tradeSize = shares);
addOrder(OrderType.SELL_TO_CLOSE, SellSignal, price = open[-1], tradeSize = shares);
addchartbubble(1, 10, "c:" + cash + "\n" + "s:" + shares + "\n" + "i:" + initialCash);
Last edited by a moderator: