Closing Whole Position Issue & False Buy and Sell Signals

cmo17

New Member
I have been programming for a few years but I am brand new to thinkscript and have run into some issues I cant fix. Any help is appreciated.

As you can see from the screen shot below the buy and sell is not working correctly. In this example this should not buy here because the close of the last bar was 2.24 and sma1 was 2.15 which means it was less. I am not sure why it is buying here.... The condition to buy is (close1 < sma1)

False buy

In the second example I am not sure why it is selling here. The bar before had close1 > sma1 and not close < sma1 like the condition is to sell.
False sell
The other problem I have is when I use entryPrice() it doesnt actually find that and just grabs the last price so I may buy 10 shares at $1 a piece and then it goes to 1.02 and now it is going to just close 9 of the shares instead of 10. Does anyone know how to just find however many shares are left and close it? Instead of making this super hard like I am. I cant seem to find anything like PositionSize() or something that I could use for tradeSize to close? Thanks!

This is my code
```
input priceType = PriceType.LAST;
plot LastPrice = close(priceType = priceType);

plot sma1 = (close[2]+close[1])/2;
def close1 = close[1];
def close2 = close[2];
def sma2 = (close[3]+close[2])/2;

AddOrder(OrderType.BUY_TO_OPEN, tradeSize = (10000/LastPrice) ,condition = ((close1 > (sma1*.9997)) and (close2<sma2)), name = "BUY");

AddOrder(OrderType.SELL_AUTO, tradeSize = (3333/entryPrice()), condition = (LastPrice crosses above (entryprice()*1.039998)), name = "TAKE PROFIT 1");
plot tp1 = if (LastPrice crosses above (entryprice()*1.039998),yes,no);
AddOrder(OrderType.SELL_AUTO, tradeSize = (3333/entryPrice()), condition = (LastPrice crosses above (entryprice()*1.069998)), name = "TAKE PROFIT 2");
plot tp2 = if (LastPrice crosses above (entryprice()*1.069998),yes,no);
AddOrder(OrderType.SELL_AUTO, tradeSize = (1667/entryPrice()), condition = (LastPrice crosses above (entryprice()*1.149998)), name = "TAKE PROFIT 3");
plot tp3 = if (LastPrice crosses above (entryprice()*1.149998),yes,no);

AddOrder(OrderType.SELL_TO_CLOSE, tradeSize = if (tp1 == no,10000/entryPrice(),if(tp1 == yes and tp2 == no,(10000*.666666667)/entryPrice(),if(tp1 == yes and tp2 == yes and tp3 == no,(10000*.3333333334)/entryPrice(),if(tp1 == yes and tp2 == yes and tp3 == yes,(10000*.1666667)/entryPrice(),10000/entryPrice())))) ,condition = (close1 < sma1), name = "CLOSE LONG POS");
```
 
Top