Total noob, so be kind.
Why is my algo taking a trade every minute, even when I told it to only take a trade if position == 0?
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stock = sid(--masked--)
for minute in range(0, 390, 1):
schedule_function(trade, date_rules.every_day())
#close out positions end of day
schedule_function(close_orders, date_rules.every_day(), time_rules.market_close(hours=0, minutes=5))
def trade(context, data):
current_position = context.portfolio.positions[context.stock].amount
price = data.current(context.stock, 'price')
# Load historical data for the stocks
#looking for 4 days worth of data
prices = data.history(context.stock, 'price', 1440, '1m')
upper, middle, lower = talib.BBANDS(
prices,
timeperiod=20,
# number of non-biased standard deviations from the mean
nbdevup=2,
nbdevdn=-2,
# Moving average type: simple moving average here
matype=0)
# If price is below the recent lower band and we have
# no long positions then go long
if price <= lower[-1] and current_position == 0 and data.can_trade(context.stock):
order_target(context.stock, 1000)
log.info('long trade taken at' + str(price))
# If price is above the recent upper band and we have
# no short positions then go short
elif price >= upper[-1] and current_position == 0 and data.can_trade(context.stock):
order_target(context.stock, -1000)
log.info('short trade taken at' + str(price))