or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcryptocurrency.mdindex.mdmarket-data.mdstreaming.mdtrading-operations.md

trading-operations.mddocs/

0

# Trading Operations

1

2

Core trading functionality for account management, order execution, position management, and portfolio analytics. These operations provide the foundation for algorithmic trading strategies and portfolio management systems.

3

4

## Capabilities

5

6

### Account Management

7

8

Access and manage account information including equity, buying power, account configurations, and trading permissions.

9

10

```python { .api }

11

def get_account() -> Account:

12

"""Get current account information."""

13

14

def get_account_configurations() -> AccountConfigurations:

15

"""Get account configuration settings."""

16

17

def update_account_configurations(

18

no_shorting: bool = None,

19

dtbp_check: str = None,

20

trade_confirm_email: str = None,

21

suspend_trade: bool = None

22

) -> AccountConfigurations:

23

"""Update account configuration settings."""

24

```

25

26

**Usage Example:**

27

28

```python

29

api = tradeapi.REST('key', 'secret')

30

31

# Get account details

32

account = api.get_account()

33

print(f"Equity: ${account.equity}")

34

print(f"Buying Power: ${account.buying_power}")

35

print(f"Day Trading Buying Power: ${account.daytrading_buying_power}")

36

37

# Update account settings

38

config = api.update_account_configurations(

39

trade_confirm_email='all'

40

)

41

```

42

43

### Order Management

44

45

Submit, manage, and track trading orders with support for various order types, time-in-force options, and advanced order strategies.

46

47

```python { .api }

48

def submit_order(

49

symbol: str,

50

qty: float = None,

51

side: str = "buy",

52

type: str = "market",

53

time_in_force: str = "day",

54

limit_price: str = None,

55

stop_price: str = None,

56

client_order_id: str = None,

57

extended_hours: bool = None,

58

order_class: str = None,

59

take_profit: dict = None,

60

stop_loss: dict = None,

61

trail_price: str = None,

62

trail_percent: str = None,

63

notional: float = None

64

) -> Order:

65

"""Submit a new order."""

66

67

def list_orders(

68

status: str = None,

69

limit: int = None,

70

after: str = None,

71

until: str = None,

72

direction: str = None,

73

nested: bool = None,

74

symbols: List[str] = None,

75

side: str = None

76

) -> List[Order]:

77

"""List orders with optional filtering."""

78

79

def get_order(order_id: str, nested: bool = None) -> Order:

80

"""Get a specific order by ID."""

81

82

def get_order_by_client_order_id(client_order_id: str) -> Order:

83

"""Get an order by client order ID."""

84

85

def replace_order(

86

order_id: str,

87

qty: str = None,

88

limit_price: str = None,

89

stop_price: str = None,

90

trail_price: str = None,

91

trail_percent: str = None,

92

time_in_force: str = None,

93

client_order_id: str = None

94

) -> Order:

95

"""Replace an existing order."""

96

97

def cancel_order(order_id: str) -> None:

98

"""Cancel a specific order."""

99

100

def cancel_all_orders() -> None:

101

"""Cancel all open orders."""

102

```

103

104

**Usage Examples:**

105

106

```python

107

# Submit a market order

108

order = api.submit_order(

109

symbol='AAPL',

110

qty=100,

111

side='buy',

112

type='market',

113

time_in_force='day'

114

)

115

116

# Submit a limit order with stop loss

117

order = api.submit_order(

118

symbol='TSLA',

119

qty=50,

120

side='buy',

121

type='limit',

122

time_in_force='gtc',

123

limit_price=250.00,

124

order_class='bracket',

125

stop_loss={'stop_price': 230.00},

126

take_profit={'limit_price': 270.00}

127

)

128

129

# List all open orders

130

orders = api.list_orders(status='open')

131

for order in orders:

132

print(f"Order {order.id}: {order.symbol} {order.side} {order.qty} @ {order.limit_price}")

133

134

# Cancel all orders

135

api.cancel_all_orders()

136

```

137

138

### Position Management

139

140

Monitor and manage trading positions including position sizes, market values, and position closing operations.

141

142

```python { .api }

143

def list_positions() -> List[Position]:

144

"""List all current positions."""

145

146

def get_position(symbol: str) -> Position:

147

"""Get a specific position by symbol."""

148

149

def close_position(symbol: str, qty: float = None) -> Position:

150

"""Close a position (full or partial)."""

151

152

def close_all_positions() -> List[Position]:

153

"""Close all open positions."""

154

```

155

156

**Usage Examples:**

157

158

```python

159

# List all positions

160

positions = api.list_positions()

161

for position in positions:

162

print(f"{position.symbol}: {position.qty} shares, P&L: ${position.unrealized_pl}")

163

164

# Get specific position

165

try:

166

position = api.get_position('AAPL')

167

print(f"AAPL position: {position.qty} shares at ${position.avg_entry_price}")

168

except tradeapi.rest.APIError as e:

169

print("No AAPL position found")

170

171

# Close half of a position

172

api.close_position('AAPL', qty=50)

173

174

# Close all positions

175

api.close_all_positions()

176

```

177

178

### Asset Information

179

180

Access information about tradeable assets including asset classes, exchange details, and trading status.

181

182

```python { .api }

183

def list_assets(status: str = None, asset_class: str = None) -> List[Asset]:

184

"""List available assets with optional filtering."""

185

186

def get_asset(symbol: str) -> Asset:

187

"""Get information about a specific asset."""

188

```

189

190

**Usage Examples:**

191

192

