Back to Community
looked everywhere! - need help with creating a sell order after holding security for 15 minutes

Tried looking everywhere, and tried some stuff on my own. I cannot figure how to record a timestamp of an order is executed. I would then like to have time held as one of the details in my algo.

I just cannot think of how to do this...Thanks.

7 responses

you can track your orders by setting a variable every time you place the order, then check those orders for filled shares, if they have filled shares then start a timer and track it in handle data.

def order_stocks(context,data):  
    order = order_target_percent(stock,1.0)  
    context.orders.append(order)


def handle_data(context, data): #every minute check  
for order in context.orders:  
     if order.filled > 0:  
         set "start" variable True  
        context.orders.remove(order)

    if start variable == True:  
        context.i +=1  
    else:  
        context.i = 0

    if context.i >= 15:  
        sell stock  
        set start False  
        context.i = 0

thanks for the help, but I can't get anything to work using this : / but I am thinking something like this would work, but i can't figure it out. Thoughts?:



    for stock in context.securities:  
        current_position = context.portfolio.positions[stock].amount  
        positions = context.portfolio.positions[stock].sid  
        if current_position > 0:  
            positions +=1

I get confused at the end - positions +=1 doesn't work, but maybe something like that?

p.s. I am able to use if current_position > 0 becuase further on I only place an order if current position = 0

struggling with this

You'll need to post an algo showing what you are trying to do for me to help you out more. The code I posted above should show you how to do it, it's pseudo-code though so you won't be able to just copy-paste, you'll need to adapt it to work with the way your algo opens positions.

Nevermind, I threw this together based on the stuff I typed above, I had some mistakes in there but the gist of it is the same. Basically you open a position and put it into a list, then you check the list for filled orders every minute. If one is filled then you start a timer for that stock. When that variable reaches 15 it sells the stock.

Clone Algorithm
0
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 5928de37209fb06ab67c2f0d
There was a runtime error.

I see. I think I'm getting close, but I can't get orders to sell. I just used: if cost basis > current price and context.i >= 15: sell

Here's the code:

Thank you! for the help.

Clone Algorithm
0
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 592983c0484cdd6dec79e553
There was a runtime error.

Ah yeah I figured you'd be doing it on multiple stocks. I'd make context.i and context.opened a dictionary. Then make an individual i entry for each stock to track each one's 15 min timer separately. Kind of like this:

context.i = {}  
context.opened = {}

for order in context.orders:  
        o = get_order(order)  
        if o.filled > 0:  
           stock = o.sid  
           context.opened[stock] = True  
           context.orders.remove(order)

for stock in context.securities:  
    if context.opened[stock] == True:  
        context.i[stock] +=1  
    else:  
        context.i[stock] = 0  

so close i can almost taste it. Still getting an error, starting on line 55 (highlighted below):

import pandas as pd

def initialize(context):  
    set_long_only()  
    context.securities = [sid(24), sid(5061), sid(26578), sid(16841), sid(4151), sid(42950), sid(8347), sid(25006), sid(3149), sid(11100), sid(700), sid(6653)]  
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))

    for i in range(15, 387, 1):    # start, stop, every n minutes, where n is 1 in this case  
        schedule_function(run_this, date_rules.every_day(), time_rules.market_open(minutes=i))  
    schedule_function(close_orders, date_rules.every_day(), time_rules.market_close(minutes=2))  
    context.long_pct_per_stock = 2.5 / len(context.securities)  
    set_slippage(slippage.FixedSlippage(spread=0.00))  
    context.i = {}  
    context.opened = {}  
    context.orders = []

def order_stocks(context,data):  
    order = order_target_percent(stock, context.long_pct_per_stock)  
    log.info("opened position")  
    context.orders.append(order)

def run_this(context, data):  
    day_low = data.history(context.securities, 'low', 1, '1d')  
    recent_low = day_low.ix[-1]  
    open_orders = get_open_orders()  
    price_history = data.history(context.securities, fields="price", bar_count=3, frequency="1m")  
    terci_bar = price_history.ix[-3]  
    prev_bar = price_history.ix[-2]  
    curr_bar = price_history.ix[-1]  
    current_price = data.current(context.securities, 'price')  
    for order in context.orders:  
        o = get_order(order)  
        if o.filled > 0:  
           stock = o.sid  
           context.opened[stock] = True  
           context.orders.remove(order)

    for stock in context.securities:  
        if context.opened[stock] == True:  ###this is line 55 - getting error here, but sure its messed up other places too :/  
            context.i[stock] +=1  
        else:  
            context.i[stock] = 0  
        current_position = context.portfolio.positions[stock].amount  
        cost_basis = context.portfolio.positions[stock].cost_basis  
        positions = context.portfolio.positions[stock].sid  
        if stock not in open_orders and data.can_trade(stock):  
            if current_price[stock] <= recent_low[stock] * 1.0005 and current_position == 0:  
                order_target_percent(stock, context.long_pct_per_stock)  
            if context.i[stock] >= 15 and cost_basis[stock] > current_price[stock]:  
                order_target_percent(stock, 0)  
                context.opened = False  
                context.i = 0  
                log.info("Closed position")  

def close_orders(context, data):  
    order_target_value(sid(24), 0)  
    order_target_value(sid(5061), 0)  
    order_target_value(sid(26578), 0)  
    order_target_value(sid(16841), 0)  
    order_target_value(sid(4151), 0)  
    order_target_value(sid(8347), 0)  
    order_target_value(sid(25006), 0)  
    order_target_value(sid(11100), 0)  
    order_target_value(sid(3149), 0)  
    order_target_value(sid(700), 0)  
    order_target_value(sid(6653), 0)  
    order_target_value(sid(42950), 0)