Hi everyone, I am new and I have a problem in my code, I try to store the buying value as soon as I buy and it does not work
I just want to store this value to calculate a simply stop loss, but I have this error :
UnboundLocalError: local variable 'selling_price' referenced before assignment
I also tried with context.selling_price = data.current(context.spy, 'price') but the problem is the same.
Is someone have an idea ? Thanks
Here is my code
def initialize(context):
context.spy = sid(5061)
set_commission(commission.PerShare(cost=0.001, min_trade_cost=1))
schedule_function(open_positions, date_rules.every_day(), time_rules.market_open(hours=1))
def open_positions(context, data):
open_orders = get_open_orders()
sma_20 = data.history(context.spy, 'price', 20, '1d').mean()
sma_50 = data.history(context.spy, 'price', 50, '1d').mean()
current_price = data.current(context.spy, 'price')
record(mma20=sma_20, mma50=sma_50, leverage = context.account.leverage, prix_actuel=current_price)
if sma_20 > sma_50:
if context.spy not in open_orders and data.can_trade(context.spy):
order_target_percent(context.spy, 1)
buying_price = data.current(context.spy, 'price')
elif sma_50 > sma_20:
if context.spy not in open_orders and data.can_trade(context.spy):
order_target_percent(context.spy, -1)
selling_price = data.current(context.spy, 'price')
#stop loss
if context.spy not in open_orders and data.can_trade(context.spy) and current_price <= 0.999*buying_price:
print 'boucle1'
order_target_percent(context.spy, -1)
if context.spy not in open_orders and data.can_trade(context.spy) and current_price >= 1.001*selling_price:
print 'boucle2'
order_target_percent(context.spy, 1)