self.buy() sends a buy order to the broker, self.sell() a sell order. By default these are market orders, executed at the open of the next bar.
self.close() sends the opposite order to the open position, with the same size: it is the safest way to exit a position.
A sell() with no position opens a short sale: you gain if the price falls and lose if it rises, with no theoretical limit.
These methods return the order they create: self.order = self.buy() lets you know an order is pending and avoid sending a second one.
Examples
ORDRE-X (fictional market) : The circles mark a high and a low. A sell() decided at the high and a buy() decided at the low would be executed at the open of the next bar, so a little away from those perfect points.
The flash crash of 6 May 2010 : That day the Dow Jones lost nearly 1,000 points in a few minutes before recovering. Some market orders were filled at absurd prices, such as Accenture shares trading at one cent: a market order guarantees execution, not price.
Key terms
buy()
Sends a buy order
sell()
Sends a sell order
close()
Closes the open position
Short sale
Selling an asset you do not own to profit from a fall