Cookbook
A market order with exits.
A market order with its exits: a take profit 1% away and a stop loss 0.5% away, placed by the API the moment it fills and kept on its servers.
The whole program, in each language. Set PHOENIXPERPS_API_KEY to a sandbox key (ppk_test_...) and run it. The position is closed at the end.
import { PhoenixPerps } from '@phoenixperps/sdk';
const client = new PhoenixPerps();
if (client.environment === 'live' && process.env.PHOENIXPERPS_ALLOW_LIVE !== 'yes') {
console.error('This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).');
process.exit(1);
}
const [account] = (await client.accounts.list()).data;
const btc = await client.markets.get('BTC-USD');
const order = await client.orders.create(account.id, {
market: 'BTC-USD',
side: 'buy',
type: 'market',
size: btc.min_size,
exits: {
take_profit: [{ percent: '1' }],
stop_loss: { percent: '0.5' },
},
});
console.log(`market order ${order.id}: ${order.status} at ${order.average_fill_price ?? '-'}`);
const exits = await client.exits.get(account.id, 'BTC-USD');
for (const tp of exits.take_profit) console.log(`take profit: ${JSON.stringify(tp)}`);
for (const sl of exits.stop_loss) console.log(`stop loss: ${JSON.stringify(sl)}`);
const close = await client.positions.close(account.id, 'BTC-USD', {});
console.log(`closed: ${close.id} ${close.status} (the exits went with the position)`);import json
import os
from phoenixperps import PhoenixPerps
client = PhoenixPerps()
if client.environment == "live" and os.environ.get("PHOENIXPERPS_ALLOW_LIVE") != "yes":
raise SystemExit("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).")
account = client.accounts.list().data[0]
btc = client.markets.get("BTC-USD")
order = client.orders.create(account["id"], {
"market": "BTC-USD",
"side": "buy",
"type": "market",
"size": btc["min_size"],
"exits": {
"take_profit": [{"percent": "1"}],
"stop_loss": {"percent": "0.5"},
},
})
print(f'market order {order["id"]}: {order["status"]} at {order.get("average_fill_price") or "-"}')
exits = client.exits.get(account["id"], "BTC-USD")
for tp in exits["take_profit"]:
print(f"take profit: {json.dumps(tp)}")
for sl in exits["stop_loss"]:
print(f"stop loss: {json.dumps(sl)}")
close = client.positions.close(account["id"], "BTC-USD", {})
print(f'closed: {close["id"]} {close["status"]} (the exits went with the position)')package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
phoenixperps "github.com/phoenixperps/sdk/go"
)
func main() {
ctx := context.Background()
client, err := phoenixperps.NewClient()
if err != nil {
log.Fatal(err)
}
if client.Environment() == "live" && os.Getenv("PHOENIXPERPS_ALLOW_LIVE") != "yes" {
log.Fatal("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).")
}
accounts, err := client.Accounts.List(ctx)
if err != nil {
log.Fatal(err)
}
account := accounts.Data[0].ID
btc, err := client.Markets.Get(ctx, "BTC-USD")
if err != nil {
log.Fatal(err)
}
order, err := client.Orders.Create(ctx, account, phoenixperps.CreateOrder{
Market: "BTC-USD",
Side: phoenixperps.OrderSideBuy,
Type: phoenixperps.CreateOrderTypeMarket,
Size: &btc.MinSize,
Exits: &phoenixperps.OrderExits{
TakeProfit: []phoenixperps.OrderExitsTakeProfit{{Percent: phoenixperps.Dec("1")}},
StopLoss: &phoenixperps.OrderExitsStopLoss{Percent: phoenixperps.Dec("0.5")},
},
})
if err != nil {
log.Fatal(err)
}
fill := "-"
if order.AverageFillPrice != nil {
fill = string(*order.AverageFillPrice)
}
fmt.Printf("market order %s: %s at %s\n", order.ID, order.Status, fill)
exits, err := client.Exits.Get(ctx, account, "BTC-USD")
if err != nil {
log.Fatal(err)
}
for _, tp := range exits.TakeProfit {
b, _ := json.Marshal(tp)
fmt.Printf("take profit: %s\n", b)
}
for _, sl := range exits.StopLoss {
b, _ := json.Marshal(sl)
fmt.Printf("stop loss: %s\n", b)
}
closed, err := client.Positions.Close(ctx, account, "BTC-USD", phoenixperps.ClosePosition{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("closed: %s %s (the exits went with the position)\n", closed.ID, closed.Status)
}#:package PhoenixPerps.Sdk@1.0.0
using System.Globalization;
using PhoenixPerps;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // decimals print as 0.0001 on every machine
using var client = new PhoenixPerpsClient();
if (client.Environment == "live" && Environment.GetEnvironmentVariable("PHOENIXPERPS_ALLOW_LIVE") != "yes")
{
Console.Error.WriteLine("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).");
return 1;
}
var account = (await client.Accounts.ListAsync()).Data[0].Id;
var btc = await client.Markets.GetAsync("BTC-USD");
var order = await client.Orders.CreateAsync(account, new CreateOrder
{
Market = "BTC-USD",
Side = OrderSide.Buy,
Type = CreateOrderType.Market,
Size = btc.MinSize,
Exits = new OrderExits
{
TakeProfit = new() { new OrderExitsTakeProfit { Percent = 1m } },
StopLoss = new OrderExitsStopLoss { Percent = 0.5m },
},
});
Console.WriteLine($"market order {order.Id}: {order.Status} at {order.AverageFillPrice?.ToString() ?? "-"}");
var exits = await client.Exits.GetAsync(account, "BTC-USD");
foreach (var tp in exits.TakeProfit) Console.WriteLine($"take profit: {tp.Size} at {tp.Price} ({tp.Status})");
foreach (var sl in exits.StopLoss) Console.WriteLine($"stop loss: {sl.Size} at {sl.Price} ({sl.Status})");
var closed = await client.Positions.CloseAsync(account, "BTC-USD", new ClosePosition());
Console.WriteLine($"closed: {closed.Id} {closed.Status} (the exits went with the position)");
return 0;import com.phoenixperpsfunding.sdk.PhoenixPerpsClient;
import com.phoenixperpsfunding.sdk.gen.ClosePosition;
import com.phoenixperpsfunding.sdk.gen.CreateOrder;
import com.phoenixperpsfunding.sdk.gen.CreateOrderType;
import com.phoenixperpsfunding.sdk.gen.Exits;
import com.phoenixperpsfunding.sdk.gen.ExitsLeg;
import com.phoenixperpsfunding.sdk.gen.Market;
import com.phoenixperpsfunding.sdk.gen.Order;
import com.phoenixperpsfunding.sdk.gen.OrderExits;
import com.phoenixperpsfunding.sdk.gen.OrderExitsStopLoss;
import com.phoenixperpsfunding.sdk.gen.OrderExitsTakeProfit;
import com.phoenixperpsfunding.sdk.gen.OrderSide;
import java.math.BigDecimal;
import java.util.List;
final class Example05 {
public static void main(String[] args) {
PhoenixPerpsClient client = PhoenixPerpsClient.fromEnv();
if ("live".equals(client.environment()) && !"yes".equals(System.getenv("PHOENIXPERPS_ALLOW_LIVE"))) {
System.err.println("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).");
System.exit(1);
}
String account = client.accounts().list().data().get(0).id();
Market btc = client.markets().get("BTC-USD");
Order order = client.orders().create(account, new CreateOrder()
.market("BTC-USD")
.side(OrderSide.BUY)
.type(CreateOrderType.MARKET)
.size(btc.minSize())
.exits(new OrderExits()
.takeProfit(List.of(new OrderExitsTakeProfit().percent(new BigDecimal("1"))))
.stopLoss(new OrderExitsStopLoss().percent(new BigDecimal("0.5")))));
System.out.printf("market order %s: %s at %s%n", order.id(), order.status(), order.averageFillPrice());
Exits exits = client.exits().get(account, "BTC-USD");
for (ExitsLeg tp : exits.takeProfit()) System.out.printf("take profit: %s at %s (%s)%n", tp.size(), tp.price(), tp.status());
for (ExitsLeg sl : exits.stopLoss()) System.out.printf("stop loss: %s at %s (%s)%n", sl.size(), sl.price(), sl.status());
Order closed = client.positions().close(account, "BTC-USD", new ClosePosition());
System.out.printf("closed: %s %s (the exits went with the position)%n", closed.id(), closed.status());
}
}use phoenixperps::{dec, Client, ClosePosition, CreateOrder, CreateOrderType, OrderExits, OrderExitsStopLoss, OrderExitsTakeProfit, OrderSide};
#[tokio::main]
async fn main() -> phoenixperps::Result<()> {
let client = Client::from_env()?;
if client.environment() == "live" && std::env::var("PHOENIXPERPS_ALLOW_LIVE").as_deref() != Ok("yes") {
eprintln!("This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).");
std::process::exit(1);
}
let account = client.accounts().list().await?.data[0].id.clone();
let btc = client.markets().get("BTC-USD").await?;
let order = client
.orders()
.create(&account, &CreateOrder {
market: "BTC-USD".into(),
side: OrderSide::Buy,
r#type: CreateOrderType::Market,
size: Some(btc.min_size),
exits: Some(OrderExits {
take_profit: Some(vec![OrderExitsTakeProfit { percent: Some(dec("1")), ..Default::default() }]),
stop_loss: Some(OrderExitsStopLoss { percent: Some(dec("0.5")), ..Default::default() }),
..Default::default()
}),
..Default::default()
})
.await?;
let fill = order.average_fill_price.map(|p| p.to_string()).unwrap_or_else(|| "-".into());
println!("market order {}: {} at {fill}", order.id, order.status);
let exits = client.exits().get(&account, "BTC-USD").await?;
for tp in &exits.take_profit {
println!("take profit: {} at {:?} ({})", tp.size, tp.price, tp.status);
}
for sl in &exits.stop_loss {
println!("stop loss: {} at {:?} ({})", sl.size, sl.price, sl.status);
}
let closed = client.positions().close(&account, "BTC-USD", &ClosePosition::default()).await?;
println!("closed: {} {} (the exits went with the position)", closed.id, closed.status);
Ok(())
}<?php
require 'vendor/autoload.php';
use PhoenixPerps\Client;
$client = new Client();
if ($client->environment === 'live' && getenv('PHOENIXPERPS_ALLOW_LIVE') !== 'yes') {
fwrite(STDERR, "This example trades: it runs on the sandbox (PHOENIXPERPS_ALLOW_LIVE=yes to run it on live).\n");
exit(1);
}
$account = $client->accounts->list()->data[0]->id;
$btc = $client->markets->get('BTC-USD');
$order = $client->orders->create($account, [
'market' => 'BTC-USD',
'side' => 'buy',
'type' => 'market',
'size' => $btc->minSize,
'exits' => [
'take_profit' => [['percent' => '1']],
'stop_loss' => ['percent' => '0.5'],
],
]);
printf("market order %s: %s at %s\n", $order->id, $order->status, $order->averageFillPrice ?? '-');
$exits = $client->exits->get($account, 'BTC-USD');
foreach ($exits->takeProfit ?? [] as $tp) {
printf("take profit: %s at %s (%s)\n", $tp->size, $tp->price ?? '-', $tp->status);
}
foreach ($exits->stopLoss ?? [] as $sl) {
printf("stop loss: %s at %s (%s)\n", $sl->size, $sl->price ?? '-', $sl->status);
}
$closed = $client->positions->close($account, 'BTC-USD', []);
printf("closed: %s %s (the exits went with the position)\n", $closed->id, $closed->status);