```python

193

# List all active US equity assets

194

assets = api.list_assets(status='active', asset_class='us_equity')

195

print(f"Found {len(assets)} active stocks")

196

197

# Get asset information

198

asset = api.get_asset('AAPL')

199

print(f"Asset: {asset.name}, Exchange: {asset.exchange}, Tradable: {asset.tradable}")

200

```

201

202

### Account Activities

203

204

Retrieve account activity history including trade executions, dividends, and other account events.

205

206

```python { .api }

207

def get_activities(

208

activity_types: str = None,

209

until: str = None,

210

after: str = None,

211

direction: str = None,

212

date: str = None,

213

page_size: int = None,

214

page_token: str = None

215

) -> List[AccountActivity]:

216

"""Get account activities with optional filtering."""

217

```

218

219

**Usage Example:**

220

221

```python

222

# Get recent trade activities

223

activities = api.get_activities(activity_types='FILL')

224

for activity in activities:

225

print(f"{activity.transaction_time}: {activity.symbol} {activity.side} {activity.qty} @ ${activity.price}")

226

```

227

228

### Watchlists

229

230

Create and manage watchlists for tracking symbols of interest.

231

232

```python { .api }

233

def get_watchlists() -> List[Watchlist]:

234

"""Get all watchlists."""

235

236

def get_watchlist(watchlist_id: str) -> Watchlist:

237

"""Get a specific watchlist by ID."""

238

239

def get_watchlist_by_name(watchlist_name: str) -> Watchlist:

240

"""Get a watchlist by name."""

241

242

def create_watchlist(watchlist_name: str, symbols: List[str] = None) -> Watchlist:

243

"""Create a new watchlist."""

244

245

def add_to_watchlist(watchlist_id: str, symbol: str) -> Watchlist:

246

"""Add a symbol to a watchlist."""

247

248

def update_watchlist(watchlist_id: str, name: str = None, symbols: List[str] = None) -> Watchlist:

249

"""Update a watchlist."""

250

251

def delete_watchlist(watchlist_id: str) -> None:

252

"""Delete a watchlist."""

253

254

def delete_from_watchlist(watchlist_id: str, symbol: str) -> None:

255

"""Remove a symbol from a watchlist."""

256

```

257

258

### Portfolio History

259

260

Access historical portfolio performance data for analysis and reporting.

261

262

```python { .api }

263

def get_portfolio_history(

264

date_start: str = None,

265

date_end: str = None,

266

period: str = None,

267

timeframe: str = None,

268

extended_hours: bool = None

269

) -> PortfolioHistory:

270

"""Get portfolio history data."""

271

```

272

273

## Types

274

275

```python { .api }

276

class Account:

277

@property

278

def id(self) -> str: ...

279

@property

280

def equity(self) -> float: ...

281

@property

282

def cash(self) -> float: ...

283

@property

284

def buying_power(self) -> float: ...

285

@property

286

def daytrading_buying_power(self) -> float: ...

287

@property

288

def status(self) -> str: ...

289

290

class Order:

291

@property

292

def id(self) -> str: ...

293

@property

294

def client_order_id(self) -> str: ...

295

@property

296

def symbol(self) -> str: ...

297

@property

298

def qty(self) -> float: ...

299

@property

300

def side(self) -> str: ...

301

@property

302

def order_type(self) -> str: ...

303

@property

304

def status(self) -> str: ...

305

@property

306

def filled_qty(self) -> float: ...

307

@property

308

def legs(self) -> List[Order]: ...

309

310

class Position:

311

@property

312

def symbol(self) -> str: ...

313

@property

314

def qty(self) -> float: ...

315

@property

316

def side(self) -> str: ...

317

@property

318

def market_value(self) -> float: ...

319

@property

320

def avg_entry_price(self) -> float: ...

321

@property

322

def unrealized_pl(self) -> float: ...

323

@property

324

def unrealized_plpc(self) -> float: ...

325

326

class Asset:

327

@property

328

def id(self) -> str: ...

329

@property

330

def symbol(self) -> str: ...

331

@property

332

def name(self) -> str: ...

333

@property

334

def exchange(self) -> str: ...

335

@property

336

def asset_class(self) -> str: ...

337

@property

338

def status(self) -> str: ...

339

@property

340

def tradable(self) -> bool: ...

341

342

class AccountActivity:

343

@property

344

def id(self) -> str: ...

345

@property

346

def activity_type(self) -> str: ...

347

@property

348

def transaction_time(self) -> pd.Timestamp: ...

349

@property

350

def symbol(self) -> str: ...

351

@property

352

def qty(self) -> float: ...

353

@property

354

def price(self) -> float: ...

355

@property

356

def side(self) -> str: ...

357

358

class AccountConfigurations:

359

@property

360

def dtbp_check(self) -> str: ...

361

@property

362

def no_shorting(self) -> bool: ...

363

@property

364

def suspend_trade(self) -> bool: ...

365

@property

366

def trade_confirm_email(self) -> str: ...

367

368

class Watchlist:

369

@property

370

def id(self) -> str: ...

371

@property

372

def name(self) -> str: ...

373

@property

374

def assets(self) -> List[Asset]: ...

375

@property

376

def created_at(self) -> pd.Timestamp: ...

377

@property

378

def updated_at(self) -> pd.Timestamp: ...

379

380

class PortfolioHistory:

381

@property

382

def df(self) -> pd.DataFrame: ...

383

@property

384

def equity(self) -> List[float]: ...

385

@property

386

def profit_loss(self) -> List[float]: ...

387

@property

388

def profit_loss_pct(self) -> List[float]: ...

389

@property

390

def base_value(self) -> float: ...

391

@property

392

def timeframe(self) -> str: ...

393

```